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