Skip to main content

common_query/
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//! Shared native histogram field contract.
16//!
17//! Prom remote-write v2 stores these names as children of one Struct field, while
18//! metric-engine uses the same contract to recognize native histogram tables.
19//! [`NativeHistogram`] is the query-time representation and therefore normalizes
20//! integer and floating-point payloads to absolute `f64` counts.
21
22mod encoding;
23
24use std::borrow::Cow;
25use std::collections::BTreeMap;
26use std::sync::Arc;
27
28use datafusion::arrow::array::{
29    Array, ArrayRef, Float64Array, Int32Array, Int64Array, ListArray, PrimitiveArray, StructArray,
30    TimestampMillisecondArray, UInt32Array,
31};
32use datafusion::arrow::buffer::NullBuffer;
33use datafusion::arrow::datatypes::{
34    ArrowPrimitiveType, DataType as ArrowDataType, Field, Float64Type, Int32Type, Int64Type,
35    TimestampMillisecondType,
36};
37use datafusion_common::{DataFusionError, Result as DfResult};
38use datatypes::data_type::{ConcreteDataType, DataType};
39pub use datatypes::series::histogram::CounterResetHint;
40use datatypes::series::histogram::{BucketSideView, HistogramBatchBuilder, HistogramView};
41use datatypes::series::samples::Samples;
42use datatypes::types::{StructField, StructType};
43pub use encoding::{
44    NativeHistogramError, decode_native_histogram_for_remote_read, encode_native_histogram,
45    native_histogram_column_schema,
46};
47use once_cell::sync::Lazy;
48
49use crate::prelude::greptime_native_histogram;
50use crate::prometheus::format_prometheus_float;
51
52pub const NATIVE_HISTOGRAM_FIELD: &str = "greptime_native_histogram";
53pub const SCHEMA_FIELD: &str = "schema";
54pub const ZERO_THRESHOLD_FIELD: &str = "zero_threshold";
55pub const SUM_FIELD: &str = "sum";
56pub const RESET_HINT_FIELD: &str = "reset_hint";
57pub const START_TIMESTAMP_FIELD: &str = "start_timestamp";
58pub const CUSTOM_VALUES_FIELD: &str = "custom_values";
59pub const POSITIVE_SPAN_OFFSETS_FIELD: &str = "positive_span_offsets";
60pub const POSITIVE_SPAN_LENGTHS_FIELD: &str = "positive_span_lengths";
61pub const NEGATIVE_SPAN_OFFSETS_FIELD: &str = "negative_span_offsets";
62pub const NEGATIVE_SPAN_LENGTHS_FIELD: &str = "negative_span_lengths";
63pub const COUNT_I64_FIELD: &str = "count_i64";
64pub const ZERO_COUNT_I64_FIELD: &str = "zero_count_i64";
65pub const POSITIVE_BUCKETS_I64_FIELD: &str = "positive_buckets_i64";
66pub const NEGATIVE_BUCKETS_I64_FIELD: &str = "negative_buckets_i64";
67pub const COUNT_F64_FIELD: &str = "count_f64";
68pub const ZERO_COUNT_F64_FIELD: &str = "zero_count_f64";
69pub const POSITIVE_BUCKETS_F64_FIELD: &str = "positive_buckets_f64";
70pub const NEGATIVE_BUCKETS_F64_FIELD: &str = "negative_buckets_f64";
71
72// Keep int and float payloads in separate columns. The populated family is the
73// type signal, so we don't need to persist an extra histogram-type tag.
74pub const NATIVE_HISTOGRAM_FIELD_NAMES: &[&str] = &[
75    SCHEMA_FIELD,
76    ZERO_THRESHOLD_FIELD,
77    SUM_FIELD,
78    RESET_HINT_FIELD,
79    START_TIMESTAMP_FIELD,
80    CUSTOM_VALUES_FIELD,
81    POSITIVE_SPAN_OFFSETS_FIELD,
82    POSITIVE_SPAN_LENGTHS_FIELD,
83    NEGATIVE_SPAN_OFFSETS_FIELD,
84    NEGATIVE_SPAN_LENGTHS_FIELD,
85    COUNT_I64_FIELD,
86    ZERO_COUNT_I64_FIELD,
87    POSITIVE_BUCKETS_I64_FIELD,
88    NEGATIVE_BUCKETS_I64_FIELD,
89    COUNT_F64_FIELD,
90    ZERO_COUNT_F64_FIELD,
91    POSITIVE_BUCKETS_F64_FIELD,
92    NEGATIVE_BUCKETS_F64_FIELD,
93];
94
95static NATIVE_HISTOGRAM_VALUE_TYPE: Lazy<ConcreteDataType> = Lazy::new(|| {
96    let fields = NATIVE_HISTOGRAM_FIELD_NAMES
97        .iter()
98        .filter_map(|name| {
99            let data_type = native_histogram_field_type(name)?;
100            Some(StructField::new((*name).to_string(), data_type, true))
101        })
102        .collect();
103    ConcreteDataType::struct_datatype(StructType::new(Arc::new(fields)))
104});
105
106/// Returns the exact Greptime type for a persisted native histogram field.
107pub fn native_histogram_field_type(name: &str) -> Option<ConcreteDataType> {
108    match name {
109        SCHEMA_FIELD | RESET_HINT_FIELD => Some(ConcreteDataType::int32_datatype()),
110        ZERO_THRESHOLD_FIELD | SUM_FIELD | COUNT_F64_FIELD | ZERO_COUNT_F64_FIELD => {
111            Some(ConcreteDataType::float64_datatype())
112        }
113        START_TIMESTAMP_FIELD => Some(ConcreteDataType::timestamp_millisecond_datatype()),
114        CUSTOM_VALUES_FIELD | POSITIVE_BUCKETS_F64_FIELD | NEGATIVE_BUCKETS_F64_FIELD => Some(
115            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::float64_datatype())),
116        ),
117        POSITIVE_SPAN_OFFSETS_FIELD | NEGATIVE_SPAN_OFFSETS_FIELD => Some(
118            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int32_datatype())),
119        ),
120        POSITIVE_SPAN_LENGTHS_FIELD | NEGATIVE_SPAN_LENGTHS_FIELD => Some(
121            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int32_datatype())),
122        ),
123        COUNT_I64_FIELD | ZERO_COUNT_I64_FIELD => Some(ConcreteDataType::int64_datatype()),
124        POSITIVE_BUCKETS_I64_FIELD | NEGATIVE_BUCKETS_I64_FIELD => Some(
125            ConcreteDataType::list_datatype(Arc::new(ConcreteDataType::int64_datatype())),
126        ),
127        _ => None,
128    }
129}
130
131/// Returns the exact Greptime type for a complete native histogram value.
132pub fn native_histogram_value_type() -> &'static ConcreteDataType {
133    &NATIVE_HISTOGRAM_VALUE_TYPE
134}
135
136/// Returns whether `data_type` matches the native histogram value contract.
137pub fn is_native_histogram_value_type(data_type: &ConcreteDataType) -> bool {
138    data_type == native_histogram_value_type()
139}
140
141/// Returns whether a named column matches the configured native histogram contract.
142pub fn is_native_histogram_value_schema(name: &str, data_type: &ConcreteDataType) -> bool {
143    name == greptime_native_histogram() && is_native_histogram_value_type(data_type)
144}
145
146#[cfg(any(test, feature = "testing"))]
147pub mod testing {
148    use api::helper::pb_value_to_value_ref;
149    use api::v1::{Value, value::ValueData};
150    use datafusion::arrow::array::{AsArray, StructArray};
151    use datatypes::vectors::Helper;
152
153    use crate::native_histogram::{native_histogram_column_schema, native_histogram_value_type};
154
155    /// Builds stored arrays through the same protobuf-to-vector path as ingestion.
156    pub fn histogram_array(values: &[Option<ValueData>]) -> StructArray {
157        let schema = native_histogram_column_schema().unwrap();
158        let rows = values
159            .iter()
160            .map(|value_data| {
161                datatypes::value::Value::from(pb_value_to_value_ref(
162                    &Value {
163                        value_data: value_data.clone(),
164                    },
165                    schema.datatype_extension.as_ref(),
166                ))
167            })
168            .collect::<Vec<_>>();
169        Helper::try_from_row_into_vector(&rows, native_histogram_value_type())
170            .unwrap()
171            .to_arrow_array()
172            .as_struct()
173            .clone()
174    }
175}
176
177/// Schema identifier for native histograms with explicit custom bucket bounds.
178pub const CUSTOM_BUCKETS_SCHEMA: i32 = -53;
179const MIN_EXPONENTIAL_SCHEMA: i32 = -4;
180const MAX_EXPONENTIAL_SCHEMA: i32 = 8;
181
182/// Reset hint indicating that the payload must be inspected.
183pub const UNKNOWN_COUNTER_RESET_HINT: CounterResetHint = CounterResetHint::Unknown;
184/// Reset hint indicating the first histogram after a counter reset.
185pub const COUNTER_RESET_HINT: CounterResetHint = CounterResetHint::CounterReset;
186/// Reset hint indicating that no counter reset occurred.
187pub const NOT_COUNTER_RESET_HINT: CounterResetHint = CounterResetHint::NotCounterReset;
188/// Reset hint identifying a gauge histogram.
189pub const GAUGE_RESET_HINT: CounterResetHint = CounterResetHint::Gauge;
190
191/// A contiguous run of populated sparse buckets.
192#[derive(Clone, Debug, PartialEq)]
193pub struct Span {
194    /// The first bucket index, or the gap after the preceding span.
195    pub offset: i32,
196    /// Number of consecutive buckets in the span.
197    pub length: i32,
198}
199
200/// Inclusion rules for a materialized bucket's lower and upper bounds.
201#[derive(Clone, Copy, Debug, PartialEq, Eq)]
202enum BoundaryRule {
203    OpenLeft = 0,
204    OpenRight = 1,
205    ClosedBoth = 3,
206}
207
208/// A materialized bucket used by query-time estimators and renderers.
209#[derive(Clone, Debug, PartialEq)]
210struct Bucket {
211    lower: f64,
212    upper: f64,
213    count: f64,
214    boundary_rule: BoundaryRule,
215}
216
217/// Additional information produced while estimating a native histogram quantile.
218#[derive(Clone, Copy, Debug, PartialEq, Eq)]
219pub enum NativeHistogramQuantileInfo {
220    /// NaN observations made the estimated quantile skew higher.
221    NaNSkew,
222    /// The requested quantile fell beyond all populated buckets because of NaN observations.
223    NaNResult,
224}
225
226/// Query-time representation of a Prometheus native histogram.
227///
228/// Bucket counts are absolute `f64` values even when the persisted payload used
229/// integer counts or deltas.
230#[derive(Clone, Debug, PartialEq)]
231pub struct NativeHistogram {
232    /// Exponential bucket schema, or [`CUSTOM_BUCKETS_SCHEMA`].
233    pub schema: i32,
234    /// Absolute width of the zero bucket.
235    pub zero_threshold: f64,
236    /// Sum of all observations.
237    pub sum: f64,
238    /// Counter reset information associated with this sample.
239    pub reset_hint: CounterResetHint,
240    /// Optional time in milliseconds when this histogram started counting.
241    pub start_timestamp: Option<i64>,
242    /// Inclusive upper bounds used when `schema` is [`CUSTOM_BUCKETS_SCHEMA`].
243    pub custom_values: Vec<f64>,
244    /// Sparse spans describing positive or custom buckets.
245    pub positive_spans: Vec<Span>,
246    /// Sparse spans describing negative buckets.
247    pub negative_spans: Vec<Span>,
248    /// Total number of observations.
249    pub count: f64,
250    /// Number of observations in the zero bucket.
251    pub zero_count: f64,
252    /// Absolute counts for positive or custom buckets.
253    pub positive_buckets: Vec<f64>,
254    /// Absolute counts for negative buckets.
255    pub negative_buckets: Vec<f64>,
256}
257
258/// Formats a histogram component like Prometheus's default `%g` formatter.
259fn format_promql_histogram_float(value: f64) -> String {
260    let abs = value.abs();
261    if !value.is_finite() || value == 0.0 || (1e-4..1e6).contains(&abs) {
262        return format_prometheus_float(value);
263    }
264
265    let scientific = format!("{value:e}");
266    let Some((mantissa, exponent)) = scientific.rsplit_once('e') else {
267        return scientific;
268    };
269    let (sign, exponent) = if let Some(exponent) = exponent.strip_prefix('-') {
270        ('-', exponent)
271    } else {
272        ('+', exponent.strip_prefix('+').unwrap_or(exponent))
273    };
274    format!("{mantissa}e{sign}{exponent:0>2}")
275}
276
277impl NativeHistogram {
278    /// Appends this histogram, borrowing its bucket and custom-bound slices as input.
279    /// Span metadata is staged into temporary column vectors; the builder copies all input
280    /// values into its owned result storage.
281    pub fn push_to(&self, builder: &mut HistogramBatchBuilder) -> datatypes::Result<u32> {
282        let positive_offsets: Vec<_> = self.positive_spans.iter().map(|span| span.offset).collect();
283        let positive_lengths: Vec<_> = self.positive_spans.iter().map(|span| span.length).collect();
284        let negative_offsets: Vec<_> = self.negative_spans.iter().map(|span| span.offset).collect();
285        let negative_lengths: Vec<_> = self.negative_spans.iter().map(|span| span.length).collect();
286        builder.push(HistogramView {
287            schema: self.schema,
288            zero_threshold: self.zero_threshold,
289            sum: self.sum,
290            count: self.count,
291            zero_count: self.zero_count,
292            reset_hint: self.reset_hint,
293            start_timestamp: self.start_timestamp,
294            custom_values: &self.custom_values,
295            positive: BucketSideView {
296                span_offsets: &positive_offsets,
297                span_lengths: &positive_lengths,
298                buckets: &self.positive_buckets,
299            },
300            negative: BucketSideView {
301                span_offsets: &negative_offsets,
302                span_lengths: &negative_lengths,
303                buckets: &self.negative_buckets,
304            },
305        })
306    }
307}
308
309impl NativeHistogram {
310    fn uses_custom_buckets(&self) -> bool {
311        self.schema == CUSTOM_BUCKETS_SCHEMA
312    }
313
314    fn compatible_with(&self, other: &Self) -> bool {
315        self.schema == other.schema
316            && self.zero_threshold == other.zero_threshold
317            && self.custom_values == other.custom_values
318    }
319
320    /// Returns a histogram with the same layout and metadata but zeroed payload values.
321    pub fn zero_like(&self) -> Self {
322        let mut result = self.clone();
323        result.count = 0.0;
324        result.zero_count = 0.0;
325        result.sum = 0.0;
326        result.positive_buckets.fill(0.0);
327        result.negative_buckets.fill(0.0);
328        result
329    }
330
331    fn combine_exact(
332        &self,
333        other: &Self,
334        reset_hint: CounterResetHint,
335        op: impl Fn(f64, f64) -> f64 + Copy,
336    ) -> Option<Self> {
337        if !self.compatible_with(other) {
338            return None;
339        }
340
341        let mut result = self.clone();
342        result.count = op(result.count, other.count);
343        result.zero_count = op(result.zero_count, other.zero_count);
344        result.sum = op(result.sum, other.sum);
345        result.reset_hint = reset_hint;
346        (result.positive_spans, result.positive_buckets) = merge_side(
347            &self.positive_spans,
348            &self.positive_buckets,
349            &other.positive_spans,
350            &other.positive_buckets,
351            op,
352        )?;
353        (result.negative_spans, result.negative_buckets) = merge_side(
354            &self.negative_spans,
355            &self.negative_buckets,
356            &other.negative_spans,
357            &other.negative_buckets,
358            op,
359        )?;
360        Some(result)
361    }
362
363    /// Adds two histograms after reconciling compatible bucket layouts.
364    ///
365    /// Returns `None` when the layouts are invalid or cannot be reconciled.
366    pub fn add(&self, other: &Self) -> Option<Self> {
367        let reset_hint = add_reset_hint(self.reset_hint, other.reset_hint);
368        let (left, right) = self.reconcile(other)?;
369        left.combine_exact(&right, reset_hint, |left, right| left + right)?
370            .compact()
371    }
372
373    /// Subtracts `other` after reconciling compatible bucket layouts.
374    ///
375    /// Returns `None` when the layouts are invalid or cannot be reconciled.
376    pub fn sub(&self, other: &Self) -> Option<Self> {
377        let (left, right) = self.reconcile(other)?;
378        left.combine_exact(&right, CounterResetHint::Gauge, |left, right| left - right)?
379            .compact()
380    }
381
382    /// Negates every payload value and marks the result as a gauge histogram.
383    pub fn negated(self) -> Self {
384        self.scale(-1.0)
385    }
386
387    /// Marks this histogram as a gauge without changing its payload.
388    pub fn into_gauge(mut self) -> Self {
389        self.reset_hint = CounterResetHint::Gauge;
390        self
391    }
392
393    /// Returns whether the histograms carry explicit, contradictory reset hints.
394    pub fn counter_reset_hints_contradict(&self, other: &Self) -> bool {
395        matches!(
396            (self.reset_hint, other.reset_hint),
397            (
398                CounterResetHint::CounterReset,
399                CounterResetHint::NotCounterReset
400            ) | (
401                CounterResetHint::NotCounterReset,
402                CounterResetHint::CounterReset
403            )
404        )
405    }
406
407    /// Returns whether two custom histograms use different bucket bounds.
408    pub fn needs_custom_reconciliation(&self, other: &Self) -> bool {
409        self.uses_custom_buckets()
410            && other.uses_custom_buckets()
411            && self.custom_values != other.custom_values
412    }
413
414    /// Compares PromQL-visible payload values by their exact bit patterns.
415    ///
416    /// Reset hints and start timestamps are ignored.
417    pub fn promql_eq(&self, other: &Self) -> bool {
418        self.schema == other.schema
419            && self.zero_threshold == other.zero_threshold
420            && self.custom_values == other.custom_values
421            && self.count.to_bits() == other.count.to_bits()
422            && self.zero_count.to_bits() == other.zero_count.to_bits()
423            && self.sum.to_bits() == other.sum.to_bits()
424            && side_layout_equal(
425                &self.positive_spans,
426                &self.positive_buckets,
427                &other.positive_spans,
428                &other.positive_buckets,
429            )
430            && side_layout_equal(
431                &self.negative_spans,
432                &self.negative_buckets,
433                &other.negative_spans,
434                &other.negative_buckets,
435            )
436    }
437
438    /// Formats this histogram using PromQL native histogram sample notation.
439    pub fn promql_string(&self) -> String {
440        let mut parts = vec![
441            format!("count:{}", format_promql_histogram_float(self.count)),
442            format!("sum:{}", format_promql_histogram_float(self.sum)),
443        ];
444        if let Some(buckets) = self.all_buckets() {
445            parts.extend(
446                buckets
447                    .into_iter()
448                    .filter(|bucket| bucket.count != 0.0)
449                    .map(|bucket| {
450                        let (left, right) = match bucket.boundary_rule {
451                            BoundaryRule::OpenLeft => ("(", "]"),
452                            BoundaryRule::OpenRight => ("[", ")"),
453                            BoundaryRule::ClosedBoth => ("[", "]"),
454                        };
455                        format!(
456                            "{}{},{}{}:{}",
457                            left,
458                            format_promql_histogram_float(bucket.lower),
459                            format_promql_histogram_float(bucket.upper),
460                            right,
461                            format_promql_histogram_float(bucket.count)
462                        )
463                    }),
464            );
465        }
466        format!("{{{}}}", parts.join(", "))
467    }
468
469    /// Estimates the population variance using each populated bucket's midpoint.
470    pub fn estimated_stdvar(&self) -> f64 {
471        if self.count == 0.0 {
472            return f64::NAN;
473        }
474        let mean = self.sum / self.count;
475        let Some(buckets) = self.all_buckets() else {
476            return f64::NAN;
477        };
478        buckets
479            .into_iter()
480            .map(|bucket| {
481                let midpoint = self.bucket_midpoint(&bucket);
482                bucket.count * (midpoint - mean).powi(2)
483            })
484            .sum::<f64>()
485            / self.count
486    }
487
488    /// Estimates the population standard deviation from [`Self::estimated_stdvar`].
489    pub fn estimated_stddev(&self) -> f64 {
490        self.estimated_stdvar().sqrt()
491    }
492
493    /// Multiplies every payload value by `factor`.
494    ///
495    /// A negative factor marks the result as a gauge histogram.
496    pub fn scale(mut self, factor: f64) -> Self {
497        self.count *= factor;
498        self.zero_count *= factor;
499        self.sum *= factor;
500        for count in &mut self.positive_buckets {
501            *count *= factor;
502        }
503        for count in &mut self.negative_buckets {
504            *count *= factor;
505        }
506        if factor < 0.0 {
507            self.reset_hint = CounterResetHint::Gauge;
508        }
509        self
510    }
511
512    /// Divides every payload value by `divisor`.
513    ///
514    /// A negative divisor marks the result as a gauge histogram.
515    pub fn divide_by(mut self, divisor: f64) -> Self {
516        self.count /= divisor;
517        self.zero_count /= divisor;
518        self.sum /= divisor;
519        if divisor == 0.0 {
520            self.positive_spans.clear();
521            self.positive_buckets.clear();
522            self.negative_spans.clear();
523            self.negative_buckets.clear();
524        } else {
525            for count in &mut self.positive_buckets {
526                *count /= divisor;
527            }
528            for count in &mut self.negative_buckets {
529                *count /= divisor;
530            }
531        }
532        if divisor < 0.0 {
533            self.reset_hint = CounterResetHint::Gauge;
534        }
535        self
536    }
537
538    fn compact(mut self) -> Option<Self> {
539        let (spans, buckets) = compact_side(&self.positive_spans, &self.positive_buckets)?;
540        self.positive_spans = spans;
541        self.positive_buckets = buckets;
542        let (spans, buckets) = compact_side(&self.negative_spans, &self.negative_buckets)?;
543        self.negative_spans = spans;
544        self.negative_buckets = buckets;
545        Some(self)
546    }
547
548    /// Detects a reset from the explicit hint and histogram payload.
549    pub fn detect_reset(&self, previous: &Self) -> bool {
550        match self.reset_hint {
551            CounterResetHint::CounterReset => return true,
552            CounterResetHint::NotCounterReset => return false,
553            CounterResetHint::Unknown
554            | CounterResetHint::Gauge
555            | CounterResetHint::Unrecognized(_) => {}
556        }
557
558        if self.count < previous.count {
559            return true;
560        }
561
562        match (self.uses_custom_buckets(), previous.uses_custom_buckets()) {
563            (true, true) => {
564                let Some((current, previous)) = reconcile_custom(self, previous) else {
565                    return true;
566                };
567                current.zero_count < previous.zero_count
568                    || current.side_has_reset(true, &previous)
569                    || current.side_has_reset(false, &previous)
570            }
571            (true, false) | (false, true) => true,
572            (false, false) => {
573                if self.schema > previous.schema || self.zero_threshold < previous.zero_threshold {
574                    return true;
575                }
576
577                let mut previous = previous.clone();
578                if self.zero_threshold > previous.zero_threshold {
579                    let Some(expanded) = previous.expanded_zero_threshold(self.zero_threshold)
580                    else {
581                        return true;
582                    };
583                    if expanded != self.zero_threshold
584                        || previous.grow_zero_threshold(self.zero_threshold).is_none()
585                    {
586                        return true;
587                    }
588                }
589                let Some(previous) = previous.copy_to_schema(self.schema) else {
590                    return true;
591                };
592
593                self.zero_count < previous.zero_count
594                    || self.side_has_reset(true, &previous)
595                    || self.side_has_reset(false, &previous)
596            }
597        }
598    }
599
600    /// Detects a counter reset using start timestamps, hints, and payload values.
601    pub fn detect_counter_reset(&self, previous: &Self, previous_ts: i64, current_ts: i64) -> bool {
602        is_start_timestamp_reset(
603            previous.start_timestamp.unwrap_or_default(),
604            previous_ts,
605            self.start_timestamp.unwrap_or_default(),
606            current_ts,
607        ) || self.detect_reset(previous)
608    }
609
610    fn all_buckets(&self) -> Option<Vec<Bucket>> {
611        Some(assemble_bucket_sides(
612            self.side_buckets(false)?,
613            self.zero_threshold,
614            self.zero_count,
615            self.side_buckets(true)?,
616        ))
617    }
618
619    fn side_buckets(&self, positive: bool) -> Option<Vec<Bucket>> {
620        let (spans, counts) = if positive {
621            (&self.positive_spans, &self.positive_buckets)
622        } else {
623            (&self.negative_spans, &self.negative_buckets)
624        };
625
626        build_side_buckets(
627            spans.iter().map(|span| (span.offset, span.length)),
628            counts,
629            self.schema,
630            &self.custom_values,
631            positive,
632        )
633    }
634
635    /// Estimates the value at quantile `q`.
636    ///
637    /// Returns negative or positive infinity outside `[0, 1]`, and `NaN` when
638    /// the quantile cannot be estimated.
639    pub fn quantile(&self, q: f64) -> f64 {
640        self.quantile_with_info(q).0
641    }
642
643    /// Estimates the value at quantile `q` and reports the effect of NaN observations.
644    pub fn quantile_with_info(&self, q: f64) -> (f64, Option<NativeHistogramQuantileInfo>) {
645        quantile_from_parts(
646            q,
647            self.schema,
648            self.count,
649            self.sum,
650            self.negative_buckets.is_empty(),
651            self.positive_buckets.is_empty(),
652            || self.all_buckets(),
653        )
654    }
655
656    /// Estimates the fraction of observations between `lower` and `upper`.
657    pub fn fraction(&self, lower: f64, upper: f64) -> f64 {
658        self.fraction_with_info(lower, upper).0
659    }
660
661    /// Estimates a fraction and reports whether NaN observations were excluded.
662    pub fn fraction_with_info(&self, lower: f64, upper: f64) -> (f64, bool) {
663        if self.count == 0.0 || lower.is_nan() || upper.is_nan() {
664            return (f64::NAN, false);
665        }
666        if lower >= upper {
667            return (0.0, false);
668        }
669
670        let Some(mut buckets) = self.all_buckets() else {
671            return (f64::NAN, false);
672        };
673        let count = if self.sum.is_nan() {
674            buckets.iter().map(|bucket| bucket.count).sum()
675        } else {
676            self.count
677        };
678
679        let mut rank = 0.0;
680        let mut lower_rank = 0.0;
681        let mut upper_rank = 0.0;
682        let mut lower_set = false;
683        let mut upper_set = false;
684
685        for bucket in &mut buckets {
686            let zero_bucket = bucket.lower <= 0.0 && bucket.upper >= 0.0;
687            if zero_bucket {
688                if self.negative_buckets.is_empty() && !self.positive_buckets.is_empty() {
689                    bucket.lower = 0.0;
690                } else if self.positive_buckets.is_empty() && !self.negative_buckets.is_empty() {
691                    bucket.upper = 0.0;
692                }
693            }
694
695            if !lower_set && bucket.lower >= lower {
696                lower_rank = rank;
697                lower_set = true;
698            }
699            if !upper_set && bucket.lower >= upper {
700                upper_rank = rank;
701                upper_set = true;
702            }
703            if lower_set && upper_set {
704                break;
705            }
706            if !lower_set && bucket.lower < lower && bucket.upper > lower {
707                lower_rank = self.interpolate_rank(bucket, rank, lower, zero_bucket);
708                lower_set = true;
709            }
710            if !upper_set && bucket.lower < upper && bucket.upper > upper {
711                upper_rank = self.interpolate_rank(bucket, rank, upper, zero_bucket);
712                upper_set = true;
713            }
714            if lower_set && upper_set {
715                break;
716            }
717            rank += bucket.count;
718        }
719
720        if !lower_set || lower_rank > count {
721            lower_rank = count;
722        }
723        if !upper_set || upper_rank > count {
724            upper_rank = count;
725        }
726
727        (
728            (upper_rank - lower_rank) / self.count,
729            self.sum.is_nan() && count < self.count,
730        )
731    }
732
733    /// Converts populated buckets to `(boundary rule, lower, upper, count)` strings.
734    pub fn to_prometheus_buckets(&self) -> Option<Vec<(u8, String, String, String)>> {
735        Some(
736            self.all_buckets()?
737                .into_iter()
738                .filter(|bucket| bucket.count != 0.0)
739                .map(|bucket| {
740                    (
741                        bucket.boundary_rule as u8,
742                        format_prometheus_float(bucket.lower),
743                        format_prometheus_float(bucket.upper),
744                        format_prometheus_float(bucket.count),
745                    )
746                })
747                .collect(),
748        )
749    }
750
751    fn interpolate_rank(&self, bucket: &Bucket, rank: f64, value: f64, zero_bucket: bool) -> f64 {
752        if self.uses_custom_buckets() || zero_bucket {
753            if bucket.lower == f64::NEG_INFINITY {
754                return bucket.count;
755            }
756            return rank + bucket.count * (value - bucket.lower) / (bucket.upper - bucket.lower);
757        }
758
759        let log_lower = bucket.lower.abs().log2();
760        let log_upper = bucket.upper.abs().log2();
761        let log_value = value.abs().log2();
762        let fraction = if value > 0.0 {
763            (log_value - log_lower) / (log_upper - log_lower)
764        } else {
765            1.0 - ((log_value - log_upper) / (log_lower - log_upper))
766        };
767        rank + bucket.count * fraction
768    }
769
770    fn bucket_midpoint(&self, bucket: &Bucket) -> f64 {
771        if self.uses_custom_buckets() {
772            return (bucket.lower + bucket.upper) / 2.0;
773        }
774        if bucket.lower <= 0.0 && bucket.upper >= 0.0 {
775            return 0.0;
776        }
777        if bucket.upper < 0.0 {
778            -((bucket.lower.abs() * bucket.upper.abs()).sqrt())
779        } else {
780            (bucket.lower * bucket.upper).sqrt()
781        }
782    }
783
784    fn side_has_reset(&self, positive: bool, previous: &Self) -> bool {
785        let (current_spans, current_buckets, previous_spans, previous_buckets) = if positive {
786            (
787                &self.positive_spans,
788                &self.positive_buckets,
789                &previous.positive_spans,
790                &previous.positive_buckets,
791            )
792        } else {
793            (
794                &self.negative_spans,
795                &self.negative_buckets,
796                &previous.negative_spans,
797                &previous.negative_buckets,
798            )
799        };
800        let Some(current) = side_counts(current_spans, current_buckets) else {
801            return true;
802        };
803        let Some(previous) = side_counts(previous_spans, previous_buckets) else {
804            return true;
805        };
806        previous.keys().chain(current.keys()).any(|idx| {
807            current.get(idx).copied().unwrap_or_default()
808                < previous.get(idx).copied().unwrap_or_default()
809        })
810    }
811
812    fn reconcile(&self, other: &Self) -> Option<(Self, Self)> {
813        match (self.uses_custom_buckets(), other.uses_custom_buckets()) {
814            (true, true) => reconcile_custom(self, other),
815            (false, false) => reconcile_exponential(self, other),
816            _ => None,
817        }
818    }
819}
820
821/// Whether a pair of start timestamps witnesses a counter reset, as Prometheus
822/// `isStartTimestampReset` decides it. A start timestamp of `0` means none was stated.
823pub fn is_start_timestamp_reset(
824    previous_start: i64,
825    previous_ts: i64,
826    current_start: i64,
827    current_ts: i64,
828) -> bool {
829    // An unchanged start never restarted, even when it is later than the previous sample.
830    if previous_start == current_start
831        || current_start == 0
832        || current_start >= current_ts
833        || current_start < previous_ts
834    {
835        return false;
836    }
837    if current_start > previous_ts {
838        return true;
839    }
840
841    // The current start points at the previous sample: a reset for a delta series, but not for
842    // a cumulative one whose start is unknown, which is what an unset or invalid previous start
843    // (later than its own sample) says.
844    previous_start <= previous_ts && previous_start != 0 && previous_start != previous_ts
845}
846
847fn reconcile_exponential(
848    left: &NativeHistogram,
849    right: &NativeHistogram,
850) -> Option<(NativeHistogram, NativeHistogram)> {
851    let schema = left.schema.min(right.schema);
852    let mut left = left.copy_to_schema(schema)?;
853    let mut right = right.copy_to_schema(schema)?;
854    let mut zero_threshold = left.zero_threshold.max(right.zero_threshold);
855    loop {
856        let expanded = left
857            .expanded_zero_threshold(zero_threshold)?
858            .max(right.expanded_zero_threshold(zero_threshold)?);
859        if expanded == zero_threshold {
860            break;
861        }
862        zero_threshold = expanded;
863    }
864    left.grow_zero_threshold(zero_threshold)?;
865    right.grow_zero_threshold(zero_threshold)?;
866    Some((left.compact()?, right.compact()?))
867}
868
869fn reconcile_custom(
870    left: &NativeHistogram,
871    right: &NativeHistogram,
872) -> Option<(NativeHistogram, NativeHistogram)> {
873    let custom_values = if left.custom_values == right.custom_values {
874        left.custom_values.clone()
875    } else {
876        left.custom_values
877            .iter()
878            .copied()
879            .filter(|value| right.custom_values.contains(value))
880            .collect()
881    };
882
883    Some((
884        left.copy_to_custom_values(custom_values.clone())?
885            .compact()?,
886        right.copy_to_custom_values(custom_values)?.compact()?,
887    ))
888}
889
890impl NativeHistogram {
891    fn copy_to_schema(&self, target_schema: i32) -> Option<Self> {
892        if self.uses_custom_buckets()
893            || !(MIN_EXPONENTIAL_SCHEMA..=MAX_EXPONENTIAL_SCHEMA).contains(&target_schema)
894            || target_schema > self.schema
895        {
896            return None;
897        }
898        if target_schema == self.schema {
899            return Some(self.clone());
900        }
901
902        let mut result = self.clone();
903        result.schema = target_schema;
904        (result.positive_spans, result.positive_buckets) = reduce_side(
905            &self.positive_spans,
906            &self.positive_buckets,
907            self.schema,
908            target_schema,
909        )?;
910        (result.negative_spans, result.negative_buckets) = reduce_side(
911            &self.negative_spans,
912            &self.negative_buckets,
913            self.schema,
914            target_schema,
915        )?;
916        Some(result)
917    }
918
919    fn copy_to_custom_values(&self, custom_values: Vec<f64>) -> Option<Self> {
920        if !self.uses_custom_buckets() {
921            return None;
922        }
923        if self.custom_values == custom_values {
924            return Some(self.clone());
925        }
926
927        let mut result = self.clone();
928        result.custom_values = custom_values.clone();
929        result.negative_spans.clear();
930        result.negative_buckets.clear();
931        (result.positive_spans, result.positive_buckets) = map_custom_side(
932            &self.positive_spans,
933            &self.positive_buckets,
934            &self.custom_values,
935            &custom_values,
936        )?;
937        Some(result)
938    }
939
940    fn grow_zero_threshold(&mut self, zero_threshold: f64) -> Option<()> {
941        if self.uses_custom_buckets() || zero_threshold == self.zero_threshold {
942            self.zero_threshold = zero_threshold;
943            return Some(());
944        }
945
946        let (spans, buckets, zero_count) = fold_zero_side(
947            &self.positive_spans,
948            &self.positive_buckets,
949            self.schema,
950            zero_threshold,
951        )?;
952        self.positive_spans = spans;
953        self.positive_buckets = buckets;
954        self.zero_count += zero_count;
955
956        let (spans, buckets, zero_count) = fold_zero_side(
957            &self.negative_spans,
958            &self.negative_buckets,
959            self.schema,
960            zero_threshold,
961        )?;
962        self.negative_spans = spans;
963        self.negative_buckets = buckets;
964        self.zero_count += zero_count;
965        self.zero_threshold = zero_threshold;
966        Some(())
967    }
968
969    fn expanded_zero_threshold(&self, mut zero_threshold: f64) -> Option<f64> {
970        if self.uses_custom_buckets() {
971            return Some(zero_threshold);
972        }
973        zero_threshold = expand_zero_threshold_side(
974            &self.positive_spans,
975            &self.positive_buckets,
976            self.schema,
977            zero_threshold,
978        )?;
979        expand_zero_threshold_side(
980            &self.negative_spans,
981            &self.negative_buckets,
982            self.schema,
983            zero_threshold,
984        )
985    }
986}
987
988fn add_reset_hint(left: CounterResetHint, right: CounterResetHint) -> CounterResetHint {
989    if left == CounterResetHint::Gauge || right == CounterResetHint::Gauge {
990        CounterResetHint::Gauge
991    } else if left == right {
992        left
993    } else {
994        CounterResetHint::Unknown
995    }
996}
997
998/// Estimates a quantile from histogram metadata and a lazily materialized bucket sequence.
999///
1000/// This is the estimator [`NativeHistogram::quantile_with_info`] and [`quantile_histogram_view`]
1001/// expose, so it stays for callers of this crate. The PromQL `histogram_quantile` does not use it:
1002/// that function reads the same histogram through the native kernel in the `promql` crate, which
1003/// walks the buckets the way Prometheus does -- from the highest bucket down for a quantile above
1004/// the median -- so one histogram has one answer instead of two that differ in their last places.
1005/// The exponential boundary below interpolates with `2^x`, which likewise stays only for this
1006/// estimator; the kernel interpolates with `exp2` over Prometheus's bound table.
1007fn quantile_from_parts(
1008    q: f64,
1009    schema: i32,
1010    count_total: f64,
1011    sum: f64,
1012    negative_empty: bool,
1013    positive_empty: bool,
1014    buckets: impl FnOnce() -> Option<Vec<Bucket>>,
1015) -> (f64, Option<NativeHistogramQuantileInfo>) {
1016    if q < 0.0 {
1017        return (f64::NEG_INFINITY, None);
1018    }
1019    if q > 1.0 {
1020        return (f64::INFINITY, None);
1021    }
1022    if count_total == 0.0 || q.is_nan() {
1023        return (f64::NAN, None);
1024    }
1025    let Some(mut buckets) = buckets() else {
1026        return (f64::NAN, None);
1027    };
1028    let bucket_total = buckets.iter().map(|bucket| bucket.count).sum::<f64>();
1029    let has_nan_observations = sum.is_nan() && bucket_total < count_total;
1030    let info = has_nan_observations.then_some(NativeHistogramQuantileInfo::NaNSkew);
1031    let rank = q * count_total;
1032    let mut count = 0.0;
1033    for bucket in &mut buckets {
1034        if bucket.count == 0.0 {
1035            continue;
1036        }
1037        count += bucket.count;
1038        if count < rank {
1039            continue;
1040        }
1041        if schema != CUSTOM_BUCKETS_SCHEMA && bucket.lower < 0.0 && bucket.upper > 0.0 {
1042            if negative_empty && !positive_empty {
1043                bucket.lower = 0.0;
1044            } else if positive_empty && !negative_empty {
1045                bucket.upper = 0.0;
1046            }
1047        } else if schema == CUSTOM_BUCKETS_SCHEMA {
1048            if bucket.lower == f64::NEG_INFINITY {
1049                if bucket.upper <= 0.0 {
1050                    return (bucket.upper, info);
1051                }
1052                bucket.lower = 0.0;
1053            } else if bucket.upper == f64::INFINITY {
1054                return (bucket.lower, info);
1055            }
1056        }
1057        let rank_in_bucket = rank - (count - bucket.count);
1058        let fraction = rank_in_bucket / bucket.count;
1059        if schema == CUSTOM_BUCKETS_SCHEMA || (bucket.lower <= 0.0 && bucket.upper >= 0.0) {
1060            return (
1061                bucket.lower + (bucket.upper - bucket.lower) * fraction,
1062                info,
1063            );
1064        }
1065        let log_lower = bucket.lower.abs().log2();
1066        let log_upper = bucket.upper.abs().log2();
1067        if bucket.lower > 0.0 {
1068            return (
1069                2.0_f64.powf(log_lower + (log_upper - log_lower) * fraction),
1070                info,
1071            );
1072        }
1073        return (
1074            -2.0_f64.powf(log_upper + (log_lower - log_upper) * (1.0 - fraction)),
1075            info,
1076        );
1077    }
1078    let info = if sum.is_nan() && count < count_total {
1079        Some(if count < rank {
1080            NativeHistogramQuantileInfo::NaNResult
1081        } else {
1082            NativeHistogramQuantileInfo::NaNSkew
1083        })
1084    } else {
1085        None
1086    };
1087    (f64::NAN, info)
1088}
1089
1090/// Quantile entrypoint operating directly on the columnar borrowed view.
1091pub fn quantile_histogram_view(
1092    view: &HistogramView<'_>,
1093    q: f64,
1094) -> (f64, Option<NativeHistogramQuantileInfo>) {
1095    quantile_from_parts(
1096        q,
1097        view.schema,
1098        view.count,
1099        view.sum,
1100        view.negative.buckets.is_empty(),
1101        view.positive.buckets.is_empty(),
1102        || {
1103            Some(assemble_bucket_sides(
1104                build_view_side(view.negative, view.schema, view.custom_values, false)?,
1105                view.zero_threshold,
1106                view.zero_count,
1107                build_view_side(view.positive, view.schema, view.custom_values, true)?,
1108            ))
1109        },
1110    )
1111}
1112
1113fn assemble_bucket_sides(
1114    mut negative: Vec<Bucket>,
1115    zero_threshold: f64,
1116    zero_count: f64,
1117    positive: Vec<Bucket>,
1118) -> Vec<Bucket> {
1119    negative.reverse();
1120    if zero_count != 0.0 {
1121        negative.push(Bucket {
1122            lower: -zero_threshold,
1123            upper: zero_threshold,
1124            count: zero_count,
1125            boundary_rule: BoundaryRule::ClosedBoth,
1126        });
1127    }
1128    negative.extend(positive);
1129    negative
1130}
1131
1132fn build_view_side(
1133    side: BucketSideView<'_>,
1134    schema: i32,
1135    custom_values: &[f64],
1136    positive: bool,
1137) -> Option<Vec<Bucket>> {
1138    if side.span_offsets.len() != side.span_lengths.len() {
1139        return None;
1140    }
1141    let mut total = 0usize;
1142    for (span_index, (&offset, &length)) in
1143        side.span_offsets.iter().zip(side.span_lengths).enumerate()
1144    {
1145        if length < 0 || (span_index > 0 && offset < 0) {
1146            return None;
1147        }
1148        total = total.checked_add(length as usize)?;
1149    }
1150    if total != side.buckets.len() {
1151        return None;
1152    }
1153    build_side_buckets(
1154        side.span_offsets
1155            .iter()
1156            .copied()
1157            .zip(side.span_lengths.iter().copied()),
1158        side.buckets,
1159        schema,
1160        custom_values,
1161        positive,
1162    )
1163}
1164
1165fn build_side_buckets(
1166    spans: impl Iterator<Item = (i32, i32)>,
1167    counts: &[f64],
1168    schema: i32,
1169    custom_values: &[f64],
1170    positive: bool,
1171) -> Option<Vec<Bucket>> {
1172    let indices = bucket_indices(spans)?;
1173    let mut result = Vec::with_capacity(counts.len());
1174    for (idx, count) in indices.into_iter().zip(counts) {
1175        let upper = get_bound(idx, schema, custom_values)?;
1176        let lower = get_bound(idx.checked_sub(1)?, schema, custom_values)?;
1177        result.push(if positive {
1178            Bucket {
1179                lower,
1180                upper,
1181                count: *count,
1182                boundary_rule: if schema == CUSTOM_BUCKETS_SCHEMA && idx == 0 {
1183                    BoundaryRule::ClosedBoth
1184                } else {
1185                    BoundaryRule::OpenLeft
1186                },
1187            }
1188        } else {
1189            Bucket {
1190                lower: -upper,
1191                upper: -lower,
1192                count: *count,
1193                boundary_rule: BoundaryRule::OpenRight,
1194            }
1195        });
1196    }
1197    Some(result)
1198}
1199
1200fn bucket_indices(spans: impl Iterator<Item = (i32, i32)>) -> Option<Vec<i32>> {
1201    let mut indices = Vec::new();
1202    let mut current_index = 0i32;
1203    let mut first = true;
1204    for (span_index, (offset, length)) in spans.enumerate() {
1205        if span_index > 0 && offset < 0 {
1206            return None;
1207        }
1208        if first {
1209            current_index = offset;
1210            first = false;
1211        } else {
1212            current_index = current_index.checked_add(offset)?;
1213        }
1214        for _ in 0..length {
1215            indices.push(current_index);
1216            current_index = current_index.checked_add(1)?;
1217        }
1218    }
1219    Some(indices)
1220}
1221
1222fn side_bucket_indices(spans: &[Span]) -> Option<Vec<i32>> {
1223    bucket_indices(spans.iter().map(|span| (span.offset, span.length)))
1224}
1225
1226fn span_bucket_len(spans: &[Span]) -> Option<usize> {
1227    spans
1228        .iter()
1229        .try_fold(0usize, |sum, span| sum.checked_add(span.length as usize))
1230}
1231
1232fn spans_from_indices_counts(values: Vec<(i32, f64)>) -> Option<(Vec<Span>, Vec<f64>)> {
1233    let mut spans = Vec::<Span>::new();
1234    let mut buckets = Vec::new();
1235    let mut previous_index = None::<i32>;
1236
1237    for (idx, count) in values {
1238        if count == 0.0 {
1239            continue;
1240        }
1241        match (spans.last_mut(), previous_index) {
1242            (Some(span), Some(previous)) if previous.checked_add(1) == Some(idx) => {
1243                span.length = span.length.checked_add(1)?;
1244            }
1245            (_, Some(previous)) => {
1246                spans.push(Span {
1247                    offset: idx.checked_sub(previous)?.checked_sub(1)?,
1248                    length: 1,
1249                });
1250            }
1251            (_, None) => {
1252                spans.push(Span {
1253                    offset: idx,
1254                    length: 1,
1255                });
1256            }
1257        }
1258        buckets.push(count);
1259        previous_index = Some(idx);
1260    }
1261
1262    Some((spans, buckets))
1263}
1264
1265fn side_counts(spans: &[Span], buckets: &[f64]) -> Option<BTreeMap<i32, f64>> {
1266    let mut values = BTreeMap::new();
1267    for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(buckets) {
1268        if *count != 0.0 {
1269            values.insert(idx, *count);
1270        }
1271    }
1272    Some(values)
1273}
1274
1275fn side_layout_equal(
1276    left_spans: &[Span],
1277    left_buckets: &[f64],
1278    right_spans: &[Span],
1279    right_buckets: &[f64],
1280) -> bool {
1281    if span_bucket_len(left_spans) != Some(left_buckets.len())
1282        || span_bucket_len(right_spans) != Some(right_buckets.len())
1283    {
1284        return false;
1285    }
1286    let Some(left_indices) = side_bucket_indices(left_spans) else {
1287        return false;
1288    };
1289    let Some(right_indices) = side_bucket_indices(right_spans) else {
1290        return false;
1291    };
1292    left_indices == right_indices
1293        && left_buckets
1294            .iter()
1295            .zip(right_buckets)
1296            .all(|(left, right)| left.to_bits() == right.to_bits())
1297}
1298
1299fn merge_side(
1300    left_spans: &[Span],
1301    left_buckets: &[f64],
1302    right_spans: &[Span],
1303    right_buckets: &[f64],
1304    op: impl Fn(f64, f64) -> f64,
1305) -> Option<(Vec<Span>, Vec<f64>)> {
1306    let left = side_counts(left_spans, left_buckets)?;
1307    let right = side_counts(right_spans, right_buckets)?;
1308    let mut values = BTreeMap::new();
1309    for idx in left.keys().chain(right.keys()) {
1310        values.insert(
1311            *idx,
1312            op(
1313                left.get(idx).copied().unwrap_or_default(),
1314                right.get(idx).copied().unwrap_or_default(),
1315            ),
1316        );
1317    }
1318    spans_from_indices_counts(values.into_iter().collect())
1319}
1320
1321fn reduce_side(
1322    spans: &[Span],
1323    buckets: &[f64],
1324    schema: i32,
1325    target_schema: i32,
1326) -> Option<(Vec<Span>, Vec<f64>)> {
1327    let factor = 1_i32.checked_shl((schema - target_schema) as u32)?;
1328    let mut values = std::collections::BTreeMap::<i32, f64>::new();
1329    for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(buckets) {
1330        let target_idx = ceil_div(idx, factor);
1331        *values.entry(target_idx).or_default() += *count;
1332    }
1333    spans_from_indices_counts(values.into_iter().collect())
1334}
1335
1336fn compact_side(spans: &[Span], buckets: &[f64]) -> Option<(Vec<Span>, Vec<f64>)> {
1337    let indices = side_bucket_indices(spans)?;
1338    spans_from_indices_counts(indices.into_iter().zip(buckets.iter().copied()).collect())
1339}
1340
1341fn map_custom_side(
1342    spans: &[Span],
1343    buckets: &[f64],
1344    old_values: &[f64],
1345    new_values: &[f64],
1346) -> Option<(Vec<Span>, Vec<f64>)> {
1347    let mut values = std::collections::BTreeMap::<i32, f64>::new();
1348    for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(buckets) {
1349        let upper = get_bound(idx, CUSTOM_BUCKETS_SCHEMA, old_values)?;
1350        let target_idx = new_values
1351            .iter()
1352            .position(|value| *value >= upper)
1353            .unwrap_or(new_values.len()) as i32;
1354        *values.entry(target_idx).or_default() += *count;
1355    }
1356    spans_from_indices_counts(values.into_iter().collect())
1357}
1358
1359fn fold_zero_side(
1360    spans: &[Span],
1361    buckets: &[f64],
1362    schema: i32,
1363    zero_threshold: f64,
1364) -> Option<(Vec<Span>, Vec<f64>, f64)> {
1365    let mut kept = Vec::new();
1366    let mut zero_count = 0.0;
1367    for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(buckets) {
1368        if get_bound(idx, schema, &[])? <= zero_threshold {
1369            zero_count += *count;
1370        } else {
1371            kept.push((idx, *count));
1372        }
1373    }
1374    let (spans, buckets) = spans_from_indices_counts(kept)?;
1375    Some((spans, buckets, zero_count))
1376}
1377
1378fn expand_zero_threshold_side(
1379    spans: &[Span],
1380    buckets: &[f64],
1381    schema: i32,
1382    mut zero_threshold: f64,
1383) -> Option<f64> {
1384    for (idx, count) in side_bucket_indices(spans)?.into_iter().zip(buckets) {
1385        if *count == 0.0 {
1386            continue;
1387        }
1388        let lower = get_bound(idx.checked_sub(1)?, schema, &[])?;
1389        let upper = get_bound(idx, schema, &[])?;
1390        if lower < zero_threshold && zero_threshold < upper {
1391            zero_threshold = upper;
1392        }
1393    }
1394    Some(zero_threshold)
1395}
1396
1397fn ceil_div(value: i32, divisor: i32) -> i32 {
1398    value.div_euclid(divisor) + i32::from(value.rem_euclid(divisor) != 0)
1399}
1400
1401/// Returns the index of the exponential bucket containing positive infinity.
1402pub fn exponential_overflow_bucket_index(schema: i32) -> Option<i32> {
1403    if !(MIN_EXPONENTIAL_SCHEMA..=MAX_EXPONENTIAL_SCHEMA).contains(&schema) {
1404        return None;
1405    }
1406    let last_finite = if schema >= 0 {
1407        1024_i64.checked_shl(schema as u32)?
1408    } else {
1409        1024_i64.checked_shr((-schema) as u32)?
1410    };
1411    i32::try_from(last_finite.checked_add(1)?).ok()
1412}
1413
1414/// The bound of bucket `idx`: a custom bound, an infinity sentinel, or `2^(idx / 2^schema)`.
1415///
1416/// The exponential case computes its bound instead of reading one, while Prometheus reads
1417/// `ExponentialBounds`: those entries are not all correctly rounded, because a bound becomes a zero
1418/// threshold that is compared exactly, and a computed one would not compare as the sender's did.
1419/// So the computed bound here agrees with the table the native histogram kernel uses only to within
1420/// an ulp. This function keeps serving the renderers and the estimators of this crate's public
1421/// `NativeHistogram` API (`promql_string`, `estimated_stdvar`, the legacy quantile above, the
1422/// zero-threshold reconciliation in `add`); the PromQL estimators read the kernel's `bound`.
1423fn get_bound(idx: i32, schema: i32, custom_values: &[f64]) -> Option<f64> {
1424    if schema == CUSTOM_BUCKETS_SCHEMA {
1425        return match idx {
1426            -1 => Some(f64::NEG_INFINITY),
1427            idx if idx == custom_values.len() as i32 => Some(f64::INFINITY),
1428            idx if idx >= 0 && (idx as usize) < custom_values.len() => {
1429                Some(custom_values[idx as usize])
1430            }
1431            _ => None,
1432        };
1433    }
1434
1435    let overflow_index = exponential_overflow_bucket_index(schema)?;
1436    if idx > overflow_index {
1437        return None;
1438    }
1439    if idx == overflow_index {
1440        return Some(f64::INFINITY);
1441    }
1442    if idx == overflow_index - 1 {
1443        return Some(f64::MAX);
1444    }
1445    if schema < 0 {
1446        let exponent = i64::from(idx).checked_shl((-schema) as u32)?;
1447        let Ok(exponent) = i32::try_from(exponent) else {
1448            return Some(0.0);
1449        };
1450        return Some(2.0_f64.powi(exponent));
1451    }
1452    let exponent = idx as f64 / (1u32 << schema) as f64;
1453    Some(2.0_f64.powf(exponent))
1454}
1455
1456/// Returns the Arrow type for a complete native histogram value.
1457pub fn native_histogram_arrow_type() -> ArrowDataType {
1458    native_histogram_value_type().as_arrow_type()
1459}
1460
1461fn struct_child<'a>(array: &'a StructArray, name: &str) -> DfResult<&'a ArrayRef> {
1462    let index = array
1463        .fields()
1464        .iter()
1465        .position(|field| field.name() == name)
1466        .ok_or_else(|| {
1467            DataFusionError::Execution(format!("native histogram missing field {name}"))
1468        })?;
1469    Ok(array.column(index))
1470}
1471
1472fn primitive_child<'a, T>(array: &'a StructArray, name: &str) -> DfResult<&'a PrimitiveArray<T>>
1473where
1474    T: ArrowPrimitiveType,
1475{
1476    let child = struct_child(array, name)?;
1477    child
1478        .as_any()
1479        .downcast_ref::<PrimitiveArray<T>>()
1480        .ok_or_else(|| {
1481            DataFusionError::Execution(format!(
1482                "native histogram field {name} has invalid type {}",
1483                child.data_type()
1484            ))
1485        })
1486}
1487
1488fn list_child<'a>(array: &'a StructArray, name: &str) -> DfResult<&'a ListArray> {
1489    let child = struct_child(array, name)?;
1490    child.as_any().downcast_ref::<ListArray>().ok_or_else(|| {
1491        DataFusionError::Execution(format!(
1492            "native histogram field {name} has invalid type {}",
1493            child.data_type()
1494        ))
1495    })
1496}
1497
1498fn required_primitive<T>(array: &StructArray, name: &str, row: usize) -> DfResult<T::Native>
1499where
1500    T: ArrowPrimitiveType,
1501{
1502    let values = primitive_child::<T>(array, name)?;
1503    if values.is_null(row) {
1504        return Err(DataFusionError::Execution(format!(
1505            "native histogram field {name} is null"
1506        )));
1507    }
1508    Ok(values.value(row))
1509}
1510
1511fn optional_primitive<T>(array: &StructArray, name: &str, row: usize) -> DfResult<Option<T::Native>>
1512where
1513    T: ArrowPrimitiveType,
1514{
1515    let values = primitive_child::<T>(array, name)?;
1516    Ok((!values.is_null(row)).then(|| values.value(row)))
1517}
1518
1519fn borrowed_list<'a, T>(
1520    list: &'a ListArray,
1521    values: &'a PrimitiveArray<T>,
1522    row: usize,
1523    name: &str,
1524) -> DfResult<&'a [T::Native]>
1525where
1526    T: ArrowPrimitiveType,
1527{
1528    if list.is_null(row) {
1529        return Ok(&[]);
1530    }
1531    let offsets = list.value_offsets();
1532    let start = offsets[row] as usize;
1533    let end = offsets[row + 1] as usize;
1534    if (start..end).any(|index| values.is_null(index)) {
1535        return Err(DataFusionError::Execution(format!(
1536            "native histogram list field {name} contains null"
1537        )));
1538    }
1539    Ok(&values.values()[start..end])
1540}
1541
1542fn list_values<T>(array: &StructArray, name: &str, row: usize) -> DfResult<Vec<T::Native>>
1543where
1544    T: ArrowPrimitiveType,
1545{
1546    let list = list_child(array, name)?;
1547    if list.is_null(row) {
1548        return Ok(Vec::new());
1549    }
1550
1551    let values = list.value(row);
1552    let values = values
1553        .as_any()
1554        .downcast_ref::<PrimitiveArray<T>>()
1555        .ok_or_else(|| {
1556            DataFusionError::Execution(format!(
1557                "native histogram list field {name} has invalid value type {}",
1558                values.data_type()
1559            ))
1560        })?;
1561
1562    values
1563        .iter()
1564        .map(|value| {
1565            value.ok_or_else(|| {
1566                DataFusionError::Execution(format!(
1567                    "native histogram list field {name} contains null"
1568                ))
1569            })
1570        })
1571        .collect()
1572}
1573
1574fn read_spans(offsets: Vec<i32>, lengths: Vec<i32>, name: &str) -> DfResult<Vec<Span>> {
1575    if offsets.len() != lengths.len() {
1576        return Err(DataFusionError::Execution(format!(
1577            "native histogram {name} span offsets and lengths mismatch: {} vs {}",
1578            offsets.len(),
1579            lengths.len()
1580        )));
1581    }
1582    offsets
1583        .into_iter()
1584        .zip(lengths)
1585        .map(|(offset, length)| {
1586            if length < 0 {
1587                return Err(DataFusionError::Execution(format!(
1588                    "native histogram {name} span has negative length {length}"
1589                )));
1590            }
1591            Ok(Span { offset, length })
1592        })
1593        .collect()
1594}
1595
1596fn check_span_bucket_count(spans: &[Span], buckets: usize, name: &str) -> DfResult<()> {
1597    let span_len = span_bucket_len(spans).ok_or_else(|| {
1598        DataFusionError::Execution(format!("native histogram {name} spans overflow"))
1599    })?;
1600    if span_len != buckets {
1601        return Err(DataFusionError::Execution(format!(
1602            "native histogram {name} spans describe {span_len} buckets, found {buckets}"
1603        )));
1604    }
1605    Ok(())
1606}
1607
1608/// Converts persisted native histograms directly into canonical columnar samples.
1609///
1610/// Bucket and custom-bound values are borrowed from Arrow until copied by the batch builder.
1611pub fn histogram_samples_from_arrow(array: &StructArray) -> DfResult<Samples> {
1612    let schema = primitive_child::<Int32Type>(array, SCHEMA_FIELD)?;
1613    let threshold = primitive_child::<Float64Type>(array, ZERO_THRESHOLD_FIELD)?;
1614    let sum = primitive_child::<Float64Type>(array, SUM_FIELD)?;
1615    let hint = primitive_child::<Int32Type>(array, RESET_HINT_FIELD)?;
1616    let start = primitive_child::<TimestampMillisecondType>(array, START_TIMESTAMP_FIELD)?;
1617    let custom_list = list_child(array, CUSTOM_VALUES_FIELD)?;
1618    let custom_values = list_primitive::<Float64Type>(custom_list, CUSTOM_VALUES_FIELD)?;
1619    let positive_offsets_list = list_child(array, POSITIVE_SPAN_OFFSETS_FIELD)?;
1620    let positive_offsets =
1621        list_primitive::<Int32Type>(positive_offsets_list, POSITIVE_SPAN_OFFSETS_FIELD)?;
1622    let positive_lengths_list = list_child(array, POSITIVE_SPAN_LENGTHS_FIELD)?;
1623    let positive_lengths =
1624        list_primitive::<Int32Type>(positive_lengths_list, POSITIVE_SPAN_LENGTHS_FIELD)?;
1625    let negative_offsets_list = list_child(array, NEGATIVE_SPAN_OFFSETS_FIELD)?;
1626    let negative_offsets =
1627        list_primitive::<Int32Type>(negative_offsets_list, NEGATIVE_SPAN_OFFSETS_FIELD)?;
1628    let negative_lengths_list = list_child(array, NEGATIVE_SPAN_LENGTHS_FIELD)?;
1629    let negative_lengths =
1630        list_primitive::<Int32Type>(negative_lengths_list, NEGATIVE_SPAN_LENGTHS_FIELD)?;
1631    let count_f = primitive_child::<Float64Type>(array, COUNT_F64_FIELD)?;
1632    let zero_f = primitive_child::<Float64Type>(array, ZERO_COUNT_F64_FIELD)?;
1633    let positive_f_list = list_child(array, POSITIVE_BUCKETS_F64_FIELD)?;
1634    let positive_f = list_primitive::<Float64Type>(positive_f_list, POSITIVE_BUCKETS_F64_FIELD)?;
1635    let negative_f_list = list_child(array, NEGATIVE_BUCKETS_F64_FIELD)?;
1636    let negative_f = list_primitive::<Float64Type>(negative_f_list, NEGATIVE_BUCKETS_F64_FIELD)?;
1637    let count_i = primitive_child::<Int64Type>(array, COUNT_I64_FIELD)?;
1638    let zero_i = primitive_child::<Int64Type>(array, ZERO_COUNT_I64_FIELD)?;
1639    let positive_i_list = list_child(array, POSITIVE_BUCKETS_I64_FIELD)?;
1640    let positive_i = list_primitive::<Int64Type>(positive_i_list, POSITIVE_BUCKETS_I64_FIELD)?;
1641    let negative_i_list = list_child(array, NEGATIVE_BUCKETS_I64_FIELD)?;
1642    let negative_i = list_primitive::<Int64Type>(negative_i_list, NEGATIVE_BUCKETS_I64_FIELD)?;
1643
1644    let mut builder = HistogramBatchBuilder::new();
1645    let mut indices = Vec::with_capacity(array.len());
1646    for row in 0..array.len() {
1647        if array.is_null(row) {
1648            indices.push(None);
1649            continue;
1650        }
1651        let required = |values: &dyn Array, name: &str| -> DfResult<()> {
1652            if values.is_null(row) {
1653                Err(DataFusionError::Execution(format!(
1654                    "native histogram field {name} is null"
1655                )))
1656            } else {
1657                Ok(())
1658            }
1659        };
1660        required(schema, SCHEMA_FIELD)?;
1661        required(threshold, ZERO_THRESHOLD_FIELD)?;
1662        required(sum, SUM_FIELD)?;
1663        required(hint, RESET_HINT_FIELD)?;
1664        let positive_offsets = borrowed_list(
1665            positive_offsets_list,
1666            positive_offsets,
1667            row,
1668            POSITIVE_SPAN_OFFSETS_FIELD,
1669        )?;
1670        let positive_lengths = borrowed_list(
1671            positive_lengths_list,
1672            positive_lengths,
1673            row,
1674            POSITIVE_SPAN_LENGTHS_FIELD,
1675        )?;
1676        let negative_offsets = borrowed_list(
1677            negative_offsets_list,
1678            negative_offsets,
1679            row,
1680            NEGATIVE_SPAN_OFFSETS_FIELD,
1681        )?;
1682        let negative_lengths = borrowed_list(
1683            negative_lengths_list,
1684            negative_lengths,
1685            row,
1686            NEGATIVE_SPAN_LENGTHS_FIELD,
1687        )?;
1688        let custom = borrowed_list(custom_list, custom_values, row, CUSTOM_VALUES_FIELD)?;
1689        let (count, zero_count, positive_buckets, negative_buckets) = if !count_f.is_null(row) {
1690            (
1691                count_f.value(row),
1692                if zero_f.is_null(row) {
1693                    0.0
1694                } else {
1695                    zero_f.value(row)
1696                },
1697                Cow::Borrowed(borrowed_list(
1698                    positive_f_list,
1699                    positive_f,
1700                    row,
1701                    POSITIVE_BUCKETS_F64_FIELD,
1702                )?),
1703                Cow::Borrowed(borrowed_list(
1704                    negative_f_list,
1705                    negative_f,
1706                    row,
1707                    NEGATIVE_BUCKETS_F64_FIELD,
1708                )?),
1709            )
1710        } else {
1711            required(count_i, COUNT_I64_FIELD)?;
1712            let p: Vec<f64> =
1713                borrowed_list(positive_i_list, positive_i, row, POSITIVE_BUCKETS_I64_FIELD)?
1714                    .iter()
1715                    .map(|v| *v as f64)
1716                    .collect();
1717            let n: Vec<f64> =
1718                borrowed_list(negative_i_list, negative_i, row, NEGATIVE_BUCKETS_I64_FIELD)?
1719                    .iter()
1720                    .map(|v| *v as f64)
1721                    .collect();
1722            (
1723                count_i.value(row) as f64,
1724                if zero_i.is_null(row) {
1725                    0.0
1726                } else {
1727                    zero_i.value(row) as f64
1728                },
1729                Cow::Owned(p),
1730                Cow::Owned(n),
1731            )
1732        };
1733        let index = builder
1734            .push(HistogramView {
1735                schema: schema.value(row),
1736                zero_threshold: threshold.value(row),
1737                sum: sum.value(row),
1738                count,
1739                zero_count,
1740                reset_hint: hint.value(row).into(),
1741                start_timestamp: (!start.is_null(row)).then(|| start.value(row)),
1742                custom_values: custom,
1743                positive: BucketSideView {
1744                    span_offsets: positive_offsets,
1745                    span_lengths: positive_lengths,
1746                    buckets: positive_buckets.as_ref(),
1747                },
1748                negative: BucketSideView {
1749                    span_offsets: negative_offsets,
1750                    span_lengths: negative_lengths,
1751                    buckets: negative_buckets.as_ref(),
1752                },
1753            })
1754            .map_err(|e| DataFusionError::External(Box::new(e)))?;
1755        indices.push(Some(index));
1756    }
1757    let batch = builder
1758        .finish()
1759        .map_err(|e| DataFusionError::External(Box::new(e)))?;
1760    Samples::try_from_histogram(UInt32Array::from(indices), batch)
1761        .map_err(|e| DataFusionError::External(Box::new(e)))
1762}
1763
1764fn list_primitive<'a, T>(list: &'a ListArray, name: &str) -> DfResult<&'a PrimitiveArray<T>>
1765where
1766    T: ArrowPrimitiveType,
1767{
1768    let values = list.values();
1769    values
1770        .as_any()
1771        .downcast_ref::<PrimitiveArray<T>>()
1772        .ok_or_else(|| {
1773            DataFusionError::Execution(format!(
1774                "native histogram list field {name} has invalid value type {}",
1775                values.data_type()
1776            ))
1777        })
1778}
1779
1780/// Decodes one native histogram row into the query-time [`NativeHistogram`] model.
1781///
1782/// A null struct returns `Ok(None)`. Integer payloads are converted to absolute
1783/// `f64` counts, and malformed child fields or span layouts return an error.
1784pub fn read_histogram(array: &StructArray, row: usize) -> DfResult<Option<NativeHistogram>> {
1785    if array.is_null(row) {
1786        return Ok(None);
1787    }
1788
1789    let schema = required_primitive::<Int32Type>(array, SCHEMA_FIELD, row)?;
1790    let positive_spans = read_spans(
1791        list_values::<Int32Type>(array, POSITIVE_SPAN_OFFSETS_FIELD, row)?,
1792        list_values::<Int32Type>(array, POSITIVE_SPAN_LENGTHS_FIELD, row)?,
1793        "positive",
1794    )?;
1795    let negative_spans = read_spans(
1796        list_values::<Int32Type>(array, NEGATIVE_SPAN_OFFSETS_FIELD, row)?,
1797        list_values::<Int32Type>(array, NEGATIVE_SPAN_LENGTHS_FIELD, row)?,
1798        "negative",
1799    )?;
1800
1801    let (count, zero_count, positive_buckets, negative_buckets) =
1802        if let Some(count) = optional_primitive::<Float64Type>(array, COUNT_F64_FIELD, row)? {
1803            (
1804                count,
1805                optional_primitive::<Float64Type>(array, ZERO_COUNT_F64_FIELD, row)?
1806                    .unwrap_or_default(),
1807                list_values::<Float64Type>(array, POSITIVE_BUCKETS_F64_FIELD, row)?,
1808                list_values::<Float64Type>(array, NEGATIVE_BUCKETS_F64_FIELD, row)?,
1809            )
1810        } else {
1811            (
1812                required_primitive::<Int64Type>(array, COUNT_I64_FIELD, row)? as f64,
1813                optional_primitive::<Int64Type>(array, ZERO_COUNT_I64_FIELD, row)?
1814                    .unwrap_or_default() as f64,
1815                list_values::<Int64Type>(array, POSITIVE_BUCKETS_I64_FIELD, row)?
1816                    .into_iter()
1817                    .map(|value| value as f64)
1818                    .collect(),
1819                list_values::<Int64Type>(array, NEGATIVE_BUCKETS_I64_FIELD, row)?
1820                    .into_iter()
1821                    .map(|value| value as f64)
1822                    .collect(),
1823            )
1824        };
1825
1826    check_span_bucket_count(&positive_spans, positive_buckets.len(), "positive")?;
1827    check_span_bucket_count(&negative_spans, negative_buckets.len(), "negative")?;
1828
1829    Ok(Some(NativeHistogram {
1830        schema,
1831        zero_threshold: required_primitive::<Float64Type>(array, ZERO_THRESHOLD_FIELD, row)?,
1832        sum: required_primitive::<Float64Type>(array, SUM_FIELD, row)?,
1833        reset_hint: required_primitive::<Int32Type>(array, RESET_HINT_FIELD, row)?.into(),
1834        start_timestamp: optional_primitive::<TimestampMillisecondType>(
1835            array,
1836            START_TIMESTAMP_FIELD,
1837            row,
1838        )?,
1839        custom_values: list_values::<Float64Type>(array, CUSTOM_VALUES_FIELD, row)?,
1840        positive_spans,
1841        negative_spans,
1842        count,
1843        zero_count,
1844        positive_buckets,
1845        negative_buckets,
1846    }))
1847}
1848
1849fn list_opt<T>(values: Vec<T>) -> Option<Vec<Option<T>>> {
1850    Some(values.into_iter().map(Some).collect())
1851}
1852
1853/// Builds a native histogram Struct array from query-time values.
1854///
1855/// The result uses the canonical `f64` payload fields. Integer count and bucket
1856/// fields remain empty because [`NativeHistogram`] no longer tracks the source
1857/// payload family after decoding.
1858pub fn build_histogram_array(values: &[Option<NativeHistogram>]) -> ArrayRef {
1859    let mut schemas = Vec::with_capacity(values.len());
1860    let mut zero_thresholds = Vec::with_capacity(values.len());
1861    let mut sums = Vec::with_capacity(values.len());
1862    let mut reset_hints = Vec::with_capacity(values.len());
1863    let mut start_timestamps = Vec::with_capacity(values.len());
1864    let mut custom_values = Vec::with_capacity(values.len());
1865    let mut positive_span_offsets = Vec::with_capacity(values.len());
1866    let mut positive_span_lengths = Vec::with_capacity(values.len());
1867    let mut negative_span_offsets = Vec::with_capacity(values.len());
1868    let mut negative_span_lengths = Vec::with_capacity(values.len());
1869    let mut count_i64 = Vec::<Option<i64>>::with_capacity(values.len());
1870    let mut zero_count_i64 = Vec::<Option<i64>>::with_capacity(values.len());
1871    let mut positive_buckets_i64 = Vec::with_capacity(values.len());
1872    let mut negative_buckets_i64 = Vec::with_capacity(values.len());
1873    let mut count_f64 = Vec::with_capacity(values.len());
1874    let mut zero_count_f64 = Vec::with_capacity(values.len());
1875    let mut positive_buckets_f64 = Vec::with_capacity(values.len());
1876    let mut negative_buckets_f64 = Vec::with_capacity(values.len());
1877    let mut validity = Vec::with_capacity(values.len());
1878
1879    for value in values {
1880        validity.push(value.is_some());
1881        if let Some(histogram) = value {
1882            schemas.push(Some(histogram.schema));
1883            zero_thresholds.push(Some(histogram.zero_threshold));
1884            sums.push(Some(histogram.sum));
1885            reset_hints.push(Some(i32::from(histogram.reset_hint)));
1886            start_timestamps.push(histogram.start_timestamp);
1887            custom_values.push(list_opt(histogram.custom_values.clone()));
1888            positive_span_offsets.push(list_opt(
1889                histogram
1890                    .positive_spans
1891                    .iter()
1892                    .map(|span| span.offset)
1893                    .collect(),
1894            ));
1895            positive_span_lengths.push(list_opt(
1896                histogram
1897                    .positive_spans
1898                    .iter()
1899                    .map(|span| span.length)
1900                    .collect(),
1901            ));
1902            negative_span_offsets.push(list_opt(
1903                histogram
1904                    .negative_spans
1905                    .iter()
1906                    .map(|span| span.offset)
1907                    .collect(),
1908            ));
1909            negative_span_lengths.push(list_opt(
1910                histogram
1911                    .negative_spans
1912                    .iter()
1913                    .map(|span| span.length)
1914                    .collect(),
1915            ));
1916            count_i64.push(None);
1917            zero_count_i64.push(None);
1918            positive_buckets_i64.push(list_opt(Vec::<i64>::new()));
1919            negative_buckets_i64.push(list_opt(Vec::<i64>::new()));
1920            count_f64.push(Some(histogram.count));
1921            zero_count_f64.push(Some(histogram.zero_count));
1922            positive_buckets_f64.push(list_opt(histogram.positive_buckets.clone()));
1923            negative_buckets_f64.push(list_opt(histogram.negative_buckets.clone()));
1924        } else {
1925            schemas.push(None);
1926            zero_thresholds.push(None);
1927            sums.push(None);
1928            reset_hints.push(None);
1929            start_timestamps.push(None);
1930            custom_values.push(None);
1931            positive_span_offsets.push(None);
1932            positive_span_lengths.push(None);
1933            negative_span_offsets.push(None);
1934            negative_span_lengths.push(None);
1935            count_i64.push(None);
1936            zero_count_i64.push(None);
1937            positive_buckets_i64.push(None);
1938            negative_buckets_i64.push(None);
1939            count_f64.push(None);
1940            zero_count_f64.push(None);
1941            positive_buckets_f64.push(None);
1942            negative_buckets_f64.push(None);
1943        }
1944    }
1945
1946    let named_arrays: Vec<(&str, ArrayRef)> = vec![
1947        (SCHEMA_FIELD, Arc::new(Int32Array::from(schemas))),
1948        (
1949            ZERO_THRESHOLD_FIELD,
1950            Arc::new(Float64Array::from(zero_thresholds)),
1951        ),
1952        (SUM_FIELD, Arc::new(Float64Array::from(sums))),
1953        (RESET_HINT_FIELD, Arc::new(Int32Array::from(reset_hints))),
1954        (
1955            START_TIMESTAMP_FIELD,
1956            Arc::new(TimestampMillisecondArray::from_iter(start_timestamps)),
1957        ),
1958        (
1959            CUSTOM_VALUES_FIELD,
1960            Arc::new(ListArray::from_iter_primitive::<Float64Type, _, _>(
1961                custom_values,
1962            )),
1963        ),
1964        (
1965            POSITIVE_SPAN_OFFSETS_FIELD,
1966            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
1967                positive_span_offsets,
1968            )),
1969        ),
1970        (
1971            POSITIVE_SPAN_LENGTHS_FIELD,
1972            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
1973                positive_span_lengths,
1974            )),
1975        ),
1976        (
1977            NEGATIVE_SPAN_OFFSETS_FIELD,
1978            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
1979                negative_span_offsets,
1980            )),
1981        ),
1982        (
1983            NEGATIVE_SPAN_LENGTHS_FIELD,
1984            Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>(
1985                negative_span_lengths,
1986            )),
1987        ),
1988        (COUNT_I64_FIELD, Arc::new(Int64Array::from(count_i64))),
1989        (
1990            ZERO_COUNT_I64_FIELD,
1991            Arc::new(Int64Array::from(zero_count_i64)),
1992        ),
1993        (
1994            POSITIVE_BUCKETS_I64_FIELD,
1995            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(
1996                positive_buckets_i64,
1997            )),
1998        ),
1999        (
2000            NEGATIVE_BUCKETS_I64_FIELD,
2001            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>(
2002                negative_buckets_i64,
2003            )),
2004        ),
2005        (COUNT_F64_FIELD, Arc::new(Float64Array::from(count_f64))),
2006        (
2007            ZERO_COUNT_F64_FIELD,
2008            Arc::new(Float64Array::from(zero_count_f64)),
2009        ),
2010        (
2011            POSITIVE_BUCKETS_F64_FIELD,
2012            Arc::new(ListArray::from_iter_primitive::<Float64Type, _, _>(
2013                positive_buckets_f64,
2014            )),
2015        ),
2016        (
2017            NEGATIVE_BUCKETS_F64_FIELD,
2018            Arc::new(ListArray::from_iter_primitive::<Float64Type, _, _>(
2019                negative_buckets_f64,
2020            )),
2021        ),
2022    ];
2023    let (fields, arrays): (Vec<_>, Vec<_>) = named_arrays
2024        .into_iter()
2025        .map(|(name, array)| (Field::new(name, array.data_type().clone(), true), array))
2026        .unzip();
2027
2028    Arc::new(StructArray::new(
2029        fields.into(),
2030        arrays,
2031        Some(NullBuffer::from(validity)),
2032    ))
2033}
2034
2035#[cfg(test)]
2036mod tests {
2037    use super::*;
2038    use datatypes::series::histogram::HistogramBatch;
2039
2040    #[test]
2041    fn assembles_bucket_sides_in_order_and_preserves_zero_count_semantics() {
2042        let bucket = |lower, upper, count, boundary_rule| Bucket {
2043            lower,
2044            upper,
2045            count,
2046            boundary_rule,
2047        };
2048        let negative = vec![
2049            bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight),
2050            bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight),
2051        ];
2052        let positive = vec![bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft)];
2053
2054        for (zero_count, expected) in [
2055            (
2056                5.0,
2057                vec![
2058                    bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight),
2059                    bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight),
2060                    bucket(-0.5, 0.5, 5.0, BoundaryRule::ClosedBoth),
2061                    bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft),
2062                ],
2063            ),
2064            (
2065                0.0,
2066                vec![
2067                    bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight),
2068                    bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight),
2069                    bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft),
2070                ],
2071            ),
2072            (
2073                -0.0,
2074                vec![
2075                    bucket(-4.0, -3.0, 2.0, BoundaryRule::OpenRight),
2076                    bucket(-3.0, -2.0, 1.0, BoundaryRule::OpenRight),
2077                    bucket(2.0, 3.0, 4.0, BoundaryRule::OpenLeft),
2078                ],
2079            ),
2080        ] {
2081            assert_eq!(
2082                assemble_bucket_sides(negative.clone(), 0.5, zero_count, positive.clone()),
2083                expected
2084            );
2085        }
2086    }
2087
2088    fn assert_histogram_view_eq(view: &HistogramView<'_>, expected: &NativeHistogram) {
2089        assert_eq!(view.schema, expected.schema);
2090        assert_eq!(
2091            view.zero_threshold.to_bits(),
2092            expected.zero_threshold.to_bits()
2093        );
2094        assert_eq!(view.sum.to_bits(), expected.sum.to_bits());
2095        assert_eq!(view.count.to_bits(), expected.count.to_bits());
2096        assert_eq!(view.zero_count.to_bits(), expected.zero_count.to_bits());
2097        assert_eq!(view.reset_hint, expected.reset_hint);
2098        assert_eq!(view.start_timestamp, expected.start_timestamp);
2099        assert_eq!(view.custom_values.len(), expected.custom_values.len());
2100        for (actual, expected) in view.custom_values.iter().zip(&expected.custom_values) {
2101            assert_eq!(actual.to_bits(), expected.to_bits());
2102        }
2103        for (actual, expected_spans, expected_buckets) in [
2104            (
2105                &view.positive,
2106                &expected.positive_spans,
2107                &expected.positive_buckets,
2108            ),
2109            (
2110                &view.negative,
2111                &expected.negative_spans,
2112                &expected.negative_buckets,
2113            ),
2114        ] {
2115            assert_eq!(
2116                actual.span_offsets,
2117                expected_spans
2118                    .iter()
2119                    .map(|span| span.offset)
2120                    .collect::<Vec<_>>()
2121            );
2122            assert_eq!(
2123                actual.span_lengths,
2124                expected_spans
2125                    .iter()
2126                    .map(|span| span.length)
2127                    .collect::<Vec<_>>()
2128            );
2129            assert_eq!(actual.buckets.len(), expected_buckets.len());
2130            for (actual, expected) in actual.buckets.iter().zip(expected_buckets) {
2131                assert_eq!(actual.to_bits(), expected.to_bits());
2132            }
2133        }
2134    }
2135
2136    fn histogram(positive_spans: Vec<Span>, positive_buckets: Vec<f64>) -> NativeHistogram {
2137        let count = positive_buckets.iter().sum();
2138        NativeHistogram {
2139            schema: 0,
2140            zero_threshold: 0.0,
2141            sum: count,
2142            reset_hint: CounterResetHint::CounterReset,
2143            start_timestamp: None,
2144            custom_values: Vec::new(),
2145            positive_spans,
2146            negative_spans: Vec::new(),
2147            count,
2148            zero_count: 0.0,
2149            positive_buckets,
2150            negative_buckets: Vec::new(),
2151        }
2152    }
2153
2154    #[test]
2155    fn borrowed_quantile_matches_owned_through_batch_builder() {
2156        let mut owned = histogram(
2157            vec![Span {
2158                offset: 0,
2159                length: 2,
2160            }],
2161            vec![1.0, 2.0],
2162        );
2163        owned.count = 5.0;
2164        owned.zero_threshold = 0.5;
2165        owned.zero_count = 1.0;
2166        owned.start_timestamp = Some(123456);
2167        owned.negative_spans = vec![Span {
2168            offset: 0,
2169            length: 1,
2170        }];
2171        owned.negative_buckets = vec![1.0];
2172        let mut builder = HistogramBatchBuilder::new();
2173        assert_eq!(owned.push_to(&mut builder).unwrap(), 0);
2174        let batch = builder.finish().unwrap();
2175        let view = batch.view(0).unwrap();
2176        for q in [-0.1, 0.0, 0.1, 0.3, 0.5, 1.0, 1.1, f64::NAN] {
2177            let expected = owned.quantile_with_info(q);
2178            let actual = quantile_histogram_view(&view, q);
2179            assert_eq!(actual.0.to_bits(), expected.0.to_bits());
2180            assert_eq!(actual.1, expected.1);
2181        }
2182        assert_eq!(view.reset_hint, owned.reset_hint);
2183        assert_eq!(view.start_timestamp, owned.start_timestamp);
2184        assert_eq!(view.count.to_bits(), owned.count.to_bits());
2185        assert_eq!(view.sum.to_bits(), owned.sum.to_bits());
2186    }
2187
2188    #[test]
2189    fn owned_malformed_spans_keep_truncating_behavior() {
2190        let malformed = NativeHistogram {
2191            schema: 0,
2192            zero_threshold: 0.0,
2193            sum: 3.0,
2194            reset_hint: CounterResetHint::Unknown,
2195            start_timestamp: None,
2196            custom_values: Vec::new(),
2197            positive_spans: vec![Span {
2198                offset: 0,
2199                length: 1,
2200            }],
2201            negative_spans: Vec::new(),
2202            count: 3.0,
2203            zero_count: 0.0,
2204            positive_buckets: vec![1.0, 2.0],
2205            negative_buckets: Vec::new(),
2206        };
2207        assert_eq!(malformed.quantile(0.0), 0.5);
2208        assert_eq!(malformed.fraction(0.0, 1.0), 1.0);
2209
2210        let negative_length = NativeHistogram {
2211            positive_spans: vec![
2212                Span {
2213                    offset: 0,
2214                    length: -1,
2215                },
2216                Span {
2217                    offset: 0,
2218                    length: 1,
2219                },
2220            ],
2221            positive_buckets: vec![1.0],
2222            count: 1.0,
2223            ..histogram(Vec::new(), Vec::new())
2224        };
2225        assert_eq!(negative_length.quantile(0.0), 0.5);
2226    }
2227
2228    #[test]
2229    fn borrowed_custom_quantile_and_nan_info_match_owned() {
2230        let owned = NativeHistogram {
2231            schema: CUSTOM_BUCKETS_SCHEMA,
2232            zero_threshold: 0.0,
2233            sum: f64::NAN,
2234            reset_hint: CounterResetHint::Unrecognized(91),
2235            start_timestamp: Some(987),
2236            custom_values: vec![-1.0, 1.0],
2237            positive_spans: vec![Span {
2238                offset: 0,
2239                length: 3,
2240            }],
2241            negative_spans: Vec::new(),
2242            count: 4.0,
2243            zero_count: 0.0,
2244            positive_buckets: vec![1.0, 1.0, 1.0],
2245            negative_buckets: Vec::new(),
2246        };
2247        let mut builder = HistogramBatchBuilder::new();
2248        owned.push_to(&mut builder).unwrap();
2249        let batch = builder.finish().unwrap();
2250        let view = batch.view(0).unwrap();
2251        for q in [0.0, 0.5, 0.99, 1.0] {
2252            let expected = owned.quantile_with_info(q);
2253            let actual = quantile_histogram_view(&view, q);
2254            assert_eq!(actual.0.to_bits(), expected.0.to_bits());
2255            assert_eq!(actual.1, expected.1);
2256        }
2257    }
2258
2259    #[test]
2260    fn borrowed_quantile_rejects_malformed_and_overflowing_spans() {
2261        let owned = histogram(
2262            vec![Span {
2263                offset: 0,
2264                length: 1,
2265            }],
2266            vec![1.0],
2267        );
2268        let mut builder = HistogramBatchBuilder::new();
2269        owned.push_to(&mut builder).unwrap();
2270        let batch = builder.finish().unwrap();
2271        let mut view = batch.view(0).unwrap();
2272        let malformed = [
2273            BucketSideView {
2274                span_offsets: &[0],
2275                span_lengths: &[],
2276                buckets: &[1.0],
2277            },
2278            BucketSideView {
2279                span_offsets: &[i32::MAX],
2280                span_lengths: &[1],
2281                buckets: &[1.0],
2282            },
2283            BucketSideView {
2284                span_offsets: &[0],
2285                span_lengths: &[-1],
2286                buckets: &[],
2287            },
2288            BucketSideView {
2289                span_offsets: &[0],
2290                span_lengths: &[2],
2291                buckets: &[1.0],
2292            },
2293            BucketSideView {
2294                span_offsets: &[0],
2295                span_lengths: &[0],
2296                buckets: &[1.0],
2297            },
2298            BucketSideView {
2299                span_offsets: &[0, -1],
2300                span_lengths: &[0, 1],
2301                buckets: &[1.0],
2302            },
2303            BucketSideView {
2304                span_offsets: &[0],
2305                span_lengths: &[i32::MAX],
2306                buckets: &[1.0],
2307            },
2308        ];
2309        for side in malformed {
2310            view.positive = side;
2311            let (value, info) = quantile_histogram_view(&view, 0.5);
2312            assert!(value.is_nan());
2313            assert_eq!(info, None);
2314        }
2315        assert_eq!(
2316            quantile_histogram_view(&view, -1.0),
2317            (f64::NEG_INFINITY, None)
2318        );
2319        assert_eq!(quantile_histogram_view(&view, 2.0), (f64::INFINITY, None));
2320    }
2321
2322    #[test]
2323    fn sliced_histogram_view_remains_valid_after_original_owner_drops() {
2324        let first = histogram(
2325            vec![Span {
2326                offset: 0,
2327                length: 1,
2328            }],
2329            vec![2.0],
2330        );
2331        let mut second = histogram(
2332            vec![Span {
2333                offset: 1,
2334                length: 1,
2335            }],
2336            vec![4.0],
2337        );
2338        second.schema = CUSTOM_BUCKETS_SCHEMA;
2339        second.custom_values = vec![10.0];
2340        second.reset_hint = CounterResetHint::Gauge;
2341        second.start_timestamp = Some(789);
2342        let expected_quantile = second.quantile_with_info(0.5);
2343        let expected_bucket = second.positive_buckets[0];
2344        let mut builder = HistogramBatchBuilder::new();
2345        first.push_to(&mut builder).unwrap();
2346        second.push_to(&mut builder).unwrap();
2347        let batch = builder.finish().unwrap();
2348        let sliced = HistogramBatch::try_from_arrow(batch.as_arrow().slice(1, 1)).unwrap();
2349        drop(batch);
2350        drop(first);
2351        drop(second);
2352        let view = sliced.view(0).unwrap();
2353        assert_eq!(view.schema, CUSTOM_BUCKETS_SCHEMA);
2354        assert_eq!(view.custom_values, &[10.0]);
2355        assert_eq!(view.positive.span_offsets, &[1]);
2356        assert_eq!(view.positive.span_lengths, &[1]);
2357        assert_eq!(view.positive.buckets, &[expected_bucket]);
2358        assert_eq!(view.reset_hint, CounterResetHint::Gauge);
2359        assert_eq!(view.start_timestamp, Some(789));
2360        assert_eq!(quantile_histogram_view(&view, 0.5), expected_quantile);
2361    }
2362
2363    #[test]
2364    fn promql_string_matches_prometheus_float_format() {
2365        assert_eq!(format_promql_histogram_float(0.0001), "0.0001");
2366        assert_eq!(format_promql_histogram_float(1_000_000.0), "1e+06");
2367
2368        let histogram = NativeHistogram {
2369            schema: CUSTOM_BUCKETS_SCHEMA,
2370            zero_threshold: 0.0,
2371            sum: 2_349_209.324,
2372            reset_hint: CounterResetHint::Unknown,
2373            start_timestamp: None,
2374            custom_values: vec![0.00001],
2375            positive_spans: vec![Span {
2376                offset: 0,
2377                length: 2,
2378            }],
2379            negative_spans: Vec::new(),
2380            count: 3.0,
2381            zero_count: 0.0,
2382            positive_buckets: vec![1.0, 2.0],
2383            negative_buckets: Vec::new(),
2384        };
2385
2386        assert_eq!(
2387            histogram.promql_string(),
2388            "{count:3, sum:2.349209324e+06, [-Inf,1e-05]:1, (1e-05,+Inf]:2}"
2389        );
2390    }
2391
2392    #[test]
2393    fn span_rebuild_checks_offsets_and_preserves_empty_input() {
2394        assert_eq!(
2395            spans_from_indices_counts(Vec::new()),
2396            Some((Vec::new(), Vec::new()))
2397        );
2398        assert_eq!(
2399            spans_from_indices_counts(vec![(2, 1.0), (3, 2.0), (5, 3.0)]),
2400            Some((
2401                vec![
2402                    Span {
2403                        offset: 2,
2404                        length: 2,
2405                    },
2406                    Span {
2407                        offset: 1,
2408                        length: 1,
2409                    },
2410                ],
2411                vec![1.0, 2.0, 3.0],
2412            ))
2413        );
2414        assert_eq!(
2415            spans_from_indices_counts(vec![(i32::MIN, 1.0), (i32::MAX, 2.0)]),
2416            None
2417        );
2418    }
2419
2420    #[test]
2421    fn direct_arrow_samples_preserve_payload_and_null_rows() {
2422        let mut expected = histogram(
2423            vec![Span {
2424                offset: 0,
2425                length: 2,
2426            }],
2427            vec![1.0, 3.0],
2428        );
2429        expected.negative_spans = vec![Span {
2430            offset: -2,
2431            length: 1,
2432        }];
2433        expected.negative_buckets = vec![7.0];
2434        expected.schema = 3;
2435        expected.zero_threshold = f64::from_bits(0x3fb9_9999_9999_999a);
2436        expected.sum = f64::from_bits(0x7ff8_0000_0000_0042);
2437        expected.zero_count = -0.0;
2438        expected.custom_values = vec![f64::from_bits(0x3ff0_0000_0000_0001)];
2439        expected.positive_spans = vec![
2440            Span {
2441                offset: 2,
2442                length: 1,
2443            },
2444            Span {
2445                offset: 1,
2446                length: 1,
2447            },
2448        ];
2449        expected.positive_buckets = vec![1.0, 3.0];
2450        expected.reset_hint = CounterResetHint::Unrecognized(42);
2451        expected.start_timestamp = Some(1234);
2452        let array = build_histogram_array(&[Some(expected.clone()), None]);
2453        let array = array.as_any().downcast_ref::<StructArray>().unwrap();
2454        let samples = histogram_samples_from_arrow(array).unwrap();
2455        assert_eq!(samples.len(), 2);
2456        let datatypes::series::samples::SampleRef::Histogram(view) = samples.sample(0) else {
2457            panic!("expected histogram sample");
2458        };
2459        assert_histogram_view_eq(&view, &expected);
2460        assert!(matches!(
2461            samples.sample(1),
2462            datatypes::series::samples::SampleRef::Missing
2463        ));
2464    }
2465
2466    #[test]
2467    fn direct_arrow_conversion_handles_sliced_parent_and_owns_result() {
2468        let mut first = histogram(
2469            vec![Span {
2470                offset: 3,
2471                length: 2,
2472            }],
2473            vec![8.0, 9.0],
2474        );
2475        first.custom_values = vec![4.0];
2476        first.negative_spans = vec![Span {
2477            offset: 1,
2478            length: 1,
2479        }];
2480        first.negative_buckets = vec![6.0];
2481        let mut second = histogram(
2482            vec![Span {
2483                offset: -1,
2484                length: 1,
2485            }],
2486            vec![2.0],
2487        );
2488        second.negative_spans = vec![Span {
2489            offset: 2,
2490            length: 1,
2491        }];
2492        second.negative_buckets = vec![3.0];
2493        second.custom_values = vec![0.5];
2494        second.start_timestamp = Some(77);
2495        second.reset_hint = CounterResetHint::Unrecognized(99);
2496        second.zero_count = -0.0;
2497        let owner = build_histogram_array(&[Some(first), Some(second.clone())]);
2498        let sliced = owner.slice(1, 1);
2499        let samples = {
2500            let struct_array = sliced.as_any().downcast_ref::<StructArray>().unwrap();
2501            histogram_samples_from_arrow(struct_array).unwrap()
2502        };
2503        drop(sliced);
2504        drop(owner);
2505        let datatypes::series::samples::SampleRef::Histogram(view) = samples.sample(0) else {
2506            panic!("expected histogram sample");
2507        };
2508        assert_histogram_view_eq(&view, &second);
2509    }
2510
2511    #[test]
2512    fn direct_arrow_entrypoint_preserves_empty_and_all_null_rows() {
2513        for (values, expected_len) in [(&[][..], 0), (&[None, None][..], 2)] {
2514            let array = build_histogram_array(values);
2515            let array = array.as_any().downcast_ref::<StructArray>().unwrap();
2516            let samples = histogram_samples_from_arrow(array).unwrap();
2517            assert_eq!(samples.len(), expected_len);
2518            assert!((0..expected_len).all(|index| matches!(
2519                samples.sample(index),
2520                datatypes::series::samples::SampleRef::Missing
2521            )));
2522        }
2523    }
2524
2525    #[test]
2526    fn direct_arrow_integer_buckets_remain_absolute_and_float_family_wins() {
2527        let value = histogram(
2528            vec![Span {
2529                offset: 0,
2530                length: 2,
2531            }],
2532            vec![1.0, 3.0],
2533        );
2534        let array = build_histogram_array(&[Some(value)]);
2535        let source = array.as_any().downcast_ref::<StructArray>().unwrap();
2536        let mut columns = source.columns().to_vec();
2537        let index = |name: &str| {
2538            source
2539                .fields()
2540                .iter()
2541                .position(|f| f.name() == name)
2542                .unwrap()
2543        };
2544        columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None]));
2545        columns[index(COUNT_I64_FIELD)] = Arc::new(Int64Array::from(vec![Some(4)]));
2546        columns[index(POSITIVE_BUCKETS_I64_FIELD)] =
2547            Arc::new(ListArray::from_iter_primitive::<Int64Type, _, _>([Some(
2548                vec![Some(1), Some(3)],
2549            )]));
2550        let integer = StructArray::new(source.fields().clone(), columns, None);
2551        let samples = histogram_samples_from_arrow(&integer).unwrap();
2552        assert!(
2553            matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view)
2554            if view.count == 4.0 && view.positive.buckets == [1.0, 3.0])
2555        );
2556
2557        let mut columns = integer.columns().to_vec();
2558        columns[index(ZERO_COUNT_I64_FIELD)] = Arc::new(Int64Array::from(vec![None]));
2559        columns[index(ZERO_COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None]));
2560        columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None]));
2561        let integer_null_zero = StructArray::new(integer.fields().clone(), columns, None);
2562        let samples = histogram_samples_from_arrow(&integer_null_zero).unwrap();
2563        assert!(
2564            matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view)
2565            if view.count == 4.0 && view.zero_count == 0.0 && view.positive.buckets == [1.0, 3.0])
2566        );
2567
2568        let mut columns = integer.columns().to_vec();
2569        columns[index(ZERO_COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![None]));
2570        columns[index(COUNT_F64_FIELD)] = Arc::new(Float64Array::from(vec![Some(5.0)]));
2571        columns[index(POSITIVE_BUCKETS_F64_FIELD)] =
2572            Arc::new(ListArray::from_iter_primitive::<Float64Type, _, _>([Some(
2573                vec![Some(2.0), Some(4.0)],
2574            )]));
2575        let both_families = StructArray::new(integer.fields().clone(), columns, None);
2576        let samples = histogram_samples_from_arrow(&both_families).unwrap();
2577        assert!(
2578            matches!(samples.sample(0), datatypes::series::samples::SampleRef::Histogram(view)
2579            if view.count == 5.0 && view.zero_count == 0.0 && view.positive.buckets == [2.0, 4.0])
2580        );
2581    }
2582
2583    #[test]
2584    fn direct_arrow_conversion_rejects_null_required_fields_and_list_items() {
2585        let value = histogram(
2586            vec![Span {
2587                offset: 0,
2588                length: 1,
2589            }],
2590            vec![1.0],
2591        );
2592        let array = build_histogram_array(&[Some(value)]);
2593        let source = array.as_any().downcast_ref::<StructArray>().unwrap();
2594        let mut columns = source.columns().to_vec();
2595        let schema_idx = source
2596            .fields()
2597            .iter()
2598            .position(|f| f.name() == SCHEMA_FIELD)
2599            .unwrap();
2600        columns[schema_idx] = Arc::new(Int32Array::from(vec![None]));
2601        let malformed_scalar = StructArray::new(source.fields().clone(), columns, None);
2602        assert!(histogram_samples_from_arrow(&malformed_scalar).is_err());
2603
2604        let mut columns = source.columns().to_vec();
2605        let buckets_idx = source
2606            .fields()
2607            .iter()
2608            .position(|f| f.name() == POSITIVE_BUCKETS_F64_FIELD)
2609            .unwrap();
2610        columns[buckets_idx] =
2611            Arc::new(ListArray::from_iter_primitive::<Float64Type, _, _>([Some(
2612                vec![None],
2613            )]));
2614        let malformed_item = StructArray::new(source.fields().clone(), columns, None);
2615        assert!(histogram_samples_from_arrow(&malformed_item).is_err());
2616
2617        let mut columns = source.columns().to_vec();
2618        let lengths_idx = source
2619            .fields()
2620            .iter()
2621            .position(|f| f.name() == POSITIVE_SPAN_LENGTHS_FIELD)
2622            .unwrap();
2623        columns[lengths_idx] = Arc::new(ListArray::from_iter_primitive::<Int32Type, _, _>([Some(
2624            vec![Some(2)],
2625        )]));
2626        let malformed_spans = StructArray::new(source.fields().clone(), columns, None);
2627        assert!(histogram_samples_from_arrow(&malformed_spans).is_err());
2628    }
2629
2630    #[test]
2631    fn datatypes_reset_hints_round_trip_through_native_histogram() {
2632        use datatypes::series::histogram::CounterResetHint as DatatypesCounterResetHint;
2633
2634        let values = [-1, 0, 1, 2, 3, 77, i32::MIN, i32::MAX];
2635        for value in values {
2636            let datatypes_hint = DatatypesCounterResetHint::from(value);
2637            let query_hint: CounterResetHint = datatypes_hint;
2638            let mut histogram = histogram(Vec::new(), Vec::new());
2639            histogram.reset_hint = query_hint;
2640            let datatypes_hint: DatatypesCounterResetHint = histogram.reset_hint;
2641            assert_eq!(i32::from(datatypes_hint), value);
2642        }
2643    }
2644
2645    #[test]
2646    fn arrow_round_trip_preserves_unrecognized_reset_hint() {
2647        let mut expected = histogram(
2648            vec![Span {
2649                offset: 0,
2650                length: 1,
2651            }],
2652            vec![1.0],
2653        );
2654        expected.reset_hint = CounterResetHint::Unrecognized(42);
2655
2656        let array = build_histogram_array(&[Some(expected.clone())]);
2657        assert_eq!(array.data_type(), &native_histogram_arrow_type());
2658        let array = array.as_any().downcast_ref::<StructArray>().unwrap();
2659
2660        assert_eq!(read_histogram(array, 0).unwrap(), Some(expected));
2661        assert!(
2662            primitive_child::<Int64Type>(array, COUNT_I64_FIELD)
2663                .unwrap()
2664                .is_null(0)
2665        );
2666        assert_eq!(
2667            primitive_child::<Float64Type>(array, COUNT_F64_FIELD)
2668                .unwrap()
2669                .value(0),
2670            1.0
2671        );
2672    }
2673
2674    #[test]
2675    fn add_uses_sparse_bucket_union() {
2676        let left = histogram(
2677            vec![Span {
2678                offset: 0,
2679                length: 1,
2680            }],
2681            vec![1.0],
2682        );
2683        let right = histogram(
2684            vec![Span {
2685                offset: 2,
2686                length: 1,
2687            }],
2688            vec![2.0],
2689        );
2690
2691        let result = left.add(&right).unwrap();
2692        assert_eq!(
2693            result.positive_spans,
2694            vec![
2695                Span {
2696                    offset: 0,
2697                    length: 1,
2698                },
2699                Span {
2700                    offset: 1,
2701                    length: 1,
2702                },
2703            ]
2704        );
2705        assert_eq!(result.positive_buckets, vec![1.0, 2.0]);
2706    }
2707
2708    #[test]
2709    fn add_combines_reset_hints_for_compatible_empty_payloads() {
2710        let mut empty = histogram(Vec::new(), Vec::new());
2711        empty.reset_hint = CounterResetHint::Gauge;
2712        let mut populated = histogram(
2713            vec![Span {
2714                offset: 0,
2715                length: 1,
2716            }],
2717            vec![1.0],
2718        );
2719        populated.reset_hint = CounterResetHint::NotCounterReset;
2720
2721        assert_eq!(
2722            empty.add(&populated).unwrap().reset_hint,
2723            CounterResetHint::Gauge
2724        );
2725        assert_eq!(
2726            populated.add(&empty).unwrap().reset_hint,
2727            CounterResetHint::Gauge
2728        );
2729    }
2730
2731    #[test]
2732    fn empty_arithmetic_rejects_incompatible_schemas() {
2733        let exponential = histogram(Vec::new(), Vec::new());
2734        let mut custom = histogram(
2735            vec![Span {
2736                offset: 0,
2737                length: 1,
2738            }],
2739            vec![2.0],
2740        );
2741        custom.schema = CUSTOM_BUCKETS_SCHEMA;
2742        custom.custom_values = vec![1.0];
2743
2744        assert!(exponential.add(&custom).is_none());
2745        assert!(custom.add(&exponential).is_none());
2746        assert!(exponential.sub(&custom).is_none());
2747        assert!(custom.sub(&exponential).is_none());
2748    }
2749
2750    #[test]
2751    fn empty_custom_histogram_still_reconciles_bounds() {
2752        let mut empty = histogram(Vec::new(), Vec::new());
2753        empty.schema = CUSTOM_BUCKETS_SCHEMA;
2754        empty.custom_values = vec![1.0];
2755        let mut populated = histogram(
2756            vec![Span {
2757                offset: 0,
2758                length: 1,
2759            }],
2760            vec![2.0],
2761        );
2762        populated.schema = CUSTOM_BUCKETS_SCHEMA;
2763        populated.custom_values = vec![2.0];
2764
2765        let result = empty.add(&populated).unwrap();
2766        assert!(result.custom_values.is_empty());
2767        assert_eq!(result.positive_buckets, vec![2.0]);
2768    }
2769
2770    #[test]
2771    fn zero_threshold_expands_to_populated_bucket_boundary() {
2772        let left = NativeHistogram {
2773            zero_threshold: 0.5,
2774            ..histogram(
2775                vec![Span {
2776                    offset: 0,
2777                    length: 1,
2778                }],
2779                vec![1.0],
2780            )
2781        };
2782        let right = NativeHistogram {
2783            zero_threshold: 0.75,
2784            ..histogram(
2785                vec![Span {
2786                    offset: 1,
2787                    length: 1,
2788                }],
2789                vec![1.0],
2790            )
2791        };
2792
2793        let result = left.add(&right).unwrap();
2794        assert_eq!(result.zero_threshold, 1.0);
2795        assert_eq!(result.zero_count, 1.0);
2796        assert_eq!(result.positive_buckets, vec![1.0]);
2797    }
2798
2799    #[test]
2800    fn custom_reconciliation_without_shared_bounds_uses_overflow_bucket() {
2801        let mut left = histogram(
2802            vec![Span {
2803                offset: 0,
2804                length: 1,
2805            }],
2806            vec![1.0],
2807        );
2808        left.schema = CUSTOM_BUCKETS_SCHEMA;
2809        left.custom_values = vec![1.0];
2810
2811        let mut right = histogram(
2812            vec![Span {
2813                offset: 0,
2814                length: 1,
2815            }],
2816            vec![2.0],
2817        );
2818        right.schema = CUSTOM_BUCKETS_SCHEMA;
2819        right.custom_values = vec![2.0];
2820
2821        let result = left.add(&right).unwrap();
2822        assert!(result.custom_values.is_empty());
2823        assert_eq!(
2824            result.positive_spans,
2825            vec![Span {
2826                offset: 0,
2827                length: 1,
2828            }]
2829        );
2830        assert_eq!(result.positive_buckets, vec![3.0]);
2831    }
2832
2833    #[test]
2834    fn promql_eq_ignores_metadata_but_compares_sparse_layout() {
2835        let mut left = histogram(
2836            vec![Span {
2837                offset: 0,
2838                length: 2,
2839            }],
2840            vec![1.0, 0.0],
2841        );
2842        left.reset_hint = CounterResetHint::CounterReset;
2843        left.start_timestamp = Some(1000);
2844
2845        let mut right = histogram(
2846            vec![Span {
2847                offset: 0,
2848                length: 1,
2849            }],
2850            vec![1.0],
2851        );
2852        right.reset_hint = CounterResetHint::NotCounterReset;
2853        right.start_timestamp = Some(2000);
2854
2855        assert!(!left.promql_eq(&right));
2856
2857        right.positive_spans = vec![
2858            Span {
2859                offset: 0,
2860                length: 0,
2861            },
2862            Span {
2863                offset: 0,
2864                length: 1,
2865            },
2866            Span {
2867                offset: 42,
2868                length: 0,
2869            },
2870        ];
2871        left.positive_spans = vec![Span {
2872            offset: 0,
2873            length: 1,
2874        }];
2875        left.positive_buckets = vec![1.0];
2876        assert!(left.promql_eq(&right));
2877    }
2878
2879    #[test]
2880    fn promql_eq_compares_payload_floats_by_bits() {
2881        let nan = f64::from_bits(0x7ff8_0000_0000_0001);
2882        let other_nan = f64::from_bits(0x7ff8_0000_0000_0002);
2883        let mut left = histogram(
2884            vec![Span {
2885                offset: 0,
2886                length: 1,
2887            }],
2888            vec![nan],
2889        );
2890        left.count = nan;
2891        left.zero_count = nan;
2892        left.sum = nan;
2893        let right = left.clone();
2894
2895        assert!(left.promql_eq(&right));
2896
2897        for changed in [
2898            NativeHistogram {
2899                count: other_nan,
2900                ..right.clone()
2901            },
2902            NativeHistogram {
2903                zero_count: other_nan,
2904                ..right.clone()
2905            },
2906            NativeHistogram {
2907                sum: other_nan,
2908                ..right.clone()
2909            },
2910            NativeHistogram {
2911                positive_buckets: vec![other_nan],
2912                ..right.clone()
2913            },
2914        ] {
2915            assert!(!left.promql_eq(&changed));
2916        }
2917
2918        let undecodable = histogram(
2919            vec![Span {
2920                offset: i32::MAX,
2921                length: 1,
2922            }],
2923            vec![1.0],
2924        );
2925        assert!(!undecodable.promql_eq(&undecodable.clone()));
2926
2927        let mut mismatched = histogram(
2928            vec![Span {
2929                offset: 0,
2930                length: 2,
2931            }],
2932            vec![1.0],
2933        );
2934        mismatched.count = 1.0;
2935        mismatched.sum = 1.0;
2936        assert!(!mismatched.promql_eq(&mismatched.clone()));
2937
2938        let invalid_offset = histogram(
2939            vec![
2940                Span {
2941                    offset: 0,
2942                    length: 1,
2943                },
2944                Span {
2945                    offset: -1,
2946                    length: 1,
2947                },
2948            ],
2949            vec![1.0, 1.0],
2950        );
2951        assert!(!invalid_offset.promql_eq(&invalid_offset.clone()));
2952    }
2953
2954    #[test]
2955    fn detect_reset_preserves_layout_direction() {
2956        let mut previous = histogram(
2957            vec![Span {
2958                offset: 1,
2959                length: 1,
2960            }],
2961            vec![1.0],
2962        );
2963        previous.reset_hint = CounterResetHint::Unknown;
2964
2965        let mut higher_resolution = previous.clone();
2966        higher_resolution.schema = 1;
2967        higher_resolution.positive_spans[0].offset = 2;
2968        assert!(higher_resolution.detect_reset(&previous));
2969
2970        let mut lower_resolution = previous.clone();
2971        lower_resolution.schema = 0;
2972        lower_resolution.positive_spans[0].offset = 1;
2973        let mut previous_higher_resolution = higher_resolution;
2974        previous_higher_resolution.reset_hint = CounterResetHint::Unknown;
2975        assert!(!lower_resolution.detect_reset(&previous_higher_resolution));
2976
2977        let mut smaller_zero_threshold = previous.clone();
2978        smaller_zero_threshold.zero_threshold = 0.5;
2979        previous.zero_threshold = 1.0;
2980        assert!(smaller_zero_threshold.detect_reset(&previous));
2981
2982        let mut previous = histogram(
2983            vec![Span {
2984                offset: 0,
2985                length: 1,
2986            }],
2987            vec![1.0],
2988        );
2989        previous.reset_hint = CounterResetHint::Unknown;
2990        let mut split_bucket = histogram(Vec::new(), Vec::new());
2991        split_bucket.reset_hint = CounterResetHint::Unknown;
2992        split_bucket.count = 1.0;
2993        split_bucket.zero_count = 1.0;
2994        split_bucket.zero_threshold = 0.75;
2995        assert!(split_bucket.detect_reset(&previous));
2996
2997        split_bucket.zero_threshold = 1.0;
2998        assert!(!split_bucket.detect_reset(&previous));
2999    }
3000
3001    #[test]
3002    fn extreme_bucket_index_returns_none_instead_of_overflowing() {
3003        assert_eq!(ceil_div(i32::MIN, 2), i32::MIN / 2);
3004
3005        let mut histogram = histogram(
3006            vec![Span {
3007                offset: i32::MIN,
3008                length: 1,
3009            }],
3010            vec![1.0],
3011        );
3012        assert!(histogram.side_buckets(true).is_none());
3013
3014        histogram.schema = 1;
3015        let reduced = histogram.copy_to_schema(0).unwrap();
3016        assert_eq!(reduced.positive_spans[0].offset, i32::MIN / 2);
3017    }
3018
3019    #[test]
3020    fn exponential_bucket_bounds_stop_after_overflow_bucket() {
3021        for schema in [-4, 0, 8] {
3022            let overflow = exponential_overflow_bucket_index(schema).unwrap();
3023            assert_eq!(get_bound(overflow - 1, schema, &[]), Some(f64::MAX));
3024            assert_eq!(get_bound(overflow, schema, &[]), Some(f64::INFINITY));
3025            assert_eq!(get_bound(overflow + 1, schema, &[]), None);
3026        }
3027        assert_eq!(exponential_overflow_bucket_index(-5), None);
3028        assert_eq!(exponential_overflow_bucket_index(9), None);
3029        assert_eq!(get_bound(i32::MIN, -4, &[]), Some(0.0));
3030    }
3031
3032    #[test]
3033    fn custom_bucket_midpoints_preserve_infinite_bounds() {
3034        let mut histogram = histogram(Vec::new(), Vec::new());
3035        histogram.schema = CUSTOM_BUCKETS_SCHEMA;
3036
3037        assert_eq!(
3038            histogram.bucket_midpoint(&Bucket {
3039                lower: f64::NEG_INFINITY,
3040                upper: -1.0,
3041                count: 1.0,
3042                boundary_rule: BoundaryRule::OpenLeft,
3043            }),
3044            f64::NEG_INFINITY
3045        );
3046        assert_eq!(
3047            histogram.bucket_midpoint(&Bucket {
3048                lower: 1.0,
3049                upper: f64::INFINITY,
3050                count: 1.0,
3051                boundary_rule: BoundaryRule::OpenLeft,
3052            }),
3053            f64::INFINITY
3054        );
3055        assert!(
3056            histogram
3057                .bucket_midpoint(&Bucket {
3058                    lower: f64::NEG_INFINITY,
3059                    upper: f64::INFINITY,
3060                    count: 1.0,
3061                    boundary_rule: BoundaryRule::OpenLeft,
3062                })
3063                .is_nan()
3064        );
3065    }
3066
3067    #[test]
3068    fn fraction_excludes_nan_observations() {
3069        let mut histogram = histogram(
3070            vec![Span {
3071                offset: 0,
3072                length: 1,
3073            }],
3074            vec![8.0],
3075        );
3076        histogram.count = 10.0;
3077        histogram.sum = f64::NAN;
3078
3079        assert_eq!(
3080            histogram.fraction_with_info(f64::NEG_INFINITY, f64::INFINITY),
3081            (0.8, true)
3082        );
3083    }
3084
3085    #[test]
3086    fn quantile_reports_nan_observation_effect() {
3087        let mut histogram = histogram(
3088            vec![Span {
3089                offset: 0,
3090                length: 1,
3091            }],
3092            vec![8.0],
3093        );
3094        histogram.count = 10.0;
3095        histogram.sum = f64::NAN;
3096
3097        let (skewed, info) = histogram.quantile_with_info(0.5);
3098        assert!(skewed.is_finite());
3099        assert_eq!(info, Some(NativeHistogramQuantileInfo::NaNSkew));
3100
3101        let (nan, info) = histogram.quantile_with_info(0.9);
3102        assert!(nan.is_nan());
3103        assert_eq!(info, Some(NativeHistogramQuantileInfo::NaNResult));
3104
3105        histogram.count = 8.0;
3106        assert_eq!(histogram.quantile_with_info(0.5).1, None);
3107
3108        histogram.count = 3.0;
3109        histogram.positive_spans.clear();
3110        histogram.positive_buckets.clear();
3111        let (nan, info) = histogram.quantile_with_info(0.0);
3112        assert!(nan.is_nan());
3113        assert_eq!(info, Some(NativeHistogramQuantileInfo::NaNSkew));
3114
3115        histogram.schema = CUSTOM_BUCKETS_SCHEMA;
3116        histogram.count = 10.0;
3117        histogram.positive_spans = vec![Span {
3118            offset: 0,
3119            length: 1,
3120        }];
3121        histogram.positive_buckets = vec![8.0];
3122        for (bound, offset, expected) in [(-1.0, 0, -1.0), (1.0, 1, 1.0)] {
3123            histogram.custom_values = vec![bound];
3124            histogram.positive_spans[0].offset = offset;
3125            assert_eq!(
3126                histogram.quantile_with_info(0.5),
3127                (expected, Some(NativeHistogramQuantileInfo::NaNSkew))
3128            );
3129        }
3130    }
3131
3132    #[test]
3133    fn subtraction_returns_gauge_histogram() {
3134        let left = histogram(
3135            vec![Span {
3136                offset: 0,
3137                length: 1,
3138            }],
3139            vec![3.0],
3140        );
3141        let right = histogram(
3142            vec![Span {
3143                offset: 0,
3144                length: 1,
3145            }],
3146            vec![1.0],
3147        );
3148
3149        let result = left.sub(&right).unwrap();
3150        assert_eq!(result.reset_hint, CounterResetHint::Gauge);
3151        assert_eq!(result.positive_buckets, vec![2.0]);
3152    }
3153
3154    #[test]
3155    fn subtraction_treats_compatible_empty_left_as_zero() {
3156        let left = histogram(vec![], vec![]);
3157        let right = histogram(
3158            vec![Span {
3159                offset: 0,
3160                length: 1,
3161            }],
3162            vec![2.0],
3163        );
3164
3165        let result = left.sub(&right).unwrap();
3166        assert_eq!(result.reset_hint, CounterResetHint::Gauge);
3167        assert_eq!(result.count, -2.0);
3168        assert_eq!(result.sum, -2.0);
3169        assert_eq!(result.positive_buckets, vec![-2.0]);
3170    }
3171
3172    #[test]
3173    fn subtraction_rejects_incompatible_empty_left() {
3174        let left = histogram(vec![], vec![]);
3175        let mut right = histogram(
3176            vec![Span {
3177                offset: 0,
3178                length: 1,
3179            }],
3180            vec![2.0],
3181        );
3182        right.schema = CUSTOM_BUCKETS_SCHEMA;
3183        right.custom_values = vec![1.0];
3184
3185        assert!(left.sub(&right).is_none());
3186    }
3187}
3188
3189// ---------------------------------------------------------------------------
3190// Stable Parquet field ids for native-histogram sub-fields.
3191//
3192// External readers resolve nested struct fields by `PARQUET:field_id`, so each
3193// sub-field (and list element) needs a stable positive id. The struct schema
3194// is fixed (always the same 18 fields). Each histogram column owns a block of
3195// ids (offset from a reserved base by the column's id), so several histogram
3196// columns in one table get disjoint sub-field ids. The reserved base is
3197// disjoint from user column ids and mito2 internal ids (`1 << 30`).
3198//
3199// The id is computed with checked arithmetic: the reserved base plus
3200// `column_id * stride` cannot always fit in a positive `i32` (a `ColumnId` is
3201// `u32`), so derivation returns `None` once the representable range is
3202// exceeded. Callers must handle `None` explicitly — the SST parquet writer
3203// surfaces it as an error rather than wrapping, panicking, or silently
3204// dropping the field id.
3205// ---------------------------------------------------------------------------
3206
3207/// Reserved base for native-histogram struct sub-field ids.
3208pub const NATIVE_HISTOGRAM_SUBFIELD_ID_BASE: i32 = 0x5000_0000;
3209
3210/// Number of ids reserved per histogram column (18 sub-fields + headroom for
3211/// list element ids), so multiple histogram columns get disjoint ids.
3212pub const NATIVE_HISTOGRAM_SUBFIELD_ID_STRIDE: i32 = 64;
3213
3214/// Offset of list element ids within a column's id block.
3215pub const NATIVE_HISTOGRAM_LIST_ELEMENT_OFFSET: i32 = 32;
3216
3217/// Returns the stable field id for a native-histogram struct sub-field,
3218/// namespaced by its parent `column_id`, or `None` if `name` is not a known
3219/// sub-field or the derived id overflows a positive `i32`.
3220pub fn native_histogram_subfield_id(column_id: i32, name: &str) -> Option<i32> {
3221    let idx = subfield_index(name)?;
3222    NATIVE_HISTOGRAM_SUBFIELD_ID_BASE
3223        .checked_add(column_id.checked_mul(NATIVE_HISTOGRAM_SUBFIELD_ID_STRIDE)?)
3224        .and_then(|v| v.checked_add(idx))
3225}
3226
3227/// Returns the stable list `element-id` for a list-typed native-histogram
3228/// sub-field, namespaced by its parent `column_id`, or `None` if `name` is not
3229/// a known sub-field or the derived id overflows a positive `i32`.
3230pub fn native_histogram_list_element_id(column_id: i32, name: &str) -> Option<i32> {
3231    let idx = subfield_index(name)?;
3232    NATIVE_HISTOGRAM_SUBFIELD_ID_BASE
3233        .checked_add(column_id.checked_mul(NATIVE_HISTOGRAM_SUBFIELD_ID_STRIDE)?)
3234        .and_then(|v| v.checked_add(NATIVE_HISTOGRAM_LIST_ELEMENT_OFFSET))
3235        .and_then(|v| v.checked_add(idx))
3236}
3237
3238fn subfield_index(name: &str) -> Option<i32> {
3239    NATIVE_HISTOGRAM_FIELD_NAMES
3240        .iter()
3241        .position(|n| *n == name)
3242        .map(|i| i as i32)
3243}
3244
3245#[cfg(test)]
3246mod subfield_id_tests {
3247    use super::*;
3248
3249    #[test]
3250    fn subfield_ids_are_namespaced_and_disjoint() {
3251        // SCHEMA=0, ZERO_THRESHOLD=1, SUM=2, ..., CUSTOM_VALUES=5.
3252        let sum_idx = 2;
3253        let custom_values_idx = 5;
3254
3255        // Ids are offset from the reserved base by the parent column id and
3256        // the sub-field index.
3257        assert_eq!(
3258            native_histogram_subfield_id(1, SUM_FIELD),
3259            Some(NATIVE_HISTOGRAM_SUBFIELD_ID_BASE + NATIVE_HISTOGRAM_SUBFIELD_ID_STRIDE + sum_idx,)
3260        );
3261        // List element ids additionally carry the list offset.
3262        assert_eq!(
3263            native_histogram_list_element_id(1, CUSTOM_VALUES_FIELD),
3264            Some(
3265                NATIVE_HISTOGRAM_SUBFIELD_ID_BASE
3266                    + NATIVE_HISTOGRAM_SUBFIELD_ID_STRIDE
3267                    + NATIVE_HISTOGRAM_LIST_ELEMENT_OFFSET
3268                    + custom_values_idx,
3269            )
3270        );
3271        // Different parent columns get disjoint ids for the same sub-field.
3272        assert_ne!(
3273            native_histogram_subfield_id(1, SUM_FIELD),
3274            native_histogram_subfield_id(7, SUM_FIELD)
3275        );
3276        // Unknown sub-field name -> None.
3277        assert_eq!(native_histogram_subfield_id(1, "not_a_field"), None);
3278    }
3279
3280    #[test]
3281    fn subfield_ids_overflow_returns_none() {
3282        // `column_id` is u32-sized, but the derived id must fit in a positive
3283        // i32. At column_id = 12_582_912, BASE + column_id*64 == i32::MAX + 1,
3284        // which previously overflowed (debug panic / release wrap). Checked
3285        // arithmetic must yield None instead of wrapping or panicking.
3286        assert_eq!(native_histogram_subfield_id(12_582_912, SUM_FIELD), None);
3287        assert_eq!(
3288            native_histogram_list_element_id(12_582_912, CUSTOM_VALUES_FIELD),
3289            None
3290        );
3291        // One below that boundary is still representable.
3292        assert!(native_histogram_subfield_id(12_582_911, SUM_FIELD).is_some());
3293    }
3294}