Skip to main content

iota_metrics/
peak.rs

1// Copyright (c) 2026 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4//! Gauges that keep the exact maximum over a sliding window.
5//!
6//! [`PeakGauge`] keeps the exact maximum over a window of the same length as
7//! that of the quantile gauges, for values that move faster than the scrape
8//! interval and would otherwise only ever be sampled at one arbitrary instant.
9//! [`PeakGaugeVec`] keeps one such peak for each value of a label.
10//! [`IntGaugeWithPeakGauge`] pairs an `IntGauge` with such a peak.
11
12use std::{
13    collections::HashMap,
14    sync::{
15        Arc,
16        atomic::{AtomicU64, Ordering},
17    },
18    time::Instant,
19};
20
21use parking_lot::{Mutex, MutexGuard, RwLock};
22use prometheus_filtered::{
23    MetricLevel, Opts, Registry,
24    core::{Collector, Desc},
25    prometheus::{IntGauge, IntGaugeVec, proto::MetricFamily},
26};
27
28use crate::quantile_gauge::{WINDOW_SLOT, WINDOW_SLOTS};
29
30/// The highest value over a sliding window, kept exactly per slot. The window
31/// has the same length as that of the quantile gauges. Observing takes no lock while the
32/// slot does not change; a change of slot and a read take a lock.
33struct PeakWindow {
34    start: Instant,
35    /// The number of the slot being filled: the time since `start` in slots.
36    current_slot: AtomicU64,
37    /// The maxima of the last `WINDOW_SLOTS` slots, slot `n` at `n %
38    /// WINDOW_SLOTS`.
39    slots: [AtomicU64; WINDOW_SLOTS],
40    rotation: Mutex<()>,
41}
42
43impl PeakWindow {
44    fn new(now: Instant) -> Self {
45        Self {
46            start: now,
47            current_slot: AtomicU64::new(0),
48            slots: std::array::from_fn(|_| AtomicU64::new(0)),
49            rotation: Mutex::new(()),
50        }
51    }
52
53    fn slot_number(&self, now: Instant) -> u64 {
54        (now.saturating_duration_since(self.start).as_nanos() / WINDOW_SLOT.as_nanos()) as u64
55    }
56
57    /// Records `value` at `now`. `now` is not later than the current time. A
58    /// value older than the window is dropped.
59    fn observe_at(&self, value: u64, now: Instant) {
60        let value_slot = self.slot_number(now);
61        let current_slot = self.current_slot.load(Ordering::Acquire);
62        if value_slot == current_slot {
63            let slot_max = self.slot_max(value_slot);
64            if value > slot_max.load(Ordering::Relaxed) {
65                slot_max.fetch_max(value, Ordering::Relaxed);
66            }
67            return;
68        }
69        let rotation = self.rotation.lock();
70        self.advance_to(&rotation, value_slot);
71        let current_slot = self.current_slot.load(Ordering::Relaxed);
72        let still_in_window = value_slot + WINDOW_SLOTS as u64 > current_slot;
73        if still_in_window {
74            self.slot_max(value_slot)
75                .fetch_max(value, Ordering::Relaxed);
76        }
77    }
78
79    fn slot_max(&self, slot: u64) -> &AtomicU64 {
80        &self.slots[slot as usize % WINDOW_SLOTS]
81    }
82
83    /// Moves to `target_slot` and clears the slots it takes over.
84    fn advance_to(&self, _rotation: &MutexGuard<'_, ()>, target_slot: u64) {
85        let current_slot = self.current_slot.load(Ordering::Relaxed);
86        if target_slot <= current_slot {
87            return;
88        }
89        let first_to_clear =
90            (current_slot + 1).max(target_slot.saturating_sub(WINDOW_SLOTS as u64 - 1));
91        for slot in first_to_clear..=target_slot {
92            self.slot_max(slot).store(0, Ordering::Relaxed);
93        }
94        self.current_slot.store(target_slot, Ordering::Release);
95    }
96
97    fn max_at(&self, now: Instant) -> u64 {
98        {
99            let rotation = self.rotation.lock();
100            self.advance_to(&rotation, self.slot_number(now));
101        }
102        self.slots
103            .iter()
104            .map(|slot| slot.load(Ordering::Relaxed))
105            .max()
106            .unwrap_or(0)
107    }
108
109    fn observe(&self, value: u64) {
110        self.observe_at(value, Instant::now());
111    }
112
113    fn max(&self) -> u64 {
114        self.max_at(Instant::now())
115    }
116}
117
118/// The highest value observed over the window, exposed as `<name>`. The value
119/// is exact. It is a scalar from [`PeakGauge::register`], or the gauge of one
120/// label value from [`PeakGaugeVec::with_label_values`].
121///
122/// Register with [`PeakGauge::register`], feed it with [`observe`], and the
123/// registry's scrape reports the peak over the current window. A window with
124/// no observation reports zero rather than dropping the series, so an idle
125/// period is visible as such.
126///
127/// For an `IntGauge` that also exports its peak, see [`IntGaugeWithPeakGauge`].
128///
129/// [`observe`]: PeakGauge::observe
130#[derive(Clone)]
131pub struct PeakGauge {
132    gauge: IntGauge,
133    window: Arc<PeakWindow>,
134    /// If set, the peak is never reported below the current value of this gauge.
135    floor: Option<IntGauge>,
136}
137
138impl PeakGauge {
139    /// # Panics
140    ///
141    /// Panics if a metric of this name is already registered.
142    pub fn register(
143        name: &str,
144        help: &str,
145        module: &str,
146        registry: &Registry,
147        level: MetricLevel,
148    ) -> Self {
149        Self::register_with_floor(name, help, module, registry, level, None)
150    }
151
152    /// Like [`register`](Self::register), and with a `floor` the peak is never
153    /// reported below the current value of `floor`.
154    fn register_with_floor(
155        name: &str,
156        help: &str,
157        module: &str,
158        registry: &Registry,
159        level: MetricLevel,
160        floor: Option<IntGauge>,
161    ) -> Self {
162        let gauge = IntGauge::with_opts(Opts::new(name, help)).expect("valid gauge options");
163        let this = Self {
164            gauge,
165            window: Arc::new(PeakWindow::new(Instant::now())),
166            floor,
167        };
168        registry
169            .register_filtered(name, module, level, this)
170            .expect("peak gauge registers without collision")
171    }
172
173    pub fn observe(&self, value: u64) {
174        self.window.observe(value);
175    }
176
177    /// Like [`observe`](Self::observe), for a caller that already read the
178    /// clock for the event. `now` is not later than the current time. A value
179    /// older than the window is dropped.
180    pub fn observe_at(&self, value: u64, now: Instant) {
181        self.window.observe_at(value, now);
182    }
183}
184
185impl Collector for PeakGauge {
186    fn desc(&self) -> Vec<&Desc> {
187        self.gauge.desc()
188    }
189
190    fn collect(&self) -> Vec<MetricFamily> {
191        let current = self
192            .floor
193            .as_ref()
194            .map_or(0, |gauge| gauge.get().max(0) as u64);
195        self.gauge
196            .set(i64::try_from(self.window.max().max(current)).unwrap_or(i64::MAX));
197        self.gauge.collect()
198    }
199}
200
201/// The highest value observed over the window per value of one label, exposed
202/// as `<name>{<label>="..."}`. A series stays after its window empties and then
203/// reports zero, so the label values must be a small fixed set.
204#[derive(Clone)]
205pub struct PeakGaugeVec {
206    gauge: IntGaugeVec,
207    windows: Arc<RwLock<HashMap<String, Arc<PeakWindow>>>>,
208}
209
210impl PeakGaugeVec {
211    /// # Panics
212    ///
213    /// Panics if a metric of this name is already registered.
214    pub fn register(
215        name: &str,
216        help: &str,
217        label: &str,
218        module: &str,
219        registry: &Registry,
220        level: MetricLevel,
221    ) -> Self {
222        let gauge = IntGaugeVec::new(Opts::new(name, help), &[label]).expect("valid gauge options");
223        let this = Self {
224            gauge,
225            windows: Arc::new(RwLock::new(HashMap::new())),
226        };
227        registry
228            .register_filtered(name, module, level, this)
229            .expect("peak gauge registers without collision")
230    }
231
232    /// The peak of `label_values`, created if needed. Its window is shared by
233    /// all peaks of the same label values.
234    ///
235    /// # Panics
236    ///
237    /// Panics if `label_values` does not hold exactly one value.
238    pub fn with_label_values(&self, label_values: &[&str]) -> PeakGauge {
239        let [label_value] = label_values else {
240            panic!("a peak gauge vector has one label");
241        };
242        PeakGauge {
243            gauge: self.gauge.with_label_values(label_values),
244            window: self.window(label_value),
245            floor: None,
246        }
247    }
248
249    fn window(&self, label_value: &str) -> Arc<PeakWindow> {
250        if let Some(window) = self.windows.read().get(label_value) {
251            return window.clone();
252        }
253        self.windows
254            .write()
255            .entry(label_value.to_owned())
256            .or_insert_with(|| Arc::new(PeakWindow::new(Instant::now())))
257            .clone()
258    }
259}
260
261impl Collector for PeakGaugeVec {
262    fn desc(&self) -> Vec<&Desc> {
263        self.gauge.desc()
264    }
265
266    fn collect(&self) -> Vec<MetricFamily> {
267        let windows: Vec<_> = self
268            .windows
269            .read()
270            .iter()
271            .map(|(label, window)| (label.clone(), window.clone()))
272            .collect();
273        for (label_value, window) in windows {
274            self.gauge
275                .with_label_values(&[label_value.as_str()])
276                .set(i64::try_from(window.max()).unwrap_or(i64::MAX));
277        }
278        self.gauge.collect()
279    }
280}
281
282/// An `IntGauge` and its peak over the window, as a [`PeakGauge`]. The peak is
283/// observed at each increment, and a scrape reports at least the current value
284/// of the gauge.
285/// A decrement that runs between an increment and the observation that
286/// follows it can make the peak miss the value the increment gave.
287#[derive(Clone)]
288pub struct IntGaugeWithPeakGauge {
289    gauge: IntGauge,
290    peak: PeakGauge,
291}
292
293impl IntGaugeWithPeakGauge {
294    /// Registers the gauge and its peak, each as `(name, help)`.
295    ///
296    /// # Panics
297    ///
298    /// Panics if a metric of one of the names is already registered.
299    pub fn register(
300        (name, help): (&str, &str),
301        (peak_name, peak_help): (&str, &str),
302        module: &str,
303        registry: &Registry,
304        level: MetricLevel,
305    ) -> Self {
306        let gauge = IntGauge::with_opts(Opts::new(name, help)).expect("valid gauge options");
307        let gauge = registry
308            .register_filtered(name, module, level, gauge)
309            .expect("gauge registers without collision");
310        let peak = PeakGauge::register_with_floor(
311            peak_name,
312            peak_help,
313            module,
314            registry,
315            level,
316            Some(gauge.clone()),
317        );
318        Self { gauge, peak }
319    }
320
321    /// Adds one and observes the new value as a peak.
322    pub fn inc(&self) {
323        self.gauge.inc();
324        self.peak.observe(self.gauge.get().max(0) as u64);
325    }
326
327    /// Subtracts one. The peak does not change.
328    pub fn dec(&self) {
329        self.gauge.dec();
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use std::time::Duration;
336
337    use super::*;
338    use crate::test_utils::MetricsReader;
339
340    #[test]
341    fn peak_is_zero_before_any_observation() {
342        let window = PeakWindow::new(Instant::now());
343        assert_eq!(window.max_at(Instant::now()), 0);
344    }
345
346    #[test]
347    fn observing_zero_leaves_the_peak_at_zero() {
348        let t0 = Instant::now();
349        let window = PeakWindow::new(t0);
350        window.observe_at(0, t0);
351        assert_eq!(window.max_at(t0), 0);
352    }
353
354    #[test]
355    fn peak_is_exact() {
356        let t0 = Instant::now();
357        for value in [32768, 1500, 1_000_003, u64::MAX / 2] {
358            let window = PeakWindow::new(t0);
359            window.observe_at(value, t0);
360            assert_eq!(window.max_at(t0), value);
361        }
362    }
363
364    #[test]
365    fn peak_is_the_highest_value_across_slots() {
366        let t0 = Instant::now();
367        let window = PeakWindow::new(t0);
368        window.observe_at(3, t0);
369        window.observe_at(70, t0 + WINDOW_SLOT);
370        window.observe_at(5, t0 + WINDOW_SLOT * 2);
371        assert_eq!(window.max_at(t0 + WINDOW_SLOT * 2), 70);
372    }
373
374    #[test]
375    fn peak_drops_values_older_than_the_window() {
376        let t0 = Instant::now();
377        let window = PeakWindow::new(t0);
378        window.observe_at(90, t0);
379        // The slot of the value is the oldest one still in the window.
380        assert_eq!(
381            window.max_at(t0 + WINDOW_SLOT * (WINDOW_SLOTS as u32 - 1)),
382            90
383        );
384        assert_eq!(window.max_at(t0 + WINDOW_SLOT * WINDOW_SLOTS as u32), 0);
385        window.observe_at(2, t0 + WINDOW_SLOT * WINDOW_SLOTS as u32);
386        assert_eq!(window.max_at(t0 + WINDOW_SLOT * WINDOW_SLOTS as u32), 2);
387    }
388
389    #[test]
390    fn peak_forgets_everything_after_a_gap_longer_than_the_window() {
391        let t0 = Instant::now();
392        let window = PeakWindow::new(t0);
393        for i in 0..WINDOW_SLOTS as u32 {
394            window.observe_at(100 + i as u64, t0 + WINDOW_SLOT * i);
395        }
396        assert_eq!(
397            window.max_at(t0 + WINDOW_SLOT * (WINDOW_SLOTS as u32 - 1)),
398            111
399        );
400        assert_eq!(window.max_at(t0 + WINDOW_SLOT * 100), 0);
401    }
402
403    #[test]
404    fn peak_accepts_a_late_value_for_a_slot_still_in_the_window() {
405        let t0 = Instant::now();
406        let window = PeakWindow::new(t0);
407        window.observe_at(1, t0 + WINDOW_SLOT * 3);
408        window.observe_at(9, t0 + WINDOW_SLOT);
409        assert_eq!(window.max_at(t0 + WINDOW_SLOT * 3), 9);
410    }
411
412    #[test]
413    fn concurrent_observations_end_with_the_highest_value() {
414        let window = Arc::new(PeakWindow::new(Instant::now()));
415        let threads: Vec<_> = (0..8u64)
416            .map(|t| {
417                let window = window.clone();
418                std::thread::spawn(move || {
419                    for i in 0..10_000u64 {
420                        window.observe(t * 10_000 + i);
421                    }
422                })
423            })
424            .collect();
425        for thread in threads {
426            thread.join().unwrap();
427        }
428        assert_eq!(window.max(), 79_999);
429    }
430
431    #[test]
432    fn observe_at_uses_the_given_time() {
433        let t0 = Instant::now();
434        let window = PeakWindow::new(t0);
435        window.observe_at(9, t0);
436        let later = t0 + WINDOW_SLOT * (WINDOW_SLOTS as u32 + 5);
437        window.observe_at(4, later);
438        assert_eq!(window.max_at(later), 4, "the earlier value left the window");
439    }
440
441    #[test]
442    fn a_late_value_at_the_edge_of_the_window_is_dropped() {
443        let t0 = Instant::now();
444        let window = PeakWindow::new(t0);
445        let edge = t0 + WINDOW_SLOT * WINDOW_SLOTS as u32;
446        window.observe_at(1, edge);
447        window.observe_at(9, t0);
448        assert_eq!(window.max_at(edge), 1);
449    }
450
451    #[test]
452    fn observing_in_the_current_slot_takes_no_lock() {
453        let t0 = Instant::now();
454        let window = Arc::new(PeakWindow::new(t0));
455        let _held = window.rotation.lock();
456        let (sender, receiver) = std::sync::mpsc::channel();
457        let observer = window.clone();
458        std::thread::spawn(move || {
459            observer.observe_at(1, t0);
460            sender.send(()).unwrap();
461        });
462        receiver
463            .recv_timeout(Duration::from_secs(5))
464            .expect("the observation waited for the rotation lock");
465    }
466
467    #[test]
468    fn peak_gauge_reports_the_exact_peak() {
469        let registry = Registry::new();
470        let gauge = PeakGauge::register(
471            "test_peak_gauge",
472            "help",
473            module_path!(),
474            &registry,
475            MetricLevel::Warn,
476        );
477        gauge.observe(32768);
478        gauge.observe(1500);
479        let families = registry.gather();
480        let family = families
481            .iter()
482            .find(|f| f.name() == "test_peak_gauge")
483            .unwrap();
484        assert_eq!(family.get_metric()[0].get_gauge().value(), 32768.0);
485    }
486
487    #[test]
488    fn int_gauge_with_peak_gauge_reports_the_peak_and_the_gauge() {
489        let registry = Registry::new();
490        let gauge = IntGaugeWithPeakGauge::register(
491            ("test_gauge", "help"),
492            ("test_gauge_peak", "help"),
493            module_path!(),
494            &registry,
495            MetricLevel::Warn,
496        );
497        let reader = MetricsReader::new(&registry);
498        for _ in 0..3 {
499            gauge.inc();
500        }
501        gauge.dec();
502        gauge.dec();
503        assert_eq!(reader.value("test_gauge", &[]), 1.0);
504        assert_eq!(reader.value("test_gauge_peak", &[]), 3.0);
505    }
506
507    #[test]
508    fn the_peak_of_a_gauge_is_never_below_the_gauge() {
509        let registry = Registry::new();
510        let gauge = IntGaugeWithPeakGauge::register(
511            ("test_gauge", "help"),
512            ("test_gauge_peak", "help"),
513            module_path!(),
514            &registry,
515            MetricLevel::Warn,
516        );
517        // The window of the peak holds no observation of this value.
518        gauge.gauge.set(5);
519        assert_eq!(
520            MetricsReader::new(&registry).value("test_gauge_peak", &[]),
521            5.0
522        );
523    }
524
525    #[test]
526    fn peak_with_a_floor_reports_the_peak_and_never_less_than_the_gauge() {
527        let registry = Registry::new();
528        let gauge = IntGauge::new("test_gauge", "help").unwrap();
529        let peak = PeakGauge::register_with_floor(
530            "test_gauge_peak",
531            "help",
532            module_path!(),
533            &registry,
534            MetricLevel::Warn,
535            Some(gauge.clone()),
536        );
537        let reader = MetricsReader::new(&registry);
538        for _ in 0..3 {
539            gauge.inc();
540            peak.observe(gauge.get() as u64);
541        }
542        gauge.dec();
543        gauge.dec();
544        assert_eq!(reader.value("test_gauge_peak", &[]), 3.0);
545
546        peak.window
547            .observe_at(0, Instant::now() + WINDOW_SLOT * (WINDOW_SLOTS as u32 + 1));
548        assert_eq!(
549            reader.value("test_gauge_peak", &[]),
550            1.0,
551            "the window is empty, so the peak is the current gauge"
552        );
553    }
554
555    #[test]
556    fn peak_gauge_vec_reports_the_peak_per_label_value() {
557        let registry = Registry::new();
558        let gauge = PeakGaugeVec::register(
559            "test_gauge_vec_peak",
560            "help",
561            "kind",
562            module_path!(),
563            &registry,
564            MetricLevel::Warn,
565        );
566        let (a, b) = (
567            gauge.with_label_values(&["a"]),
568            gauge.with_label_values(&["b"]),
569        );
570        a.observe(2);
571        a.observe(1);
572        b.observe(7);
573        let reader = MetricsReader::new(&registry);
574        assert_eq!(reader.value("test_gauge_vec_peak", &[("kind", "a")]), 2.0);
575        assert_eq!(reader.value("test_gauge_vec_peak", &[("kind", "b")]), 7.0);
576        assert_eq!(
577            gauge.with_label_values(&["a"]).window.max(),
578            2,
579            "a second peak of the label value shares the window"
580        );
581    }
582
583    #[test]
584    fn threads_that_get_the_same_peak_share_one_window() {
585        let registry = Registry::new();
586        let gauge = PeakGaugeVec::register(
587            "test_gauge_vec_threads",
588            "help",
589            "kind",
590            module_path!(),
591            &registry,
592            MetricLevel::Warn,
593        );
594        for round in 0..200 {
595            let label = round.to_string();
596            let barrier = std::sync::Barrier::new(8);
597            std::thread::scope(|scope| {
598                for value in 1..=8 {
599                    let (gauge, barrier, label) = (&gauge, &barrier, label.as_str());
600                    scope.spawn(move || {
601                        barrier.wait();
602                        gauge.with_label_values(&[label]).observe(value);
603                    });
604                }
605            });
606            assert_eq!(
607                gauge.with_label_values(&[&label]).window.max(),
608                8,
609                "round {round}"
610            );
611        }
612    }
613}