Skip to main content

mira_core/
diag.rs

1//! Where an export's latency actually goes, measured from inside the process.
2//!
3//! These exist because the 32-to-96-connection plateau could not be explained
4//! from outside. A closed-loop load generator reports `connections × batch /
5//! ack latency`, so every hypothesis predicts the same throughput curve, and
6//! the server's CPU was flat at 2.23 of 12 cores at both ends of the sweep —
7//! which rules out "it is working harder" and says nothing about what it is
8//! doing instead. The answer needed a number from inside: the parts of
9//! `submit` do not add up to `submit`, and the gap is the finding.
10//!
11//! They are also the reason the finding is checkable. Section 11's numbers are
12//! reproducible on the machine that produced them, and a diagnosis resting on
13//! instrumentation that was deleted before the commit is not.
14//!
15//! **Cost.** Two `Instant::now()` pairs and five relaxed atomics per export.
16//! On aarch64-apple-darwin `Instant::now()` is `mach_absolute_time`, ~25 ns, so
17//! the whole of it is under 150 ns against a critical section measured at 2.2
18//! ms — five parts per million, and it is on the path whose *milliseconds* are
19//! the subject. Nothing here allocates and nothing takes a lock; a counter that
20//! contended would be measuring itself.
21//!
22//! **Reading them.** Nothing prints unless the dump task is running, which
23//! `mira` only starts when its target is enabled:
24//!
25//! ```sh
26//! RUST_LOG=mira=info,mira_core=info,mira::probe=debug mira --data-dir ./data
27//! ```
28//!
29//! Counters are cumulative from start, so two dumps five seconds apart are a
30//! rate and one dump is a mean over the run.
31
32use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
33
34/// Count, total, maximum and two tail buckets for one interval.
35///
36/// Not a histogram: the question these answer is "which of these three numbers
37/// is the other two", and a mean plus a max plus how many samples were absurd
38/// settles that in four atomics. A real histogram would be the right shape for
39/// an SLO and the wrong shape for an afternoon.
40#[derive(Default)]
41pub struct Probe {
42    pub n: AtomicU64,
43    pub ns: AtomicU64,
44    pub max_ns: AtomicU64,
45    pub over_10ms: AtomicU64,
46    pub over_100ms: AtomicU64,
47}
48
49impl Probe {
50    pub const fn new() -> Self {
51        Self {
52            n: AtomicU64::new(0),
53            ns: AtomicU64::new(0),
54            max_ns: AtomicU64::new(0),
55            over_10ms: AtomicU64::new(0),
56            over_100ms: AtomicU64::new(0),
57        }
58    }
59
60    pub fn record(&self, ns: u64) {
61        self.n.fetch_add(1, Relaxed);
62        self.ns.fetch_add(ns, Relaxed);
63        self.max_ns.fetch_max(ns, Relaxed);
64        if ns > 10_000_000 {
65            self.over_10ms.fetch_add(1, Relaxed);
66        }
67        if ns > 100_000_000 {
68            self.over_100ms.fetch_add(1, Relaxed);
69        }
70    }
71
72    fn line(&self, name: &str) -> String {
73        let n = self.n.load(Relaxed);
74        let ns = self.ns.load(Relaxed);
75        format!(
76            "{name:<18} n={n:<9} total={:>9.3}s mean={:>8.3}ms max={:>9.3}ms >10ms={:<8} >100ms={}",
77            ns as f64 / 1e9,
78            ns.checked_div(n).unwrap_or(0) as f64 / 1e6,
79            self.max_ns.load(Relaxed) as f64 / 1e6,
80            self.over_10ms.load(Relaxed),
81            self.over_100ms.load(Relaxed),
82        )
83    }
84}
85
86/// Entering [`crate::wal::Wal::append_then`] to holding the log's mutex.
87///
88/// The headline. There is one mutex for all three signals and all shards, and
89/// this is what every appender pays for the one inside it.
90pub static WAL_LOCK_WAIT: Probe = Probe::new();
91/// Holding it: the CRC over the body, the three `write_all`s, the enqueue.
92pub static WAL_HELD: Probe = Probe::new();
93/// Of that, just the three `write_all` syscalls.
94pub static WAL_WRITE: Probe = Probe::new();
95/// `encode_to_vec` — the re-encode an export pays to be framed.
96pub static WAL_ENCODE: Probe = Probe::new();
97/// Admission: `reserve()`, plus the `ADMIT_WAIT` park if every shard was full.
98pub static SUBMIT_ADMIT: Probe = Probe::new();
99/// The whole of `submit`, so the parts can be checked against the sum. They do
100/// not add up, which is the entire reason the rest of this module exists.
101pub static SUBMIT_TOTAL: Probe = Probe::new();
102/// Waiting for the publish, on the no-log ack path.
103pub static SUBMIT_WAIT_ACK: Probe = Probe::new();
104
105/// How late a task that asked to sleep 50 ms actually woke.
106///
107/// The one number here that owes nothing to the client. Ack latency cannot
108/// separate "the server is working hard" from "the server cannot schedule
109/// anything"; this can, because it measures a task that does no work at all.
110/// A 50 ms sleep returning 110 ms late means every runtime worker was blocked
111/// in a syscall, and no property of the connection count or the load generator
112/// explains it.
113pub static RUNTIME_LAG: Probe = Probe::new();
114
115/// Callers currently inside `append_then`, and the high-water mark.
116///
117/// The mark is the proof, not the gauge. `std::sync::Mutex` on
118/// aarch64-apple-darwin is the pthread backend, so a contended `lock()` parks
119/// the OS thread in the kernel — and a parked tokio worker runs no other task
120/// and is not replaced. A mark equal to the worker count means every worker
121/// was in here at once and the runtime could make no progress at all.
122pub static WAL_INFLIGHT: AtomicU64 = AtomicU64::new(0);
123pub static WAL_INFLIGHT_MAX: AtomicU64 = AtomicU64::new(0);
124
125/// Records elapsed time into `p` when dropped, so an early `return` inside the
126/// measured function still lands a sample.
127pub struct Scope<'a> {
128    p: &'a Probe,
129    t: std::time::Instant,
130}
131
132impl<'a> Scope<'a> {
133    pub fn new(p: &'a Probe) -> Self {
134        Self {
135            p,
136            t: std::time::Instant::now(),
137        }
138    }
139}
140
141impl Drop for Scope<'_> {
142    fn drop(&mut self) {
143        self.p.record(self.t.elapsed().as_nanos() as u64);
144    }
145}
146
147pub struct WalScope;
148
149impl Drop for WalScope {
150    fn drop(&mut self) {
151        WAL_INFLIGHT.fetch_sub(1, Relaxed);
152    }
153}
154
155pub fn wal_scope() -> WalScope {
156    let now = WAL_INFLIGHT.fetch_add(1, Relaxed) + 1;
157    WAL_INFLIGHT_MAX.fetch_max(now, Relaxed);
158    WalScope
159}
160
161pub fn dump() -> String {
162    let mut s = String::from("\n");
163    for (name, p) in [
164        ("submit.total", &SUBMIT_TOTAL),
165        ("submit.admit", &SUBMIT_ADMIT),
166        ("submit.wait_ack", &SUBMIT_WAIT_ACK),
167        ("wal.encode", &WAL_ENCODE),
168        ("wal.lock_wait", &WAL_LOCK_WAIT),
169        ("wal.held", &WAL_HELD),
170        ("wal.write", &WAL_WRITE),
171        ("runtime.lag", &RUNTIME_LAG),
172    ] {
173        s.push_str(&p.line(name));
174        s.push('\n');
175    }
176    s.push_str(&format!(
177        "wal.inflight_max   {}\n",
178        WAL_INFLIGHT_MAX.load(Relaxed)
179    ));
180    s
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    /// A probe with no samples must not divide by zero, and the tail buckets
188    /// have to count the right side of their thresholds. Both are the kind of
189    /// thing that is only wrong in the dump nobody reads until 3am.
190    #[test]
191    fn a_probe_summarises_what_it_was_given() {
192        let p = Probe::new();
193        assert!(p.line("empty").contains("mean=   0.000ms"));
194        p.record(1_000_000);
195        p.record(50_000_000);
196        p.record(500_000_000);
197        let line = p.line("x");
198        assert!(line.contains("n=3"), "{line}");
199        // 551 ms over three samples.
200        assert!(line.contains("mean= 183.667ms"), "{line}");
201        assert!(line.contains("max=  500.000ms"), "{line}");
202        // Strictly over: 1 ms is in neither bucket, 50 ms is in one, 500 in both.
203        assert!(line.contains(">10ms=2"), "{line}");
204        assert!(line.contains(">100ms=1"), "{line}");
205    }
206
207    /// The dump is the whole point of the module, and the failure it can have
208    /// is silent: a probe added above and not listed below simply never
209    /// appears, and the run it was added for is measured without it. So the
210    /// test names every probe the diagnosis in `docs/architecture/performance-ingest.md`
211    /// section 11 is read off, and a nine-line dump is what that section quotes.
212    #[test]
213    fn the_dump_names_every_probe_the_diagnosis_reads() {
214        let _scope = wal_scope();
215        let out = dump();
216        for name in [
217            "submit.total",
218            "submit.admit",
219            "submit.wait_ack",
220            "wal.encode",
221            "wal.lock_wait",
222            "wal.held",
223            "wal.write",
224            "runtime.lag",
225            "wal.inflight_max",
226        ] {
227            assert!(out.contains(name), "{name} is missing from:{out}");
228        }
229        assert_eq!(out.trim_start().lines().count(), 9, "{out}");
230        // `wal_scope` is live, so the high-water mark has seen at least one.
231        assert!(WAL_INFLIGHT_MAX.load(Relaxed) >= 1);
232        assert!(WAL_INFLIGHT.load(Relaxed) >= 1);
233    }
234}