Skip to main content

subc_daemon/
observability.rs

1use std::{
2    collections::{BTreeMap, HashMap, VecDeque},
3    sync::{
4        atomic::{AtomicU64, Ordering},
5        Arc, Mutex, MutexGuard,
6    },
7    time::Duration,
8};
9
10use serde_json::{json, Value};
11use tracing::{debug, warn};
12
13use crate::registry::ConnectionId;
14
15/// The slash prevents collision with a module ID: `module_id_path_hazard`
16/// rejects separators in `registry.rs:855-875`.
17pub(crate) const CONTROL_WAIT_BUCKET: &str = "daemon/control";
18
19/// The only keys the route.open refusal counter may carry. A module's own
20/// error code on a rejected bind is counted under `module_rejected` and rides
21/// the log event as a separate field: if the module's string were the key, a
22/// module could grow this map for the daemon's lifetime and push terminal
23/// control sequences through `ck daemon` to an operator's screen. The
24/// `&'static str` increment signature plus the debug assertion keep the set
25/// closed at the call site, not just here.
26const ROUTE_OPEN_REFUSAL_COUNTER_CODES: &[&str] = &[
27    "module_warming",
28    ROUTE_OPEN_REFUSED_DECLARED_NOT_READY,
29    ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED,
30    "target_unavailable",
31    subc_protocol::error_codes::TARGET_FLOW_UNSUPPORTED,
32    subc_protocol::error_codes::TARGET_FEDERATED_UNSUPPORTED,
33    subc_protocol::error_codes::FEDERATED_STAMP_REQUIRED,
34    subc_protocol::error_codes::TARGET_AGENT_RUN_UNSUPPORTED,
35    "module_removed",
36    "module_no_protocol",
37    "unknown_module",
38    "module_reloading",
39    "op_not_allowed",
40    "bad_consumer_identity",
41    crate::supervise::REGISTRATION_CHANNEL_CLOSED,
42    "capability_forbidden",
43    "admission_facts_not_permitted",
44    "admission_facts_target_not_allowed",
45    "route_limit",
46    "forwarding_error",
47    "module_timeout",
48    ROUTE_OPEN_REFUSED_BREAKER_OPEN,
49    "module_rejected",
50    subc_protocol::error_codes::SCOPE_EPOCH_REQUIRED,
51    subc_protocol::error_codes::SCOPE_NOT_SYNCED,
52    subc_protocol::error_codes::SCOPE_NOT_LIVE,
53    subc_protocol::error_codes::SCOPE_ENDED,
54    subc_protocol::error_codes::SCOPE_NOT_CARRIER,
55    subc_protocol::error_codes::SCOPE_BIND_PROOF_REQUIRED,
56    subc_protocol::error_codes::SCOPE_BIND_PROOF_MISMATCH,
57    subc_protocol::error_codes::SCOPE_CHANGED,
58    subc_protocol::error_codes::INVALID_REQUEST,
59];
60
61/// Counter key for a `route.open` refused by the per-module bind-relay breaker
62/// before any relay was attempted.
63///
64/// The frame the caller receives carries `module_timeout`, because both SDKs
65/// already classify that as retryable with capped backoff and inventing a new
66/// wire code would need a change in each of them. The COUNTER is deliberately a
67/// different key: "this module burned the full bind budget" and "this module is
68/// being refused in microseconds because it already did that repeatedly" are
69/// the two states an operator most needs to tell apart, and they are
70/// indistinguishable from the client side, where both look like one retryable
71/// error that the next attempt may well satisfy.
72pub(crate) const ROUTE_OPEN_REFUSED_BREAKER_OPEN: &str = "module_timeout_breaker_open";
73
74/// Counter key for a registered module that declared itself not ready.
75///
76/// The caller still receives `module_warming`, but operators must be able to
77/// distinguish declared readiness from a supervised process that has not
78/// registered yet.
79pub(crate) const ROUTE_OPEN_REFUSED_DECLARED_NOT_READY: &str = "module_warming_declared_not_ready";
80
81/// Counter key for a registered, declared-ready module held not-ready because
82/// a capability it declares `need: required` has no registered provider.
83///
84/// The caller still receives `module_warming`; a separate key lets an operator
85/// tell "the module says it is warming" from "the module is waiting on a
86/// provider that is not running", which point at different fixes.
87pub(crate) const ROUTE_OPEN_REFUSED_REQUIRED_CAPABILITY_UNPROVIDED: &str =
88    "module_warming_required_capability_unprovided";
89
90/// Shared count of authenticated socket connections accepted by the daemon.
91#[derive(Debug, Clone, Default)]
92pub struct ConnectedClients {
93    count: Arc<AtomicU64>,
94}
95
96impl ConnectedClients {
97    pub fn new() -> Self {
98        Self::default()
99    }
100
101    pub fn count(&self) -> u64 {
102        self.count.load(Ordering::SeqCst)
103    }
104
105    pub(crate) fn open(&self, connection_id: ConnectionId) -> ConnectedClientGuard {
106        let previous = self.count.fetch_add(1, Ordering::SeqCst);
107        let current = previous + 1;
108        // DEBUG, not INFO: this pair fired on every connect and disconnect and was
109        // measured at 43-74% of the daemon's own log (issue #114), burying the
110        // lines an operator opens the file for. The count itself is not lost: it
111        // is served live as `connected_clients` on server.describe (`ck daemon`),
112        // and a connection that opens a route still names its connection_id on the
113        // `route.open accepted` line, so per-connection forensics survive where
114        // they matter. Raise the filter (`CK_LOG=subc=debug`) to see every churn.
115        debug!(
116            connection_id = connection_id.get(),
117            connected_clients = current,
118            previous_connected_clients = previous,
119            "authenticated connection count changed"
120        );
121        ConnectedClientGuard {
122            clients: self.clone(),
123            connection_id,
124        }
125    }
126}
127
128pub(crate) struct ConnectedClientGuard {
129    clients: ConnectedClients,
130    connection_id: ConnectionId,
131}
132
133impl Drop for ConnectedClientGuard {
134    fn drop(&mut self) {
135        let previous = self.clients.count.fetch_sub(1, Ordering::SeqCst);
136        let current = previous.saturating_sub(1);
137        // DEBUG for the same reason as the open side above.
138        debug!(
139            connection_id = self.connection_id.get(),
140            connected_clients = current,
141            previous_connected_clients = previous,
142            "authenticated connection count changed"
143        );
144    }
145}
146
147/// Counters for route lifecycle drops, delivery failures and reader waits.
148#[derive(Debug, Clone, Default)]
149pub struct DaemonCounters {
150    stalled_cancels: crate::forwarding::StalledCancels,
151    reader_diagnostics: Arc<Mutex<ReaderDiagnostics>>,
152    carried_containment_anchor_lost: Arc<AtomicU64>,
153    /// Every non-request frame a module sent on a (channel, epoch) the daemon
154    /// holds no bound route for, dropped. Counts both kinds below: orphan
155    /// traffic on a route the daemon released, and frames on a (channel,
156    /// epoch) that was never allocated on that module connection.
157    module_frames_dropped_no_route: Arc<AtomicU64>,
158    /// The orphan-traffic part of `module_frames_dropped_no_route`: the daemon
159    /// had allocated that (channel, epoch) on the sending module connection and
160    /// has since released it, so the module is still holding a route the
161    /// daemon closed. `module_frames_dropped_no_route` minus this is the count
162    /// of frames on a (channel, epoch) that never existed on the connection.
163    module_frames_dropped_released_route: Arc<AtomicU64>,
164    module_frames_dropped_released_route_by_module: Arc<Mutex<HashMap<String, u64>>>,
165    /// Route GOODBYEs the daemon enqueued to a module in answer to its frames
166    /// on a (channel, epoch) the daemon holds no route for, telling the module
167    /// to drop the route. Rate-limited per module connection and channel, so
168    /// this counts answers, not orphan frames.
169    module_orphan_route_goodbyes_sent: Arc<AtomicU64>,
170    // Per-module maps and the rate window are daemon-lifetime diagnostics only:
171    // they deliberately reset on restart instead of becoming durable daemon state.
172    module_frames_dropped_no_route_by_module: Arc<Mutex<HashMap<String, u64>>>,
173    agent_command_refusals_dropped_by_module: Arc<Mutex<HashMap<String, u64>>>,
174    agent_command_refusals_dropped_unlabelled: Arc<std::sync::atomic::AtomicU64>,
175    route_open_refused_by_code: Arc<Mutex<HashMap<String, u64>>>,
176    route_open_accepted_by_principal: Arc<Mutex<HashMap<String, u64>>>,
177    module_frames_dropped_no_route_window: Arc<Mutex<DropWindow>>,
178    module_requests_dropped_stale_route: Arc<AtomicU64>,
179    client_frames_dropped_stale_route: Arc<AtomicU64>,
180    client_egress_close_delivery_failed: Arc<AtomicU64>,
181    goodbye_relay_client_failed: Arc<AtomicU64>,
182    goodbye_relay_module_dropped: Arc<AtomicU64>,
183    goodbye_relay_module_dropped_by_module: Arc<Mutex<HashMap<String, u64>>>,
184    route_released_epoch_fenced: Arc<AtomicU64>,
185    route_release_stale_skipped: Arc<AtomicU64>,
186    drains_with_undeclared_gauge: Arc<AtomicU64>,
187}
188
189#[derive(Debug, Default)]
190struct ReaderDiagnostics {
191    busy: BTreeMap<String, BTreeMap<String, u64>>,
192    waits: BTreeMap<String, BTreeMap<String, BTreeMap<String, u64>>>,
193    warned_waits: HashMap<(String, String), tokio::time::Instant>,
194}
195
196/// Ten one-minute buckets make sustained module-to-client route drops visible
197/// without retaining one record for every dropped frame.
198#[derive(Debug)]
199struct DropWindow {
200    started_at: tokio::time::Instant,
201    buckets: VecDeque<DropBucket>,
202}
203
204#[derive(Debug)]
205struct DropBucket {
206    minute: u64,
207    count: u64,
208}
209
210impl Default for DropWindow {
211    fn default() -> Self {
212        Self {
213            started_at: tokio::time::Instant::now(),
214            buckets: VecDeque::new(),
215        }
216    }
217}
218
219impl DropWindow {
220    const MINUTE: Duration = Duration::from_secs(60);
221    const BUCKETS: u64 = 10;
222
223    fn record(&mut self, now: tokio::time::Instant) {
224        let minute = self.minute_at(now);
225        self.prune_before(minute);
226        match self.buckets.back_mut() {
227            Some(bucket) if bucket.minute == minute => bucket.count += 1,
228            _ => self.buckets.push_back(DropBucket { minute, count: 1 }),
229        }
230    }
231
232    fn count_last_10m(&mut self, now: tokio::time::Instant) -> u64 {
233        let minute = self.minute_at(now);
234        self.prune_before(minute);
235        self.buckets.iter().map(|bucket| bucket.count).sum()
236    }
237
238    fn nonzero_minutes_last_10m(&mut self, now: tokio::time::Instant) -> u64 {
239        let minute = self.minute_at(now);
240        self.prune_before(minute);
241        self.buckets.len() as u64
242    }
243
244    fn minute_at(&self, now: tokio::time::Instant) -> u64 {
245        now.saturating_duration_since(self.started_at).as_secs() / Self::MINUTE.as_secs()
246    }
247
248    fn prune_before(&mut self, current_minute: u64) {
249        while self
250            .buckets
251            .front()
252            .is_some_and(|bucket| current_minute.saturating_sub(bucket.minute) >= Self::BUCKETS)
253        {
254            self.buckets.pop_front();
255        }
256    }
257}
258
259impl DaemonCounters {
260    pub fn new() -> Self {
261        Self::default()
262    }
263
264    pub(crate) fn stalled_cancels(&self) -> &crate::forwarding::StalledCancels {
265        &self.stalled_cancels
266    }
267
268    /// Returns a JSON snapshot whose stable, additive schema keeps the
269    /// `server.describe` diagnostic endpoint backward-compatible.
270    pub fn snapshot(&self) -> Value {
271        let mut snapshot = serde_json::Map::new();
272        snapshot.insert(
273            "stalled_cancels".into(),
274            self.stalled_cancels.count().into(),
275        );
276        let diagnostics = self
277            .reader_diagnostics
278            .lock()
279            .unwrap_or_else(|p| p.into_inner());
280        if !diagnostics.busy.is_empty() {
281            snapshot.insert(
282                "route_busy_by_module_principal".into(),
283                json!(diagnostics.busy),
284            );
285        }
286        if !diagnostics.waits.is_empty() {
287            snapshot.insert(
288                "reader_wait_over_5s_by_module_principal".into(),
289                json!(diagnostics.waits),
290            );
291        }
292        drop(diagnostics);
293        snapshot.insert(
294            "carried_containment_anchor_lost".into(),
295            self.carried_containment_anchor_lost
296                .load(Ordering::Relaxed)
297                .into(),
298        );
299        snapshot.insert(
300            "module_frames_dropped_no_route".into(),
301            self.module_frames_dropped_no_route
302                .load(Ordering::Relaxed)
303                .into(),
304        );
305        let mut drop_window = self
306            .module_frames_dropped_no_route_window
307            .lock()
308            .expect("drop-rate window mutex poisoned");
309        let now = tokio::time::Instant::now();
310        snapshot.insert(
311            "module_frames_dropped_no_route_last_10m".into(),
312            drop_window.count_last_10m(now).into(),
313        );
314        snapshot.insert(
315            "module_frames_dropped_no_route_nonzero_minutes_last_10m".into(),
316            drop_window.nonzero_minutes_last_10m(now).into(),
317        );
318        insert_nonempty_counts(
319            &mut snapshot,
320            "module_frames_dropped_no_route_by_module",
321            &self.module_frames_dropped_no_route_by_module,
322        );
323        insert_nonempty_counts(
324            &mut snapshot,
325            "agent_command_refusals_dropped_by_module",
326            &self.agent_command_refusals_dropped_by_module,
327        );
328        let unlabelled = self
329            .agent_command_refusals_dropped_unlabelled
330            .load(Ordering::Relaxed);
331        if unlabelled != 0 {
332            snapshot.insert(
333                "agent_command_refusals_dropped_unlabelled".into(),
334                unlabelled.into(),
335            );
336        }
337        snapshot.insert(
338            "module_frames_dropped_released_route".into(),
339            self.module_frames_dropped_released_route
340                .load(Ordering::Relaxed)
341                .into(),
342        );
343        insert_nonempty_counts(
344            &mut snapshot,
345            "module_frames_dropped_released_route_by_module",
346            &self.module_frames_dropped_released_route_by_module,
347        );
348        snapshot.insert(
349            "module_orphan_route_goodbyes_sent".into(),
350            self.module_orphan_route_goodbyes_sent
351                .load(Ordering::Relaxed)
352                .into(),
353        );
354        insert_nonempty_counts(
355            &mut snapshot,
356            "route_open_refused_by_code",
357            &self.route_open_refused_by_code,
358        );
359        insert_nonempty_counts(
360            &mut snapshot,
361            "route_open_accepted_by_principal",
362            &self.route_open_accepted_by_principal,
363        );
364        snapshot.insert(
365            "module_requests_dropped_stale_route".into(),
366            self.module_requests_dropped_stale_route
367                .load(Ordering::Relaxed)
368                .into(),
369        );
370        snapshot.insert(
371            "client_frames_dropped_stale_route".into(),
372            self.client_frames_dropped_stale_route
373                .load(Ordering::Relaxed)
374                .into(),
375        );
376        snapshot.insert(
377            "client_egress_close_delivery_failed".into(),
378            self.client_egress_close_delivery_failed
379                .load(Ordering::Relaxed)
380                .into(),
381        );
382        snapshot.insert(
383            "goodbye_relay_client_failed".into(),
384            self.goodbye_relay_client_failed
385                .load(Ordering::Relaxed)
386                .into(),
387        );
388        snapshot.insert(
389            "goodbye_relay_module_dropped".into(),
390            self.goodbye_relay_module_dropped
391                .load(Ordering::Relaxed)
392                .into(),
393        );
394        insert_nonempty_counts(
395            &mut snapshot,
396            "goodbye_relay_module_dropped_by_module",
397            &self.goodbye_relay_module_dropped_by_module,
398        );
399        snapshot.insert(
400            "route_released_epoch_fenced".into(),
401            self.route_released_epoch_fenced
402                .load(Ordering::Relaxed)
403                .into(),
404        );
405        snapshot.insert(
406            "route_release_stale_skipped".into(),
407            self.route_release_stale_skipped
408                .load(Ordering::Relaxed)
409                .into(),
410        );
411        snapshot.insert(
412            "drains_with_undeclared_gauge".into(),
413            self.drains_with_undeclared_gauge
414                .load(Ordering::Relaxed)
415                .into(),
416        );
417        Value::Object(snapshot)
418    }
419
420    pub(crate) fn increment_route_busy(&self, module: &str, principal: &str) {
421        let mut diagnostics = self
422            .reader_diagnostics
423            .lock()
424            .unwrap_or_else(|p| p.into_inner());
425        *diagnostics
426            .busy
427            .entry(module.into())
428            .or_default()
429            .entry(principal.into())
430            .or_default() += 1;
431    }
432
433    /// Observe a wait without imposing a deadline or cancelling its future.
434    /// Counts advance once at five seconds, even if the peer never recovers.
435    pub(crate) async fn observe_reader_wait<F: std::future::Future>(
436        &self,
437        labels: impl FnOnce() -> (String, String),
438        kind: &'static str,
439        future: F,
440    ) -> F::Output {
441        tokio::pin!(future);
442        // Ready sends need neither a timer nor diagnostic labels. Poll before
443        // constructing Sleep, which would otherwise touch the runtime clock.
444        if let std::task::Poll::Ready(result) =
445            std::future::poll_fn(|cx| std::task::Poll::Ready(future.as_mut().poll(cx))).await
446        {
447            return result;
448        }
449        tokio::select! {
450            biased;
451            result = &mut future => return result,
452            _ = tokio::time::sleep(Duration::from_secs(5)) => {}
453        }
454        let (module, principal) = labels();
455        let should_warn = {
456            let mut diagnostics = self
457                .reader_diagnostics
458                .lock()
459                .unwrap_or_else(|p| p.into_inner());
460            *diagnostics
461                .waits
462                .entry(module.clone())
463                .or_default()
464                .entry(principal.clone())
465                .or_default()
466                .entry(kind.into())
467                .or_default() += 1;
468            let now = tokio::time::Instant::now();
469            let key = (module.to_owned(), principal.to_owned());
470            let should_warn = diagnostics
471                .warned_waits
472                .get(&key)
473                .is_none_or(|last| now.duration_since(*last) >= Duration::from_secs(60));
474            if should_warn {
475                diagnostics.warned_waits.insert(key, now);
476            }
477            should_warn
478        };
479        if should_warn {
480            warn!(
481                module_id = module,
482                client_principal = principal,
483                wait_kind = kind,
484                "connection reader wait exceeded 5 seconds"
485            );
486        }
487        future.await
488    }
489
490    pub(crate) fn increment_module_frames_dropped_no_route(&self, module_id: Option<&str>) {
491        self.module_frames_dropped_no_route
492            .fetch_add(1, Ordering::Relaxed);
493        if let Some(module_id) = module_id {
494            increment_keyed_count(&self.module_frames_dropped_no_route_by_module, module_id);
495        }
496        self.module_frames_dropped_no_route_window
497            .lock()
498            .expect("drop-rate window mutex poisoned")
499            .record(tokio::time::Instant::now());
500    }
501
502    pub(crate) fn increment_agent_command_refusal_dropped(
503        &self,
504        module_id: Option<&str>,
505        registry: &crate::registry::Registry,
506    ) {
507        let Some(module_id) =
508            module_id.filter(|id| registry.get_module(id).ok().flatten().is_some())
509        else {
510            self.agent_command_refusals_dropped_unlabelled
511                .fetch_add(1, Ordering::Relaxed);
512            return;
513        };
514        let mut counts = self
515            .agent_command_refusals_dropped_by_module
516            .lock()
517            .unwrap_or_else(|p| p.into_inner());
518        if let Some(count) = counts.get_mut(module_id) {
519            *count = count.saturating_add(1);
520        } else if counts.len() < MAX_AGENT_REFUSAL_MODULES {
521            counts.insert(module_id.to_owned(), 1);
522        } else {
523            self.agent_command_refusals_dropped_unlabelled
524                .fetch_add(1, Ordering::Relaxed);
525        }
526    }
527
528    /// Count a dropped module frame whose (channel, epoch) the daemon had
529    /// allocated on that connection and since released. Called in addition to
530    /// [`Self::increment_module_frames_dropped_no_route`], never instead of it.
531    pub(crate) fn increment_module_frames_dropped_released_route(&self, module_id: Option<&str>) {
532        self.module_frames_dropped_released_route
533            .fetch_add(1, Ordering::Relaxed);
534        if let Some(module_id) = module_id {
535            increment_keyed_count(
536                &self.module_frames_dropped_released_route_by_module,
537                module_id,
538            );
539        }
540    }
541
542    pub(crate) fn increment_module_orphan_route_goodbyes_sent(&self) {
543        self.module_orphan_route_goodbyes_sent
544            .fetch_add(1, Ordering::Relaxed);
545    }
546
547    pub(crate) fn increment_route_open_refused(&self, code: &'static str) {
548        debug_assert!(ROUTE_OPEN_REFUSAL_COUNTER_CODES.contains(&code));
549        increment_keyed_count(&self.route_open_refused_by_code, code);
550    }
551
552    /// Count an accepted route.open by the principal the daemon stamped.
553    ///
554    /// THE KEY SPACE IS CLOSED BY CONSTRUCTION, unlike the refusal counter which
555    /// needs an explicit allowlist: a principal is `direct` or
556    /// `reserved:<module_id>`, and a module id was already refused at HELLO
557    /// unless it is a single path component free of control characters. So an
558    /// untrusted string cannot expand this map without first passing module-id
559    /// validation, and the bound is the number of modules rather than the number
560    /// of distinct strings a caller can invent.
561    pub(crate) fn increment_route_open_accepted(&self, principal: &str) {
562        increment_keyed_count(&self.route_open_accepted_by_principal, principal);
563    }
564
565    pub(crate) fn increment_module_requests_dropped_stale_route(&self) {
566        self.module_requests_dropped_stale_route
567            .fetch_add(1, Ordering::Relaxed);
568    }
569
570    pub(crate) fn increment_client_frames_dropped_stale_route(&self) {
571        self.client_frames_dropped_stale_route
572            .fetch_add(1, Ordering::Relaxed);
573    }
574
575    pub(crate) fn increment_client_egress_close_delivery_failed(&self) {
576        self.client_egress_close_delivery_failed
577            .fetch_add(1, Ordering::Relaxed);
578    }
579
580    pub(crate) fn increment_goodbye_relay_client_failed(&self) {
581        self.goodbye_relay_client_failed
582            .fetch_add(1, Ordering::Relaxed);
583    }
584
585    pub(crate) fn increment_goodbye_relay_module_dropped(&self, module_id: Option<&str>) {
586        self.goodbye_relay_module_dropped
587            .fetch_add(1, Ordering::Relaxed);
588        if let Some(module_id) = module_id {
589            increment_keyed_count(&self.goodbye_relay_module_dropped_by_module, module_id);
590        }
591    }
592
593    pub(crate) fn increment_route_released_epoch_fenced(&self) {
594        self.route_released_epoch_fenced
595            .fetch_add(1, Ordering::Relaxed);
596    }
597
598    pub(crate) fn increment_route_release_stale_skipped(&self) {
599        self.route_release_stale_skipped
600            .fetch_add(1, Ordering::Relaxed);
601    }
602
603    pub(crate) fn increment_drains_with_undeclared_gauge(&self) {
604        self.drains_with_undeclared_gauge
605            .fetch_add(1, Ordering::Relaxed);
606    }
607
608    #[cfg(unix)]
609    pub(crate) fn increment_carried_containment_anchor_lost(&self) {
610        self.carried_containment_anchor_lost
611            .fetch_add(1, Ordering::Relaxed);
612    }
613}
614
615const MAX_AGENT_REFUSAL_MODULES: usize = 1_024;
616
617#[cfg(test)]
618mod refusal_label_tests {
619    use super::*;
620
621    #[test]
622    fn dropped_refusal_labels_require_registration_and_stop_at_the_hard_cap() {
623        let registry = crate::Registry::default();
624        let counters = DaemonCounters::default();
625        counters.increment_agent_command_refusal_dropped(Some("unregistered"), &registry);
626        assert!(counters
627            .snapshot()
628            .get("agent_command_refusals_dropped_by_module")
629            .is_none());
630        for index in 0..=1_024 {
631            let id = format!("registered-{index}");
632            registry
633                .register_with_control_ops(
634                    subc_protocol::manifest::ModuleManifest::builder(&id, "0.1.0")
635                        .protocol_ver(1)
636                        .build(),
637                    1,
638                    crate::ConnectionId::new(index as u64 + 1),
639                    Vec::new(),
640                )
641                .unwrap();
642            counters.increment_agent_command_refusal_dropped(Some(&id), &registry);
643        }
644        counters.increment_agent_command_refusal_dropped(Some("registered-0"), &registry);
645        let snapshot = counters.snapshot();
646        let labels = snapshot["agent_command_refusals_dropped_by_module"]
647            .as_object()
648            .unwrap();
649        assert_eq!(labels.len(), 1_024);
650        assert_eq!(labels["registered-0"], 2);
651        assert!(!labels.contains_key("registered-1024"));
652        assert_eq!(snapshot["agent_command_refusals_dropped_unlabelled"], 2);
653    }
654}
655
656fn increment_keyed_count(counts: &Mutex<HashMap<String, u64>>, key: &str) {
657    *counts
658        .lock()
659        .expect("keyed counter mutex poisoned")
660        .entry(key.to_string())
661        .or_default() += 1;
662}
663
664fn insert_nonempty_counts(
665    snapshot: &mut serde_json::Map<String, Value>,
666    key: &str,
667    counts: &Mutex<HashMap<String, u64>>,
668) {
669    let counts: MutexGuard<'_, HashMap<String, u64>> =
670        counts.lock().expect("keyed counter mutex poisoned");
671    if !counts.is_empty() {
672        snapshot.insert(key.to_string(), json!(&*counts));
673    }
674}
675
676#[cfg(test)]
677mod tests {
678    use super::*;
679
680    #[test]
681    fn registration_channel_closed_route_refusal_is_counted() {
682        let counters = DaemonCounters::new();
683        counters.increment_route_open_refused(crate::supervise::REGISTRATION_CHANNEL_CLOSED);
684        assert_eq!(
685            counters.snapshot()["route_open_refused_by_code"],
686            serde_json::json!({"registration_channel_closed": 1})
687        );
688    }
689
690    #[test]
691    fn ready_reader_wait_needs_no_runtime_clock_or_labels() {
692        use std::{
693            future::Future,
694            task::{Context, Poll, Waker},
695        };
696
697        let counters = DaemonCounters::new();
698        let wait = counters.observe_reader_wait(
699            || panic!("ready waits must not resolve diagnostic labels"),
700            "module_queue",
701            std::future::ready(7),
702        );
703        let mut wait = std::pin::pin!(wait);
704        let mut cx = Context::from_waker(Waker::noop());
705        // No Tokio runtime exists here: even constructing Sleep would panic.
706        assert_eq!(wait.as_mut().poll(&mut cx), Poll::Ready(7));
707        assert!(counters.reader_diagnostics.lock().unwrap().waits.is_empty());
708    }
709
710    #[tokio::test(start_paused = true)]
711    async fn reader_wait_labels_are_resolved_once_only_after_five_seconds() {
712        use std::{
713            cell::Cell,
714            future::{poll_fn, Future},
715            task::Poll,
716        };
717
718        let counters = DaemonCounters::new();
719        let calls = Cell::new(0);
720        let (sender, receiver) = tokio::sync::oneshot::channel();
721        let wait = counters.observe_reader_wait(
722            || {
723                calls.set(calls.get() + 1);
724                ("alpha".into(), "direct".into())
725            },
726            "module_queue",
727            receiver,
728        );
729        tokio::pin!(wait);
730        assert!(poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx)))
731            .await
732            .is_pending());
733        tokio::time::advance(Duration::from_secs(4)).await;
734        assert!(poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx)))
735            .await
736            .is_pending());
737        assert_eq!(calls.get(), 0);
738        tokio::time::advance(Duration::from_secs(1)).await;
739        assert!(poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx)))
740            .await
741            .is_pending());
742        assert_eq!(calls.get(), 1);
743        assert_eq!(
744            counters.snapshot()["reader_wait_over_5s_by_module_principal"]["alpha"]["direct"]
745                ["module_queue"],
746            1
747        );
748        sender.send(()).unwrap();
749        wait.await.unwrap();
750        assert_eq!(calls.get(), 1);
751    }
752
753    #[test]
754    fn counter_snapshot_includes_zero_rate_and_omits_empty_module_maps() {
755        let counters = DaemonCounters::new();
756        let snapshot = counters.snapshot();
757
758        assert_eq!(snapshot["module_frames_dropped_no_route_last_10m"], 0);
759        assert_eq!(
760            snapshot["module_frames_dropped_no_route_nonzero_minutes_last_10m"],
761            0
762        );
763        assert!(snapshot
764            .get("module_frames_dropped_no_route_by_module")
765            .is_none());
766        assert!(snapshot
767            .get("goodbye_relay_module_dropped_by_module")
768            .is_none());
769    }
770
771    #[tokio::test(start_paused = true)]
772    async fn module_frame_drops_are_attributed_to_the_emitting_module() {
773        let counters = DaemonCounters::new();
774        counters.increment_module_frames_dropped_no_route(Some("alpha"));
775        counters.increment_module_frames_dropped_no_route(Some("alpha"));
776
777        let snapshot = counters.snapshot();
778        assert_eq!(snapshot["module_frames_dropped_no_route"], 2);
779        assert_eq!(
780            snapshot["module_frames_dropped_no_route_by_module"],
781            json!({ "alpha": 2 })
782        );
783        assert_eq!(snapshot["module_frames_dropped_no_route_last_10m"], 2);
784    }
785
786    #[tokio::test(start_paused = true)]
787    async fn frame_drop_rate_ages_out_after_ten_minute_buckets() {
788        let counters = DaemonCounters::new();
789        counters.increment_module_frames_dropped_no_route(Some("alpha"));
790
791        tokio::time::advance(Duration::from_secs(9 * 60)).await;
792        assert_eq!(
793            counters.snapshot()["module_frames_dropped_no_route_last_10m"],
794            1
795        );
796
797        tokio::time::advance(Duration::from_secs(60)).await;
798        assert_eq!(
799            counters.snapshot()["module_frames_dropped_no_route_last_10m"],
800            0
801        );
802    }
803
804    #[tokio::test(start_paused = true)]
805    async fn frame_drop_window_counts_only_nonzero_minutes() {
806        let counters = DaemonCounters::new();
807        for minute in 0..10 {
808            if minute > 0 {
809                tokio::time::advance(Duration::from_secs(60)).await;
810            }
811            if minute != 4 {
812                counters.increment_module_frames_dropped_no_route(Some("alpha"));
813            }
814        }
815
816        assert_eq!(
817            counters.snapshot()["module_frames_dropped_no_route_nonzero_minutes_last_10m"],
818            9
819        );
820    }
821
822    #[test]
823    fn goodbye_relay_drops_are_attributed_to_the_target_module() {
824        let counters = DaemonCounters::new();
825        counters.increment_goodbye_relay_module_dropped(Some("alpha"));
826
827        assert_eq!(
828            counters.snapshot()["goodbye_relay_module_dropped_by_module"],
829            json!({ "alpha": 1 })
830        );
831    }
832}