ic_metrics/histogram/mod.rs
1//! Fixed-size distributions without sampling or reporting policy.
2
3use core::fmt;
4
5use crate::{MeasurementAggregate, MeasurementStateError, add_count};
6
7#[cfg(test)]
8mod tests;
9
10/// A bound is not strictly greater than the preceding bound.
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
12pub struct HistogramBoundsError {
13 index: usize,
14}
15
16impl HistogramBoundsError {
17 /// Zero-based index of the first invalid bound, always at least one.
18 #[must_use]
19 pub const fn index(self) -> usize {
20 self.index
21 }
22}
23
24impl fmt::Display for HistogramBoundsError {
25 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
26 write!(
27 formatter,
28 "histogram bound {} is not strictly increasing",
29 self.index
30 )
31 }
32}
33
34impl core::error::Error for HistogramBoundsError {}
35
36/// Why a histogram cannot supply an exact reporting projection.
37#[derive(Clone, Copy, Debug, Eq, PartialEq)]
38pub enum HistogramQueryError {
39 /// The index does not name one of the configured finite upper bounds.
40 BucketOutOfBounds {
41 /// Requested zero-based bound index.
42 index: usize,
43 /// Number of configured finite upper bounds.
44 buckets: usize,
45 },
46 /// A nearest-rank fraction must satisfy `0 < numerator <= denominator`.
47 InvalidQuantile,
48 /// A required count or cumulative sum has actually overflowed.
49 CountOverflow,
50}
51
52impl fmt::Display for HistogramQueryError {
53 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54 match self {
55 Self::BucketOutOfBounds { index, buckets } => {
56 write!(
57 formatter,
58 "histogram bound index {index} is outside {buckets} bounds"
59 )
60 }
61 Self::InvalidQuantile => {
62 formatter.write_str("quantile must be greater than zero and at most one")
63 }
64 Self::CountOverflow => formatter.write_str("histogram reporting count has overflowed"),
65 }
66 }
67}
68
69impl core::error::Error for HistogramQueryError {}
70
71/// Why two histogram distributions cannot be combined.
72#[derive(Clone, Copy, Debug, Eq, PartialEq)]
73pub struct HistogramMergeError {
74 index: usize,
75}
76
77impl HistogramMergeError {
78 /// Zero-based index of the first differing inclusive upper bound.
79 #[must_use]
80 pub const fn index(self) -> usize {
81 self.index
82 }
83}
84
85impl fmt::Display for HistogramMergeError {
86 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
87 write!(formatter, "histogram merge bound {} differs", self.index)
88 }
89}
90
91impl core::error::Error for HistogramMergeError {}
92
93/// The observation range of a histogram bucket, not an exact percentile value.
94///
95/// A missing lower bound includes zero; otherwise the lower bound is exclusive.
96/// The upper bound is inclusive when present. A missing upper bound is overflow
97/// beyond the configured bounds. With no configured bounds both are absent and
98/// the range covers all `u64` observations.
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub struct HistogramRange {
101 lower_exclusive: Option<u64>,
102 upper_inclusive: Option<u64>,
103}
104
105impl HistogramRange {
106 /// Exclusive lower bound, or `None` when zero is included.
107 #[must_use]
108 pub const fn lower_exclusive(self) -> Option<u64> {
109 self.lower_exclusive
110 }
111
112 /// Inclusive upper bound, or `None` for overflow without a configured ceiling.
113 #[must_use]
114 pub const fn upper_inclusive(self) -> Option<u64> {
115 self.upper_inclusive
116 }
117}
118
119/// Fixed-size histogram of observations in one consumer-selected unit.
120///
121/// `N` strictly increasing inclusive upper bounds define `N` disjoint buckets.
122/// The first bucket includes zero; later buckets exclude the preceding bound.
123/// Values above the last bound go into a separate overflow bucket. With no
124/// bounds, every observation goes into overflow. A final bound of `u64::MAX`
125/// is valid and leaves overflow empty.
126///
127/// Each observation updates one bucket and the accompanying
128/// [`MeasurementAggregate`]. Counts clip independently at `u64::MAX`, with sticky
129/// flags for actual overflow; exactly reached caps remain exact. Exact
130/// bucket counts remain useful after the aggregate's total overflows. Overflow
131/// can prevent bucket counts from summing to the aggregate's sample count.
132/// Buckets describe ranges, not exact percentiles; no latest value is retained.
133///
134/// Storage is fixed arrays, overflow state and one aggregate, with no heap
135/// allocation. Recording searches at most `N` bounds. Consumers choose bounds,
136/// units, sample admission, identity and reset boundaries. Bounds are immutable
137/// after construction; report encoding and persistence remain consumer-owned.
138///
139/// ```
140/// use ic_metrics::MeasurementHistogram;
141///
142/// # fn main() -> Result<(), ic_metrics::HistogramBoundsError> {
143/// let mut histogram = MeasurementHistogram::new([10, 100])?;
144/// for value in [0, 10, 11, 101] {
145/// histogram.record(value);
146/// }
147/// assert_eq!(histogram.bucket_counts(), &[2, 1]);
148/// assert_eq!(histogram.overflow(), 1);
149/// assert_eq!(histogram.aggregate().samples(), 4);
150/// # Ok(())
151/// # }
152/// ```
153#[derive(Clone, Copy, Debug, Eq, PartialEq)]
154pub struct MeasurementHistogram<const N: usize> {
155 upper_bounds: [u64; N],
156 bucket_counts: [u64; N],
157 overflow: u64,
158 bucket_overflowed: [bool; N],
159 overflow_count_overflowed: bool,
160 aggregate: MeasurementAggregate,
161}
162
163impl<const N: usize> MeasurementHistogram<N> {
164 /// Restore disjoint buckets and an admitted aggregate without replaying samples.
165 ///
166 /// This checks structural arithmetic consistency, not observation provenance.
167 /// Consumers retain units, attribution and reset identity.
168 ///
169 /// # Errors
170 /// Rejects invalid bounds, overflow flags without clipped caps, disagreement
171 /// between bucket counts and the aggregate, or an incompatible maximum.
172 pub const fn from_parts(
173 upper_bounds: [u64; N],
174 bucket_counts: [u64; N],
175 overflow: u64,
176 bucket_overflowed: [bool; N],
177 overflow_count_overflowed: bool,
178 aggregate: MeasurementAggregate,
179 ) -> Result<Self, MeasurementStateError> {
180 if Self::new(upper_bounds).is_err() {
181 return Err(MeasurementStateError::InvalidBounds);
182 }
183 if overflow_count_overflowed && overflow != u64::MAX {
184 return Err(MeasurementStateError::InvalidOverflowFlag);
185 }
186 let mut count = overflow;
187 let mut overflowed = overflow_count_overflowed;
188 let mut index = 0;
189 let mut highest = None;
190 while index < N {
191 if bucket_overflowed[index] && bucket_counts[index] != u64::MAX {
192 return Err(MeasurementStateError::InvalidOverflowFlag);
193 }
194 add_count(&mut count, &mut overflowed, bucket_counts[index]);
195 overflowed |= bucket_overflowed[index];
196 if bucket_counts[index] != 0 {
197 highest = Some(index);
198 }
199 index += 1;
200 }
201 if count != aggregate.samples() || overflowed != aggregate.samples_overflowed() {
202 return Err(MeasurementStateError::InvalidDistribution);
203 }
204 if let Some(maximum) = aggregate.maximum() {
205 if overflow != 0 {
206 if N != 0 && maximum <= upper_bounds[N - 1] {
207 return Err(MeasurementStateError::InvalidDistribution);
208 }
209 } else if let Some(index) = highest {
210 if maximum > upper_bounds[index]
211 || (index != 0 && maximum <= upper_bounds[index - 1])
212 {
213 return Err(MeasurementStateError::InvalidDistribution);
214 }
215 } else {
216 return Err(MeasurementStateError::InvalidDistribution);
217 }
218 if !valid_distribution_total(
219 &upper_bounds,
220 &bucket_counts,
221 overflow,
222 &bucket_overflowed,
223 overflow_count_overflowed,
224 aggregate,
225 ) {
226 return Err(MeasurementStateError::InvalidDistribution);
227 }
228 }
229 Ok(Self {
230 upper_bounds,
231 bucket_counts,
232 overflow,
233 bucket_overflowed,
234 overflow_count_overflowed,
235 aggregate,
236 })
237 }
238
239 /// Construct an empty histogram with inclusive upper bounds.
240 ///
241 /// Bounds and observations must use the same unit. A bound of zero and an
242 /// empty bounds array are valid.
243 ///
244 /// # Errors
245 ///
246 /// Returns [`HistogramBoundsError`] for the first duplicate or descending
247 /// bound. The error identifies the right-hand bound in that pair.
248 pub const fn new(upper_bounds: [u64; N]) -> Result<Self, HistogramBoundsError> {
249 let mut index = 1;
250 while index < N {
251 // Both indices are within the array, including when N is zero.
252 if upper_bounds[index - 1] >= upper_bounds[index] {
253 return Err(HistogramBoundsError { index });
254 }
255 index += 1;
256 }
257 Ok(Self {
258 upper_bounds,
259 bucket_counts: [0; N],
260 overflow: 0,
261 bucket_overflowed: [false; N],
262 overflow_count_overflowed: false,
263 aggregate: MeasurementAggregate::EMPTY,
264 })
265 }
266
267 /// Record one completed observation, including zero.
268 ///
269 /// Updates the aggregate and exactly one disjoint bucket. Every observation
270 /// must use the same unit as the bounds and earlier observations.
271 pub const fn record(&mut self, value: u64) {
272 self.aggregate.record(value);
273 let mut index = 0;
274 while index < N {
275 // Both arrays have length N; the guard establishes valid indices.
276 if value <= self.upper_bounds[index] {
277 add_count(
278 &mut self.bucket_counts[index],
279 &mut self.bucket_overflowed[index],
280 1,
281 );
282 return;
283 }
284 index += 1;
285 }
286 add_count(&mut self.overflow, &mut self.overflow_count_overflowed, 1);
287 }
288
289 /// Immutable inclusive upper bounds corresponding to [`Self::bucket_counts`].
290 #[must_use]
291 pub const fn upper_bounds(&self) -> &[u64; N] {
292 &self.upper_bounds
293 }
294
295 /// Disjoint bucket counts, each saturating independently at `u64::MAX`.
296 ///
297 /// These exclude overflow and are not cumulative counts. Inspect
298 /// [`Self::bucket_overflowed`] before using clipped counts as exact values.
299 #[must_use]
300 pub const fn bucket_counts(&self) -> &[u64; N] {
301 &self.bucket_counts
302 }
303
304 /// Count above the last bound, saturating independently at `u64::MAX`.
305 ///
306 /// With no bounds, this counts all observations. Inspect
307 /// [`Self::overflow_count_overflowed`] before treating the clipped count as exact.
308 #[must_use]
309 pub const fn overflow(&self) -> u64 {
310 self.overflow
311 }
312
313 /// Sticky actual-overflow flags corresponding to [`Self::bucket_counts`].
314 #[must_use]
315 pub const fn bucket_overflowed(&self) -> &[bool; N] {
316 &self.bucket_overflowed
317 }
318
319 /// Whether the overflow bucket's count has actually overflowed.
320 #[must_use]
321 pub const fn overflow_count_overflowed(&self) -> bool {
322 self.overflow_count_overflowed
323 }
324
325 /// Mergeable aggregate of all observations, including overflow.
326 #[must_use]
327 pub const fn aggregate(&self) -> MeasurementAggregate {
328 self.aggregate
329 }
330
331 /// Combine a distribution with exactly the same finite bounds.
332 ///
333 /// Consumers establish matching units and deliberate sample attribution.
334 /// This adds observations without deduplication or ordering. Source overflow
335 /// propagates independently for each count and the aggregate.
336 ///
337 /// # Errors
338 /// Returns [`HistogramMergeError`] for the first differing bound, leaving
339 /// the entire destination unchanged. Different bound counts are different
340 /// Rust types and cannot be merged.
341 pub const fn merge(&mut self, other: &Self) -> Result<(), HistogramMergeError> {
342 let mut index = 0;
343 while index < N {
344 if self.upper_bounds[index] != other.upper_bounds[index] {
345 return Err(HistogramMergeError { index });
346 }
347 index += 1;
348 }
349 index = 0;
350 while index < N {
351 add_count(
352 &mut self.bucket_counts[index],
353 &mut self.bucket_overflowed[index],
354 other.bucket_counts[index],
355 );
356 self.bucket_overflowed[index] |= other.bucket_overflowed[index];
357 index += 1;
358 }
359 add_count(
360 &mut self.overflow,
361 &mut self.overflow_count_overflowed,
362 other.overflow,
363 );
364 self.overflow_count_overflowed |= other.overflow_count_overflowed;
365 self.aggregate.merge(other.aggregate);
366 Ok(())
367 }
368
369 /// Count observations at or below the finite upper bound at `index`.
370 ///
371 /// Sums disjoint buckets through that index, excluding overflow. Empty
372 /// histograms return zero for valid indices. Later buckets, overflow and
373 /// aggregate overflow do not invalidate an otherwise exact prefix count.
374 /// Arbitrary thresholds inside a bucket cannot be answered exactly.
375 ///
376 /// # Errors
377 ///
378 /// Returns [`HistogramQueryError::BucketOutOfBounds`] when `index >= N`, or
379 /// [`HistogramQueryError::CountOverflow`] when a contributing count or sum
380 /// has actually overflowed; an exactly reached `u64::MAX` is valid.
381 pub const fn cumulative_count(&self, index: usize) -> Result<u64, HistogramQueryError> {
382 if index >= N {
383 return Err(HistogramQueryError::BucketOutOfBounds { index, buckets: N });
384 }
385 let mut total = 0_u64;
386 let mut position = 0;
387 while position <= index {
388 if self.bucket_overflowed[position] {
389 return Err(HistogramQueryError::CountOverflow);
390 }
391 total = match total.checked_add(self.bucket_counts[position]) {
392 Some(next) => next,
393 None => return Err(HistogramQueryError::CountOverflow),
394 };
395 position += 1;
396 }
397 Ok(total)
398 }
399
400 /// Locate the bucket containing the nearest-rank quantile `numerator / denominator`.
401 ///
402 /// The one-based rank is `ceil(samples * numerator / denominator)`, with
403 /// `0 < numerator <= denominator`. Returns `None` for no observations and
404 /// otherwise a range, including overflow. It never interpolates an exact
405 /// percentile value. Recording and retained state are unchanged.
406 ///
407 /// # Errors
408 ///
409 /// Returns [`HistogramQueryError::InvalidQuantile`] first for an invalid
410 /// fraction, or [`HistogramQueryError::CountOverflow`] if the sample count
411 /// or any bucket count has actually overflowed. A overflowed value total does not
412 /// invalidate a distribution whose counts remain exact.
413 ///
414 /// ```
415 /// use ic_metrics::MeasurementHistogram;
416 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
417 /// let mut histogram = MeasurementHistogram::new([10, 100])?;
418 /// for value in [0, 10, 11, 101] { histogram.record(value); }
419 /// assert_eq!(histogram.cumulative_count(0)?, 2);
420 /// let median = histogram.quantile_bucket(1, 2)?.unwrap();
421 /// assert_eq!(median.upper_inclusive(), Some(10));
422 /// assert_eq!(histogram.quantile_bucket(95, 100)?.unwrap().upper_inclusive(), None);
423 /// # Ok(())
424 /// # }
425 /// ```
426 pub const fn quantile_bucket(
427 &self,
428 numerator: u64,
429 denominator: u64,
430 ) -> Result<Option<HistogramRange>, HistogramQueryError> {
431 let rank = match quantile_rank(self.aggregate.samples(), numerator, denominator) {
432 Ok(Some(rank)) => rank,
433 Ok(None) => return Ok(None),
434 Err(error) => return Err(error),
435 };
436 if self.aggregate.samples_overflowed() {
437 return Err(HistogramQueryError::CountOverflow);
438 }
439 // Recording, merging and restoration carry every bucket's count loss
440 // into the aggregate. An exact aggregate count admits the distribution.
441 let mut index = 0;
442 let mut cumulative = 0_u128;
443 while index < N {
444 cumulative += self.bucket_counts[index] as u128;
445 if cumulative >= rank {
446 return Ok(Some(HistogramRange {
447 lower_exclusive: if index == 0 {
448 None
449 } else {
450 Some(self.upper_bounds[index - 1])
451 },
452 upper_inclusive: Some(self.upper_bounds[index]),
453 }));
454 }
455 index += 1;
456 }
457 Ok(Some(HistogramRange {
458 lower_exclusive: if N == 0 {
459 None
460 } else {
461 Some(self.upper_bounds[N - 1])
462 },
463 upper_inclusive: None,
464 }))
465 }
466}
467
468// Use native-width division when the product fits; otherwise retain exact wide ranks.
469const fn quantile_rank(
470 samples: u64,
471 numerator: u64,
472 denominator: u64,
473) -> Result<Option<u128>, HistogramQueryError> {
474 if numerator == 0 || numerator > denominator {
475 return Err(HistogramQueryError::InvalidQuantile);
476 }
477 if samples == 0 {
478 return Ok(None);
479 }
480 if let Some(product) = samples.checked_mul(numerator) {
481 return Ok(Some(product.div_ceil(denominator) as u128));
482 }
483 Ok(Some(
484 ((samples as u128) * (numerator as u128)).div_ceil(denominator as u128),
485 ))
486}
487
488// Canonical range admission for restored counts, including clipped lower bounds.
489const fn valid_distribution_total<const N: usize>(
490 upper_bounds: &[u64; N],
491 bucket_counts: &[u64; N],
492 overflow: u64,
493 bucket_overflowed: &[bool; N],
494 overflow_count_overflowed: bool,
495 aggregate: MeasurementAggregate,
496) -> bool {
497 let Some(maximum) = aggregate.maximum() else {
498 return true;
499 };
500 let mut minimum_total = 0_u128;
501 let mut maximum_total = 0_u128;
502 let mut maximum_overflow = false;
503 let mut minimum_overflow = false;
504 let mut maximum_lower = 0_u64;
505 let mut index = 0;
506 // Counts retain a lower bound after clipping. Exact bucket counts
507 // also constrain totals; a clipped positive bucket has no upper
508 // count bound. Keep all admission arithmetic checked or saturating.
509 while index <= N {
510 let (count, lost, lower, upper) = if index < N {
511 let lower = if index == 0 {
512 0
513 } else {
514 upper_bounds[index - 1].saturating_add(1)
515 };
516 (
517 bucket_counts[index],
518 bucket_overflowed[index],
519 lower,
520 if upper_bounds[index] < maximum {
521 upper_bounds[index]
522 } else {
523 maximum
524 },
525 )
526 } else {
527 let lower = if N == 0 {
528 0
529 } else {
530 upper_bounds[N - 1].saturating_add(1)
531 };
532 (overflow, overflow_count_overflowed, lower, maximum)
533 };
534 if count != 0 {
535 maximum_lower = lower;
536 let minimum_count = count as u128 + lost as u128;
537 let minimum = minimum_count * lower as u128;
538 if let Some(next) = minimum_total.checked_add(minimum) {
539 minimum_total = next;
540 } else {
541 minimum_overflow = true;
542 }
543 if lost && upper != 0 {
544 maximum_overflow = true;
545 }
546 let upper_total = count as u128 * upper as u128;
547 if let Some(next) = maximum_total.checked_add(upper_total) {
548 maximum_total = next;
549 } else {
550 maximum_overflow = true;
551 }
552 }
553 index += 1;
554 }
555 // At least one observation actually attains the stored maximum.
556 if let Some(next) = minimum_total.checked_add(maximum.saturating_sub(maximum_lower) as u128) {
557 minimum_total = next;
558 } else {
559 minimum_overflow = true;
560 }
561 if aggregate.total_overflowed() {
562 maximum_overflow
563 } else {
564 !minimum_overflow
565 && aggregate.total() >= minimum_total
566 && (maximum_overflow || aggregate.total() <= maximum_total)
567 }
568}