Skip to main content

promql/histogram_eval/
native.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//! Prometheus `HistogramQuantile`, `HistogramFraction` and the `histogramVariance` estimate over
16//! one native histogram, with the bucket iteration of `model/histogram`.
17
18use datafusion::error::{DataFusionError, Result};
19use datatypes::series::histogram::{BucketSideView, HistogramView};
20
21use crate::functions::kahan_inc;
22use crate::go_format::format_float_g;
23use crate::histogram_eval::bounds::EXPONENTIAL_BOUNDS;
24
25pub(super) const CUSTOM_BUCKETS_SCHEMA: i32 = -53;
26
27#[derive(Debug, Clone, Copy)]
28pub(super) struct NativeBucket {
29    lower: f64,
30    upper: f64,
31    count: f64,
32    /// The bucket's index on its side; meaningless for the zero bucket.
33    index: i32,
34}
35
36/// The buckets of `h` from the lowest to the highest, or the reverse: negative buckets, the zero
37/// bucket when it has observations, then positive buckets (Go `AllBucketIterator` and
38/// `AllReverseBucketIterator`). Buckets overlapping the zero bucket are clipped to it.
39pub(super) fn all_buckets(
40    h: &HistogramView<'_>,
41    reverse: bool,
42    out: &mut Vec<NativeBucket>,
43) -> Result<()> {
44    out.clear();
45    let (low, high) = if reverse {
46        (h.positive, h.negative)
47    } else {
48        (h.negative, h.positive)
49    };
50    // The first side runs from its highest index down, the second from its lowest index up.
51    side(h, low, reverse, out)?;
52    out.reverse();
53    if h.zero_count > 0.0 {
54        if h.schema == CUSTOM_BUCKETS_SCHEMA {
55            return Err(DataFusionError::Execution(
56                "histograms with custom buckets have no zero bucket".into(),
57            ));
58        }
59        out.push(NativeBucket {
60            lower: -h.zero_threshold,
61            upper: h.zero_threshold,
62            count: h.zero_count,
63            index: 0,
64        });
65    }
66    side(h, high, !reverse, out)?;
67    for bucket in out.iter_mut() {
68        if bucket.upper < 0.0 && bucket.upper > -h.zero_threshold {
69            bucket.upper = -h.zero_threshold;
70        } else if bucket.lower > 0.0 && bucket.lower < h.zero_threshold {
71            bucket.lower = h.zero_threshold;
72        }
73    }
74    Ok(())
75}
76
77/// Appends the buckets of one side by increasing index.
78fn side(
79    h: &HistogramView<'_>,
80    side: BucketSideView<'_>,
81    positive: bool,
82    out: &mut Vec<NativeBucket>,
83) -> Result<()> {
84    if side.span_offsets.len() != side.span_lengths.len() {
85        return Err(invalid_layout());
86    }
87    let mut counts = side.buckets.iter();
88    let mut index = 0i64;
89    for (&offset, &length) in side.span_offsets.iter().zip(side.span_lengths) {
90        if length < 0 {
91            return Err(invalid_layout());
92        }
93        index += i64::from(offset);
94        for _ in 0..length {
95            let count = *counts.next().ok_or_else(invalid_layout)?;
96            let idx = i32::try_from(index).map_err(|_| invalid_layout())?;
97            out.push(bucket(h, idx, count, positive)?);
98            index += 1;
99        }
100    }
101    if counts.next().is_some() {
102        return Err(invalid_layout());
103    }
104    Ok(())
105}
106
107fn bucket(h: &HistogramView<'_>, idx: i32, count: f64, positive: bool) -> Result<NativeBucket> {
108    let bound = |idx: i32| bound(idx, h.schema, h.custom_values);
109    Ok(if positive {
110        NativeBucket {
111            lower: bound(idx - 1)?,
112            upper: bound(idx)?,
113            count,
114            index: idx,
115        }
116    } else {
117        NativeBucket {
118            lower: -bound(idx)?,
119            upper: -bound(idx - 1)?,
120            count,
121            index: idx,
122        }
123    })
124}
125
126/// Go `FloatHistogram.String`, the form `count_values` writes a histogram value in: the count and
127/// sum, then the buckets holding observations from the lowest up -- negative, zero, positive --
128/// each as `[lower,upper):count` with its bounds' inclusiveness, every number in Go's `%g`.
129/// Unlike [`all_buckets`], the buckets keep the bounds their index gives, unclipped by the zero
130/// bucket.
131pub(super) fn go_string(h: &HistogramView<'_>) -> Result<String> {
132    let mut text = format!(
133        "{{count:{}, sum:{}",
134        format_float_g(h.count),
135        format_float_g(h.sum)
136    );
137    let custom = h.schema == CUSTOM_BUCKETS_SCHEMA;
138    let mut buckets = Vec::new();
139    side(h, h.negative, false, &mut buckets)?;
140    for bucket in buckets.iter().rev().filter(|bucket| bucket.count != 0.0) {
141        push_bucket(&mut text, bucket, custom);
142    }
143    if h.zero_count != 0.0 {
144        if custom {
145            return Err(DataFusionError::Execution(
146                "histograms with custom buckets have no zero bucket".into(),
147            ));
148        }
149        text.push_str(&format!(
150            ", [{},{}]:{}",
151            format_float_g(-h.zero_threshold),
152            format_float_g(h.zero_threshold),
153            format_float_g(h.zero_count)
154        ));
155    }
156    buckets.clear();
157    side(h, h.positive, true, &mut buckets)?;
158    for bucket in buckets.iter().filter(|bucket| bucket.count != 0.0) {
159        push_bucket(&mut text, bucket, custom);
160    }
161    text.push('}');
162    Ok(text)
163}
164
165/// Go `Bucket.String`, with the inclusiveness `baseBucketIterator.at` gives the bucket.
166fn push_bucket(text: &mut String, bucket: &NativeBucket, custom: bool) {
167    let (lower_inclusive, upper_inclusive) = if custom {
168        (bucket.index == 0, true)
169    } else {
170        (bucket.lower < 0.0, bucket.upper > 0.0)
171    };
172    text.push_str(&format!(
173        ", {}{},{}{}:{}",
174        if lower_inclusive { '[' } else { '(' },
175        format_float_g(bucket.lower),
176        format_float_g(bucket.upper),
177        if upper_inclusive { ']' } else { ')' },
178        format_float_g(bucket.count)
179    ));
180}
181
182/// Go `getBound`.
183pub(super) fn bound(idx: i32, schema: i32, custom_values: &[f64]) -> Result<f64> {
184    if schema == CUSTOM_BUCKETS_SCHEMA {
185        let len = custom_values.len() as i64;
186        return match i64::from(idx) {
187            -1 => Ok(f64::NEG_INFINITY),
188            i if i == len => Ok(f64::INFINITY),
189            i if (0..len).contains(&i) => Ok(custom_values[i as usize]),
190            _ => Err(invalid_layout()),
191        };
192    }
193    if schema < 0 {
194        if schema < -4 {
195            return Err(invalid_layout());
196        }
197        let exp = i64::from(idx) << -schema;
198        if exp == 1024 {
199            // The last bucket of finite values; its computed bound would overflow to +Inf,
200            // which Go reserves for the bucket of infinite observations.
201            return Ok(f64::MAX);
202        }
203        return Ok(ldexp(1.0, exp));
204    }
205    // Go's table entries are not all correctly rounded, and bounds become zero thresholds that
206    // are compared exactly, so the table is used rather than computing `2^(idx / 2^schema)`.
207    let bounds = EXPONENTIAL_BOUNDS
208        .get(schema as usize)
209        .ok_or_else(invalid_layout)?;
210    let frac = bounds[(idx & ((1 << schema) - 1)) as usize];
211    let exp = i64::from(idx >> schema) + 1;
212    if frac == 0.5 && exp == 1025 {
213        return Ok(f64::MAX);
214    }
215    Ok(ldexp(frac, exp))
216}
217
218/// Go `math.Ldexp` for a positive normal `frac`.
219fn ldexp(frac: f64, exp: i64) -> f64 {
220    let bits = frac.to_bits();
221    let exp = exp + ((bits >> 52) & 0x7FF) as i64 - 1023;
222    if exp < -1075 {
223        return 0.0;
224    }
225    if exp > 1023 {
226        return f64::INFINITY;
227    }
228    let (exp, scale) = if exp < -1022 {
229        (exp + 53, 1.0 / (1u64 << 53) as f64)
230    } else {
231        (exp, 1.0)
232    };
233    scale * f64::from_bits((bits & !(0x7FF << 52)) | (((exp + 1023) as u64) << 52))
234}
235
236fn invalid_layout() -> DataFusionError {
237    DataFusionError::Execution("native histogram has an invalid bucket layout".into())
238}
239
240/// Prometheus `HistogramQuantile`.
241pub(super) fn quantile(
242    q: f64,
243    h: &HistogramView<'_>,
244    buckets: &mut Vec<NativeBucket>,
245) -> Result<f64> {
246    if q < 0.0 {
247        return Ok(f64::NEG_INFINITY);
248    }
249    if q > 1.0 {
250        return Ok(f64::INFINITY);
251    }
252    if h.count == 0.0 || q.is_nan() {
253        return Ok(f64::NAN);
254    }
255    let custom = h.schema == CUSTOM_BUCKETS_SCHEMA;
256    let forward = h.sum.is_nan() || q < 0.5;
257    all_buckets(h, !forward, buckets)?;
258    let mut rank = if forward {
259        q * h.count
260    } else {
261        (1.0 - q) * h.count
262    };
263    // Go keeps the last bucket visited, empty or not, and a zero bucket when there is none.
264    let mut bucket = NativeBucket {
265        lower: 0.0,
266        upper: 0.0,
267        count: 0.0,
268        index: 0,
269    };
270    let mut count = 0.0;
271    let mut visited = 0;
272    for &next in buckets.iter() {
273        visited += 1;
274        bucket = next;
275        if bucket.count == 0.0 {
276            continue;
277        }
278        count += bucket.count;
279        if count >= rank {
280            break;
281        }
282    }
283    if !custom && bucket.lower < 0.0 && bucket.upper > 0.0 {
284        if h.negative.buckets.is_empty() && !h.positive.buckets.is_empty() {
285            bucket.lower = 0.0;
286        } else if h.positive.buckets.is_empty() && !h.negative.buckets.is_empty() {
287            bucket.upper = 0.0;
288        }
289    } else if custom {
290        if bucket.lower == f64::NEG_INFINITY {
291            if bucket.upper <= 0.0 {
292                return Ok(bucket.upper);
293            }
294            bucket.lower = 0.0;
295        } else if bucket.upper == f64::INFINITY {
296            return Ok(bucket.lower);
297        }
298    }
299    if count > h.count {
300        count = h.count;
301    }
302    if count < rank {
303        return Ok(if h.sum.is_nan() {
304            f64::NAN
305        } else {
306            bucket.upper
307        });
308    }
309    if forward {
310        rank -= count - bucket.count;
311    } else {
312        rank = count - rank;
313    }
314    if h.sum.is_nan() {
315        // Prometheus walks the remaining buckets to annotate NaN observations and leaves the last
316        // one in `bucket`, which the interpolation below then uses.
317        for &next in &buckets[visited..] {
318            bucket = next;
319        }
320    }
321    let fraction = rank / bucket.count;
322    if custom || (bucket.lower <= 0.0 && bucket.upper >= 0.0) {
323        return Ok(bucket.lower + (bucket.upper - bucket.lower) * fraction);
324    }
325    let log_lower = bucket.lower.abs().log2();
326    let log_upper = bucket.upper.abs().log2();
327    if bucket.lower > 0.0 {
328        return Ok((log_lower + (log_upper - log_lower) * fraction).exp2());
329    }
330    Ok(-(log_upper + (log_lower - log_upper) * (1.0 - fraction)).exp2())
331}
332
333/// Prometheus `HistogramFraction`.
334pub(super) fn fraction(
335    lower: f64,
336    upper: f64,
337    h: &HistogramView<'_>,
338    buckets: &mut Vec<NativeBucket>,
339) -> Result<f64> {
340    if h.count == 0.0 || lower.is_nan() || upper.is_nan() {
341        return Ok(f64::NAN);
342    }
343    if lower >= upper {
344        return Ok(0.0);
345    }
346    let custom = h.schema == CUSTOM_BUCKETS_SCHEMA;
347    all_buckets(h, false, buckets)?;
348    let (mut count, mut rank, mut lower_rank, mut upper_rank) = (0.0, 0.0, 0.0, 0.0);
349    let (mut lower_set, mut upper_set) = (false, false);
350    let mut visited = 0;
351    for b in buckets.iter() {
352        visited += 1;
353        let mut b = *b;
354        count += b.count;
355        let mut zero_bucket = false;
356        if b.lower <= 0.0 && b.upper >= 0.0 {
357            zero_bucket = true;
358            if h.negative.buckets.is_empty() && !h.positive.buckets.is_empty() {
359                b.lower = 0.0;
360            } else if h.positive.buckets.is_empty() && !h.negative.buckets.is_empty() {
361                b.upper = 0.0;
362            }
363        }
364        let interpolate = |v: f64| {
365            if custom || zero_bucket {
366                if b.lower == f64::NEG_INFINITY {
367                    b.count
368                } else {
369                    rank + b.count * ((v - b.lower) / (b.upper - b.lower))
370                }
371            } else {
372                rank + b.count * fraction_below_exponential(b, v)
373            }
374        };
375        if !lower_set && b.lower >= lower {
376            lower_rank = rank;
377            lower_set = true;
378        }
379        if !upper_set && b.lower >= upper {
380            upper_rank = rank;
381            upper_set = true;
382        }
383        if lower_set && upper_set {
384            break;
385        }
386        if !lower_set && b.lower < lower && b.upper > lower {
387            lower_rank = interpolate(lower);
388            lower_set = true;
389        }
390        if !upper_set && b.lower < upper && b.upper > upper {
391            upper_rank = interpolate(upper);
392            upper_set = true;
393        }
394        if lower_set && upper_set {
395            break;
396        }
397        rank += b.count;
398    }
399    if h.sum.is_nan() {
400        for b in &buckets[visited..] {
401            count += b.count;
402        }
403    } else {
404        count = h.count;
405    }
406    if !lower_set || lower_rank > count {
407        lower_rank = count;
408    }
409    if !upper_set || upper_rank > count {
410        upper_rank = count;
411    }
412    Ok((upper_rank - lower_rank) / h.count)
413}
414
415/// Go `Bucket.FractionBelow` with exponential interpolation.
416fn fraction_below_exponential(b: NativeBucket, v: f64) -> f64 {
417    let log_lower = b.lower.abs().log2();
418    let log_upper = b.upper.abs().log2();
419    let log_v = v.abs().log2();
420    if v > 0.0 {
421        (log_v - log_lower) / (log_upper - log_lower)
422    } else {
423        1.0 - ((log_v - log_upper) / (log_lower - log_upper))
424    }
425}
426
427/// Prometheus `histogramVariance`: bucket midpoints weighted by count around the mean.
428pub(super) fn variance(h: &HistogramView<'_>, buckets: &mut Vec<NativeBucket>) -> Result<f64> {
429    let mean = h.sum / h.count;
430    let custom = h.schema == CUSTOM_BUCKETS_SCHEMA;
431    all_buckets(h, false, buckets)?;
432    let (mut variance, mut compensation) = (0.0, 0.0);
433    for bucket in buckets.iter().filter(|bucket| bucket.count != 0.0) {
434        let value = if custom {
435            (bucket.upper + bucket.lower) / 2.0
436        } else if bucket.lower <= 0.0 && bucket.upper >= 0.0 {
437            0.0
438        } else {
439            let value = (bucket.upper * bucket.lower).sqrt();
440            if bucket.upper < 0.0 { -value } else { value }
441        };
442        let delta = value - mean;
443        (variance, compensation) = kahan_inc(bucket.count * delta * delta, variance, compensation);
444    }
445    Ok((variance + compensation) / h.count)
446}
447
448#[cfg(test)]
449mod tests {
450    /// The last bucket of finite values ends at `f64::MAX`; only the next one, which counts
451    /// infinite observations, ends at +Inf.
452    #[test]
453    fn last_finite_bucket_ends_at_max() {
454        for schema in [-4, 0, 3, 8] {
455            let last = 1024i32 << schema.max(0) >> (-schema).max(0);
456            assert_eq!(super::bound(last, schema, &[]).unwrap(), f64::MAX);
457            assert_eq!(super::bound(last + 1, schema, &[]).unwrap(), f64::INFINITY);
458        }
459    }
460}