1use datafusion::error::{DataFusionError, Result};
25use datatypes::series::histogram::{
26 BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView,
27};
28
29use crate::functions::kahan_inc;
30use crate::histogram_eval::native::{CUSTOM_BUCKETS_SCHEMA, bound};
31
32type Buckets = Vec<(i32, f64)>;
33
34#[cfg(test)]
40pub(crate) mod copies {
41 use std::cell::Cell;
42
43 thread_local! {
44 static MATERIALIZED: Cell<usize> = const { Cell::new(0) };
46 }
47
48 pub(crate) fn record_materialized() {
50 MATERIALIZED.with(|built| built.set(built.get() + 1));
51 }
52
53 pub(crate) fn take_materialized() -> usize {
56 MATERIALIZED.with(|built| built.replace(0))
57 }
58}
59
60#[derive(Debug)]
62pub(crate) struct FloatHistogram {
63 pub(crate) reset_hint: CounterResetHint,
64 pub(crate) start_timestamp: Option<i64>,
80 pub(crate) schema: i32,
81 pub(crate) zero_threshold: f64,
82 pub(crate) zero_count: f64,
83 pub(crate) count: f64,
84 pub(crate) sum: f64,
85 pub(crate) positive: Buckets,
86 pub(crate) negative: Buckets,
87 pub(crate) custom_values: Vec<f64>,
88 layout: Option<[Vec<(i32, i32)>; 2]>,
92}
93
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
96pub(crate) struct AddOutcome {
97 pub(crate) counter_reset_collision: bool,
99 pub(crate) custom_bounds_reconciled: bool,
101}
102
103impl Clone for FloatHistogram {
104 fn clone(&self) -> Self {
105 Self {
106 reset_hint: self.reset_hint,
107 start_timestamp: self.start_timestamp,
108 schema: self.schema,
109 zero_threshold: self.zero_threshold,
110 zero_count: self.zero_count,
111 count: self.count,
112 sum: self.sum,
113 positive: self.positive.clone(),
114 negative: self.negative.clone(),
115 custom_values: self.custom_values.clone(),
116 layout: self.layout.clone(),
117 }
118 }
119}
120
121impl FloatHistogram {
122 pub(crate) fn try_from_view(view: &HistogramView<'_>) -> Result<Self> {
123 #[cfg(test)]
124 copies::record_materialized();
125 Ok(Self {
126 reset_hint: view.reset_hint,
127 start_timestamp: view.start_timestamp,
128 schema: view.schema,
129 zero_threshold: view.zero_threshold,
130 zero_count: view.zero_count,
131 count: view.count,
132 sum: view.sum,
133 positive: side_from_view(view.positive)?,
134 negative: side_from_view(view.negative)?,
135 custom_values: view.custom_values.to_vec(),
136 layout: Some([view.positive, view.negative].map(|side| {
137 side.span_offsets
138 .iter()
139 .copied()
140 .zip(side.span_lengths.iter().copied())
141 .collect()
142 })),
143 })
144 }
145
146 pub(crate) fn heap_bytes(&self) -> usize {
151 fn buckets(side: &Buckets) -> usize {
152 side.capacity() * std::mem::size_of::<(i32, f64)>()
153 }
154 let layout = self.layout.as_ref().map_or(0, |sides| {
155 std::mem::size_of::<[Vec<(i32, i32)>; 2]>().saturating_add(
156 sides
157 .iter()
158 .map(|side| side.capacity() * std::mem::size_of::<(i32, i32)>())
159 .fold(0, usize::saturating_add),
160 )
161 });
162 buckets(&self.positive)
163 .saturating_add(buckets(&self.negative))
164 .saturating_add(
165 self.custom_values
166 .capacity()
167 .saturating_mul(std::mem::size_of::<f64>()),
168 )
169 .saturating_add(layout)
170 }
171
172 pub(crate) fn spans(&self) -> [Vec<(i32, i32)>; 2] {
179 self.layout
180 .clone()
181 .unwrap_or_else(|| [&self.positive, &self.negative].map(canonical_spans))
182 }
183
184 pub(crate) fn push_to(&self, builder: &mut HistogramBatchBuilder) -> Result<u32> {
186 let [positive_spans, negative_spans] = self.spans();
187 let (positive_offsets, positive_lengths): (Vec<_>, Vec<_>) =
188 positive_spans.into_iter().unzip();
189 let (negative_offsets, negative_lengths): (Vec<_>, Vec<_>) =
190 negative_spans.into_iter().unzip();
191 let positive_counts: Vec<f64> = self.positive.iter().map(|&(_, count)| count).collect();
192 let negative_counts: Vec<f64> = self.negative.iter().map(|&(_, count)| count).collect();
193 builder
194 .push(HistogramView {
195 schema: self.schema,
196 zero_threshold: self.zero_threshold,
197 sum: self.sum,
198 count: self.count,
199 zero_count: self.zero_count,
200 reset_hint: self.reset_hint,
201 start_timestamp: self.start_timestamp,
202 custom_values: &self.custom_values,
203 positive: BucketSideView {
204 span_offsets: &positive_offsets,
205 span_lengths: &positive_lengths,
206 buckets: &positive_counts,
207 },
208 negative: BucketSideView {
209 span_offsets: &negative_offsets,
210 span_lengths: &negative_lengths,
211 buckets: &negative_counts,
212 },
213 })
214 .map_err(|error| DataFusionError::External(Box::new(error)))
215 }
216
217 pub(crate) fn empty_like(&self) -> Self {
220 Self {
221 reset_hint: CounterResetHint::Unknown,
222 start_timestamp: None,
223 schema: self.schema,
224 zero_threshold: 0.0,
225 zero_count: 0.0,
226 count: 0.0,
227 sum: 0.0,
228 positive: Vec::new(),
229 negative: Vec::new(),
230 custom_values: self.custom_values.clone(),
231 layout: None,
232 }
233 }
234
235 pub(crate) fn uses_custom_buckets(&self) -> bool {
236 self.schema == CUSTOM_BUCKETS_SCHEMA
237 }
238
239 pub(crate) fn mul(&mut self, factor: f64) {
241 self.start_timestamp = None;
243 self.zero_count *= factor;
244 self.count *= factor;
245 self.sum *= factor;
246 for (_, count) in self.positive.iter_mut().chain(self.negative.iter_mut()) {
247 *count *= factor;
248 }
249 if factor < 0.0 {
250 self.reset_hint = CounterResetHint::Gauge;
251 }
252 }
253
254 pub(crate) fn div(&mut self, scalar: f64) {
256 self.start_timestamp = None;
258 self.zero_count /= scalar;
259 self.count /= scalar;
260 self.sum /= scalar;
261 if scalar == 0.0 {
262 self.positive.clear();
263 self.negative.clear();
264 self.layout = None;
265 return;
266 }
267 for (_, count) in self.positive.iter_mut().chain(self.negative.iter_mut()) {
268 *count /= scalar;
269 }
270 if scalar < 0.0 {
271 self.reset_hint = CounterResetHint::Gauge;
272 }
273 }
274
275 pub(crate) fn has_overflow(&self) -> bool {
277 [self.zero_count, self.count, self.sum]
278 .into_iter()
279 .chain(
280 self.positive
281 .iter()
282 .chain(&self.negative)
283 .map(|&(_, count)| count),
284 )
285 .chain(self.custom_values.iter().copied())
286 .any(f64::is_infinite)
287 }
288
289 pub(crate) fn compact(&mut self) {
291 self.start_timestamp = None;
293 self.positive.retain(|&(_, count)| count != 0.0);
294 self.negative.retain(|&(_, count)| count != 0.0);
295 self.layout = None;
296 }
297
298 pub(crate) fn copy_to_schema(&self, target: i32) -> Result<Self> {
300 if target == self.schema {
301 return Ok(Self {
304 start_timestamp: None,
305 ..self.clone()
306 });
307 }
308 if self.uses_custom_buckets() || target == CUSTOM_BUCKETS_SCHEMA || target > self.schema {
309 return Err(incompatible_schema());
310 }
311 Ok(Self {
312 reset_hint: CounterResetHint::Unknown,
313 start_timestamp: None,
314 schema: target,
315 zero_threshold: self.zero_threshold,
316 zero_count: self.zero_count,
317 count: self.count,
318 sum: self.sum,
319 positive: reduce_resolution(&self.positive, self.schema, target),
320 negative: reduce_resolution(&self.negative, self.schema, target),
321 custom_values: Vec::new(),
322 layout: None,
323 })
324 }
325
326 pub(crate) fn add(&mut self, other: &Self) -> Result<AddOutcome> {
328 self.add_or_sub(other, false)
329 }
330
331 pub(crate) fn sub(&mut self, other: &Self) -> Result<AddOutcome> {
333 self.add_or_sub(other, true)
334 }
335
336 fn add_or_sub(&mut self, other: &Self, subtract: bool) -> Result<AddOutcome> {
337 check_schemas(self, other)?;
338 self.layout = None;
339 self.start_timestamp = None;
341 let mut outcome = AddOutcome {
342 counter_reset_collision: self.adjust_counter_reset(other),
343 custom_bounds_reconciled: false,
344 };
345 let sign = if subtract { -1.0 } else { 1.0 };
346 if !self.uses_custom_buckets() {
347 let (other_zero_count, _) = self.reconcile_zero_buckets(other, None)?;
348 if subtract {
349 self.zero_count -= other_zero_count;
350 } else {
351 self.zero_count += other_zero_count;
352 }
353 }
354 if subtract {
355 self.count -= other.count;
356 self.sum -= other.sum;
357 } else {
358 self.count += other.count;
359 self.sum += other.sum;
360 }
361
362 if self.uses_custom_buckets() {
363 if self.custom_values == other.custom_values {
364 add_buckets(self, &other.positive, sign, None, None, true)?;
365 } else {
366 outcome.custom_bounds_reconciled = true;
367 let bounds = intersect_custom_bounds(&self.custom_values, &other.custom_values);
368 (self.positive, _) = add_custom_buckets_with_mismatches(
369 subtract,
370 &self.positive,
371 &self.custom_values,
372 &other.positive,
373 &other.custom_values,
374 None,
375 &bounds,
376 );
377 self.custom_values = bounds;
378 }
379 return Ok(outcome);
380 }
381
382 let reduced;
383 let (other_positive, other_negative) = if other.schema < self.schema {
384 self.positive = reduce_resolution(&self.positive, self.schema, other.schema);
385 self.negative = reduce_resolution(&self.negative, self.schema, other.schema);
386 self.schema = other.schema;
387 (&other.positive, &other.negative)
388 } else if other.schema > self.schema {
389 reduced = [&other.positive, &other.negative]
390 .map(|side| reduce_resolution(side, other.schema, self.schema));
391 (&reduced[0], &reduced[1])
392 } else {
393 (&other.positive, &other.negative)
394 };
395 add_buckets(self, other_positive, sign, None, None, true)?;
396 add_buckets(self, other_negative, sign, None, None, false)?;
397 Ok(outcome)
398 }
399
400 pub(crate) fn kahan_add(
403 &mut self,
404 other: &Self,
405 c: Option<Self>,
406 ) -> Result<(Self, AddOutcome)> {
407 check_schemas(self, other)?;
408 self.layout = None;
409 self.start_timestamp = None;
411 let mut outcome = AddOutcome {
412 counter_reset_collision: self.adjust_counter_reset(other),
413 custom_bounds_reconciled: false,
414 };
415 let mut c = c.unwrap_or_else(|| self.new_compensation());
416 if !self.uses_custom_buckets() {
417 let (other_zero_count, other_c_zero_count) =
418 self.reconcile_zero_buckets(other, Some(&mut c))?;
419 (self.zero_count, c.zero_count) =
420 kahan_inc(other_zero_count, self.zero_count, c.zero_count);
421 (self.zero_count, c.zero_count) =
422 kahan_inc(other_c_zero_count, self.zero_count, c.zero_count);
423 }
424 (self.count, c.count) = kahan_inc(other.count, self.count, c.count);
425 (self.sum, c.sum) = kahan_inc(other.sum, self.sum, c.sum);
426
427 if self.uses_custom_buckets() {
428 if self.custom_values == other.custom_values {
429 add_buckets(self, &other.positive, 1.0, Some(&mut c), None, true)?;
430 } else {
431 outcome.custom_bounds_reconciled = true;
432 let bounds = intersect_custom_bounds(&self.custom_values, &other.custom_values);
433 let compensation: Vec<f64> = c.positive.iter().map(|&(_, c)| c).collect();
434 let (positive, positive_c) = add_custom_buckets_with_mismatches(
435 false,
436 &self.positive,
437 &self.custom_values,
438 &other.positive,
439 &other.custom_values,
440 Some(&compensation),
441 &bounds,
442 );
443 self.positive = positive;
444 c.positive = positive_c;
445 self.custom_values = bounds.clone();
446 c.custom_values = bounds;
447 }
448 return Ok((c, outcome));
449 }
450
451 let mut other_positive = None;
452 let mut other_negative = None;
453 if other.schema < self.schema {
454 (self.positive, c.positive) =
455 kahan_reduce_resolution(&self.positive, &c.positive, self.schema, other.schema);
456 (self.negative, c.negative) =
457 kahan_reduce_resolution(&self.negative, &c.negative, self.schema, other.schema);
458 self.schema = other.schema;
459 } else if other.schema > self.schema {
460 if !other.positive.is_empty() {
461 let zeros = zero_compensation(&other.positive);
462 other_positive = Some(kahan_reduce_resolution(
463 &other.positive,
464 &zeros,
465 other.schema,
466 self.schema,
467 ));
468 }
469 if !other.negative.is_empty() {
470 let zeros = zero_compensation(&other.negative);
471 other_negative = Some(kahan_reduce_resolution(
472 &other.negative,
473 &zeros,
474 other.schema,
475 self.schema,
476 ));
477 }
478 }
479 let (positive, positive_c) = match &other_positive {
480 Some((buckets, c)) => (buckets, Some(c)),
481 None => (&other.positive, None),
482 };
483 add_buckets(self, positive, 1.0, Some(&mut c), positive_c, true)?;
484 let (negative, negative_c) = match &other_negative {
485 Some((buckets, c)) => (buckets, Some(c)),
486 None => (&other.negative, None),
487 };
488 add_buckets(self, negative, 1.0, Some(&mut c), negative_c, false)?;
489 c.schema = self.schema;
490 c.zero_threshold = self.zero_threshold;
491 Ok((c, outcome))
492 }
493
494 pub(crate) fn new_compensation(&self) -> Self {
500 Self {
501 reset_hint: self.reset_hint,
502 start_timestamp: None,
503 schema: self.schema,
504 zero_threshold: self.zero_threshold,
505 zero_count: 0.0,
506 count: 0.0,
507 sum: 0.0,
508 positive: zero_compensation(&self.positive),
509 negative: if self.uses_custom_buckets() {
510 Vec::new()
511 } else {
512 zero_compensation(&self.negative)
513 },
514 custom_values: self.custom_values.clone(),
515 layout: None,
516 }
517 }
518
519 fn adjust_counter_reset(&mut self, other: &Self) -> bool {
521 use CounterResetHint::{Gauge, Unknown};
522 match (self.reset_hint, other.reset_hint) {
523 (mine, theirs) if mine == theirs => false,
524 (Gauge, _) => false,
525 (_, Gauge) => {
526 self.reset_hint = Gauge;
527 false
528 }
529 (Unknown, _) => false,
530 (_, Unknown) => {
531 self.reset_hint = Unknown;
532 false
533 }
534 _ => {
535 self.reset_hint = Unknown;
536 true
537 }
538 }
539 }
540
541 fn zero_count_for_larger_threshold(
545 &self,
546 mut larger_threshold: f64,
547 c: Option<&Self>,
548 ) -> Result<(f64, f64, f64)> {
549 let mut c_zero_count = c.map_or(0.0, |c| c.zero_count);
550 if larger_threshold == self.zero_threshold {
551 return Ok((self.zero_count, larger_threshold, c_zero_count));
552 }
553 'outer: loop {
554 let mut zero_count = self.zero_count;
556 for (position, &(idx, count)) in self.positive.iter().enumerate() {
557 let (lower, upper) = (self.bound(idx - 1)?, self.bound(idx)?);
558 if lower >= larger_threshold {
559 break;
560 }
561 (zero_count, c_zero_count) = kahan_inc(count, zero_count, c_zero_count);
562 if let Some(c) = c {
563 (zero_count, c_zero_count) =
564 kahan_inc(c.positive[position].1, zero_count, c_zero_count);
565 }
566 if upper > larger_threshold {
567 if count != 0.0 {
568 larger_threshold = upper;
569 }
570 break;
571 }
572 }
573 for (position, &(idx, count)) in self.negative.iter().enumerate() {
574 let (lower, upper) = (-self.bound(idx)?, -self.bound(idx - 1)?);
575 if upper <= -larger_threshold {
576 break;
577 }
578 (zero_count, c_zero_count) = kahan_inc(count, zero_count, c_zero_count);
579 if let Some(c) = c {
580 (zero_count, c_zero_count) =
581 kahan_inc(c.negative[position].1, zero_count, c_zero_count);
582 }
583 if lower < -larger_threshold {
584 if count != 0.0 {
585 larger_threshold = -lower;
586 continue 'outer;
587 }
588 break;
589 }
590 }
591 return Ok((zero_count, larger_threshold, c_zero_count));
592 }
593 }
594
595 fn trim_buckets_in_zero_bucket(&mut self, c: Option<&mut Self>) -> Result<()> {
597 let mut trimmed_positive = 0;
598 for &(idx, _) in &self.positive {
599 if self.bound(idx - 1)? >= self.zero_threshold {
600 break;
601 }
602 trimmed_positive += 1;
603 }
604 let mut trimmed_negative = 0;
605 for &(idx, _) in &self.negative {
606 if -self.bound(idx - 1)? <= -self.zero_threshold {
607 break;
608 }
609 trimmed_negative += 1;
610 }
611 for bucket in &mut self.positive[..trimmed_positive] {
612 bucket.1 = 0.0;
613 }
614 for bucket in &mut self.negative[..trimmed_negative] {
615 bucket.1 = 0.0;
616 }
617 match c {
618 Some(c) => {
619 for bucket in &mut c.positive[..trimmed_positive] {
620 bucket.1 = 0.0;
621 }
622 for bucket in &mut c.negative[..trimmed_negative] {
623 bucket.1 = 0.0;
624 }
625 compact_with(&mut self.positive, &mut c.positive);
626 compact_with(&mut self.negative, &mut c.negative);
627 }
628 None => self.compact(),
629 }
630 Ok(())
631 }
632
633 fn reconcile_zero_buckets(
636 &mut self,
637 other: &Self,
638 mut c: Option<&mut Self>,
639 ) -> Result<(f64, f64)> {
640 let mut other_zero_count = other.zero_count;
641 let mut other_zero_threshold = other.zero_threshold;
642 let mut other_c_zero_count = 0.0;
643 while other_zero_threshold != self.zero_threshold {
644 if self.zero_threshold > other_zero_threshold {
645 (other_zero_count, other_zero_threshold, other_c_zero_count) =
646 other.zero_count_for_larger_threshold(self.zero_threshold, None)?;
647 }
648 if other_zero_threshold > self.zero_threshold {
649 let (zero_count, threshold, c_zero_count) =
650 self.zero_count_for_larger_threshold(other_zero_threshold, c.as_deref())?;
651 self.zero_count = zero_count;
652 self.zero_threshold = threshold;
653 if let Some(c) = c.as_deref_mut() {
654 c.zero_count = c_zero_count;
655 }
656 self.trim_buckets_in_zero_bucket(c.as_deref_mut())?;
657 }
658 }
659 Ok((other_zero_count, other_c_zero_count))
660 }
661
662 fn bound(&self, idx: i32) -> Result<f64> {
663 bound(idx, self.schema, &self.custom_values)
664 }
665
666 pub(crate) fn start_timestamp_reset(
675 current_start: i64,
676 previous_start: i64,
677 previous_ts: i64,
678 current_ts: i64,
679 ) -> bool {
680 if current_start == 0 || current_start >= current_ts || current_start < previous_ts {
681 return false;
682 }
683 if current_start > previous_ts {
684 return true;
685 }
686
687 previous_start <= previous_ts && previous_start != 0 && previous_start != previous_ts
698 }
699
700 pub(crate) fn detect_counter_reset_shifted(
714 &self,
715 previous: &Self,
716 previous_ts: i64,
717 current_ts: i64,
718 offset_ms: i64,
719 ) -> bool {
720 Self::start_timestamp_reset(
721 self.start_timestamp.unwrap_or_default(),
722 previous.start_timestamp.unwrap_or_default(),
723 previous_ts.wrapping_sub(offset_ms),
724 current_ts.wrapping_sub(offset_ms),
725 ) || self.detect_reset(previous).unwrap_or(false)
726 }
727
728 pub(crate) fn detect_reset(&self, previous: &Self) -> Result<bool> {
729 match self.reset_hint {
730 CounterResetHint::CounterReset => return Ok(true),
731 CounterResetHint::NotCounterReset => return Ok(false),
732 _ => {}
733 }
734 if self.count < previous.count {
735 return Ok(true);
736 }
737 if self.uses_custom_buckets() {
738 if !previous.uses_custom_buckets() {
739 return Ok(true);
740 }
741 if self.custom_values != previous.custom_values {
742 return self.detect_reset_with_mismatched_custom_bounds(previous);
743 }
744 }
745 if self.schema > previous.schema || self.zero_threshold < previous.zero_threshold {
746 return Ok(true);
747 }
748 let (previous_zero_count, threshold, _) =
749 previous.zero_count_for_larger_threshold(self.zero_threshold, None)?;
750 if threshold != self.zero_threshold || self.zero_count < previous_zero_count {
751 return Ok(true);
752 }
753 for (current, earlier) in [
754 (&self.positive, &previous.positive),
755 (&self.negative, &previous.negative),
756 ] {
757 let current = iterate(current, self.schema, self.schema, self.zero_threshold)?;
758 let earlier = iterate(earlier, previous.schema, self.schema, self.zero_threshold)?;
759 if side_reset(¤t, &earlier) {
760 return Ok(true);
761 }
762 }
763 Ok(false)
764 }
765
766 fn detect_reset_with_mismatched_custom_bounds(&self, previous: &Self) -> Result<bool> {
769 let current_bounds = &self.custom_values;
770 let previous_bounds = &previous.custom_values;
771 let mut current = RollUp::new(self);
772 let mut earlier = RollUp::new(previous);
773 let (mut i, mut j) = (0, 0);
774 while i <= current_bounds.len() && j <= previous_bounds.len() {
775 let current_bound = current_bounds.get(i).copied().unwrap_or(f64::INFINITY);
776 let previous_bound = previous_bounds.get(j).copied().unwrap_or(f64::INFINITY);
777 if current_bound == previous_bound {
778 let current_sum = current.sum_up_to(current_bound)?;
779 let previous_sum = earlier.sum_up_to(current_bound)?;
780 if current_sum < previous_sum {
781 return Ok(true);
782 }
783 i += 1;
784 j += 1;
785 } else if current_bound < previous_bound {
786 i += 1;
787 } else {
788 j += 1;
789 }
790 }
791 Ok(false)
792 }
793
794 pub(crate) fn equals(&self, other: &Self) -> bool {
796 let same_side = |a: &Buckets, b: &Buckets| {
797 a.len() == b.len()
798 && a.iter()
799 .zip(b)
800 .all(|(a, b)| a.0 == b.0 && a.1.to_bits() == b.1.to_bits())
801 };
802 self.schema == other.schema
803 && self.count.to_bits() == other.count.to_bits()
804 && self.sum.to_bits() == other.sum.to_bits()
805 && (!self.uses_custom_buckets() || self.custom_values == other.custom_values)
806 && self.zero_threshold == other.zero_threshold
807 && self.zero_count.to_bits() == other.zero_count.to_bits()
808 && same_side(&self.negative, &other.negative)
809 && same_side(&self.positive, &other.positive)
810 && {
811 let ([positive, negative], [other_positive, other_negative]) =
812 (self.spans(), other.spans());
813 spans_match(&negative, &other_negative) && spans_match(&positive, &other_positive)
814 }
815 }
816}
817
818struct RollUp<'a> {
821 histogram: &'a FloatHistogram,
822 next: usize,
823 started: bool,
824 has_more: bool,
825}
826
827impl<'a> RollUp<'a> {
828 fn new(histogram: &'a FloatHistogram) -> Self {
829 Self {
830 histogram,
831 next: 0,
832 started: false,
833 has_more: false,
834 }
835 }
836
837 fn sum_up_to(&mut self, bound: f64) -> Result<f64> {
838 if self.started && !self.has_more {
839 return Ok(0.0);
840 }
841 self.started = true;
842 let mut sum = 0.0;
843 while let Some(&(idx, count)) = self.histogram.positive.get(self.next) {
844 if self.histogram.bound(idx)? > bound {
845 self.has_more = true;
846 return Ok(sum);
847 }
848 sum += count;
849 self.next += 1;
850 }
851 self.has_more = false;
852 Ok(sum)
853 }
854}
855
856fn incompatible_schema() -> DataFusionError {
857 DataFusionError::Execution(
858 "cannot apply this operation to histograms with exponential and custom buckets".into(),
859 )
860}
861
862fn check_schemas(a: &FloatHistogram, b: &FloatHistogram) -> Result<()> {
863 if a.uses_custom_buckets() != b.uses_custom_buckets() {
864 return Err(incompatible_schema());
865 }
866 Ok(())
867}
868
869fn iterate(side: &Buckets, schema: i32, target: i32, threshold: f64) -> Result<Buckets> {
872 let mut out: Buckets = Vec::with_capacity(side.len());
873 for &(idx, count) in side {
874 let target_idx = target_index(idx, schema, target);
875 match out.last_mut() {
876 Some(last) if schema != target && last.0 == target_idx => last.1 += count,
877 _ => out.push((target_idx, count)),
878 }
879 }
880 if target != CUSTOM_BUCKETS_SCHEMA && threshold != 0.0 {
882 let mut skipped = 0;
883 for &(idx, _) in &out {
884 if bound(idx, target, &[])? > threshold {
885 break;
886 }
887 skipped += 1;
888 }
889 out.drain(..skipped);
890 }
891 Ok(out)
892}
893
894fn target_index(idx: i32, schema: i32, target: i32) -> i32 {
896 if schema == target {
897 return idx;
898 }
899 ((idx - 1) >> (schema - target)) + 1
900}
901
902fn reduce_resolution(side: &Buckets, schema: i32, target: i32) -> Buckets {
904 let mut out: Buckets = Vec::with_capacity(side.len());
905 for &(idx, count) in side {
906 let target_idx = target_index(idx, schema, target);
907 match out.last_mut() {
908 Some(last) if last.0 == target_idx => last.1 += count,
909 _ => out.push((target_idx, count)),
910 }
911 }
912 out
913}
914
915fn kahan_reduce_resolution(
917 side: &Buckets,
918 compensation: &Buckets,
919 schema: i32,
920 target: i32,
921) -> (Buckets, Buckets) {
922 let mut out: Buckets = Vec::with_capacity(side.len());
923 let mut out_c: Buckets = Vec::with_capacity(side.len());
924 for (&(idx, count), &(_, c)) in side.iter().zip(compensation) {
925 let target_idx = target_index(idx, schema, target);
926 match (out.last_mut(), out_c.last_mut()) {
927 (Some(last), Some(last_c)) if last.0 == target_idx => {
928 (last.1, last_c.1) = kahan_inc(count, last.1, last_c.1);
929 (last.1, last_c.1) = kahan_inc(c, last.1, last_c.1);
930 }
931 _ => {
932 out.push((target_idx, count));
933 out_c.push((target_idx, c));
934 }
935 }
936 }
937 (out, out_c)
938}
939
940fn zero_compensation(side: &Buckets) -> Buckets {
941 side.iter().map(|&(idx, _)| (idx, 0.0)).collect()
942}
943
944fn compact_with(side: &mut Buckets, compensation: &mut Buckets) {
946 let keep: Vec<bool> = side
947 .iter()
948 .zip(compensation.iter())
949 .map(|(&(_, count), &(_, c))| count != 0.0 || c != 0.0)
950 .collect();
951 let mut flags = keep.iter();
952 side.retain(|_| *flags.next().unwrap());
953 let mut flags = keep.iter();
954 compensation.retain(|_| *flags.next().unwrap());
955}
956
957fn add_buckets(
960 h: &mut FloatHistogram,
961 other: &Buckets,
962 sign: f64,
963 c: Option<&mut FloatHistogram>,
964 other_c: Option<&Buckets>,
965 positive: bool,
966) -> Result<()> {
967 let exponential = !h.uses_custom_buckets();
968 let threshold = h.zero_threshold;
969 let schema = h.schema;
970 let side = if positive {
971 &mut h.positive
972 } else {
973 &mut h.negative
974 };
975 let mut side_c = c.map(|c| {
976 if positive {
977 &mut c.positive
978 } else {
979 &mut c.negative
980 }
981 });
982 let mut below_threshold = true;
983 let mut position = 0;
984 for (k, &(idx, count)) in other.iter().enumerate() {
985 if below_threshold && exponential && bound(idx, schema, &[])? <= threshold {
986 continue;
987 }
988 below_threshold = false;
989 let value = count * sign;
990 let value_c = other_c.map_or(0.0, |other_c| other_c[k].1) * sign;
991 while position < side.len() && side[position].0 < idx {
992 position += 1;
993 }
994 if position < side.len() && side[position].0 == idx {
995 match side_c.as_deref_mut() {
996 Some(side_c) => {
997 let (sum, comp) = (&mut side[position].1, &mut side_c[position].1);
998 (*sum, *comp) = kahan_inc(value, *sum, *comp);
999 if value_c != 0.0 {
1000 (*sum, *comp) = kahan_inc(value_c, *sum, *comp);
1001 }
1002 }
1003 None => side[position].1 += value,
1004 }
1005 } else {
1006 side.insert(position, (idx, value));
1007 if let Some(side_c) = side_c.as_deref_mut() {
1008 side_c.insert(position, (idx, value_c));
1009 }
1010 }
1011 }
1012 Ok(())
1013}
1014
1015fn intersect_custom_bounds(a: &[f64], b: &[f64]) -> Vec<f64> {
1017 let mut out = Vec::new();
1018 let (mut i, mut j) = (0, 0);
1019 while i < a.len() && j < b.len() {
1020 if a[i] == b[j] {
1021 out.push(a[i]);
1022 i += 1;
1023 j += 1;
1024 } else if a[i] < b[j] {
1025 i += 1;
1026 } else {
1027 j += 1;
1028 }
1029 }
1030 out
1031}
1032
1033fn add_custom_buckets_with_mismatches(
1037 subtract: bool,
1038 a: &Buckets,
1039 a_bounds: &[f64],
1040 b: &Buckets,
1041 b_bounds: &[f64],
1042 a_compensation: Option<&[f64]>,
1043 bounds: &[f64],
1044) -> (Buckets, Buckets) {
1045 let mut target = vec![0.0; bounds.len() + 1];
1046 let mut target_c = vec![0.0; bounds.len() + 1];
1047 let mut map = |side: &Buckets, side_bounds: &[f64], negate: bool, c: Option<&[f64]>| {
1048 let mut intersect_idx = 0;
1049 for (k, &(idx, value)) in side.iter().enumerate() {
1050 let mut target_idx = target.len() - 1;
1051 if let Some(&source_bound) = usize::try_from(idx).ok().and_then(|i| side_bounds.get(i))
1052 {
1053 while intersect_idx < bounds.len() {
1054 if bounds[intersect_idx] >= source_bound {
1055 target_idx = intersect_idx;
1056 break;
1057 }
1058 intersect_idx += 1;
1059 }
1060 }
1061 let (sum, comp) = (&mut target[target_idx], &mut target_c[target_idx]);
1062 if negate {
1063 (*sum, *comp) = kahan_inc(-value, *sum, *comp);
1064 } else {
1065 (*sum, *comp) = kahan_inc(value, *sum, *comp);
1066 if let Some(c) = c {
1067 (*sum, *comp) = kahan_inc(c[k], *sum, *comp);
1068 }
1069 }
1070 }
1071 };
1072 map(a, a_bounds, false, a_compensation);
1073 map(b, b_bounds, subtract, None);
1074 let mut out = Vec::new();
1075 let mut out_c = Vec::new();
1076 for (i, (&value, &c)) in target.iter().zip(&target_c).enumerate() {
1077 if value == 0.0 && c == 0.0 {
1078 continue;
1079 }
1080 out.push((i as i32, value));
1081 out_c.push((i as i32, c));
1082 }
1083 (out, out_c)
1084}
1085
1086fn side_reset(current: &Buckets, previous: &Buckets) -> bool {
1088 let mut current = current.iter().peekable();
1089 for &(idx, count) in previous {
1090 while current.next_if(|bucket| bucket.0 < idx).is_some() {}
1091 match current.peek() {
1092 Some(&&(current_idx, current_count)) if current_idx == idx => {
1093 if current_count < count {
1094 return true;
1095 }
1096 }
1097 _ if count != 0.0 => return true,
1098 _ => {}
1099 }
1100 }
1101 false
1102}
1103
1104fn side_from_view(side: BucketSideView<'_>) -> Result<Buckets> {
1105 let invalid = || DataFusionError::Execution("native histogram has an invalid layout".into());
1106 if side.span_offsets.len() != side.span_lengths.len() {
1107 return Err(invalid());
1108 }
1109 let mut out = Vec::with_capacity(side.buckets.len());
1110 let mut counts = side.buckets.iter();
1111 let mut idx = 0i64;
1112 for (&offset, &length) in side.span_offsets.iter().zip(side.span_lengths) {
1113 if length < 0 {
1114 return Err(invalid());
1115 }
1116 idx += i64::from(offset);
1117 for _ in 0..length {
1118 let count = *counts.next().ok_or_else(invalid)?;
1119 out.push((i32::try_from(idx).map_err(|_| invalid())?, count));
1120 idx += 1;
1121 }
1122 }
1123 if counts.next().is_some() {
1124 return Err(invalid());
1125 }
1126 Ok(out)
1127}
1128
1129fn canonical_spans(side: &Buckets) -> Vec<(i32, i32)> {
1131 let mut spans: Vec<(i32, i32)> = Vec::new();
1132 let mut next = None;
1133 for &(idx, _) in side {
1134 match next {
1135 Some(expected) if expected == idx => spans.last_mut().unwrap().1 += 1,
1136 _ => spans.push((next.map_or(idx, |expected| idx - expected), 1)),
1137 }
1138 next = Some(idx + 1);
1139 }
1140 spans
1141}
1142
1143fn spans_match(a: &[(i32, i32)], b: &[(i32, i32)]) -> bool {
1145 fn fold(spans: &[(i32, i32)]) -> Vec<(i32, i32)> {
1146 let mut out = Vec::new();
1147 let mut offset = 0;
1148 for &(span_offset, length) in spans {
1149 offset += span_offset;
1150 if length != 0 {
1151 out.push((offset, length));
1152 offset = 0;
1153 }
1154 }
1155 out
1156 }
1157 fold(a) == fold(b)
1158}