Skip to main content

ntex_rt/
metrics.rs

1//! Runtime, arbiter, and blocking thread pool metrics.
2//!
3//! Use [`Histogram`] for duration distributions, [`LatencyMetrics`] for arbiter
4//! scheduling latency, [`PoolMetrics`] for blocking pool activity, and
5//! [`PingRecord`] for arbiter ping results.
6
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, OnceLock};
9use std::{future::poll_fn, time::Duration, time::Instant};
10
11use crate::time::TimerHandle;
12
13pub use crate::pool::PoolMetrics;
14pub use crate::system::PingRecord;
15
16/// Number of [`Histogram`] buckets.
17pub const HISTOGRAM_BUCKETS: usize = 16;
18
19/// upper bound of the first bucket, in microseconds
20const FIRST_BUCKET_US: u64 = 16;
21
22/// Snapshot of a duration histogram.
23///
24/// Bucket `0` counts durations below 16µs, bucket `i` counts durations in
25/// `[16µs * 2^(i-1), 16µs * 2^i)`, and the last bucket counts durations of
26/// 262.144ms and longer.
27///
28/// Counts are totals since the histogram was created, the distribution over an
29/// interval is the [`delta`](Self::delta) of two snapshots.
30/// Buckets are sampled independently, so a concurrent snapshot need not
31/// represent one instant in time. Counts and arithmetic wrap on overflow.
32#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
33pub struct Histogram {
34    buckets: [u64; HISTOGRAM_BUCKETS],
35}
36
37impl Histogram {
38    /// Returns the bucket counts.
39    pub fn buckets(&self) -> &[u64; HISTOGRAM_BUCKETS] {
40        &self.buckets
41    }
42
43    /// Returns the total number of recorded durations.
44    pub fn count(&self) -> u64 {
45        self.buckets.iter().fold(0, |acc, c| acc.wrapping_add(*c))
46    }
47
48    /// Returns the duration range of a bucket.
49    ///
50    /// The lower bound is inclusive, the upper bound is exclusive and `None`
51    /// for the last bucket.
52    ///
53    /// # Panics
54    ///
55    /// Panics if `idx` is not less than [`HISTOGRAM_BUCKETS`].
56    pub fn bucket_range(idx: usize) -> (Duration, Option<Duration>) {
57        assert!(idx < HISTOGRAM_BUCKETS, "bucket index out of range");
58        let upper = |i: usize| Duration::from_micros(FIRST_BUCKET_US << i);
59        let lower = if idx == 0 { Duration::ZERO } else { upper(idx - 1) };
60        if idx == HISTOGRAM_BUCKETS - 1 {
61            (lower, None)
62        } else {
63            (lower, Some(upper(idx)))
64        }
65    }
66
67    /// Returns the counts recorded since the `prev` snapshot.
68    ///
69    /// `prev` should be an earlier snapshot of the same histogram. Subtraction
70    /// wraps to account for counter overflow rather than saturating at zero.
71    #[must_use]
72    pub fn delta(&self, prev: &Histogram) -> Histogram {
73        let mut buckets = self.buckets;
74        for (b, p) in buckets.iter_mut().zip(prev.buckets.iter()) {
75            *b = b.wrapping_sub(*p);
76        }
77        Histogram { buckets }
78    }
79
80    /// Returns the sum of two histograms, for example to combine the
81    /// histograms of several runtimes.
82    #[must_use]
83    pub fn merge(&self, other: &Histogram) -> Histogram {
84        let mut buckets = self.buckets;
85        for (b, o) in buckets.iter_mut().zip(other.buckets.iter()) {
86            *b = b.wrapping_add(*o);
87        }
88        Histogram { buckets }
89    }
90}
91
92/// Duration histogram updated by a single thread.
93#[derive(Debug, Default)]
94pub(crate) struct AtomicHistogram {
95    buckets: [AtomicU64; HISTOGRAM_BUCKETS],
96}
97
98impl AtomicHistogram {
99    fn bucket(d: Duration) -> usize {
100        if d < Duration::from_micros(FIRST_BUCKET_US) {
101            0
102        } else {
103            let us = u64::try_from(d.as_micros()).unwrap_or(u64::MAX);
104            // 16µs..32µs is bucket 1
105            let idx = (63 - us.leading_zeros() as usize) - 3;
106            idx.min(HISTOGRAM_BUCKETS - 1)
107        }
108    }
109
110    /// Records a duration, must be called by a single thread.
111    pub(crate) fn record(&self, d: Duration) {
112        let b = &self.buckets[Self::bucket(d)];
113        b.store(b.load(Ordering::Relaxed).wrapping_add(1), Ordering::Relaxed);
114    }
115
116    pub(crate) fn snapshot(&self) -> Histogram {
117        let mut buckets = [0; HISTOGRAM_BUCKETS];
118        for (b, a) in buckets.iter_mut().zip(self.buckets.iter()) {
119            *b = a.load(Ordering::Relaxed);
120        }
121        Histogram { buckets }
122    }
123}
124
125/// Snapshot of an arbiter's scheduling latency.
126///
127/// The arbiter runs a task that sleeps for `interval` on the runtime timer
128/// wheel and records how late it wakes up. Lateness is measured from the
129/// deadline of the wheel, which rounds `interval` up to the wheel granularity.
130/// It includes the time the runtime spent running other tasks and handling
131/// driver events, and the timer's own wake-up latency.
132/// Fields are sampled independently and may be slightly inconsistent during
133/// concurrent updates.
134#[derive(Copy, Clone, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub struct LatencyMetrics {
137    /// Sampling interval.
138    pub interval: Duration,
139    /// Lateness of the most recent sample, or zero before the first sample.
140    pub last: Duration,
141    /// Lateness of all samples.
142    pub histogram: Histogram,
143    /// Time of the most recent sample, `None` if no sample has been recorded.
144    ///
145    /// A time much older than `interval` means the arbiter is blocked.
146    pub last_sample: Option<Instant>,
147    /// Number of stalls detected by the watchdog.
148    ///
149    /// An arbiter is stalled when its pending sample is late by more than
150    /// the [`ping_threshold`](crate::Builder::ping_threshold).
151    pub stalls: u64,
152    /// Total lateness accumulated by recovered stalls.
153    ///
154    /// Each recovery contributes the lateness of the sample that ended the
155    /// stall. A stall still in progress is not included.
156    pub stall_duration: Duration,
157    /// Whether the arbiter is currently stalled.
158    pub stalled: bool,
159}
160
161/// Change of an arbiter stall state.
162#[derive(Debug, PartialEq, Eq)]
163pub(crate) enum Stall {
164    None,
165    /// Arbiter stalled, time since the last sample
166    Started(Duration),
167    /// Arbiter recovered, duration of the stall
168    Recovered(Duration),
169}
170
171#[derive(Debug, Default)]
172pub(crate) struct LatencyStats {
173    // in nanoseconds, zero if sampling is disabled
174    interval: AtomicU64,
175    last: AtomicU64,
176    // nanoseconds since `base`, plus one, zero before the first sample
177    last_sample: AtomicU64,
178    // deadline of the pending sample, nanoseconds since `base`
179    next: AtomicU64,
180    base: OnceLock<Instant>,
181    histogram: AtomicHistogram,
182    // written by the watchdog thread only
183    stalls: AtomicU64,
184    stall_duration: AtomicU64,
185    stalled: AtomicBool,
186    // expected sample time of the current stall, nanoseconds since `base`
187    stalled_at: AtomicU64,
188}
189
190fn as_nanos(d: Duration) -> u64 {
191    u64::try_from(d.as_nanos()).unwrap_or(u64::MAX)
192}
193
194impl LatencyStats {
195    fn record(&self, lateness: Duration, now: Instant) {
196        let base = *self.base.get_or_init(|| now);
197        self.histogram.record(lateness);
198        self.last.store(as_nanos(lateness), Ordering::Relaxed);
199        self.last_sample
200            .store(as_nanos(now - base).saturating_add(1), Ordering::Relaxed);
201    }
202
203    /// Sets the deadline of the pending sample.
204    fn expect(&self, deadline: Instant) {
205        let base = *self.base.get_or_init(|| deadline);
206        self.next
207            .store(as_nanos(deadline - base), Ordering::Relaxed);
208    }
209
210    pub(crate) fn metrics(&self) -> Option<LatencyMetrics> {
211        let interval = self.interval.load(Ordering::Relaxed);
212        if interval == 0 {
213            return None;
214        }
215        let last_sample = match self.last_sample.load(Ordering::Relaxed) {
216            0 => None,
217            n => self
218                .base
219                .get()
220                .map(|base| *base + Duration::from_nanos(n - 1)),
221        };
222        Some(LatencyMetrics {
223            interval: Duration::from_nanos(interval),
224            last: Duration::from_nanos(self.last.load(Ordering::Relaxed)),
225            histogram: self.histogram.snapshot(),
226            last_sample,
227            stalls: self.stalls.load(Ordering::Relaxed),
228            stall_duration: Duration::from_nanos(self.stall_duration.load(Ordering::Relaxed)),
229            stalled: self.stalled.load(Ordering::Relaxed),
230        })
231    }
232
233    /// Checks whether the arbiter stopped recording samples.
234    ///
235    /// Must be called from a single thread.
236    pub(crate) fn check(&self, now: Instant, threshold: Duration) -> Stall {
237        let interval = Duration::from_nanos(self.interval.load(Ordering::Relaxed));
238        let Some(base) = self.base.get() else {
239            return Stall::None;
240        };
241        if interval.is_zero() {
242            return Stall::None;
243        }
244
245        // sampler start time until the first sample
246        let last = self.last_sample.load(Ordering::Relaxed).saturating_sub(1);
247        if self.stalled.load(Ordering::Relaxed) {
248            let expected = self.stalled_at.load(Ordering::Relaxed);
249            if last < expected {
250                return Stall::None;
251            }
252            let stall = Duration::from_nanos(last - expected);
253            self.stalled.store(false, Ordering::Relaxed);
254            self.stall_duration.store(
255                self.stall_duration
256                    .load(Ordering::Relaxed)
257                    .saturating_add(as_nanos(stall)),
258                Ordering::Relaxed,
259            );
260            Stall::Recovered(stall)
261        } else {
262            // The pending deadline is at least `interval` after the last
263            // sample, a deadline older than the last sample is stale
264            let expected = self
265                .next
266                .load(Ordering::Relaxed)
267                .max(last.saturating_add(as_nanos(interval)));
268            let late = now.saturating_duration_since(*base + Duration::from_nanos(expected));
269            if late <= threshold {
270                return Stall::None;
271            }
272            let age = now.saturating_duration_since(*base + Duration::from_nanos(last));
273            self.stalled_at.store(expected, Ordering::Relaxed);
274            self.stalled.store(true, Ordering::Relaxed);
275            self.stalls.store(
276                self.stalls.load(Ordering::Relaxed).wrapping_add(1),
277                Ordering::Relaxed,
278            );
279            Stall::Started(age)
280        }
281    }
282}
283
284/// Samples the scheduling latency of the current arbiter.
285pub(crate) fn start_latency_sampler(stats: &Arc<LatencyStats>, interval_ms: usize) {
286    if interval_ms == 0 {
287        return;
288    }
289    let interval = Duration::from_millis(interval_ms as u64);
290    stats.base.get_or_init(Instant::now);
291    stats.interval.store(as_nanos(interval), Ordering::Relaxed);
292
293    let stats = stats.clone();
294    crate::spawn_detached(async move {
295        let timer = TimerHandle::new(0);
296        // a stale handle means the runtime is gone
297        while let Some(deadline) = timer.reset_deadline(interval_ms as u64) {
298            stats.expect(deadline);
299            poll_fn(|cx| timer.poll_elapsed(cx)).await;
300            let now = Instant::now();
301            stats.record(now.saturating_duration_since(deadline), now);
302        }
303    });
304}
305
306#[cfg(test)]
307#[path = "../tests/unit/metrics.rs"]
308mod tests;