Skip to main content

schedr_agent/
metrics.rs

1//! The worker agent's metrics (see archive/PROJECT.md, Observability), registered in the process's
2//! registry and served on the ops port. Each is updated where things happen; none costs
3//! anything at a scrape.
4
5use prometheus_client::encoding::EncodeLabelSet;
6use prometheus_client::metrics::counter::Counter;
7use prometheus_client::metrics::family::Family;
8use prometheus_client::metrics::gauge::Gauge;
9use prometheus_client::metrics::histogram::{Histogram, exponential_buckets};
10use prometheus_client::registry::Registry;
11use schedr_model::metric_doc::{MetricDoc, MetricKind};
12
13use crate::attempt::StartTimes;
14
15#[cfg(test)]
16mod tests;
17
18const SLOTS: MetricDoc = MetricDoc {
19    name: "worker_slots",
20    kind: MetricKind::Gauge,
21    labels: &[],
22    help: "Task slots",
23};
24const SLOTS_USED: MetricDoc = MetricDoc {
25    name: "worker_slots_used",
26    kind: MetricKind::Gauge,
27    labels: &[],
28    help: "Task slots in use",
29};
30const ATTEMPTS: MetricDoc = MetricDoc {
31    name: "worker_attempts",
32    kind: MetricKind::Counter,
33    labels: &["status"],
34    help: "Attempts ended on this worker, by status",
35};
36const TASK_START: MetricDoc = MetricDoc {
37    name: "worker_task_start_seconds",
38    kind: MetricKind::Histogram,
39    labels: &["method", "phase"],
40    help: "How long Python tasks took to start, by start method (spawn, fork) and phase \
41        (runner: from starting the process to the runner's hello; import: from sending the \
42        task to the DAG file imported, not counted when that fails)",
43};
44const ASSIGN_TO_STARTED: MetricDoc = MetricDoc {
45    name: "worker_assign_to_started_seconds",
46    kind: MetricKind::Histogram,
47    labels: &[],
48    help: "How long an assignment took from its `AssignTask` taken by the agent's loop to its \
49        `Started` sent (its plan, inputs and journal record): not counted when rejected",
50};
51const JOURNAL_WRITE: MetricDoc = MetricDoc {
52    name: "worker_journal_write_seconds",
53    kind: MetricKind::Histogram,
54    labels: &["record"],
55    help: "How long the journal took to keep records on disk, by record (start: a group of \
56        attempts before their `Started`s; process: a group of their processes' identities; \
57        results: a group of results)",
58};
59const MASTER_SAMPLE_AGE: MetricDoc = MetricDoc {
60    name: "worker_master_sample_age_seconds",
61    kind: MetricKind::Gauge,
62    labels: &[],
63    help: "How old the heartbeat is that the worker reads master time from (decision 447: the \
64        tightest of its window; growing past a few heartbeats means the master isn't answering)",
65};
66const MASTER_ROUND_TRIP: MetricDoc = MetricDoc {
67    name: "worker_master_round_trip_seconds",
68    kind: MetricKind::Gauge,
69    labels: &[],
70    help: "That message's round trip, from its send to the master's answer naming it: how much \
71        the worker's master-time deadlines lose to the link",
72};
73const OLDER_EPOCH: MetricDoc = MetricDoc {
74    name: "worker_older_epoch_refusals",
75    kind: MetricKind::Counter,
76    labels: &[],
77    help: "Streams ended because their master leads with a lower lease epoch than one seen \
78        (decision 444: a deposed master still answering)",
79};
80const WATCHDOG_KILLS: MetricDoc = MetricDoc {
81    name: "worker_watchdog_kills",
82    kind: MetricKind::Counter,
83    labels: &[],
84    help: "Tasks and parse runners killed over their memory budget",
85};
86const JOURNAL_RECORDS: MetricDoc = MetricDoc {
87    name: "worker_journal_records",
88    kind: MetricKind::Gauge,
89    labels: &[],
90    help: "Attempts in the journal (running, or results not acknowledged)",
91};
92const LOG_BYTES: MetricDoc = MetricDoc {
93    name: "worker_log_bytes",
94    kind: MetricKind::Gauge,
95    labels: &[],
96    help: "Bytes of logs kept, as of the last retention sweep",
97};
98const FORK_SERVERS: MetricDoc = MetricDoc {
99    name: "worker_fork_servers",
100    kind: MetricKind::Gauge,
101    labels: &["interpreter", "kind", "state"],
102    help: "Fork servers by interpreter, kind (preloaded, bare) and state (up, down, disabled): \
103        1 for each server's current state",
104};
105const FORK_FALLBACKS: MetricDoc = MetricDoc {
106    name: "worker_fork_fallbacks",
107    kind: MetricKind::Counter,
108    labels: &["interpreter", "reason"],
109    help: "Python tasks a fork server didn't fork, by interpreter and reason (disabled, down, \
110        fork_failed, shim_died); the next fork server, or spawn, starts them",
111};
112const LOG_SWEPT_BYTES: MetricDoc = MetricDoc {
113    name: "worker_log_swept_bytes",
114    kind: MetricKind::Counter,
115    labels: &[],
116    help: "Bytes of logs deleted by retention",
117};
118const WATCHER_SLOTS: MetricDoc = MetricDoc {
119    name: "worker_watcher_slots",
120    kind: MetricKind::Gauge,
121    labels: &[],
122    help: "Slots for wait steps",
123};
124const WATCHER_SLOTS_USED: MetricDoc = MetricDoc {
125    name: "worker_watcher_slots_used",
126    kind: MetricKind::Gauge,
127    labels: &[],
128    help: "Wait steps running",
129};
130const WATCHER_HOSTS: MetricDoc = MetricDoc {
131    name: "worker_watcher_hosts",
132    kind: MetricKind::Gauge,
133    labels: &[],
134    help: "Processes running wait steps, one per code set",
135};
136const WATCHER_THREADS: MetricDoc = MetricDoc {
137    name: "worker_watcher_threads",
138    kind: MetricKind::Gauge,
139    labels: &["kind"],
140    help: "Threads of the hosts, by kind (tied: running a wait step's `to_thread` calls or \
141        started by it; untied: the rest of the process, a library's pools among them)",
142};
143const WATCHER_MEMORY: MetricDoc = MetricDoc {
144    name: "worker_watcher_memory_bytes",
145    kind: MetricKind::Gauge,
146    labels: &[],
147    help: "Memory the hosts use together, against `[watchers] memory_budget`",
148};
149const WATCHER_LOOP_LAG: MetricDoc = MetricDoc {
150    name: "worker_watcher_loop_lag_seconds",
151    kind: MetricKind::Histogram,
152    labels: &[],
153    help: "How long a host's event loop took to get to a call: long ones are wait steps \
154        holding it up, short of `[watchers] block_limit`",
155};
156const WATCHER_BLOCKED_KILLS: MetricDoc = MetricDoc {
157    name: "worker_watcher_blocked_kills",
158    kind: MetricKind::Counter,
159    labels: &[],
160    help: "Hosts killed for one wait step: it held the event loop, a thread of it stayed stuck, \
161        or it ignored its cancel",
162};
163const WATCHER_RESTARTS: MetricDoc = MetricDoc {
164    name: "worker_watcher_restarts",
165    kind: MetricKind::Counter,
166    labels: &[],
167    help: "Wait steps started again on a new host, as another one got theirs killed",
168};
169const WATCHER_HOSTS_LOST: MetricDoc = MetricDoc {
170    name: "worker_watcher_hosts_lost",
171    kind: MetricKind::Counter,
172    labels: &["code"],
173    help: "Hosts ended with no wait step to blame (a crash, a memory kill, silence), by the code \
174        they ran: their wait steps use a retry",
175};
176const WATCHER_THREAD_STOPS: MetricDoc = MetricDoc {
177    name: "worker_watcher_thread_stops",
178    kind: MetricKind::Counter,
179    labels: &[],
180    help: "`to_thread` calls stopped at their wait step's end, each of which may have left \
181        shared state half updated",
182};
183
184/// The worker agent's metrics, as registered (under `schedr_`).
185pub const METRICS: &[MetricDoc] = &[
186    SLOTS,
187    SLOTS_USED,
188    ATTEMPTS,
189    TASK_START,
190    ASSIGN_TO_STARTED,
191    JOURNAL_WRITE,
192    MASTER_SAMPLE_AGE,
193    MASTER_ROUND_TRIP,
194    OLDER_EPOCH,
195    WATCHDOG_KILLS,
196    JOURNAL_RECORDS,
197    LOG_BYTES,
198    LOG_SWEPT_BYTES,
199    FORK_SERVERS,
200    FORK_FALLBACKS,
201    WATCHER_SLOTS,
202    WATCHER_SLOTS_USED,
203    WATCHER_HOSTS,
204    WATCHER_THREADS,
205    WATCHER_MEMORY,
206    WATCHER_LOOP_LAG,
207    WATCHER_BLOCKED_KILLS,
208    WATCHER_RESTARTS,
209    WATCHER_HOSTS_LOST,
210    WATCHER_THREAD_STOPS,
211];
212
213/// An attempt's status.
214#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
215pub struct StatusLabels {
216    /// The status.
217    pub status: String,
218}
219
220/// How a task's process was started, and which part of its start.
221#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
222pub struct StartLabels {
223    /// `spawn` or `fork`.
224    pub method: String,
225    /// `runner` or `import`.
226    pub phase: String,
227}
228
229/// A kind of journal record.
230#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
231pub struct RecordLabels {
232    /// `start`, `process` or `results`.
233    pub record: String,
234}
235
236/// A fork server and its state.
237#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
238pub struct ForkServerLabels {
239    /// The interpreter's name.
240    pub interpreter: String,
241    /// `preloaded` or `bare`.
242    pub kind: String,
243    /// `up`, `down` or `disabled`.
244    pub state: String,
245}
246
247/// Why a fork server didn't fork a task.
248#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
249pub struct ForkFallbackLabels {
250    /// The interpreter's name.
251    pub interpreter: String,
252    /// `disabled`, `down`, `fork_failed` or `shim_died`.
253    pub reason: String,
254}
255
256/// Which of a host's threads.
257#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
258pub struct ThreadLabels {
259    /// `tied` or `untied`.
260    pub kind: String,
261}
262
263/// The code a host ran.
264#[derive(Debug, Clone, Hash, PartialEq, Eq, EncodeLabelSet)]
265pub struct CodeLabels {
266    /// Its folders' names, the copies' hashes.
267    pub code: String,
268}
269
270/// The wait step hosts' metrics (cheap to clone; clones share them).
271#[derive(Debug, Clone)]
272pub struct WatcherMetrics {
273    /// Slots for wait steps.
274    pub slots: Gauge,
275    /// Wait steps running.
276    pub slots_used: Gauge,
277    /// Hosts running.
278    pub hosts: Gauge,
279    /// Their threads, by kind.
280    pub threads: Family<ThreadLabels, Gauge>,
281    /// The memory they use together.
282    pub memory: Gauge,
283    /// How long their event loops took to get to a call.
284    pub loop_lag: Histogram,
285    /// Hosts killed for one wait step.
286    pub blocked_kills: Counter,
287    /// Wait steps started again on a new host.
288    pub restarts: Counter,
289    /// Hosts ended with no wait step to blame, by code.
290    pub hosts_lost: Family<CodeLabels, Counter>,
291    /// `to_thread` calls stopped.
292    pub thread_stops: Counter,
293}
294
295impl Default for WatcherMetrics {
296    fn default() -> Self {
297        Self {
298            slots: Gauge::default(),
299            slots_used: Gauge::default(),
300            hosts: Gauge::default(),
301            threads: Family::default(),
302            memory: Gauge::default(),
303            // 1 ms to about 30 s: `[watchers] block_limit` is 30 s by default.
304            loop_lag: Histogram::new(exponential_buckets(0.001, 2.0, 16)),
305            blocked_kills: Counter::default(),
306            restarts: Counter::default(),
307            hosts_lost: Family::default(),
308            thread_stops: Counter::default(),
309        }
310    }
311}
312
313impl WatcherMetrics {
314    fn register(&self, r: &mut Registry) {
315        r.register(WATCHER_SLOTS.name, WATCHER_SLOTS.help, self.slots.clone());
316        r.register(
317            WATCHER_SLOTS_USED.name,
318            WATCHER_SLOTS_USED.help,
319            self.slots_used.clone(),
320        );
321        r.register(WATCHER_HOSTS.name, WATCHER_HOSTS.help, self.hosts.clone());
322        r.register(
323            WATCHER_THREADS.name,
324            WATCHER_THREADS.help,
325            self.threads.clone(),
326        );
327        r.register(
328            WATCHER_MEMORY.name,
329            WATCHER_MEMORY.help,
330            self.memory.clone(),
331        );
332        r.register(
333            WATCHER_LOOP_LAG.name,
334            WATCHER_LOOP_LAG.help,
335            self.loop_lag.clone(),
336        );
337        r.register(
338            WATCHER_BLOCKED_KILLS.name,
339            WATCHER_BLOCKED_KILLS.help,
340            self.blocked_kills.clone(),
341        );
342        r.register(
343            WATCHER_RESTARTS.name,
344            WATCHER_RESTARTS.help,
345            self.restarts.clone(),
346        );
347        r.register(
348            WATCHER_HOSTS_LOST.name,
349            WATCHER_HOSTS_LOST.help,
350            self.hosts_lost.clone(),
351        );
352        r.register(
353            WATCHER_THREAD_STOPS.name,
354            WATCHER_THREAD_STOPS.help,
355            self.thread_stops.clone(),
356        );
357    }
358
359    /// The hosts' threads now.
360    pub fn set_threads(&self, tied: u64, untied: u64) {
361        for (kind, count) in [("tied", tied), ("untied", untied)] {
362            self.threads
363                .get_or_create(&ThreadLabels {
364                    kind: kind.to_owned(),
365                })
366                .set(i64::try_from(count).unwrap_or(i64::MAX));
367        }
368    }
369}
370
371type StartHistograms = Family<StartLabels, Histogram, fn() -> Histogram>;
372
373/// The agent's metrics (cheap to clone; clones share them).
374#[derive(Debug, Clone)]
375pub struct AgentMetrics {
376    /// Task slots.
377    pub slots: Gauge,
378    /// Task slots in use.
379    pub slots_used: Gauge,
380    /// Attempts ended here, by status.
381    pub attempts: Family<StatusLabels, Counter>,
382    /// How long Python tasks took to start, by start method and phase.
383    pub task_start: StartHistograms,
384    /// From an `AssignTask` taken to its `Started` sent.
385    pub assign_to_started: Histogram,
386    /// How long the journal took to keep a record, by record.
387    pub journal_write: Family<RecordLabels, Histogram, fn() -> Histogram>,
388    /// The age of the heartbeat master time is read from, in seconds (decision 448).
389    pub master_sample_age: Gauge<f64, std::sync::atomic::AtomicU64>,
390    /// Its round trip, in seconds.
391    pub master_round_trip: Gauge<f64, std::sync::atomic::AtomicU64>,
392    /// Streams ended for a lower lease epoch.
393    pub older_epoch: Counter,
394    /// Tasks and parse runners the memory watchdog killed.
395    pub watchdog_kills: Counter,
396    /// Attempts in the journal (running, or results not acknowledged).
397    pub journal_records: Gauge,
398    /// Bytes of task and parse logs kept, as of the last retention sweep.
399    pub log_bytes: Gauge,
400    /// Bytes of logs deleted by retention.
401    pub log_swept_bytes: Counter,
402    /// The fork servers' states and fallbacks.
403    pub fork: crate::fork::ForkMetrics,
404    /// The wait step hosts'.
405    pub watchers: WatcherMetrics,
406}
407
408impl Default for AgentMetrics {
409    fn default() -> Self {
410        Self {
411            slots: Gauge::default(),
412            slots_used: Gauge::default(),
413            attempts: Family::default(),
414            // 10 ms to about 40 s.
415            task_start: Family::new_with_constructor(|| {
416                Histogram::new(exponential_buckets(0.01, 2.0, 13))
417            }),
418            // 0.1 ms to about 26 s, each bucket 2 times the last.
419            assign_to_started: Histogram::new(exponential_buckets(0.0001, 2.0, 19)),
420            journal_write: Family::new_with_constructor(|| {
421                Histogram::new(exponential_buckets(0.0001, 2.0, 19))
422            }),
423            master_sample_age: Gauge::default(),
424            master_round_trip: Gauge::default(),
425            // 10 ms to about 160 s.
426            older_epoch: Counter::default(),
427            watchdog_kills: Counter::default(),
428            journal_records: Gauge::default(),
429            log_bytes: Gauge::default(),
430            log_swept_bytes: Counter::default(),
431            fork: crate::fork::ForkMetrics::default(),
432            watchers: WatcherMetrics::default(),
433        }
434    }
435}
436
437impl AgentMetrics {
438    /// Registers every metric in `registry` (names get the `schedr_` prefix there), as
439    /// [`METRICS`] describes them.
440    pub fn register(&self, registry: &mut Registry) {
441        let r = registry;
442        r.register(SLOTS.name, SLOTS.help, self.slots.clone());
443        r.register(SLOTS_USED.name, SLOTS_USED.help, self.slots_used.clone());
444        r.register(ATTEMPTS.name, ATTEMPTS.help, self.attempts.clone());
445        r.register(TASK_START.name, TASK_START.help, self.task_start.clone());
446        r.register(
447            ASSIGN_TO_STARTED.name,
448            ASSIGN_TO_STARTED.help,
449            self.assign_to_started.clone(),
450        );
451        r.register(
452            JOURNAL_WRITE.name,
453            JOURNAL_WRITE.help,
454            self.journal_write.clone(),
455        );
456        r.register(
457            MASTER_SAMPLE_AGE.name,
458            MASTER_SAMPLE_AGE.help,
459            self.master_sample_age.clone(),
460        );
461        r.register(
462            MASTER_ROUND_TRIP.name,
463            MASTER_ROUND_TRIP.help,
464            self.master_round_trip.clone(),
465        );
466        r.register(OLDER_EPOCH.name, OLDER_EPOCH.help, self.older_epoch.clone());
467        r.register(
468            WATCHDOG_KILLS.name,
469            WATCHDOG_KILLS.help,
470            self.watchdog_kills.clone(),
471        );
472        r.register(
473            JOURNAL_RECORDS.name,
474            JOURNAL_RECORDS.help,
475            self.journal_records.clone(),
476        );
477        r.register(LOG_BYTES.name, LOG_BYTES.help, self.log_bytes.clone());
478        r.register(
479            LOG_SWEPT_BYTES.name,
480            LOG_SWEPT_BYTES.help,
481            self.log_swept_bytes.clone(),
482        );
483        r.register(
484            FORK_SERVERS.name,
485            FORK_SERVERS.help,
486            self.fork.servers.clone(),
487        );
488        r.register(
489            FORK_FALLBACKS.name,
490            FORK_FALLBACKS.help,
491            self.fork.fallbacks.clone(),
492        );
493        self.watchers.register(r);
494    }
495
496    /// Records how long a Python task started `method` took to start.
497    pub fn task_started(&self, method: &str, start: &StartTimes) {
498        let phases = [("runner", Some(start.runner)), ("import", start.import)];
499        for (phase, took) in phases {
500            if let Some(took) = took {
501                self.task_start
502                    .get_or_create(&StartLabels {
503                        method: method.to_owned(),
504                        phase: phase.to_owned(),
505                    })
506                    .observe(took.as_secs_f64());
507            }
508        }
509    }
510
511    /// Records the journal keeping a `record` in `took`.
512    pub fn journal_written(&self, record: &str, took: std::time::Duration) {
513        self.journal_write
514            .get_or_create(&RecordLabels {
515                record: record.to_owned(),
516            })
517            .observe(took.as_secs_f64());
518    }
519
520    /// Counts one ended attempt.
521    pub fn attempt_ended(&self, status: &impl ToString) {
522        self.attempts
523            .get_or_create(&StatusLabels {
524                status: status.to_string(),
525            })
526            .inc();
527    }
528}