Skip to main content

saluki_metrics/
derived.rs

1//! Support for gauges that track the lowest or highest value recorded to a histogram.
2
3#[cfg(not(all(test, feature = "loom")))]
4use std::sync::{atomic::AtomicU64, Mutex};
5use std::sync::{atomic::Ordering::Relaxed, Arc, PoisonError};
6
7#[cfg(all(test, feature = "loom"))]
8use loom::sync::{atomic::AtomicU64, Mutex};
9use metrics::{Gauge, Histogram, IntoF64};
10
11/// The bits of the starting value. `NaN` means that the tracker holds no value yet.
12const UNSET: u64 = f64::NAN.to_bits();
13
14#[derive(Clone, Copy, Debug)]
15enum Kind {
16    Min,
17    Max,
18}
19
20impl Kind {
21    /// Returns `true` if `value` is lower (`Min`) or higher (`Max`) than `current`.
22    ///
23    /// A `NaN` value never improves. Any other value improves on an unset (`NaN`) current value.
24    #[inline]
25    fn improves(self, value: f64, current: f64) -> bool {
26        !value.is_nan()
27            && (current.is_nan()
28                || match self {
29                    Kind::Min => value < current,
30                    Kind::Max => value > current,
31                })
32    }
33}
34
35#[derive(Debug)]
36struct State {
37    current: AtomicU64,
38    gauge: Mutex<Gauge>,
39}
40
41/// A gauge that holds the lowest or highest value observed so far.
42///
43/// The gauge only changes when a value is lower (for `min`) or higher (for `max`) than all values observed before it,
44/// so it never moves back. The gauge ignores `NaN` values. The tracked value never resets.
45///
46/// Clones share the tracking state, so every clone of the containing metrics struct updates the same value. Separate
47/// instances do not share state: if two instances write to the same gauge, the gauge can move back.
48///
49/// This type is an implementation detail of the `static_metrics` attribute macro. Don't construct or use it directly.
50#[derive(Clone, Debug)]
51pub struct DerivedGauge {
52    kind: Kind,
53    state: Arc<State>,
54}
55
56impl DerivedGauge {
57    fn new(kind: Kind, gauge: Gauge) -> Self {
58        Self {
59            kind,
60            state: Arc::new(State {
61                current: AtomicU64::new(UNSET),
62                gauge: Mutex::new(gauge),
63            }),
64        }
65    }
66
67    /// Creates a `DerivedGauge` that sets `gauge` to the lowest value observed.
68    pub fn min(gauge: Gauge) -> Self {
69        Self::new(Kind::Min, gauge)
70    }
71
72    /// Creates a `DerivedGauge` that sets `gauge` to the highest value observed.
73    pub fn max(gauge: Gauge) -> Self {
74        Self::new(Kind::Max, gauge)
75    }
76
77    /// Observes a value, and updates the gauge if the value is a new lowest or highest value.
78    #[inline]
79    pub fn observe(&self, value: f64) {
80        // `current` only moves toward the extreme, so a stale value here can only send us to `publish` without need.
81        if self
82            .kind
83            .improves(value, f64::from_bits(self.state.current.load(Relaxed)))
84        {
85            self.publish(value);
86        }
87    }
88
89    #[cold]
90    #[inline(never)]
91    fn publish(&self, value: f64) {
92        // All writes to `current` and to the gauge happen under this lock, so the gauge never moves back. We store
93        // `current` before we set the gauge, so a panic in `set` can't let a later, worse value overwrite this one.
94        let gauge = self.state.gauge.lock().unwrap_or_else(PoisonError::into_inner);
95        if self
96            .kind
97            .improves(value, f64::from_bits(self.state.current.load(Relaxed)))
98        {
99            self.state.current.store(value.to_bits(), Relaxed);
100            gauge.set(value);
101        }
102    }
103}
104
105/// A histogram that also updates one or more [`DerivedGauge`]s.
106///
107/// The accessor that `static_metrics` generates for a histogram field with `#[metric(derived(...))]` returns this type.
108/// Each recorded value goes to the histogram, then to each derived gauge.
109#[derive(Clone, Copy, Debug)]
110#[must_use = "histograms do nothing unless you use them"]
111pub struct DerivedHistogram<'a> {
112    histogram: &'a Histogram,
113    derived: &'a [DerivedGauge],
114}
115
116impl<'a> DerivedHistogram<'a> {
117    /// Creates a `DerivedHistogram` from a histogram and its derived gauges.
118    ///
119    /// This is an implementation detail of the `static_metrics` attribute macro.
120    pub fn new(histogram: &'a Histogram, derived: &'a [DerivedGauge]) -> Self {
121        Self { histogram, derived }
122    }
123
124    /// Records a value into the histogram, and updates the derived gauges.
125    pub fn record<T: IntoF64>(&self, value: T) {
126        let value = value.into_f64();
127        self.histogram.record(value);
128        self.observe(value);
129    }
130
131    /// Records a value into the histogram multiple times, and updates the derived gauges.
132    ///
133    /// If `count` is zero, this method records nothing and leaves the derived gauges unchanged.
134    pub fn record_many<T: IntoF64>(&self, value: T, count: usize) {
135        let value = value.into_f64();
136        self.histogram.record_many(value, count);
137        if count > 0 {
138            self.observe(value);
139        }
140    }
141
142    fn observe(&self, value: f64) {
143        for derived in self.derived {
144            derived.observe(value);
145        }
146    }
147}
148
149#[cfg(all(test, not(feature = "loom")))]
150mod tests {
151    use std::{sync::Mutex as StdMutex, thread};
152
153    use metrics::{GaugeFn, HistogramFn, Key, Label};
154    use proptest::{collection::vec, prelude::*};
155
156    use super::*;
157
158    /// A gauge that records every value passed to `set`, so that tests can tell a missing write from a repeated one.
159    #[derive(Default)]
160    struct RecordingGauge {
161        writes: StdMutex<Vec<f64>>,
162    }
163
164    impl RecordingGauge {
165        fn writes(&self) -> Vec<f64> {
166            self.writes.lock().unwrap().clone()
167        }
168    }
169
170    impl GaugeFn for RecordingGauge {
171        fn increment(&self, _: f64) {
172            unreachable!("derived gauges only call `set`");
173        }
174
175        fn decrement(&self, _: f64) {
176            unreachable!("derived gauges only call `set`");
177        }
178
179        fn set(&self, value: f64) {
180            self.writes.lock().unwrap().push(value);
181        }
182    }
183
184    #[derive(Default)]
185    struct RecordingHistogram {
186        samples: StdMutex<Vec<f64>>,
187    }
188
189    impl HistogramFn for RecordingHistogram {
190        fn record(&self, value: f64) {
191            self.samples.lock().unwrap().push(value);
192        }
193    }
194
195    fn recording_tracker(kind: Kind) -> (DerivedGauge, Arc<RecordingGauge>) {
196        let recording = Arc::new(RecordingGauge::default());
197        let derived = DerivedGauge::new(kind, Gauge::from_arc(Arc::clone(&recording)));
198        (derived, recording)
199    }
200
201    fn observe_all(derived: &DerivedGauge, values: &[f64]) {
202        for value in values {
203            derived.observe(*value);
204        }
205    }
206
207    #[test]
208    fn max_writes_only_new_highest_values() {
209        let (derived, recording) = recording_tracker(Kind::Max);
210        observe_all(&derived, &[5.0, 3.0, 5.0, 7.0, 6.0]);
211        assert_eq!(recording.writes(), vec![5.0, 7.0]);
212    }
213
214    #[test]
215    fn min_writes_only_new_lowest_values() {
216        let (derived, recording) = recording_tracker(Kind::Min);
217        observe_all(&derived, &[5.0, 7.0, 5.0, 3.0, 4.0]);
218        assert_eq!(recording.writes(), vec![5.0, 3.0]);
219    }
220
221    #[test]
222    fn nan_never_changes_the_gauge() {
223        let (derived, recording) = recording_tracker(Kind::Max);
224        observe_all(&derived, &[f64::NAN, f64::NAN]);
225        assert!(recording.writes().is_empty());
226
227        observe_all(&derived, &[1.0, f64::NAN, 2.0]);
228        assert_eq!(recording.writes(), vec![1.0, 2.0]);
229    }
230
231    #[test]
232    fn infinities_are_published() {
233        // An infinite starting value would hide these, so the tracker starts unset instead.
234        let (derived, recording) = recording_tracker(Kind::Max);
235        observe_all(&derived, &[f64::NEG_INFINITY, 1.0, f64::INFINITY]);
236        assert_eq!(recording.writes(), vec![f64::NEG_INFINITY, 1.0, f64::INFINITY]);
237
238        let (derived, recording) = recording_tracker(Kind::Min);
239        observe_all(&derived, &[f64::INFINITY, -1.0, f64::NEG_INFINITY]);
240        assert_eq!(recording.writes(), vec![f64::INFINITY, -1.0, f64::NEG_INFINITY]);
241    }
242
243    #[test]
244    fn clones_share_tracked_value() {
245        let (derived, recording) = recording_tracker(Kind::Max);
246        let clone = derived.clone();
247        derived.observe(10.0);
248        clone.observe(5.0);
249        assert_eq!(recording.writes(), vec![10.0]);
250
251        let threads: Vec<_> = (0..4)
252            .map(|offset| {
253                let derived = derived.clone();
254                thread::spawn(move || {
255                    for i in 0..1_000 {
256                        derived.observe(f64::from(i * 4 + offset));
257                    }
258                })
259            })
260            .collect();
261        for thread in threads {
262            thread.join().unwrap();
263        }
264
265        let writes = recording.writes();
266        assert!(
267            writes.windows(2).all(|pair| pair[1] > pair[0]),
268            "gauge moved backwards: {writes:?}"
269        );
270        assert_eq!(writes.last(), Some(&3_999.0));
271    }
272
273    #[test]
274    fn derived_histogram_records_then_updates_every_gauge() {
275        let samples = Arc::new(RecordingHistogram::default());
276        let histogram = Histogram::from_arc(Arc::clone(&samples));
277        let (min, min_recording) = recording_tracker(Kind::Min);
278        let (max, max_recording) = recording_tracker(Kind::Max);
279        let derived = [min, max];
280        let wrapped = DerivedHistogram::new(&histogram, &derived);
281
282        wrapped.record(4u32);
283        wrapped.record(2.0);
284        wrapped.record(8.0);
285
286        assert_eq!(*samples.samples.lock().unwrap(), vec![4.0, 2.0, 8.0]);
287        assert_eq!(min_recording.writes(), vec![4.0, 2.0]);
288        assert_eq!(max_recording.writes(), vec![4.0, 8.0]);
289    }
290
291    #[test]
292    fn record_many_observes_once_and_not_at_all_for_zero() {
293        let samples = Arc::new(RecordingHistogram::default());
294        let histogram = Histogram::from_arc(Arc::clone(&samples));
295        let (max, recording) = recording_tracker(Kind::Max);
296        let derived = [max];
297        let wrapped = DerivedHistogram::new(&histogram, &derived);
298
299        wrapped.record_many(9.0, 0);
300        assert!(samples.samples.lock().unwrap().is_empty());
301        assert!(recording.writes().is_empty());
302
303        wrapped.record_many(3.0, 2);
304        assert_eq!(*samples.samples.lock().unwrap(), vec![3.0, 3.0]);
305        assert_eq!(recording.writes(), vec![3.0]);
306    }
307
308    #[crate::static_metrics(prefix = derived_test, labels(id))]
309    #[derive(Clone)]
310    struct Telemetry {
311        #[metric(mapped(reason))]
312        dropped_total: crate::Counter,
313        #[metric(derived(min, max))]
314        latency_seconds: crate::Histogram,
315    }
316
317    #[test]
318    fn static_metrics_registers_and_updates_derived_gauges() {
319        let recorder = crate::test::TestRecorder::default();
320        let _recorder_guard = metrics::set_default_local_recorder(&recorder);
321        let key = |name: &'static str| Key::from_parts(name, vec![Label::new("id", "a")]);
322
323        assert_eq!(Telemetry::latency_seconds_name(), "derived_test_latency_seconds");
324        assert_eq!(
325            Telemetry::latency_seconds_min_name(),
326            "derived_test_latency_seconds_min"
327        );
328        assert_eq!(
329            Telemetry::latency_seconds_max_name(),
330            "derived_test_latency_seconds_max"
331        );
332        assert_eq!(Telemetry::dropped_total_name(), "derived_test_dropped_total");
333
334        let telemetry = Telemetry::new("a");
335
336        // The gauges register in `new()`, with the histogram's labels, so they read 0 before the first value.
337        assert_eq!(recorder.gauge(key("derived_test_latency_seconds_min")), Some(0.0));
338        assert_eq!(recorder.gauge(key("derived_test_latency_seconds_max")), Some(0.0));
339
340        let clone = telemetry.clone();
341        telemetry.latency_seconds().record(0.5);
342        clone.latency_seconds().record(2.0);
343        telemetry.latency_seconds().record(0.25);
344        clone.latency_seconds().record(1.0);
345
346        assert_eq!(
347            recorder.histogram(key("derived_test_latency_seconds")),
348            Some(vec![0.5, 2.0, 0.25, 1.0])
349        );
350        assert_eq!(recorder.gauge(key("derived_test_latency_seconds_min")), Some(0.25));
351        assert_eq!(recorder.gauge(key("derived_test_latency_seconds_max")), Some(2.0));
352
353        telemetry.dropped_total("full").increment(1);
354        let dropped_key = Key::from_parts(
355            "derived_test_dropped_total",
356            vec![Label::new("id", "a"), Label::new("reason", "full")],
357        );
358        assert_eq!(recorder.counter(dropped_key), Some(1));
359    }
360
361    proptest! {
362        #[test]
363        fn property_test_derived_gauge_matches_running_extreme(
364            // `any::<f64>()` never yields `NaN` or infinities, and small integers make repeated values likely.
365            values in vec(prop_oneof![(-4i8..4).prop_map(f64::from), proptest::num::f64::ANY], 0..64),
366            track_max in any::<bool>(),
367        ) {
368            let (derived, recording) = recording_tracker(if track_max { Kind::Max } else { Kind::Min });
369
370            // The model publishes each non-`NaN` value that is strictly lower or higher than every value before it.
371            let mut expected = Vec::new();
372            let mut extreme: Option<f64> = None;
373            for value in &values {
374                derived.observe(*value);
375                let improves = !value.is_nan()
376                    && extreme.is_none_or(|extreme| if track_max { *value > extreme } else { *value < extreme });
377                if improves {
378                    extreme = Some(*value);
379                    expected.push(*value);
380                }
381            }
382
383            prop_assert_eq!(recording.writes(), expected);
384        }
385    }
386}
387
388#[cfg(all(test, feature = "loom"))]
389mod loom_tests {
390    use loom::sync::{atomic::AtomicU64, Mutex};
391    use metrics::GaugeFn;
392
393    use super::*;
394
395    /// A gauge that records every value passed to `set`.
396    ///
397    /// It uses a loom mutex, so loom can switch threads between a tracker update and the gauge write.
398    #[derive(Default)]
399    struct RecordingGauge {
400        writes: Mutex<Vec<f64>>,
401    }
402
403    impl GaugeFn for RecordingGauge {
404        fn increment(&self, _: f64) {
405            unreachable!("derived gauges only call `set`");
406        }
407
408        fn decrement(&self, _: f64) {
409            unreachable!("derived gauges only call `set`");
410        }
411
412        fn set(&self, value: f64) {
413            self.writes.lock().unwrap().push(value);
414        }
415    }
416
417    /// A tracker that updates its value with a CAS and then sets the gauge outside any lock.
418    ///
419    /// Two callers can both win a CAS and then set the gauge in the opposite order. This is the race that
420    /// `DerivedGauge::publish` prevents with its lock.
421    struct UnlockedTracker {
422        current: AtomicU64,
423        gauge: Gauge,
424    }
425
426    impl UnlockedTracker {
427        fn observe(&self, value: f64) {
428            let updated = self.current.fetch_update(Relaxed, Relaxed, |current| {
429                Kind::Max
430                    .improves(value, f64::from_bits(current))
431                    .then_some(value.to_bits())
432            });
433            if updated.is_ok() {
434                self.gauge.set(value);
435            }
436        }
437    }
438
439    fn check_writes(writes: &[f64], inputs: &[f64], kind: Kind, expected: f64) {
440        for pair in writes.windows(2) {
441            assert!(
442                kind.improves(pair[1], pair[0]),
443                "gauge moved backwards or repeated a value: {writes:?}"
444            );
445        }
446        assert_eq!(writes.last(), Some(&expected), "final gauge value is wrong: {writes:?}");
447        assert!(
448            writes.iter().all(|write| inputs.contains(write)),
449            "unexpected write: {writes:?}"
450        );
451    }
452
453    /// Observes `inputs[0]` on the model's main thread and each other input on its own thread.
454    fn model_derived_gauge(kind: Kind, inputs: [f64; 3], expected: f64) {
455        loom::model(move || {
456            let recording = Arc::new(RecordingGauge::default());
457            let derived = DerivedGauge::new(kind, Gauge::from_arc(Arc::clone(&recording)));
458
459            let threads: Vec<_> = inputs[1..]
460                .iter()
461                .map(|&value| {
462                    let derived = derived.clone();
463                    loom::thread::spawn(move || derived.observe(value))
464                })
465                .collect();
466            derived.observe(inputs[0]);
467            for thread in threads {
468                thread.join().unwrap();
469            }
470
471            check_writes(&recording.writes.lock().unwrap(), &inputs, kind, expected);
472        });
473    }
474
475    #[test]
476    fn max_never_moves_back_and_ends_at_highest() {
477        model_derived_gauge(Kind::Max, [2.0, 3.0, 1.0], 3.0);
478    }
479
480    #[test]
481    fn min_never_moves_back_and_ends_at_lowest() {
482        model_derived_gauge(Kind::Min, [2.0, 1.0, 3.0], 1.0);
483    }
484
485    #[test]
486    fn equal_values_write_once() {
487        model_derived_gauge(Kind::Max, [2.0, 2.0, 1.0], 2.0);
488    }
489
490    // Shows that the model can catch the race that the lock in `DerivedGauge::publish` prevents.
491    #[test]
492    #[should_panic(expected = "gauge moved backwards")]
493    fn unlocked_publish_can_move_the_gauge_back() {
494        loom::model(|| {
495            let recording = Arc::new(RecordingGauge::default());
496            let tracker = Arc::new(UnlockedTracker {
497                current: AtomicU64::new(UNSET),
498                gauge: Gauge::from_arc(Arc::clone(&recording)),
499            });
500
501            let other = Arc::clone(&tracker);
502            let thread = loom::thread::spawn(move || other.observe(2.0));
503            tracker.observe(1.0);
504            thread.join().unwrap();
505
506            check_writes(&recording.writes.lock().unwrap(), &[1.0, 2.0], Kind::Max, 2.0);
507        });
508    }
509}