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