Skip to main content

promql/histogram_eval/
float_histogram.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Arithmetic on owned native histograms, following Prometheus `FloatHistogram`
16//! (`model/histogram/float_histogram.go`): `Add`, `KahanAdd`, `Sub`, `Mul`, `Div`, `Compact`,
17//! `CopyToSchema`, `DetectReset` and `Equals`, including zero bucket reconciliation, resolution
18//! reduction and the intersection of mismatched custom bounds.
19//!
20//! Each side is a list of `(bucket index, count)` sorted by index. Consecutive indices may share
21//! a span. An explicitly represented zero can affect the order of compensated additions when
22//! several indices map to one bucket.
23
24use std::collections::BTreeMap;
25use std::collections::btree_map::Entry;
26use std::ops::Range;
27
28use datafusion::error::{DataFusionError, Result};
29use datatypes::series::histogram::{
30    BucketSideView, CounterResetHint, HistogramBatchBuilder, HistogramView,
31};
32
33use crate::functions::kahan_inc;
34use crate::histogram_eval::native::{CUSTOM_BUCKETS_SCHEMA, bound};
35
36type Buckets = Vec<(i32, f64)>;
37// Only the signs are needed to restore the two zero operands bit for bit.
38type EmptySide = BTreeMap<i32, (bool, bool)>;
39
40/// Whether a fold keeps explicitly represented empty buckets.
41#[derive(Clone, Copy, PartialEq, Eq)]
42pub(crate) enum BucketLayout {
43    Preserve,
44    Compact,
45}
46
47/// Explicit zero pairs omitted from a range accumulator while a later sample can still rebin it.
48#[derive(Default)]
49pub(super) struct EmptyBuckets {
50    positive: EmptySide,
51    negative: EmptySide,
52}
53
54impl EmptyBuckets {
55    pub(super) fn take_from(
56        &mut self,
57        value: &mut FloatHistogram,
58        c: &mut FloatHistogram,
59        sample: &FloatHistogram,
60        all: bool,
61    ) {
62        for (empty, side, correction, incoming) in [
63            (
64                &mut self.positive,
65                &mut value.positive,
66                &mut c.positive,
67                &sample.positive,
68            ),
69            (
70                &mut self.negative,
71                &mut value.negative,
72                &mut c.negative,
73                &sample.negative,
74            ),
75        ] {
76            let range = if all {
77                0..side.len()
78            } else if let (Some(first), Some(last)) = (incoming.first(), incoming.last()) {
79                let first = target_index(first.0, sample.schema, value.schema);
80                let last = target_index(last.0, sample.schema, value.schema);
81                side.partition_point(|b| b.0 < first)..side.partition_point(|b| b.0 <= last)
82            } else {
83                continue;
84            };
85            compact_range(side, correction, range, |idx, count, residual| {
86                empty.insert(idx, (count.is_sign_negative(), residual.is_sign_negative()));
87            });
88        }
89    }
90
91    /// Restores the zeros needed for this addition and skips redundant zeros in the incoming sample.
92    /// Reducing the accumulator or widening its zero bucket visits the whole old layout.
93    pub(super) fn prepare_for_add(
94        &mut self,
95        value: &mut FloatHistogram,
96        c: &mut FloatHistogram,
97        sample: &mut FloatHistogram,
98    ) -> Result<()> {
99        if self.positive.is_empty() && self.negative.is_empty() {
100            return Ok(());
101        }
102        let restore_all = sample.schema < value.schema
103            || sample.zero_threshold > value.zero_threshold
104            || (sample.zero_threshold < value.zero_threshold
105                && sample
106                    .zero_count_for_larger_threshold(value.zero_threshold, None)?
107                    .1
108                    > value.zero_threshold);
109        let widen_input_to =
110            (sample.zero_threshold < value.zero_threshold).then_some(value.zero_threshold);
111        for (empty, side, correction, incoming) in [
112            (
113                &mut self.positive,
114                &mut value.positive,
115                &mut c.positive,
116                &mut sample.positive,
117            ),
118            (
119                &mut self.negative,
120                &mut value.negative,
121                &mut c.negative,
122                &mut sample.negative,
123            ),
124        ] {
125            if empty.is_empty() {
126                continue;
127            }
128            if restore_all {
129                merge_empty_buckets(side, correction, std::mem::take(empty).into_iter());
130                continue;
131            }
132            let original_len = incoming.len();
133            let restored =
134                take_touched_zeros(empty, incoming, sample.schema, value.schema, widen_input_to)?;
135            if incoming.len() != original_len {
136                sample.layout = None;
137                sample.start_timestamp = None;
138            }
139            merge_empty_buckets(side, correction, restored.into_iter());
140        }
141        Ok(())
142    }
143}
144
145/// Takes the deferred destinations needed for the add. Outside zero-bucket reconciliation, an
146/// all-zero source group can be omitted when it preserves the signs of the count and correction.
147fn take_touched_zeros(
148    empty: &mut EmptySide,
149    incoming: &mut Buckets,
150    schema: i32,
151    target_schema: i32,
152    mut widen_input_to: Option<f64>,
153) -> Result<Vec<(i32, (bool, bool))>> {
154    let mut restored = Vec::new();
155    let mut kept = 0;
156    let mut start = 0;
157    while start < incoming.len() {
158        let target = target_index(incoming[start].0, schema, target_schema);
159        let mut end = start + 1;
160        while end < incoming.len() && target_index(incoming[end].0, schema, target_schema) == target
161        {
162            end += 1;
163        }
164        if let Entry::Occupied(entry) = empty.entry(target) {
165            // From the first lower bound beyond the widened zero bucket, no later group is visited.
166            if let Some(threshold) = widen_input_to
167                && bound(incoming[start].0.saturating_sub(1), schema, &[])? >= threshold
168            {
169                widen_input_to = None;
170            }
171            let (negative_count, negative_correction) = *entry.get();
172            // A lone -0 preserves a -0 count. Reducing multiple buckets also adds their corrections.
173            let keeps_count_sign =
174                !negative_count || (end == start + 1 && incoming[start].1.is_sign_negative());
175            // A zero beside a nonzero can affect rounding when the source group is reduced.
176            if widen_input_to.is_none()
177                && !negative_correction
178                && keeps_count_sign
179                && incoming[start..end].iter().all(|&(_, count)| count == 0.0)
180            {
181                start = end;
182                continue;
183            }
184            restored.push(entry.remove_entry());
185        }
186        if kept != start {
187            incoming.copy_within(start..end, kept);
188        }
189        kept += end - start;
190        start = end;
191    }
192    incoming.truncate(kept);
193    Ok(restored)
194}
195
196fn merge_empty_buckets(
197    side: &mut Buckets,
198    correction: &mut Buckets,
199    restored: impl DoubleEndedIterator<Item = (i32, (bool, bool))> + ExactSizeIterator,
200) {
201    let mut live = side.len();
202    let mut dest = live + restored.len();
203    side.resize(dest, (0, 0.0));
204    correction.resize(dest, (0, 0.0));
205    // The two runs are ordered and disjoint. Filling from the end moves each live pair at most once.
206    for (idx, (negative_count, negative_residual)) in restored.rev() {
207        while live > 0 && side[live - 1].0 > idx {
208            live -= 1;
209            dest -= 1;
210            side[dest] = side[live];
211            correction[dest] = correction[live];
212        }
213        dest -= 1;
214        side[dest] = (idx, if negative_count { -0.0 } else { 0.0 });
215        correction[dest] = (idx, if negative_residual { -0.0 } else { 0.0 });
216    }
217}
218
219/// Counts owned histograms built from views on this thread, so a test can assert that a path
220/// borrows instead of copying; the values alone cannot tell the two apart.
221#[cfg(test)]
222pub(crate) mod copies {
223    use std::cell::Cell;
224
225    thread_local! {
226        /// Owned histograms [`super::FloatHistogram::try_from_view`] built on this thread.
227        static MATERIALIZED: Cell<usize> = const { Cell::new(0) };
228        static CLONED_BUCKETS: Cell<usize> = const { Cell::new(0) };
229    }
230
231    pub(crate) fn record_materialized() {
232        MATERIALIZED.with(|built| built.set(built.get() + 1));
233    }
234
235    /// Returns the count since the last call and resets it.
236    pub(crate) fn take_materialized() -> usize {
237        MATERIALIZED.with(|built| built.replace(0))
238    }
239
240    pub(super) fn record_cloned_buckets(count: usize) {
241        CLONED_BUCKETS.with(|total| total.set(total.get() + count));
242    }
243
244    pub(crate) fn take_cloned_buckets() -> usize {
245        CLONED_BUCKETS.replace(0)
246    }
247}
248
249/// A native histogram with absolute bucket counts.
250#[derive(Debug)]
251pub(crate) struct FloatHistogram {
252    pub(crate) reset_hint: CounterResetHint,
253    /// The start timestamp of the sample this histogram was read from, in milliseconds.
254    ///
255    /// GreptimeDB row metadata; Prometheus `FloatHistogram` has no such field. [`Self::try_from_view`]
256    /// reads it and [`Self::push_to`] writes it back. A histogram derived by an operation
257    /// ([`Self::add`], [`Self::kahan_add`], [`Self::sub`], [`Self::mul`], [`Self::div`],
258    /// [`Self::compact`], [`Self::copy_to_schema`], [`Self::empty_like`]) has none, and
259    /// [`Self::equals`] ignores it. The native range kernels read it to detect counter resets
260    /// ([`Self::detect_counter_reset_shifted`]) and to extrapolate `rate`/`increase` to a zero point.
261    pub(crate) start_timestamp: Option<i64>,
262    pub(crate) schema: i32,
263    pub(crate) zero_threshold: f64,
264    pub(crate) zero_count: f64,
265    pub(crate) count: f64,
266    pub(crate) sum: f64,
267    pub(crate) positive: Buckets,
268    pub(crate) negative: Buckets,
269    pub(crate) custom_values: Vec<f64>,
270    /// The positive and negative spans of a histogram read from a view, kept until its buckets
271    /// change, because Go `Equals` compares span layouts. Otherwise consecutive indices form one
272    /// span, the layout Go `Compact` produces.
273    layout: Option<[Vec<(i32, i32)>; 2]>,
274}
275
276/// What an addition or subtraction reports besides its result.
277#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
278pub(crate) struct AddOutcome {
279    /// One side was a counter reset and the other was not.
280    pub(crate) counter_reset_collision: bool,
281    /// Custom bounds differed and the result uses their intersection.
282    pub(crate) custom_bounds_reconciled: bool,
283}
284
285impl Clone for FloatHistogram {
286    fn clone(&self) -> Self {
287        #[cfg(test)]
288        copies::record_cloned_buckets(self.positive.len() + self.negative.len());
289        Self {
290            reset_hint: self.reset_hint,
291            start_timestamp: self.start_timestamp,
292            schema: self.schema,
293            zero_threshold: self.zero_threshold,
294            zero_count: self.zero_count,
295            count: self.count,
296            sum: self.sum,
297            positive: self.positive.clone(),
298            negative: self.negative.clone(),
299            custom_values: self.custom_values.clone(),
300            layout: self.layout.clone(),
301        }
302    }
303}
304
305impl FloatHistogram {
306    pub(crate) fn try_from_view(view: &HistogramView<'_>) -> Result<Self> {
307        #[cfg(test)]
308        copies::record_materialized();
309        Ok(Self {
310            reset_hint: view.reset_hint,
311            start_timestamp: view.start_timestamp,
312            schema: view.schema,
313            zero_threshold: view.zero_threshold,
314            zero_count: view.zero_count,
315            count: view.count,
316            sum: view.sum,
317            positive: side_from_view(view.positive)?,
318            negative: side_from_view(view.negative)?,
319            custom_values: view.custom_values.to_vec(),
320            layout: Some([view.positive, view.negative].map(|side| {
321                side.span_offsets
322                    .iter()
323                    .copied()
324                    .zip(side.span_lengths.iter().copied())
325                    .collect()
326            })),
327        })
328    }
329
330    /// Estimated heap bytes of the bucket lists, custom bounds and span layout, for memory
331    /// reservations; may overestimate slightly.
332    pub(crate) fn heap_bytes(&self) -> usize {
333        fn buckets(side: &Buckets) -> usize {
334            side.capacity() * std::mem::size_of::<(i32, f64)>()
335        }
336        let layout = self.layout.as_ref().map_or(0, |sides| {
337            std::mem::size_of::<[Vec<(i32, i32)>; 2]>().saturating_add(
338                sides
339                    .iter()
340                    .map(|side| side.capacity() * std::mem::size_of::<(i32, i32)>())
341                    .fold(0, usize::saturating_add),
342            )
343        });
344        buckets(&self.positive)
345            .saturating_add(buckets(&self.negative))
346            .saturating_add(
347                self.custom_values
348                    .capacity()
349                    .saturating_mul(std::mem::size_of::<f64>()),
350            )
351            .saturating_add(layout)
352    }
353
354    /// The spans of each side: the layout a view was read with, or the compacted layout of a
355    /// derived histogram.
356    pub(crate) fn spans(&self) -> [Vec<(i32, i32)>; 2] {
357        self.layout
358            .clone()
359            .unwrap_or_else(|| [&self.positive, &self.negative].map(canonical_spans))
360    }
361
362    /// Appends the histogram to `builder`; consecutive bucket indices share a span.
363    pub(crate) fn push_to(&self, builder: &mut HistogramBatchBuilder) -> Result<u32> {
364        let [positive_spans, negative_spans] = self.spans();
365        let (positive_offsets, positive_lengths): (Vec<_>, Vec<_>) =
366            positive_spans.into_iter().unzip();
367        let (negative_offsets, negative_lengths): (Vec<_>, Vec<_>) =
368            negative_spans.into_iter().unzip();
369        let positive_counts: Vec<f64> = self.positive.iter().map(|&(_, count)| count).collect();
370        let negative_counts: Vec<f64> = self.negative.iter().map(|&(_, count)| count).collect();
371        builder
372            .push(HistogramView {
373                schema: self.schema,
374                zero_threshold: self.zero_threshold,
375                sum: self.sum,
376                count: self.count,
377                zero_count: self.zero_count,
378                reset_hint: self.reset_hint,
379                start_timestamp: self.start_timestamp,
380                custom_values: &self.custom_values,
381                positive: BucketSideView {
382                    span_offsets: &positive_offsets,
383                    span_lengths: &positive_lengths,
384                    buckets: &positive_counts,
385                },
386                negative: BucketSideView {
387                    span_offsets: &negative_offsets,
388                    span_lengths: &negative_lengths,
389                    buckets: &negative_counts,
390                },
391            })
392            .map_err(|error| DataFusionError::External(Box::new(error)))
393    }
394
395    /// A histogram with no observations and the bucket layout of `self`, like Go's
396    /// `&FloatHistogram{Schema: h.Schema, CustomValues: h.CustomValues}`.
397    pub(crate) fn empty_like(&self) -> Self {
398        Self {
399            reset_hint: CounterResetHint::Unknown,
400            start_timestamp: None,
401            schema: self.schema,
402            zero_threshold: 0.0,
403            zero_count: 0.0,
404            count: 0.0,
405            sum: 0.0,
406            positive: Vec::new(),
407            negative: Vec::new(),
408            custom_values: self.custom_values.clone(),
409            layout: None,
410        }
411    }
412
413    pub(crate) fn uses_custom_buckets(&self) -> bool {
414        self.schema == CUSTOM_BUCKETS_SCHEMA
415    }
416
417    /// Go `Mul`.
418    pub(crate) fn mul(&mut self, factor: f64) {
419        self.start_timestamp = None;
420        self.zero_count *= factor;
421        self.count *= factor;
422        self.sum *= factor;
423        for (_, count) in self.positive.iter_mut().chain(self.negative.iter_mut()) {
424            *count *= factor;
425        }
426        if factor < 0.0 {
427            self.reset_hint = CounterResetHint::Gauge;
428        }
429    }
430
431    /// Go `Div`; dividing by zero removes every bucket.
432    pub(crate) fn div(&mut self, scalar: f64) {
433        self.start_timestamp = None;
434        self.zero_count /= scalar;
435        self.count /= scalar;
436        self.sum /= scalar;
437        if scalar == 0.0 {
438            self.positive.clear();
439            self.negative.clear();
440            self.layout = None;
441            return;
442        }
443        for (_, count) in self.positive.iter_mut().chain(self.negative.iter_mut()) {
444            *count /= scalar;
445        }
446        if scalar < 0.0 {
447            self.reset_hint = CounterResetHint::Gauge;
448        }
449    }
450
451    /// Go `HasOverflow`: whether any count, the sum or a custom bound is infinite.
452    pub(crate) fn has_overflow(&self) -> bool {
453        [self.zero_count, self.count, self.sum]
454            .into_iter()
455            .chain(
456                self.positive
457                    .iter()
458                    .chain(&self.negative)
459                    .map(|&(_, count)| count),
460            )
461            .chain(self.custom_values.iter().copied())
462            .any(f64::is_infinite)
463    }
464
465    /// Go `Compact(0)`: drops empty buckets.
466    pub(crate) fn compact(&mut self) {
467        self.start_timestamp = None;
468        self.positive.retain(|&(_, count)| count != 0.0);
469        self.negative.retain(|&(_, count)| count != 0.0);
470        self.layout = None;
471    }
472
473    /// Drops buckets whose value and correction are both zero, keeping the two lists aligned.
474    pub(super) fn compact_with_compensation(&mut self, c: &mut Self) {
475        compact_with(&mut self.positive, &mut c.positive);
476        if !self.uses_custom_buckets() {
477            compact_with(&mut self.negative, &mut c.negative);
478        }
479    }
480
481    /// Go `CopyToSchema`; `target` must not exceed the schema.
482    pub(crate) fn copy_to_schema(&self, target: i32) -> Result<Self> {
483        if target == self.schema {
484            return Ok(Self {
485                start_timestamp: None,
486                ..self.clone()
487            });
488        }
489        if self.uses_custom_buckets() || target == CUSTOM_BUCKETS_SCHEMA || target > self.schema {
490            return Err(incompatible_schema());
491        }
492        Ok(Self {
493            reset_hint: CounterResetHint::Unknown,
494            start_timestamp: None,
495            schema: target,
496            zero_threshold: self.zero_threshold,
497            zero_count: self.zero_count,
498            count: self.count,
499            sum: self.sum,
500            positive: reduce_resolution(&self.positive, self.schema, target),
501            negative: reduce_resolution(&self.negative, self.schema, target),
502            custom_values: Vec::new(),
503            layout: None,
504        })
505    }
506
507    /// Go `Add`.
508    pub(crate) fn add(&mut self, other: &Self) -> Result<AddOutcome> {
509        self.add_or_sub(other, false)
510    }
511
512    /// Go `Sub`. The `-` operator also sets the hint to gauge, which is left to the caller.
513    pub(crate) fn sub(&mut self, other: &Self) -> Result<AddOutcome> {
514        self.add_or_sub(other, true)
515    }
516
517    fn add_or_sub(&mut self, other: &Self, subtract: bool) -> Result<AddOutcome> {
518        check_schemas(self, other)?;
519        self.layout = None;
520        self.start_timestamp = None;
521        let mut outcome = AddOutcome {
522            counter_reset_collision: self.adjust_counter_reset(other),
523            custom_bounds_reconciled: false,
524        };
525        let sign = if subtract { -1.0 } else { 1.0 };
526        if !self.uses_custom_buckets() {
527            let (other_zero_count, _) = self.reconcile_zero_buckets(other, None)?;
528            if subtract {
529                self.zero_count -= other_zero_count;
530            } else {
531                self.zero_count += other_zero_count;
532            }
533        }
534        if subtract {
535            self.count -= other.count;
536            self.sum -= other.sum;
537        } else {
538            self.count += other.count;
539            self.sum += other.sum;
540        }
541
542        if self.uses_custom_buckets() {
543            if self.custom_values == other.custom_values {
544                add_buckets(self, &other.positive, sign, None, None, true)?;
545            } else {
546                outcome.custom_bounds_reconciled = true;
547                let bounds = intersect_custom_bounds(&self.custom_values, &other.custom_values);
548                (self.positive, _) = add_custom_buckets_with_mismatches(
549                    subtract,
550                    &self.positive,
551                    &self.custom_values,
552                    &other.positive,
553                    &other.custom_values,
554                    None,
555                    &bounds,
556                );
557                self.custom_values = bounds;
558            }
559            return Ok(outcome);
560        }
561
562        let reduced;
563        let (other_positive, other_negative) = if other.schema < self.schema {
564            self.positive = reduce_resolution(&self.positive, self.schema, other.schema);
565            self.negative = reduce_resolution(&self.negative, self.schema, other.schema);
566            self.schema = other.schema;
567            (&other.positive, &other.negative)
568        } else if other.schema > self.schema {
569            reduced = [&other.positive, &other.negative]
570                .map(|side| reduce_resolution(side, other.schema, self.schema));
571            (&reduced[0], &reduced[1])
572        } else {
573            (&other.positive, &other.negative)
574        };
575        add_buckets(self, other_positive, sign, None, None, true)?;
576        add_buckets(self, other_negative, sign, None, None, false)?;
577        Ok(outcome)
578    }
579
580    /// Go `KahanAdd`: adds `other` with compensation `c`, created when `None`, and returns the
581    /// updated compensation.
582    pub(crate) fn kahan_add(
583        &mut self,
584        other: &Self,
585        c: Option<Self>,
586    ) -> Result<(Self, AddOutcome)> {
587        self.kahan_add_with_layout(other, c, BucketLayout::Preserve)
588    }
589
590    /// A compact range fold may discard empty pairs when both operands share a schema.
591    pub(super) fn kahan_add_with_layout(
592        &mut self,
593        other: &Self,
594        c: Option<Self>,
595        layout: BucketLayout,
596    ) -> Result<(Self, AddOutcome)> {
597        debug_assert!(layout == BucketLayout::Preserve || self.schema == other.schema);
598        check_schemas(self, other)?;
599        self.layout = None;
600        self.start_timestamp = None;
601        let mut outcome = AddOutcome {
602            counter_reset_collision: self.adjust_counter_reset(other),
603            custom_bounds_reconciled: false,
604        };
605        let mut c = c.unwrap_or_else(|| self.new_compensation());
606        if !self.uses_custom_buckets() {
607            let (other_zero_count, other_c_zero_count) =
608                self.reconcile_zero_buckets(other, Some(&mut c))?;
609            (self.zero_count, c.zero_count) =
610                kahan_inc(other_zero_count, self.zero_count, c.zero_count);
611            (self.zero_count, c.zero_count) =
612                kahan_inc(other_c_zero_count, self.zero_count, c.zero_count);
613        }
614        (self.count, c.count) = kahan_inc(other.count, self.count, c.count);
615        (self.sum, c.sum) = kahan_inc(other.sum, self.sum, c.sum);
616
617        if self.uses_custom_buckets() {
618            if self.custom_values == other.custom_values {
619                add_buckets(
620                    self,
621                    &other.positive,
622                    1.0,
623                    Some((&mut c, layout)),
624                    None,
625                    true,
626                )?;
627            } else {
628                outcome.custom_bounds_reconciled = true;
629                let bounds = intersect_custom_bounds(&self.custom_values, &other.custom_values);
630                let compensation: Vec<f64> = c.positive.iter().map(|&(_, c)| c).collect();
631                let (positive, positive_c) = add_custom_buckets_with_mismatches(
632                    false,
633                    &self.positive,
634                    &self.custom_values,
635                    &other.positive,
636                    &other.custom_values,
637                    Some(&compensation),
638                    &bounds,
639                );
640                self.positive = positive;
641                c.positive = positive_c;
642                self.custom_values = bounds.clone();
643                c.custom_values = bounds;
644            }
645            return Ok((c, outcome));
646        }
647
648        let mut other_positive = None;
649        let mut other_negative = None;
650        if other.schema < self.schema {
651            (self.positive, c.positive) =
652                kahan_reduce_resolution(&self.positive, &c.positive, self.schema, other.schema);
653            (self.negative, c.negative) =
654                kahan_reduce_resolution(&self.negative, &c.negative, self.schema, other.schema);
655            self.schema = other.schema;
656        } else if other.schema > self.schema {
657            if !other.positive.is_empty() {
658                let zeros = zero_compensation(&other.positive);
659                other_positive = Some(kahan_reduce_resolution(
660                    &other.positive,
661                    &zeros,
662                    other.schema,
663                    self.schema,
664                ));
665            }
666            if !other.negative.is_empty() {
667                let zeros = zero_compensation(&other.negative);
668                other_negative = Some(kahan_reduce_resolution(
669                    &other.negative,
670                    &zeros,
671                    other.schema,
672                    self.schema,
673                ));
674            }
675        }
676        let (positive, positive_c) = match &other_positive {
677            Some((buckets, c)) => (buckets, Some(c)),
678            None => (&other.positive, None),
679        };
680        add_buckets(
681            self,
682            positive,
683            1.0,
684            Some((&mut c, layout)),
685            positive_c,
686            true,
687        )?;
688        let (negative, negative_c) = match &other_negative {
689            Some((buckets, c)) => (buckets, Some(c)),
690            None => (&other.negative, None),
691        };
692        add_buckets(
693            self,
694            negative,
695            1.0,
696            Some((&mut c, layout)),
697            negative_c,
698            false,
699        )?;
700        c.schema = self.schema;
701        c.zero_threshold = self.zero_threshold;
702        Ok((c, outcome))
703    }
704
705    /// Go `newCompensationHistogram`: the layout of `self` with zero counts.
706    ///
707    /// A compensated add must start from this, not from [`Self::empty_like`]: the Kahan update
708    /// indexes the compensation by the value's bucket positions.
709    pub(crate) fn new_compensation(&self) -> Self {
710        Self {
711            reset_hint: self.reset_hint,
712            start_timestamp: None,
713            schema: self.schema,
714            zero_threshold: self.zero_threshold,
715            zero_count: 0.0,
716            count: 0.0,
717            sum: 0.0,
718            positive: zero_compensation(&self.positive),
719            negative: if self.uses_custom_buckets() {
720                Vec::new()
721            } else {
722                zero_compensation(&self.negative)
723            },
724            custom_values: self.custom_values.clone(),
725            layout: None,
726        }
727    }
728
729    /// Go `adjustCounterReset`.
730    fn adjust_counter_reset(&mut self, other: &Self) -> bool {
731        use CounterResetHint::{Gauge, Unknown};
732        match (self.reset_hint, other.reset_hint) {
733            (mine, theirs) if mine == theirs => false,
734            (Gauge, _) => false,
735            (_, Gauge) => {
736                self.reset_hint = Gauge;
737                false
738            }
739            (Unknown, _) => false,
740            (_, Unknown) => {
741                self.reset_hint = Unknown;
742                false
743            }
744            _ => {
745                self.reset_hint = Unknown;
746                true
747            }
748        }
749    }
750
751    /// Go `zeroCountForLargerThreshold`: the zero count after widening the zero bucket to at
752    /// least `larger_threshold`, the threshold actually needed so no bucket straddles it, and
753    /// the Kahan compensation of the count.
754    fn zero_count_for_larger_threshold(
755        &self,
756        mut larger_threshold: f64,
757        c: Option<&Self>,
758    ) -> Result<(f64, f64, f64)> {
759        let mut c_zero_count = c.map_or(0.0, |c| c.zero_count);
760        if larger_threshold == self.zero_threshold {
761            return Ok((self.zero_count, larger_threshold, c_zero_count));
762        }
763        'outer: loop {
764            // Go keeps the compensation accumulated by an abandoned pass.
765            let mut zero_count = self.zero_count;
766            for (position, &(idx, count)) in self.positive.iter().enumerate() {
767                let (lower, upper) = (self.bound(idx - 1)?, self.bound(idx)?);
768                if lower >= larger_threshold {
769                    break;
770                }
771                (zero_count, c_zero_count) = kahan_inc(count, zero_count, c_zero_count);
772                if let Some(c) = c {
773                    (zero_count, c_zero_count) =
774                        kahan_inc(c.positive[position].1, zero_count, c_zero_count);
775                }
776                if upper > larger_threshold {
777                    if count != 0.0 {
778                        larger_threshold = upper;
779                    }
780                    break;
781                }
782            }
783            for (position, &(idx, count)) in self.negative.iter().enumerate() {
784                let (lower, upper) = (-self.bound(idx)?, -self.bound(idx - 1)?);
785                if upper <= -larger_threshold {
786                    break;
787                }
788                (zero_count, c_zero_count) = kahan_inc(count, zero_count, c_zero_count);
789                if let Some(c) = c {
790                    (zero_count, c_zero_count) =
791                        kahan_inc(c.negative[position].1, zero_count, c_zero_count);
792                }
793                if lower < -larger_threshold {
794                    if count != 0.0 {
795                        larger_threshold = -lower;
796                        continue 'outer;
797                    }
798                    break;
799                }
800            }
801            return Ok((zero_count, larger_threshold, c_zero_count));
802        }
803    }
804
805    /// Go `trimBucketsInZeroBucket`: empties the buckets inside the zero bucket, then compacts.
806    fn trim_buckets_in_zero_bucket(&mut self, c: Option<&mut Self>) -> Result<()> {
807        let mut trimmed_positive = 0;
808        for &(idx, _) in &self.positive {
809            if self.bound(idx - 1)? >= self.zero_threshold {
810                break;
811            }
812            trimmed_positive += 1;
813        }
814        let mut trimmed_negative = 0;
815        for &(idx, _) in &self.negative {
816            if -self.bound(idx - 1)? <= -self.zero_threshold {
817                break;
818            }
819            trimmed_negative += 1;
820        }
821        for bucket in &mut self.positive[..trimmed_positive] {
822            bucket.1 = 0.0;
823        }
824        for bucket in &mut self.negative[..trimmed_negative] {
825            bucket.1 = 0.0;
826        }
827        match c {
828            Some(c) => {
829                for bucket in &mut c.positive[..trimmed_positive] {
830                    bucket.1 = 0.0;
831                }
832                for bucket in &mut c.negative[..trimmed_negative] {
833                    bucket.1 = 0.0;
834                }
835                self.compact_with_compensation(c);
836            }
837            None => self.compact(),
838        }
839        Ok(())
840    }
841
842    /// Go `reconcileZeroBuckets`: widens whichever zero bucket is narrower until both match, and
843    /// returns the zero count of `other` for that threshold with its compensation.
844    fn reconcile_zero_buckets(
845        &mut self,
846        other: &Self,
847        mut c: Option<&mut Self>,
848    ) -> Result<(f64, f64)> {
849        let mut other_zero_count = other.zero_count;
850        let mut other_zero_threshold = other.zero_threshold;
851        let mut other_c_zero_count = 0.0;
852        while other_zero_threshold != self.zero_threshold {
853            if self.zero_threshold > other_zero_threshold {
854                (other_zero_count, other_zero_threshold, other_c_zero_count) =
855                    other.zero_count_for_larger_threshold(self.zero_threshold, None)?;
856            }
857            if other_zero_threshold > self.zero_threshold {
858                let (zero_count, threshold, c_zero_count) =
859                    self.zero_count_for_larger_threshold(other_zero_threshold, c.as_deref())?;
860                self.zero_count = zero_count;
861                self.zero_threshold = threshold;
862                if let Some(c) = c.as_deref_mut() {
863                    c.zero_count = c_zero_count;
864                }
865                self.trim_buckets_in_zero_bucket(c.as_deref_mut())?;
866            }
867        }
868        Ok((other_zero_count, other_c_zero_count))
869    }
870
871    fn bound(&self, idx: i32) -> Result<f64> {
872        bound(idx, self.schema, &self.custom_values)
873    }
874
875    /// Detects a counter reset from `previous` to `self`, by start timestamp (Prometheus
876    /// `isStartTimestampReset`) or by `detect_reset`. `previous_ts` and `current_ts` are sample
877    /// times already shifted by `offset_ms`, as `range_eval` hands them.
878    ///
879    /// The sample times are shifted back rather than the start timestamps forward: a start of `0`
880    /// means none was stated, and shifting could turn a real start into `0` (2500ms under
881    /// `offset -2.5s`). The subtraction wraps, like Go `int64` arithmetic.
882    pub(crate) fn detect_counter_reset_shifted(
883        &self,
884        previous: &Self,
885        previous_ts: i64,
886        current_ts: i64,
887        offset_ms: i64,
888    ) -> bool {
889        common_query::native_histogram::is_start_timestamp_reset(
890            previous.start_timestamp.unwrap_or_default(),
891            previous_ts.wrapping_sub(offset_ms),
892            self.start_timestamp.unwrap_or_default(),
893            current_ts.wrapping_sub(offset_ms),
894        ) || self.detect_reset(previous).unwrap_or(false)
895    }
896
897    pub(crate) fn detect_reset(&self, previous: &Self) -> Result<bool> {
898        match self.reset_hint {
899            CounterResetHint::CounterReset => return Ok(true),
900            CounterResetHint::NotCounterReset => return Ok(false),
901            _ => {}
902        }
903        if self.count < previous.count {
904            return Ok(true);
905        }
906        if self.uses_custom_buckets() {
907            if !previous.uses_custom_buckets() {
908                return Ok(true);
909            }
910            if self.custom_values != previous.custom_values {
911                return self.detect_reset_with_mismatched_custom_bounds(previous);
912            }
913        }
914        if self.schema > previous.schema || self.zero_threshold < previous.zero_threshold {
915            return Ok(true);
916        }
917        let (previous_zero_count, threshold, _) =
918            previous.zero_count_for_larger_threshold(self.zero_threshold, None)?;
919        if threshold != self.zero_threshold || self.zero_count < previous_zero_count {
920            return Ok(true);
921        }
922        for (current, earlier) in [
923            (&self.positive, &previous.positive),
924            (&self.negative, &previous.negative),
925        ] {
926            let current = iterate(current, self.schema, self.schema, self.zero_threshold)?;
927            let earlier = iterate(earlier, previous.schema, self.schema, self.zero_threshold)?;
928            if side_reset(&current, &earlier) {
929                return Ok(true);
930            }
931        }
932        Ok(false)
933    }
934
935    /// Go `detectResetWithMismatchedCustomBounds`: compares the counts rolled up to each bound
936    /// both histograms share.
937    fn detect_reset_with_mismatched_custom_bounds(&self, previous: &Self) -> Result<bool> {
938        let current_bounds = &self.custom_values;
939        let previous_bounds = &previous.custom_values;
940        let mut current = RollUp::new(self);
941        let mut earlier = RollUp::new(previous);
942        let (mut i, mut j) = (0, 0);
943        while i <= current_bounds.len() && j <= previous_bounds.len() {
944            let current_bound = current_bounds.get(i).copied().unwrap_or(f64::INFINITY);
945            let previous_bound = previous_bounds.get(j).copied().unwrap_or(f64::INFINITY);
946            if current_bound == previous_bound {
947                let current_sum = current.sum_up_to(current_bound)?;
948                let previous_sum = earlier.sum_up_to(current_bound)?;
949                if current_sum < previous_sum {
950                    return Ok(true);
951                }
952                i += 1;
953                j += 1;
954            } else if current_bound < previous_bound {
955                i += 1;
956            } else {
957                j += 1;
958            }
959        }
960        Ok(false)
961    }
962
963    /// Go `Equals`: bit equality of counts and of the bucket layout.
964    pub(crate) fn equals(&self, other: &Self) -> bool {
965        let same_side = |a: &Buckets, b: &Buckets| {
966            a.len() == b.len()
967                && a.iter()
968                    .zip(b)
969                    .all(|(a, b)| a.0 == b.0 && a.1.to_bits() == b.1.to_bits())
970        };
971        self.schema == other.schema
972            && self.count.to_bits() == other.count.to_bits()
973            && self.sum.to_bits() == other.sum.to_bits()
974            && (!self.uses_custom_buckets() || self.custom_values == other.custom_values)
975            && self.zero_threshold == other.zero_threshold
976            && self.zero_count.to_bits() == other.zero_count.to_bits()
977            && same_side(&self.negative, &other.negative)
978            && same_side(&self.positive, &other.positive)
979            && {
980                let ([positive, negative], [other_positive, other_negative]) =
981                    (self.spans(), other.spans());
982                spans_match(&negative, &other_negative) && spans_match(&positive, &other_positive)
983            }
984    }
985}
986
987/// The rolling sum of custom buckets up to a bound, as Go's `rollupSumForBound` closure keeps
988/// it across calls.
989struct RollUp<'a> {
990    histogram: &'a FloatHistogram,
991    next: usize,
992    started: bool,
993    has_more: bool,
994}
995
996impl<'a> RollUp<'a> {
997    fn new(histogram: &'a FloatHistogram) -> Self {
998        Self {
999            histogram,
1000            next: 0,
1001            started: false,
1002            has_more: false,
1003        }
1004    }
1005
1006    fn sum_up_to(&mut self, bound: f64) -> Result<f64> {
1007        if self.started && !self.has_more {
1008            return Ok(0.0);
1009        }
1010        self.started = true;
1011        let mut sum = 0.0;
1012        while let Some(&(idx, count)) = self.histogram.positive.get(self.next) {
1013            if self.histogram.bound(idx)? > bound {
1014                self.has_more = true;
1015                return Ok(sum);
1016            }
1017            sum += count;
1018            self.next += 1;
1019        }
1020        self.has_more = false;
1021        Ok(sum)
1022    }
1023}
1024
1025fn incompatible_schema() -> DataFusionError {
1026    DataFusionError::Execution(
1027        "cannot apply this operation to histograms with exponential and custom buckets".into(),
1028    )
1029}
1030
1031fn check_schemas(a: &FloatHistogram, b: &FloatHistogram) -> Result<()> {
1032    if a.uses_custom_buckets() != b.uses_custom_buckets() {
1033        return Err(incompatible_schema());
1034    }
1035    Ok(())
1036}
1037
1038/// Go `floatBucketIterator`: the buckets of `side` merged down to `target`, without the leading
1039/// ones whose upper bound is at most `threshold`.
1040fn iterate(side: &Buckets, schema: i32, target: i32, threshold: f64) -> Result<Buckets> {
1041    let mut out: Buckets = Vec::with_capacity(side.len());
1042    for &(idx, count) in side {
1043        let target_idx = target_index(idx, schema, target);
1044        match out.last_mut() {
1045            Some(last) if schema != target && last.0 == target_idx => last.1 += count,
1046            _ => out.push((target_idx, count)),
1047        }
1048    }
1049    // Go starts skipping only for a nonzero start value.
1050    if target != CUSTOM_BUCKETS_SCHEMA && threshold != 0.0 {
1051        let mut skipped = 0;
1052        for &(idx, _) in &out {
1053            if bound(idx, target, &[])? > threshold {
1054                break;
1055            }
1056            skipped += 1;
1057        }
1058        out.drain(..skipped);
1059    }
1060    Ok(out)
1061}
1062
1063/// Go `targetIdx`.
1064fn target_index(idx: i32, schema: i32, target: i32) -> i32 {
1065    if schema == target {
1066        return idx;
1067    }
1068    ((idx - 1) >> (schema - target)) + 1
1069}
1070
1071/// Go `reduceResolution` without delta encoding.
1072fn reduce_resolution(side: &Buckets, schema: i32, target: i32) -> Buckets {
1073    let mut out: Buckets = Vec::with_capacity(side.len());
1074    for &(idx, count) in side {
1075        let target_idx = target_index(idx, schema, target);
1076        match out.last_mut() {
1077            Some(last) if last.0 == target_idx => last.1 += count,
1078            _ => out.push((target_idx, count)),
1079        }
1080    }
1081    out
1082}
1083
1084/// Go `kahanReduceResolution`.
1085fn kahan_reduce_resolution(
1086    side: &Buckets,
1087    compensation: &Buckets,
1088    schema: i32,
1089    target: i32,
1090) -> (Buckets, Buckets) {
1091    let mut out: Buckets = Vec::with_capacity(side.len());
1092    let mut out_c: Buckets = Vec::with_capacity(side.len());
1093    for (&(idx, count), &(_, c)) in side.iter().zip(compensation) {
1094        let target_idx = target_index(idx, schema, target);
1095        match (out.last_mut(), out_c.last_mut()) {
1096            (Some(last), Some(last_c)) if last.0 == target_idx => {
1097                (last.1, last_c.1) = kahan_inc(count, last.1, last_c.1);
1098                (last.1, last_c.1) = kahan_inc(c, last.1, last_c.1);
1099            }
1100            _ => {
1101                out.push((target_idx, count));
1102                out_c.push((target_idx, c));
1103            }
1104        }
1105    }
1106    (out, out_c)
1107}
1108
1109fn zero_compensation(side: &Buckets) -> Buckets {
1110    side.iter().map(|&(idx, _)| (idx, 0.0)).collect()
1111}
1112
1113/// Go `kahanCompact(0)`: drops the buckets whose count and compensation are both zero.
1114fn compact_with(side: &mut Buckets, compensation: &mut Buckets) {
1115    compact_range(side, compensation, 0..side.len(), |_, _, _| {});
1116}
1117
1118fn compact_range(
1119    side: &mut Buckets,
1120    compensation: &mut Buckets,
1121    range: Range<usize>,
1122    mut on_empty: impl FnMut(i32, f64, f64),
1123) {
1124    let mut kept = range.start;
1125    let end = range.end;
1126    for i in range {
1127        if side[i].1 != 0.0 || compensation[i].1 != 0.0 {
1128            side[kept] = side[i];
1129            compensation[kept] = compensation[i];
1130            kept += 1;
1131        } else {
1132            on_empty(side[i].0, side[i].1, compensation[i].1);
1133        }
1134    }
1135    if kept < end {
1136        side.drain(kept..end);
1137        compensation.drain(kept..end);
1138    }
1139}
1140
1141/// Go `addBuckets` and `kahanAddBuckets`: adds `sign * other` to one side of `h`, inserting the
1142/// buckets `h` lacks. Leading buckets of `other` inside the zero bucket are skipped.
1143fn add_buckets(
1144    h: &mut FloatHistogram,
1145    other: &Buckets,
1146    sign: f64,
1147    c: Option<(&mut FloatHistogram, BucketLayout)>,
1148    other_c: Option<&Buckets>,
1149    positive: bool,
1150) -> Result<()> {
1151    let exponential = !h.uses_custom_buckets();
1152    let threshold = h.zero_threshold;
1153    let schema = h.schema;
1154    let side = if positive {
1155        &mut h.positive
1156    } else {
1157        &mut h.negative
1158    };
1159    let (c, layout) = c.unzip();
1160    let compact = layout == Some(BucketLayout::Compact);
1161    let mut side_c = c.map(|c| {
1162        if positive {
1163            &mut c.positive
1164        } else {
1165            &mut c.negative
1166        }
1167    });
1168    let mut below_threshold = true;
1169    let mut position = 0;
1170    let mut cancelled = false;
1171    for (k, &(idx, count)) in other.iter().enumerate() {
1172        if below_threshold && exponential && bound(idx, schema, &[])? <= threshold {
1173            continue;
1174        }
1175        below_threshold = false;
1176        let value = count * sign;
1177        let value_c = other_c.map_or(0.0, |other_c| other_c[k].1) * sign;
1178        if compact && value == 0.0 && value_c == 0.0 {
1179            continue;
1180        }
1181        while position < side.len() && side[position].0 < idx {
1182            position += 1;
1183        }
1184        if position < side.len() && side[position].0 == idx {
1185            match side_c.as_deref_mut() {
1186                Some(side_c) => {
1187                    let (sum, comp) = (&mut side[position].1, &mut side_c[position].1);
1188                    (*sum, *comp) = kahan_inc(value, *sum, *comp);
1189                    if value_c != 0.0 {
1190                        (*sum, *comp) = kahan_inc(value_c, *sum, *comp);
1191                    }
1192                    cancelled |= compact && *sum == 0.0 && *comp == 0.0;
1193                }
1194                None => side[position].1 += value,
1195            }
1196        } else {
1197            side.insert(position, (idx, value));
1198            if let Some(side_c) = side_c.as_deref_mut() {
1199                side_c.insert(position, (idx, value_c));
1200            }
1201        }
1202    }
1203    // Remove all cancellations together so a dense subtraction moves each surviving bucket once.
1204    if cancelled && let Some(side_c) = side_c {
1205        compact_with(side, side_c);
1206    }
1207    Ok(())
1208}
1209
1210/// Go `intersectCustomBucketBounds`.
1211fn intersect_custom_bounds(a: &[f64], b: &[f64]) -> Vec<f64> {
1212    let mut out = Vec::new();
1213    let (mut i, mut j) = (0, 0);
1214    while i < a.len() && j < b.len() {
1215        if a[i] == b[j] {
1216            out.push(a[i]);
1217            i += 1;
1218            j += 1;
1219        } else if a[i] < b[j] {
1220            i += 1;
1221        } else {
1222            j += 1;
1223        }
1224    }
1225    out
1226}
1227
1228/// Go `addCustomBucketsWithMismatches`: maps both sides onto the intersected bounds, adding
1229/// with Kahan summation, and drops buckets left empty. Returns the buckets and their
1230/// compensation.
1231fn add_custom_buckets_with_mismatches(
1232    subtract: bool,
1233    a: &Buckets,
1234    a_bounds: &[f64],
1235    b: &Buckets,
1236    b_bounds: &[f64],
1237    a_compensation: Option<&[f64]>,
1238    bounds: &[f64],
1239) -> (Buckets, Buckets) {
1240    let mut target = vec![0.0; bounds.len() + 1];
1241    let mut target_c = vec![0.0; bounds.len() + 1];
1242    let mut map = |side: &Buckets, side_bounds: &[f64], negate: bool, c: Option<&[f64]>| {
1243        let mut intersect_idx = 0;
1244        for (k, &(idx, value)) in side.iter().enumerate() {
1245            let mut target_idx = target.len() - 1;
1246            if let Some(&source_bound) = usize::try_from(idx).ok().and_then(|i| side_bounds.get(i))
1247            {
1248                while intersect_idx < bounds.len() {
1249                    if bounds[intersect_idx] >= source_bound {
1250                        target_idx = intersect_idx;
1251                        break;
1252                    }
1253                    intersect_idx += 1;
1254                }
1255            }
1256            let (sum, comp) = (&mut target[target_idx], &mut target_c[target_idx]);
1257            if negate {
1258                (*sum, *comp) = kahan_inc(-value, *sum, *comp);
1259            } else {
1260                (*sum, *comp) = kahan_inc(value, *sum, *comp);
1261                if let Some(c) = c {
1262                    (*sum, *comp) = kahan_inc(c[k], *sum, *comp);
1263                }
1264            }
1265        }
1266    };
1267    map(a, a_bounds, false, a_compensation);
1268    map(b, b_bounds, subtract, None);
1269    let mut out = Vec::new();
1270    let mut out_c = Vec::new();
1271    for (i, (&value, &c)) in target.iter().zip(&target_c).enumerate() {
1272        if value == 0.0 && c == 0.0 {
1273            continue;
1274        }
1275        out.push((i as i32, value));
1276        out_c.push((i as i32, c));
1277    }
1278    (out, out_c)
1279}
1280
1281/// Go `detectReset` over two sides with matching indices.
1282fn side_reset(current: &Buckets, previous: &Buckets) -> bool {
1283    let mut current = current.iter().peekable();
1284    for &(idx, count) in previous {
1285        while current.next_if(|bucket| bucket.0 < idx).is_some() {}
1286        match current.peek() {
1287            Some(&&(current_idx, current_count)) if current_idx == idx => {
1288                if current_count < count {
1289                    return true;
1290                }
1291            }
1292            _ if count != 0.0 => return true,
1293            _ => {}
1294        }
1295    }
1296    false
1297}
1298
1299fn side_from_view(side: BucketSideView<'_>) -> Result<Buckets> {
1300    let invalid = || DataFusionError::Execution("native histogram has an invalid layout".into());
1301    if side.span_offsets.len() != side.span_lengths.len() {
1302        return Err(invalid());
1303    }
1304    let mut out = Vec::with_capacity(side.buckets.len());
1305    let mut counts = side.buckets.iter();
1306    let mut idx = 0i64;
1307    for (&offset, &length) in side.span_offsets.iter().zip(side.span_lengths) {
1308        if length < 0 {
1309            return Err(invalid());
1310        }
1311        idx += i64::from(offset);
1312        for _ in 0..length {
1313            let count = *counts.next().ok_or_else(invalid)?;
1314            out.push((i32::try_from(idx).map_err(|_| invalid())?, count));
1315            idx += 1;
1316        }
1317    }
1318    if counts.next().is_some() {
1319        return Err(invalid());
1320    }
1321    Ok(out)
1322}
1323
1324/// Spans with one span per run of consecutive indices.
1325fn canonical_spans(side: &Buckets) -> Vec<(i32, i32)> {
1326    let mut spans: Vec<(i32, i32)> = Vec::new();
1327    let mut next = None;
1328    for &(idx, _) in side {
1329        match next {
1330            Some(expected) if expected == idx => spans.last_mut().unwrap().1 += 1,
1331            _ => spans.push((next.map_or(idx, |expected| idx - expected), 1)),
1332        }
1333        next = Some(idx + 1);
1334    }
1335    spans
1336}
1337
1338/// Go `spansMatch`: equal layouts once zero-length spans are folded into the next span.
1339fn spans_match(a: &[(i32, i32)], b: &[(i32, i32)]) -> bool {
1340    fn fold(spans: &[(i32, i32)]) -> Vec<(i32, i32)> {
1341        let mut out = Vec::new();
1342        let mut offset = 0;
1343        for &(span_offset, length) in spans {
1344            offset += span_offset;
1345            if length != 0 {
1346                out.push((offset, length));
1347                offset = 0;
1348            }
1349        }
1350        out
1351    }
1352    fold(a) == fold(b)
1353}