Skip to main content

rings_node/
observability.rs

1//! Versioned, bounded operator observability for a running node.
2//!
3//! [`Observability`](crate::observability::Observability) is the synchronous adapter installed at
4//! the core swarm boundary. It keeps
5//! process-lifetime counters, a fixed-size recent-event ring, and bounded DHT lookup correlation
6//! state. The native HTTP layer combines that state with live session, mailbox, peer-rating, and
7//! overlay snapshots in the authenticated `/status?view=observability` JSON response. No payload,
8//! key material, message identifier, mailbox identifier, or lookup correlation key crosses the
9//! export boundary.
10
11use std::collections::BTreeMap;
12use std::collections::VecDeque;
13use std::sync::Arc;
14use std::sync::Mutex;
15use std::sync::MutexGuard;
16
17use rings_core::message::MessageCategory;
18use rings_core::swarm::observer::LookupCorrelation;
19use rings_core::swarm::observer::LookupKind;
20use rings_core::swarm::observer::LookupOutcome;
21use rings_core::swarm::observer::MessageActivity;
22use rings_core::swarm::observer::MessageObservation;
23use rings_core::swarm::observer::ObservationOutcome;
24use rings_core::swarm::observer::SwarmObserver;
25use rings_core::utils::SharedClock;
26use rings_core::utils::SystemClock;
27use serde::Serialize;
28
29/// Version of the observability object nested in the HTTP status response.
30pub const OPERATOR_SCHEMA_VERSION: u16 = 1;
31/// Maximum number of recent message records retained in process memory and one status response.
32pub const RECENT_MESSAGE_CAPACITY: usize = 32;
33/// Maximum number of peer-rating records returned by one structured snapshot.
34pub const PEER_RATING_CAPACITY: usize = 32;
35/// Maximum number of lookup correlations retained until completion or timeout.
36const LOOKUP_CAPACITY: usize = 1024;
37/// Lookup age at which a scrape classifies an unanswered operation as timed out.
38const LOOKUP_TIMEOUT_MS: u128 = 30_000;
39/// Finite cumulative histogram boundaries for local DHT lookup latency.
40const LOOKUP_LATENCY_BUCKETS_MS: [u64; 12] = [
41    5, 10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000, 10_000, 30_000,
42];
43
44/// Process-local observability recorder shared by the processor and core swarm.
45pub struct Observability {
46    /// Unix epoch millisecond at which this recorder was constructed.
47    process_started_at_ms: u128,
48    /// Injected epoch clock capability for event and lookup correlation timestamps.
49    clock: SharedClock,
50    /// Complete bounded state protected for one short synchronous transition.
51    state: Mutex<RuntimeState>,
52}
53
54/// Mutable state behind [`Observability`].
55struct RuntimeState {
56    /// Monotonic sequence assigned to bounded recent message records.
57    next_event_sequence: u64,
58    /// Counters indexed by activity, traffic category, then outcome.
59    message_counts: [[[u64; 2]; 4]; 4],
60    /// Oldest-first bounded message record ring.
61    recent_messages: VecDeque<RecentMessageEvent>,
62    /// Correlated lookup starts, never exported with their keys.
63    lookups: BTreeMap<(LookupKind, LookupCorrelation), LookupStart>,
64    /// Cumulative process-lifetime lookup totals and latency buckets.
65    lookup_totals: LookupTotals,
66}
67
68/// Internal start witness for one in-flight lookup.
69#[derive(Clone, Copy)]
70struct LookupStart {
71    /// Epoch millisecond of the local start observation.
72    started_at_ms: u128,
73}
74
75/// Mutable cumulative DHT lookup counters.
76#[derive(Clone, Default)]
77struct LookupTotals {
78    /// Lookup rounds begun during this process lifetime.
79    started: u64,
80    /// Lookup rounds that accepted an answer.
81    succeeded: u64,
82    /// Lookup rounds that failed before an answer.
83    failed: u64,
84    /// Lookup rounds classified as timed out by bounded retention.
85    timed_out: u64,
86    /// Sum of completed lookup latencies in milliseconds.
87    latency_sum_ms: u128,
88    /// Number of terminal lookups represented in the latency histogram.
89    latency_count: u64,
90    /// Cumulative histogram buckets in the order of [`LOOKUP_LATENCY_BUCKETS_MS`].
91    latency_buckets: [u64; LOOKUP_LATENCY_BUCKETS_MS.len()],
92}
93
94/// One privacy-safe recent message record.
95#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
96pub struct RecentMessageEvent {
97    /// Process-local order, useful for polling without a message identifier.
98    pub sequence: u64,
99    /// Unix epoch millisecond at which the operation completed locally.
100    pub observed_at_ms: u128,
101    /// `sent`, `received`, `forwarded`, or `stored`.
102    pub action: &'static str,
103    /// Finite scheduling category such as `application` or `dht_control`.
104    pub category: &'static str,
105    /// Compile-time protocol variant name; never an application topic or payload value.
106    pub message_class: &'static str,
107    /// `succeeded` or `failed`.
108    pub outcome: &'static str,
109}
110
111/// Process-lifetime message counters with node-local semantics.
112#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
113pub struct MessageTotals {
114    /// Successful locally originated operations accepted by the next hop.
115    pub sent: u64,
116    /// Successful logical inbound operations accepted by this node.
117    pub received: u64,
118    /// Successful relays accepted by their next hop.
119    pub forwarded: u64,
120    /// Successful offline-message holds written to a relay inbox.
121    pub stored: u64,
122    /// Failed operations across every action above.
123    pub failed: u64,
124}
125
126/// Public DHT lookup counters and latency distribution.
127#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
128pub struct DhtLookupSnapshot {
129    /// Lookup rounds begun during this process lifetime.
130    pub total: u64,
131    /// Lookup rounds that accepted a local or authenticated remote answer.
132    pub succeeded: u64,
133    /// Lookup rounds that terminated with an explicit local failure.
134    pub failed: u64,
135    /// Lookup rounds retained past the thirty-second observation bound.
136    pub timed_out: u64,
137    /// Lookup rounds still awaiting an answer.
138    pub in_flight: u64,
139    /// Sum of terminal lookup latency in milliseconds.
140    pub latency_sum_ms: u128,
141    /// Number of terminal lookups in the latency distribution.
142    pub latency_count: u64,
143    /// Cumulative latency buckets for external rate and threshold calculations.
144    pub latency_buckets: Vec<LatencyBucket>,
145}
146
147/// One cumulative DHT latency histogram bucket.
148#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
149pub struct LatencyBucket {
150    /// Inclusive upper bound in milliseconds.
151    pub le_ms: u64,
152    /// Number of completed lookups at or below the bound.
153    pub count: u64,
154}
155
156/// Active session-key lifecycle without key material or key-derived identifiers.
157#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
158pub struct SessionKeySnapshot {
159    /// Whether the active delegation is valid at snapshot time.
160    pub valid: bool,
161    /// Delegation creation time in Unix epoch milliseconds.
162    pub created_at_ms: u128,
163    /// Delegation expiry in Unix epoch milliseconds.
164    pub expires_at_ms: u128,
165    /// Saturating time until expiry in milliseconds.
166    pub remaining_ms: u128,
167    /// Successful runtime rotations during this process lifetime.
168    pub rotation_succeeded_total: u64,
169    /// Failed runtime rotations during this process lifetime.
170    pub rotation_failed_total: u64,
171    /// Whether this process can replace its signing delegation without restart.
172    pub runtime_rotation_supported: bool,
173}
174
175/// Aggregate live relay-mailbox state.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
177pub struct MailboxSnapshot {
178    /// Live relay-inbox carriers retained by this node.
179    pub registered: u64,
180    /// Live held messages across all retained inboxes.
181    pub held_messages: u64,
182    /// Successful holds during this process lifetime.
183    pub stored_total: u64,
184}
185
186/// Bounded structured local assessment of one peer.
187#[derive(Clone, Debug, PartialEq, Serialize)]
188pub struct PeerRatingSnapshot {
189    /// Public peer DID, present only in this bounded authenticated JSON response.
190    pub peer: String,
191    /// Advisory `healthy`, `unknown`, or `degraded` local reliability class.
192    pub reliability: &'static str,
193    /// Local resource-priority multiplier, not a network-wide reputation score.
194    pub credit_score: f64,
195    /// Successful recent sends in the active reliability epoch.
196    pub sent: u64,
197    /// Failed recent sends in the active reliability epoch.
198    pub failed_to_send: u64,
199    /// Successful recent receives in the active reliability epoch.
200    pub received: u64,
201    /// Failed recent receives in the active reliability epoch.
202    pub failed_to_receive: u64,
203}
204
205/// Explicit separation of HTTP-process liveness and overlay readiness.
206#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
207pub struct HealthSnapshot {
208    /// True because producing the response proves the authenticated API task is serving.
209    pub process_api_healthy: bool,
210    /// Number of active routable transport peers in the current snapshot.
211    pub admitted_peer_count: u64,
212    /// Whether the node currently has at least one admitted transport peer.
213    pub has_admitted_peer: bool,
214    /// Whether the local DHT currently has a successor.
215    pub has_successor: bool,
216    /// Whether the local DHT currently has a predecessor.
217    pub has_predecessor: bool,
218    /// Conservative participation signal: an admitted peer and a successor are both present,
219    /// and the node's own delegation is before its signing horizon, so its frames still leave
220    /// (#1063).
221    pub overlay_ready: bool,
222}
223
224/// Complete JSON response returned by the v1 operator endpoint.
225#[derive(Clone, Debug, PartialEq, Serialize)]
226pub struct OperatorSnapshot {
227    /// Schema version for compatibility-sensitive consumers.
228    pub schema_version: u16,
229    /// Unix epoch millisecond at which this snapshot was assembled.
230    pub generated_at_ms: u128,
231    /// Unix epoch millisecond at which process-local counters began.
232    pub process_started_at_ms: u128,
233    /// Explicit scope of message and lookup counters.
234    pub counter_scope: &'static str,
235    /// Process-lifetime node-local message totals.
236    pub messages: MessageTotals,
237    /// Oldest-first bounded recent message activity.
238    pub recent_messages: Vec<RecentMessageEvent>,
239    /// Session delegation lifecycle.
240    pub session_key: SessionKeySnapshot,
241    /// Aggregate local relay-mailbox state.
242    pub mailboxes: MailboxSnapshot,
243    /// Process-lifetime DHT lookup outcomes and latency.
244    pub dht_lookups: DhtLookupSnapshot,
245    /// Bounded local peer assessments.
246    pub peer_ratings: Vec<PeerRatingSnapshot>,
247    /// Process/API and overlay health as separate propositions.
248    pub health: HealthSnapshot,
249}
250
251impl Default for RuntimeState {
252    fn default() -> Self {
253        Self {
254            next_event_sequence: 0,
255            message_counts: [[[0; 2]; 4]; 4],
256            recent_messages: VecDeque::with_capacity(RECENT_MESSAGE_CAPACITY),
257            lookups: BTreeMap::new(),
258            lookup_totals: LookupTotals::default(),
259        }
260    }
261}
262
263impl Observability {
264    /// Construct an empty process-local recorder at the current wall-clock instant.
265    pub fn new() -> Self {
266        Self::new_with_clock(Arc::new(SystemClock))
267    }
268
269    /// Construct an empty process-local recorder bound to `clock`.
270    pub fn new_with_clock(clock: SharedClock) -> Self {
271        let process_started_at_ms = clock.now_ms();
272        Self {
273            process_started_at_ms,
274            clock,
275            state: Mutex::new(RuntimeState::default()),
276        }
277    }
278
279    /// Return the beginning of the process-local counter scope.
280    pub const fn process_started_at_ms(&self) -> u128 {
281        self.process_started_at_ms
282    }
283
284    /// Produce message and lookup state, expiring stale correlations as timeouts first.
285    pub fn runtime_snapshot(&self, observed_at_ms: u128) -> RuntimeSnapshot {
286        let mut state = lock_or_recover(&self.state);
287        expire_lookups(&mut state, observed_at_ms);
288        RuntimeSnapshot {
289            messages: message_totals(&state.message_counts),
290            recent_messages: state.recent_messages.iter().cloned().collect(),
291            dht_lookups: lookup_snapshot(&state),
292        }
293    }
294}
295
296impl Default for Observability {
297    fn default() -> Self {
298        Self::new()
299    }
300}
301
302/// Recorder-owned part of an operator snapshot.
303pub struct RuntimeSnapshot {
304    /// Process-lifetime message totals.
305    pub messages: MessageTotals,
306    /// Bounded recent message records.
307    pub recent_messages: Vec<RecentMessageEvent>,
308    /// Bounded lookup state and cumulative outcomes.
309    pub dht_lookups: DhtLookupSnapshot,
310}
311
312impl SwarmObserver for Observability {
313    fn observe_message(&self, observation: MessageObservation) {
314        let observed_at_ms = self.clock.now_ms();
315        let mut state = lock_or_recover(&self.state);
316        let activity = activity_index(observation.activity);
317        let category = category_index(observation.category);
318        let outcome = outcome_index(observation.outcome);
319        if let Some(count) = state
320            .message_counts
321            .get_mut(activity)
322            .and_then(|categories| categories.get_mut(category))
323            .and_then(|outcomes| outcomes.get_mut(outcome))
324        {
325            *count = count.saturating_add(1);
326        }
327        let sequence = state.next_event_sequence;
328        state.next_event_sequence = state.next_event_sequence.saturating_add(1);
329        if state.recent_messages.len() == RECENT_MESSAGE_CAPACITY {
330            state.recent_messages.pop_front();
331        }
332        state.recent_messages.push_back(RecentMessageEvent {
333            sequence,
334            observed_at_ms,
335            action: activity_name(observation.activity),
336            category: category_name(observation.category),
337            message_class: observation.message_class,
338            outcome: outcome_name(observation.outcome),
339        });
340    }
341
342    fn lookup_started(&self, kind: LookupKind, correlation: LookupCorrelation) {
343        let observed_at_ms = self.clock.now_ms();
344        let mut state = lock_or_recover(&self.state);
345        expire_lookups(&mut state, observed_at_ms);
346        if let Some(previous) = state.lookups.remove(&(kind, correlation)) {
347            finish_lookup(&mut state.lookup_totals, previous, observed_at_ms, None);
348        }
349        while state.lookups.len() >= LOOKUP_CAPACITY {
350            let Some(oldest) = state
351                .lookups
352                .iter()
353                .min_by_key(|(_, start)| start.started_at_ms)
354                .map(|(key, _)| *key)
355            else {
356                break;
357            };
358            if let Some(start) = state.lookups.remove(&oldest) {
359                finish_lookup(&mut state.lookup_totals, start, observed_at_ms, None);
360            }
361        }
362        state.lookup_totals.started = state.lookup_totals.started.saturating_add(1);
363        state.lookups.insert((kind, correlation), LookupStart {
364            started_at_ms: observed_at_ms,
365        });
366    }
367
368    fn lookup_finished(
369        &self,
370        kind: LookupKind,
371        correlation: LookupCorrelation,
372        outcome: LookupOutcome,
373    ) {
374        let observed_at_ms = self.clock.now_ms();
375        let mut state = lock_or_recover(&self.state);
376        expire_lookups(&mut state, observed_at_ms);
377        if let Some(start) = state.lookups.remove(&(kind, correlation)) {
378            finish_lookup(
379                &mut state.lookup_totals,
380                start,
381                observed_at_ms,
382                Some(outcome),
383            );
384        }
385    }
386}
387
388/// Return the current Unix epoch time in milliseconds for unit tests.
389#[cfg(test)]
390fn now_ms() -> u128 {
391    rings_core::utils::get_epoch_ms()
392}
393
394/// Acquire a recorder lock, preserving collected state after an earlier panic.
395fn lock_or_recover<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
396    mutex
397        .lock()
398        .unwrap_or_else(std::sync::PoisonError::into_inner)
399}
400
401/// Map a finite message activity to its counter-array index.
402const fn activity_index(activity: MessageActivity) -> usize {
403    match activity {
404        MessageActivity::Sent => 0,
405        MessageActivity::Received => 1,
406        MessageActivity::Forwarded => 2,
407        MessageActivity::Stored => 3,
408    }
409}
410
411/// Map a finite message category to its counter-array index.
412const fn category_index(category: MessageCategory) -> usize {
413    match category {
414        MessageCategory::DhtControl => 0,
415        MessageCategory::Storage => 1,
416        MessageCategory::E2e => 2,
417        MessageCategory::Application => 3,
418    }
419}
420
421/// Map a finite operation outcome to its counter-array index.
422const fn outcome_index(outcome: ObservationOutcome) -> usize {
423    match outcome {
424        ObservationOutcome::Succeeded => 0,
425        ObservationOutcome::Failed => 1,
426    }
427}
428
429/// Return the stable lowercase export name for a message activity.
430const fn activity_name(activity: MessageActivity) -> &'static str {
431    match activity {
432        MessageActivity::Sent => "sent",
433        MessageActivity::Received => "received",
434        MessageActivity::Forwarded => "forwarded",
435        MessageActivity::Stored => "stored",
436    }
437}
438
439/// Return the stable lowercase export name for a scheduling category.
440const fn category_name(category: MessageCategory) -> &'static str {
441    match category {
442        MessageCategory::DhtControl => "dht_control",
443        MessageCategory::Storage => "storage",
444        MessageCategory::E2e => "e2e",
445        MessageCategory::Application => "application",
446    }
447}
448
449/// Return the stable lowercase export name for an operation outcome.
450const fn outcome_name(outcome: ObservationOutcome) -> &'static str {
451    match outcome {
452        ObservationOutcome::Succeeded => "succeeded",
453        ObservationOutcome::Failed => "failed",
454    }
455}
456
457/// Collapse category-specific counters into the public message totals.
458fn message_totals(counts: &[[[u64; 2]; 4]; 4]) -> MessageTotals {
459    let successful = |activity: MessageActivity| {
460        counts
461            .get(activity_index(activity))
462            .into_iter()
463            .flatten()
464            .fold(0_u64, |total, category| {
465                total.saturating_add(category.first().copied().unwrap_or_default())
466            })
467    };
468    let failed = counts
469        .iter()
470        .flat_map(|categories| categories.iter())
471        .fold(0_u64, |total, outcomes| {
472            total.saturating_add(outcomes.get(1).copied().unwrap_or_default())
473        });
474    MessageTotals {
475        sent: successful(MessageActivity::Sent),
476        received: successful(MessageActivity::Received),
477        forwarded: successful(MessageActivity::Forwarded),
478        stored: successful(MessageActivity::Stored),
479        failed,
480    }
481}
482
483/// Complete all retained lookups older than the observation timeout.
484fn expire_lookups(state: &mut RuntimeState, observed_at_ms: u128) {
485    let expired = state
486        .lookups
487        .iter()
488        .filter(|(_, start)| {
489            observed_at_ms.saturating_sub(start.started_at_ms) >= LOOKUP_TIMEOUT_MS
490        })
491        .map(|(key, _)| *key)
492        .collect::<Vec<_>>();
493    for key in expired {
494        if let Some(start) = state.lookups.remove(&key) {
495            finish_lookup(&mut state.lookup_totals, start, observed_at_ms, None);
496        }
497    }
498}
499
500/// Record one terminal lookup outcome and its cumulative latency buckets.
501fn finish_lookup(
502    totals: &mut LookupTotals,
503    start: LookupStart,
504    observed_at_ms: u128,
505    outcome: Option<LookupOutcome>,
506) {
507    let latency_ms = observed_at_ms.saturating_sub(start.started_at_ms);
508    match outcome {
509        Some(LookupOutcome::Succeeded) => totals.succeeded = totals.succeeded.saturating_add(1),
510        Some(LookupOutcome::Failed) => totals.failed = totals.failed.saturating_add(1),
511        None => totals.timed_out = totals.timed_out.saturating_add(1),
512    }
513    totals.latency_sum_ms = totals.latency_sum_ms.saturating_add(latency_ms);
514    totals.latency_count = totals.latency_count.saturating_add(1);
515    for (count, bound) in totals
516        .latency_buckets
517        .iter_mut()
518        .zip(LOOKUP_LATENCY_BUCKETS_MS)
519    {
520        if latency_ms <= u128::from(bound) {
521            *count = count.saturating_add(1);
522        }
523    }
524}
525
526/// Copy internal bounded lookup state into its identifier-free public form.
527fn lookup_snapshot(state: &RuntimeState) -> DhtLookupSnapshot {
528    DhtLookupSnapshot {
529        total: state.lookup_totals.started,
530        succeeded: state.lookup_totals.succeeded,
531        failed: state.lookup_totals.failed,
532        timed_out: state.lookup_totals.timed_out,
533        in_flight: u64::try_from(state.lookups.len()).unwrap_or(u64::MAX),
534        latency_sum_ms: state.lookup_totals.latency_sum_ms,
535        latency_count: state.lookup_totals.latency_count,
536        latency_buckets: LOOKUP_LATENCY_BUCKETS_MS
537            .iter()
538            .copied()
539            .zip(state.lookup_totals.latency_buckets)
540            .map(|(le_ms, count)| LatencyBucket { le_ms, count })
541            .collect(),
542    }
543}
544
545#[cfg(test)]
546mod tests {
547    use super::*;
548
549    fn observation(activity: MessageActivity, outcome: ObservationOutcome) -> MessageObservation {
550        MessageObservation {
551            activity,
552            category: MessageCategory::Application,
553            message_class: "CustomMessage",
554            outcome,
555        }
556    }
557
558    #[test]
559    fn recent_activity_is_bounded_and_payload_free() {
560        let recorder = Observability::new();
561        for _ in 0..(RECENT_MESSAGE_CAPACITY + 7) {
562            recorder.observe_message(observation(
563                MessageActivity::Received,
564                ObservationOutcome::Succeeded,
565            ));
566        }
567        let snapshot = recorder.runtime_snapshot(now_ms());
568        assert_eq!(snapshot.recent_messages.len(), RECENT_MESSAGE_CAPACITY);
569        assert_eq!(
570            snapshot.messages.received,
571            (RECENT_MESSAGE_CAPACITY + 7) as u64
572        );
573        let json = serde_json::to_string(&snapshot.recent_messages).expect("serialize events");
574        assert!(!json.contains("payload"));
575        assert!(!json.contains("transaction"));
576    }
577
578    #[test]
579    fn timed_out_lookup_leaves_no_in_flight_identifier() {
580        let recorder = Observability::new();
581        let correlation = LookupCorrelation::Transaction(uuid::Uuid::new_v4());
582        recorder.lookup_started(LookupKind::Successor, correlation);
583        let future = now_ms().saturating_add(LOOKUP_TIMEOUT_MS);
584        let snapshot = recorder.runtime_snapshot(future);
585        assert_eq!(snapshot.dht_lookups.total, 1);
586        assert_eq!(snapshot.dht_lookups.timed_out, 1);
587        assert_eq!(snapshot.dht_lookups.in_flight, 0);
588    }
589
590    #[test]
591    fn production_bounded_snapshot_fixture_stays_under_32_kib() {
592        /// Test-only wire shape matching the compact HTTP status projection.
593        #[derive(Serialize)]
594        struct CompactStatusFixture {
595            /// Conservative version string included in every compact response.
596            version: &'static str,
597            /// Maximum-width observability fixture under the production collection caps.
598            observability: OperatorSnapshot,
599        }
600
601        let message_class = "ConservativeSixtyFourCharacterProtocolMessageClassNamePlaceholderXX";
602        let peer = "did:ring:conservative-sixty-four-character-peer-identifier-placeholder";
603        let snapshot = OperatorSnapshot {
604            schema_version: OPERATOR_SCHEMA_VERSION,
605            generated_at_ms: 2,
606            process_started_at_ms: 1,
607            counter_scope: "node_local_process_lifetime",
608            messages: MessageTotals {
609                sent: u64::MAX,
610                received: u64::MAX,
611                forwarded: u64::MAX,
612                stored: u64::MAX,
613                failed: u64::MAX,
614            },
615            recent_messages: (0..RECENT_MESSAGE_CAPACITY)
616                .map(|index| RecentMessageEvent {
617                    sequence: u64::try_from(index).unwrap_or(u64::MAX),
618                    observed_at_ms: u128::MAX.saturating_sub(index as u128),
619                    action: "forwarded",
620                    category: "application",
621                    message_class,
622                    outcome: "succeeded",
623                })
624                .collect(),
625            session_key: SessionKeySnapshot {
626                valid: true,
627                created_at_ms: u128::MAX,
628                expires_at_ms: u128::MAX,
629                remaining_ms: u128::MAX,
630                rotation_succeeded_total: u64::MAX,
631                rotation_failed_total: u64::MAX,
632                runtime_rotation_supported: false,
633            },
634            mailboxes: MailboxSnapshot {
635                registered: u64::MAX,
636                held_messages: u64::MAX,
637                stored_total: u64::MAX,
638            },
639            dht_lookups: DhtLookupSnapshot {
640                total: u64::MAX,
641                succeeded: u64::MAX,
642                failed: u64::MAX,
643                timed_out: u64::MAX,
644                in_flight: u64::MAX,
645                latency_sum_ms: u128::MAX,
646                latency_count: u64::MAX,
647                latency_buckets: (0..LOOKUP_LATENCY_BUCKETS_MS.len())
648                    .map(|_| LatencyBucket {
649                        le_ms: u64::MAX,
650                        count: u64::MAX,
651                    })
652                    .collect(),
653            },
654            peer_ratings: (0..PEER_RATING_CAPACITY)
655                .map(|_| PeerRatingSnapshot {
656                    peer: peer.to_string(),
657                    reliability: "degraded",
658                    credit_score: f64::MAX,
659                    sent: u64::MAX,
660                    failed_to_send: u64::MAX,
661                    received: u64::MAX,
662                    failed_to_receive: u64::MAX,
663                })
664                .collect(),
665            health: HealthSnapshot {
666                process_api_healthy: true,
667                admitted_peer_count: u64::MAX,
668                has_admitted_peer: true,
669                has_successor: true,
670                has_predecessor: false,
671                overlay_ready: true,
672            },
673        };
674
675        let response = CompactStatusFixture {
676            version: "0.30.0-conservative-version-placeholder",
677            observability: snapshot,
678        };
679        let encoded = serde_json::to_vec(&response).expect("serialize compact status response");
680        assert!(
681            encoded.len() < 32 * 1024,
682            "compact status response was {} bytes",
683            encoded.len()
684        );
685    }
686
687    #[test]
688    fn injected_manual_clock_drives_event_and_lookup_timestamps() {
689        use rings_core::utils::Clock;
690
691        let manual = rings_core::utils::ManualClock::new(1_700_000_000_000);
692        let shared: SharedClock = Arc::new(manual.clone());
693        let recorder = Observability::new_with_clock(shared);
694        assert_eq!(recorder.process_started_at_ms(), 1_700_000_000_000);
695
696        manual.advance(125);
697        recorder.observe_message(observation(
698            MessageActivity::Sent,
699            ObservationOutcome::Succeeded,
700        ));
701        let correlation = LookupCorrelation::Transaction(uuid::Uuid::new_v4());
702        recorder.lookup_started(LookupKind::Successor, correlation);
703
704        manual.advance(250);
705        recorder.lookup_finished(LookupKind::Successor, correlation, LookupOutcome::Succeeded);
706
707        let snapshot = recorder.runtime_snapshot(manual.now_ms());
708        assert_eq!(
709            snapshot.recent_messages[0].observed_at_ms,
710            1_700_000_000_125
711        );
712        assert_eq!(snapshot.dht_lookups.succeeded, 1);
713        assert_eq!(snapshot.dht_lookups.latency_sum_ms, 250);
714    }
715}