Skip to main content

promql/histogram_eval/
classic.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 `BucketQuantile` and `BucketFraction` over the buckets of a classic histogram at
16//! one point.
17
18/// Relative difference under which neighbouring bucket counts are taken as equal.
19const SMALL_DELTA_TOLERANCE: f64 = 1e-12;
20
21/// Go's `strconv.ParseFloat`, which rejects finite literals out of the f64 range and a signed
22/// NaN, and accepts `_` between digits. Hexadecimal literals are not supported.
23pub(super) fn parse_bound(text: &str) -> Option<f64> {
24    let unsigned = text.trim_start_matches(['+', '-']);
25    if unsigned.len() != text.len() && unsigned.eq_ignore_ascii_case("nan") {
26        return None;
27    }
28    let value: f64 = if text.contains('_') {
29        if !underscores_ok(text) {
30            return None;
31        }
32        text.replace('_', "").parse().ok()?
33    } else {
34        text.parse().ok()?
35    };
36    if value.is_infinite() {
37        let unsigned = text.trim_start_matches(['+', '-']);
38        if !unsigned.eq_ignore_ascii_case("inf") && !unsigned.eq_ignore_ascii_case("infinity") {
39            return None;
40        }
41    }
42    Some(value)
43}
44
45/// Go's `strconv.underscoreOK` for a decimal literal: every `_` sits between two digits.
46fn underscores_ok(text: &str) -> bool {
47    let digits = text.strip_prefix(['+', '-']).unwrap_or(text).as_bytes();
48    digits.iter().enumerate().all(|(i, &byte)| {
49        byte != b'_'
50            || (i > 0
51                && digits[i - 1].is_ascii_digit()
52                && digits.get(i + 1).is_some_and(u8::is_ascii_digit))
53    })
54}
55
56#[derive(Debug, Clone, Copy)]
57pub(super) struct Bucket {
58    pub(super) upper_bound: f64,
59    pub(super) count: f64,
60}
61
62/// Prometheus `BucketQuantile` over buckets sorted by upper bound.
63pub(super) fn bucket_quantile(q: f64, buckets: &mut Vec<Bucket>) -> f64 {
64    if q.is_nan() {
65        return f64::NAN;
66    }
67    if q < 0.0 {
68        return f64::NEG_INFINITY;
69    }
70    if q > 1.0 {
71        return f64::INFINITY;
72    }
73    if buckets.last().unwrap().upper_bound != f64::INFINITY {
74        return f64::NAN;
75    }
76    coalesce(buckets);
77    ensure_monotonic(buckets);
78    if buckets.len() < 2 {
79        return f64::NAN;
80    }
81    let observations = buckets.last().unwrap().count;
82    if observations == 0.0 {
83        return f64::NAN;
84    }
85    let mut rank = q * observations;
86    let b = go_search(buckets.len() - 1, |i| buckets[i].count >= rank);
87    if b == buckets.len() - 1 {
88        return buckets[buckets.len() - 2].upper_bound;
89    }
90    if b == 0 && buckets[0].upper_bound <= 0.0 {
91        return buckets[0].upper_bound;
92    }
93    let mut bucket_start = 0.0;
94    let bucket_end = buckets[b].upper_bound;
95    let mut count = buckets[b].count;
96    if b > 0 {
97        bucket_start = buckets[b - 1].upper_bound;
98        count -= buckets[b - 1].count;
99        rank -= buckets[b - 1].count;
100    }
101    bucket_start + (bucket_end - bucket_start) * (rank / count)
102}
103
104/// Prometheus `BucketFraction` over buckets sorted by upper bound.
105pub(super) fn bucket_fraction(lower: f64, upper: f64, buckets: &mut Vec<Bucket>) -> f64 {
106    if buckets.last().unwrap().upper_bound != f64::INFINITY {
107        return f64::NAN;
108    }
109    coalesce(buckets);
110    let count = buckets.last().unwrap().count;
111    if count == 0.0 || lower.is_nan() || upper.is_nan() {
112        return f64::NAN;
113    }
114    if lower >= upper {
115        return 0.0;
116    }
117
118    let (mut rank, mut lower_rank, mut upper_rank) = (0.0, 0.0, 0.0);
119    let (mut lower_set, mut upper_set) = (false, false);
120    let mut lower_bound = if buckets[0].upper_bound <= 0.0 {
121        f64::NEG_INFINITY
122    } else {
123        0.0
124    };
125    for (i, bucket) in buckets.iter().enumerate() {
126        if i > 0 {
127            lower_bound = buckets[i - 1].upper_bound;
128        }
129        let upper_bound = bucket.upper_bound;
130        // An infinite-width bucket contributes nothing to the interpolation.
131        let interpolate = |value: f64| {
132            if lower_bound == f64::NEG_INFINITY {
133                bucket.count
134            } else {
135                rank + (bucket.count - rank) * (value - lower_bound) / (upper_bound - lower_bound)
136            }
137        };
138        if !lower_set && lower_bound >= lower {
139            lower_rank = rank;
140            lower_set = true;
141        }
142        if !upper_set && lower_bound >= upper {
143            upper_rank = rank;
144            upper_set = true;
145        }
146        if lower_set && upper_set {
147            break;
148        }
149        if !lower_set && lower_bound < lower && upper_bound > lower {
150            lower_rank = interpolate(lower);
151            lower_set = true;
152        }
153        if !upper_set && lower_bound < upper && upper_bound > upper {
154            upper_rank = interpolate(upper);
155            upper_set = true;
156        }
157        if lower_set && upper_set {
158            break;
159        }
160        rank = bucket.count;
161    }
162    if !lower_set || lower_rank > count {
163        lower_rank = count;
164    }
165    if !upper_set || upper_rank > count {
166        upper_rank = count;
167    }
168    (upper_rank - lower_rank) / count
169}
170
171/// Merges buckets with the same upper bound.
172fn coalesce(buckets: &mut Vec<Bucket>) {
173    let mut last = buckets[0];
174    let mut i = 0;
175    for j in 1..buckets.len() {
176        let bucket = buckets[j];
177        if bucket.upper_bound == last.upper_bound {
178            last.count += bucket.count;
179        } else {
180            buckets[i] = last;
181            last = bucket;
182            i += 1;
183        }
184    }
185    buckets[i] = last;
186    buckets.truncate(i + 1);
187}
188
189/// Prometheus `ensureMonotonicAndIgnoreSmallDeltas`: counts that differ from the previous one by
190/// a negligible relative amount, or are lower, are raised to it.
191fn ensure_monotonic(buckets: &mut [Bucket]) {
192    let mut prev = buckets[0].count;
193    for bucket in &mut buckets[1..] {
194        let curr = bucket.count;
195        if curr == prev {
196            continue;
197        }
198        if almost_equal(prev, curr, SMALL_DELTA_TOLERANCE) || curr < prev {
199            bucket.count = prev;
200            continue;
201        }
202        prev = curr;
203    }
204}
205
206/// Prometheus `almost.Equal`.
207fn almost_equal(a: f64, b: f64, epsilon: f64) -> bool {
208    if a.is_nan() && b.is_nan() {
209        return true;
210    }
211    if a == b {
212        return true;
213    }
214    let abs_sum = a.abs() + b.abs();
215    let diff = (a - b).abs();
216    if a == 0.0 || b == 0.0 || abs_sum < f64::MIN_POSITIVE {
217        return diff < epsilon * f64::MIN_POSITIVE;
218    }
219    diff / abs_sum.min(f64::MAX) < epsilon
220}
221
222/// Go's `sort.Search`: the smallest index in `[0, n)` where `f` holds, or `n`, found by the same
223/// bisection, so a predicate that is not monotonic (NaN counts) picks the same index.
224fn go_search(n: usize, f: impl Fn(usize) -> bool) -> usize {
225    let (mut i, mut j) = (0, n);
226    while i < j {
227        let h = (i + j) / 2;
228        if !f(h) {
229            i = h + 1;
230        } else {
231            j = h;
232        }
233    }
234    i
235}