Skip to main content

saluki_core/observability/metrics/
mod.rs

1//! Internal metrics support.
2//!
3//! Includes the [`MetricsStream`] broadcast of internally emitted metrics events and the
4//! [`Reflector`]-based [`AggregatedMetricsState`] view that downstream callers query for
5//! Prometheus exposition.
6
7use std::{
8    num::NonZeroUsize,
9    pin::Pin,
10    sync::{
11        atomic::{AtomicBool, AtomicU32, Ordering},
12        Arc, LazyLock, Mutex, OnceLock,
13    },
14    task::{self, ready, Poll},
15    time::Duration,
16};
17
18use async_trait::async_trait;
19use futures::Stream;
20use metrics::{
21    atomics::AtomicU64, Counter, CounterFn, Gauge, GaugeFn, Histogram, HistogramFn, Key, KeyName, Level, Metadata,
22    Recorder, SetRecorderError, SharedString, Unit,
23};
24use metrics_util::storage::AtomicBucket;
25use saluki_common::{
26    collections::{FastHashMap, FastHashSet},
27    sync::shutdown::ShutdownHandle,
28};
29use saluki_error::GenericError;
30use tokio::{
31    select,
32    sync::broadcast::{self, error::RecvError, Receiver},
33};
34use tokio_util::sync::ReusableBoxFuture;
35use tracing::debug;
36
37use crate::{
38    data_model::{
39        event::{
40            metric::{
41                context::{Context, ContextResolver, ContextResolverBuilder},
42                *,
43            },
44            Event,
45        },
46        origin::RawOrigin,
47        tags::{Tag, TagSet},
48    },
49    runtime::{InitializationError, Supervisable, SupervisorFuture},
50};
51
52mod aggregated;
53pub use self::aggregated::{
54    get_shared_metrics_state, initialize_shared_metrics_state, AggregatedMetricValue, AggregatedMetricsProcessor,
55    AggregatedMetricsState, SharedMetricsWorker,
56};
57
58mod api;
59pub use self::api::InternalTelemetryAPIWorker;
60
61mod histogram;
62pub use self::histogram::AggregatedHistogram;
63
64mod processor;
65pub use self::processor::TelemetryProcessor;
66
67mod reflector;
68pub use self::reflector::{Processor, Reflector, ReflectorWorker};
69
70mod remapper;
71pub use self::remapper::{RemappedMetric, RemapperRule};
72
73const FLUSH_INTERVAL: Duration = Duration::from_secs(1);
74const INTERNAL_METRICS_INTERNER_SIZE: NonZeroUsize = NonZeroUsize::new(16_384).unwrap();
75
76/// Number of consecutive flush intervals that a metric must go without a live handle and without being re-registered
77/// before it is evicted from the registry.
78///
79/// This grace period prevents metrics that are emitted through `metrics` macros without caching the returned handle --
80/// and that therefore re-register on every call -- from being churned in and out of the registry while they are still
81/// being emitted. Naturally, this only applies to metrics which re-register within `IDLE_EVICT_INTERVALS *
82/// FLUSH_INTERVAL`, which is 3 seconds by default... but that's a tradeoff we're making here to avoid unbounded growth.
83const IDLE_EVICT_INTERVALS: u32 = 3;
84
85static RECEIVER_STATE: OnceLock<Arc<State>> = OnceLock::new();
86
87/// A batch of metric updates produced by a single flush.
88#[derive(Clone, Default)]
89pub struct MetricsSnapshot {
90    /// Updates to active metrics.
91    pub upserts: Vec<Event>,
92
93    /// Metrics which are no longer active and should be removed.
94    pub evictions: Vec<Context>,
95}
96
97/// A [`MetricsSnapshot`] that can be cheaply cloned and shared between multiple consumers.
98pub type SharedMetricsSnapshot = Arc<MetricsSnapshot>;
99
100struct Handle<T> {
101    inner: T,
102    level: Level,
103    idle: AtomicU32,
104}
105
106impl<T> Handle<T> {
107    const fn new(inner: T, level: Level) -> Self {
108        Self {
109            inner,
110            level,
111            idle: AtomicU32::new(0),
112        }
113    }
114
115    fn level(&self) -> Level {
116        self.level
117    }
118
119    fn reset_idle(&self) {
120        self.idle.store(0, Ordering::Relaxed);
121    }
122
123    fn bump_idle(&self) -> u32 {
124        self.idle.fetch_add(1, Ordering::Relaxed).saturating_add(1)
125    }
126}
127
128struct CounterInner {
129    value: AtomicU64,
130}
131
132impl Handle<CounterInner> {
133    const fn new_counter(level: Level) -> Self {
134        Self::new(
135            CounterInner {
136                value: AtomicU64::new(0),
137            },
138            level,
139        )
140    }
141
142    /// Consumes the accumulated delta since the last flush, resetting the counter to zero.
143    fn consume(&self) -> u64 {
144        self.inner.value.swap(0, Ordering::Relaxed)
145    }
146}
147
148impl CounterFn for Handle<CounterInner> {
149    fn increment(&self, value: u64) {
150        CounterFn::increment(&self.inner.value, value);
151    }
152
153    fn absolute(&self, value: u64) {
154        CounterFn::absolute(&self.inner.value, value);
155    }
156}
157
158struct GaugeInner {
159    value: AtomicU64,
160    // Tracks whether or not the gauge has been written since the last flush, since the gauge _could_
161    // be modified in a way where the value seen by two consecutive flushes is the same, even though
162    // it _was_ modified between the two and should be considered non-idle.
163    dirty: AtomicBool,
164}
165
166impl Handle<GaugeInner> {
167    const fn new_gauge(level: Level) -> Self {
168        Self::new(
169            GaugeInner {
170                value: AtomicU64::new(0),
171                dirty: AtomicBool::new(false),
172            },
173            level,
174        )
175    }
176
177    /// Reads the current gauge value.
178    fn load(&self) -> f64 {
179        f64::from_bits(self.inner.value.load(Ordering::Relaxed))
180    }
181
182    /// Returns whether the gauge was written since the last flush, clearing the flag.
183    fn take_dirty(&self) -> bool {
184        self.inner.dirty.swap(false, Ordering::Relaxed)
185    }
186}
187
188impl GaugeFn for Handle<GaugeInner> {
189    fn increment(&self, value: f64) {
190        GaugeFn::increment(&self.inner.value, value);
191        self.inner.dirty.store(true, Ordering::Relaxed);
192    }
193
194    fn decrement(&self, value: f64) {
195        GaugeFn::decrement(&self.inner.value, value);
196        self.inner.dirty.store(true, Ordering::Relaxed);
197    }
198
199    fn set(&self, value: f64) {
200        GaugeFn::set(&self.inner.value, value);
201        self.inner.dirty.store(true, Ordering::Relaxed);
202    }
203}
204
205/// Storage for a single histogram, shared between the registry and every caller-held [`Histogram`].
206struct HistogramInner {
207    value: AtomicBucket<f64>,
208}
209
210impl Handle<HistogramInner> {
211    fn new_histogram(level: Level) -> Self {
212        Self::new(
213            HistogramInner {
214                value: AtomicBucket::new(),
215            },
216            level,
217        )
218    }
219
220    /// Drains all recorded samples since the last flush into `out`, clearing the histogram.
221    fn drain_into(&self, out: &mut Vec<f64>) {
222        self.inner.value.clear_with(|samples| out.extend(samples));
223    }
224}
225
226impl HistogramFn for Handle<HistogramInner> {
227    fn record(&self, value: f64) {
228        self.inner.value.push(value);
229    }
230}
231
232/// A registry for all internal metrics.
233///
234/// Optimized for simplicity and the ability to efficiently track metric state and evict idle metrics. Not optimized for
235/// high concurrency with regards to registration, so metric handles should always be held for as long as possible, when
236/// possible.
237#[derive(Default)]
238struct MetricsRegistry {
239    maps: Mutex<RegistryMaps>,
240}
241
242#[derive(Default)]
243struct RegistryMaps {
244    counters: FastHashMap<Key, Arc<Handle<CounterInner>>>,
245    gauges: FastHashMap<Key, Arc<Handle<GaugeInner>>>,
246    histograms: FastHashMap<Key, Arc<Handle<HistogramInner>>>,
247    // Explicitly deleted counters whose resolver cache entries the next flush must retire.
248    //
249    // This is a set so that a counter deleted repeatedly between two flushes (for example, origin telemetry cycling
250    // more origins than it retains) is queued once: the queue is bounded by the number of distinct keys, not by the
251    // number of deletions.
252    deleted_counters: FastHashSet<Key>,
253}
254
255impl MetricsRegistry {
256    /// Returns a handle to the counter for `key`, creating it at `level` if it doesn't yet exist.
257    ///
258    /// The level is fixed when the metric is first created; re-registration only refreshes the idle
259    /// counter (the activity signal that keeps actively emitted metrics from being evicted).
260    fn get_or_create_counter(&self, key: &Key, level: Level) -> Counter {
261        let mut maps = self.maps.lock().unwrap();
262        let handle = if let Some(handle) = maps.counters.get(key) {
263            handle.reset_idle();
264            Arc::clone(handle)
265        } else {
266            let handle = Arc::new(Handle::new_counter(level));
267            maps.counters.insert(key.clone(), Arc::clone(&handle));
268            handle
269        };
270
271        Counter::from_arc(handle)
272    }
273
274    fn remove_counter(&self, key: &Key) -> Option<Arc<Handle<CounterInner>>> {
275        let mut maps = self.maps.lock().unwrap();
276        let handle = maps.counters.remove(key)?;
277        // Only clone the key the first time it's queued.
278        if !maps.deleted_counters.contains(key) {
279            maps.deleted_counters.insert(key.clone());
280        }
281        Some(handle)
282    }
283
284    /// Returns a handle to the gauge for `key`, creating it at `level` if it doesn't yet exist.
285    fn get_or_create_gauge(&self, key: &Key, level: Level) -> Gauge {
286        let mut maps = self.maps.lock().unwrap();
287        let handle = if let Some(handle) = maps.gauges.get(key) {
288            handle.reset_idle();
289            Arc::clone(handle)
290        } else {
291            let handle = Arc::new(Handle::new_gauge(level));
292            maps.gauges.insert(key.clone(), Arc::clone(&handle));
293            handle
294        };
295
296        Gauge::from_arc(handle)
297    }
298
299    /// Returns a handle to the histogram for `key`, creating it at `level` if it doesn't yet exist.
300    fn get_or_create_histogram(&self, key: &Key, level: Level) -> Histogram {
301        let mut maps = self.maps.lock().unwrap();
302        let handle = if let Some(handle) = maps.histograms.get(key) {
303            handle.reset_idle();
304            Arc::clone(handle)
305        } else {
306            let handle = Arc::new(Handle::new_histogram(level));
307            maps.histograms.insert(key.clone(), Arc::clone(&handle));
308            handle
309        };
310
311        Histogram::from_arc(handle)
312    }
313}
314
315/// Handle to the metrics filter.
316///
317/// Allows for overriding the current metrics filter level, which influences which metrics are emitted to downstream
318/// receivers.
319pub struct FilterHandle {
320    state: Arc<State>,
321}
322
323impl FilterHandle {
324    /// Overrides the current metrics filter level.
325    pub fn override_filter(&self, level: Level) {
326        *self.state.current_level.lock().unwrap() = level;
327    }
328
329    /// Resets the metrics filter level to the default that was configured when the metrics subsystem was initialized.
330    pub fn reset_filter(&self) {
331        *self.state.current_level.lock().unwrap() = self.state.default_level;
332    }
333}
334
335struct State {
336    registry: MetricsRegistry,
337    flush_tx: broadcast::Sender<SharedMetricsSnapshot>,
338    metrics_prefix: String,
339    default_level: Level,
340    current_level: Mutex<Level>,
341    idle_evict_intervals: u32,
342    flush_interval: Duration,
343}
344
345struct MetricsRecorder {
346    state: Arc<State>,
347}
348
349impl MetricsRecorder {
350    fn new(metrics_prefix: String, default_level: Level) -> Self {
351        let (flush_tx, _) = broadcast::channel(2);
352        Self {
353            state: Arc::new(State {
354                registry: MetricsRegistry::default(),
355                flush_tx,
356                metrics_prefix,
357                default_level,
358                current_level: Mutex::new(default_level),
359                idle_evict_intervals: IDLE_EVICT_INTERVALS,
360                flush_interval: FLUSH_INTERVAL,
361            }),
362        }
363    }
364
365    fn filter_handle(&self) -> FilterHandle {
366        FilterHandle {
367            state: Arc::clone(&self.state),
368        }
369    }
370
371    fn install(self) -> Result<(), SetRecorderError<Self>> {
372        let state = Arc::clone(&self.state);
373        metrics::set_global_recorder(self)?;
374
375        if RECEIVER_STATE.set(state).is_err() {
376            panic!("metrics receiver should never be set prior to global recorder being installed");
377        }
378
379        Ok(())
380    }
381
382    fn prefix_key(&self, key: &Key) -> Key {
383        Key::from_parts(format!("{}.{}", self.state.metrics_prefix, key.name()), key.labels())
384    }
385}
386
387impl Recorder for MetricsRecorder {
388    fn describe_counter(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
389    fn describe_gauge(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
390    fn describe_histogram(&self, _: KeyName, _: Option<Unit>, _: SharedString) {}
391
392    fn register_counter(&self, key: &Key, metadata: &Metadata<'_>) -> Counter {
393        let prefixed_key = self.prefix_key(key);
394        self.state
395            .registry
396            .get_or_create_counter(&prefixed_key, *metadata.level())
397    }
398
399    fn register_gauge(&self, key: &Key, metadata: &Metadata<'_>) -> Gauge {
400        let prefixed_key = self.prefix_key(key);
401        self.state
402            .registry
403            .get_or_create_gauge(&prefixed_key, *metadata.level())
404    }
405
406    fn register_histogram(&self, key: &Key, metadata: &Metadata<'_>) -> Histogram {
407        let prefixed_key = self.prefix_key(key);
408        self.state
409            .registry
410            .get_or_create_histogram(&prefixed_key, *metadata.level())
411    }
412}
413
414/// Deletes an internal counter from the metrics registry.
415///
416/// If the counter exists and metrics snapshots are being consumed, this sends any pending counter
417/// delta before the eviction update so downstream consumers do not lose the final increment.
418pub fn delete_counter(key: Key) -> bool {
419    let Some(state) = RECEIVER_STATE.get() else {
420        return false;
421    };
422
423    let prefixed_key = Key::from_parts(format!("{}.{}", state.metrics_prefix, key.name()), key.labels());
424    let Some(snapshot) = delete_counter_from_state(state, &prefixed_key) else {
425        return false;
426    };
427
428    if state.flush_tx.receiver_count() > 0 {
429        let _ = state.flush_tx.send(Arc::new(snapshot));
430    }
431
432    true
433}
434
435fn delete_counter_from_state(state: &State, prefixed_key: &Key) -> Option<MetricsSnapshot> {
436    let handle = state.registry.remove_counter(prefixed_key)?;
437    let delta = handle.consume();
438    let context = context_from_key(prefixed_key);
439    let current_level = *state.current_level.lock().unwrap();
440
441    let mut snapshot = MetricsSnapshot {
442        upserts: Vec::new(),
443        evictions: vec![context.clone()],
444    };
445    if delta > 0 && handle.level() >= current_level {
446        snapshot
447            .upserts
448            .push(Event::Metric(Metric::counter(context, delta as f64)));
449    }
450
451    Some(snapshot)
452}
453
454fn context_from_key(key: &Key) -> Context {
455    let tags = key
456        .labels()
457        .map(|l| Tag::from(format!("{}:{}", l.key(), l.value())))
458        .collect::<TagSet>();
459
460    Context::from_parts(key.name().to_string(), tags)
461}
462
463/// Internal metrics stream
464///
465/// Used to receive periodic snapshots of the internal metrics registry, which contains all metrics that are currently
466/// active within the process.
467pub struct MetricsStream {
468    inner: ReusableBoxFuture<
469        'static,
470        (
471            Result<SharedMetricsSnapshot, RecvError>,
472            Receiver<SharedMetricsSnapshot>,
473        ),
474    >,
475}
476
477impl MetricsStream {
478    /// Creates a new `MetricsStream` that receives updates from the internal metrics registry.
479    pub fn register() -> Self {
480        let state = RECEIVER_STATE.get().expect("metrics receiver should be set");
481        Self {
482            inner: ReusableBoxFuture::new(make_rx_future(state.flush_tx.subscribe())),
483        }
484    }
485}
486
487impl Stream for MetricsStream {
488    type Item = SharedMetricsSnapshot;
489
490    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
491        loop {
492            // Poll the receiver, and rearm the future once we actually resolve it.
493            let (result, rx) = ready!(self.inner.poll(cx));
494            self.inner.set(make_rx_future(rx));
495
496            match result {
497                Ok(item) => return Poll::Ready(Some(item)),
498                Err(RecvError::Closed) => return Poll::Ready(None),
499                Err(RecvError::Lagged(n)) => {
500                    debug!(
501                        missed_payloads = n,
502                        "Stream lagging behind internal metrics producer. Internal metrics may have been lost."
503                    );
504                    continue;
505                }
506            }
507        }
508    }
509}
510
511async fn make_rx_future(
512    mut rx: Receiver<SharedMetricsSnapshot>,
513) -> (
514    Result<SharedMetricsSnapshot, RecvError>,
515    Receiver<SharedMetricsSnapshot>,
516) {
517    let result = rx.recv().await;
518    (result, rx)
519}
520
521#[derive(Default)]
522struct FlushState {
523    counter_emits: Vec<(Key, f64)>,
524    gauge_emits: Vec<(Key, f64)>,
525    histogram_emits: Vec<(Key, Vec<f64>)>,
526    evicted_keys: Vec<Key>,
527}
528
529impl FlushState {
530    fn clear(&mut self) {
531        self.counter_emits.clear();
532        self.gauge_emits.clear();
533        self.histogram_emits.clear();
534        self.evicted_keys.clear();
535    }
536}
537
538async fn flush_metrics() {
539    let mut context_resolver = MetricsContextResolver::new(INTERNAL_METRICS_INTERNER_SIZE);
540
541    let state = RECEIVER_STATE.get().expect("metrics receiver should be set");
542
543    let mut flush_interval = tokio::time::interval(state.flush_interval);
544    flush_interval.tick().await;
545
546    let mut flush_state = FlushState::default();
547
548    loop {
549        flush_interval.tick().await;
550        flush_once(state, &mut context_resolver, &mut flush_state);
551    }
552}
553
554/// Performs a single flush pass over the registry: consumes each metric's value, evicts metrics that
555/// are no longer referenced and have gone idle, and broadcasts the resulting metric values and
556/// evictions to downstream consumers.
557fn flush_once(state: &State, context_resolver: &mut MetricsContextResolver, flush_state: &mut FlushState) {
558    let has_listeners = state.flush_tx.receiver_count() > 0;
559    let current_level = *state.current_level.lock().unwrap();
560    let idle_threshold = state.idle_evict_intervals;
561    let mut snapshot = MetricsSnapshot::default();
562
563    flush_state.clear();
564    let FlushState {
565        counter_emits,
566        gauge_emits,
567        histogram_emits,
568        evicted_keys,
569    } = flush_state;
570
571    {
572        let mut maps = state.registry.maps.lock().unwrap();
573
574        // `delete_counter` already sent its own eviction, but a flush that collected the counter just before the
575        // deletion can still publish it afterwards. Evicting again here, after that flush, also retires the cached
576        // context. Re-registered counters are live again and keep theirs.
577        let RegistryMaps {
578            counters,
579            gauges,
580            histograms,
581            deleted_counters,
582        } = &mut *maps;
583        for key in deleted_counters.drain() {
584            // The resolver cache is keyed by `Key` alone, so a gauge or histogram sharing the key still needs it.
585            if counters.contains_key(&key) || gauges.contains_key(&key) || histograms.contains_key(&key) {
586                continue;
587            }
588            if let Some(context) = context_resolver.take(&key) {
589                if has_listeners {
590                    snapshot.evictions.push(context);
591                }
592            }
593        }
594
595        // Counters: a counter is never idle so long as it has a non-zero delta during a flush _or_ has
596        // an active reference (strong count > 1).
597        //
598        // The strong-count check precedes `consume()`, with an Acquire fence on the orphaned path:
599        // observing `strong_count == 1` synchronizes-with the dropping thread's release, which
600        // guarantees the following `consume()` observes that thread's final increment.
601        maps.counters.retain(|key, handle| {
602            let idle = handle.bump_idle();
603            let orphaned = Arc::strong_count(handle) == 1;
604            if orphaned {
605                std::sync::atomic::fence(Ordering::Acquire);
606            }
607            let delta = handle.consume();
608
609            if orphaned && delta == 0 && idle >= idle_threshold {
610                evicted_keys.push(key.clone());
611                return false;
612            }
613
614            if has_listeners && handle.level() >= current_level {
615                counter_emits.push((key.clone(), delta as f64));
616            }
617            true
618        });
619
620        // Gauges: a gauge is never idle so long as it was touched ("dirty") prior to a flush _or_ has
621        // an active reference (strong count > 1).
622        maps.gauges.retain(|key, handle| {
623            let idle = handle.bump_idle();
624            let orphaned = Arc::strong_count(handle) == 1;
625            if orphaned {
626                std::sync::atomic::fence(Ordering::Acquire);
627            }
628            let value = handle.load();
629            let written = handle.take_dirty();
630
631            if orphaned && !written && idle >= idle_threshold {
632                evicted_keys.push(key.clone());
633                return false;
634            }
635
636            if has_listeners && handle.level() >= current_level {
637                gauge_emits.push((key.clone(), value));
638            }
639            true
640        });
641
642        // Histograms: a histogram is never idle so long as it has recorded samples prior to a flush _or_
643        // has an active reference (strong count > 1).
644        //
645        // The strong-count check precedes the drain, with an Acquire fence on the orphaned path, so the
646        // drain observes a dropping thread's final `record()`.
647        maps.histograms.retain(|key, handle| {
648            let idle = handle.bump_idle();
649            let orphaned = Arc::strong_count(handle) == 1;
650            if orphaned {
651                std::sync::atomic::fence(Ordering::Acquire);
652            }
653            let mut histogram_samples = Vec::new();
654            handle.drain_into(&mut histogram_samples);
655            let had_samples = !histogram_samples.is_empty();
656
657            if orphaned && !had_samples && idle >= idle_threshold {
658                evicted_keys.push(key.clone());
659                return false;
660            }
661
662            if has_listeners && had_samples && handle.level() >= current_level {
663                histogram_emits.push((key.clone(), histogram_samples));
664            }
665            true
666        });
667    }
668
669    // For every evicted key we collected, take its cached context (if it exists) and add it to the
670    // snapshot's evictions list.
671    for key in evicted_keys {
672        if let Some(context) = context_resolver.take(key) {
673            if has_listeners {
674                snapshot.evictions.push(context);
675            }
676        }
677    }
678
679    if !has_listeners {
680        return;
681    }
682
683    for (key, value) in counter_emits.drain(..) {
684        let context = context_resolver.resolve_from_key(key);
685        snapshot.upserts.push(Event::Metric(Metric::counter(context, value)));
686    }
687    for (key, value) in gauge_emits.drain(..) {
688        let context = context_resolver.resolve_from_key(key);
689        snapshot.upserts.push(Event::Metric(Metric::gauge(context, value)));
690    }
691    for (key, samples) in histogram_emits.drain(..) {
692        let context = context_resolver.resolve_from_key(key);
693        snapshot
694            .upserts
695            .push(Event::Metric(Metric::histogram(context, &samples[..])));
696    }
697
698    if !snapshot.upserts.is_empty() || !snapshot.evictions.is_empty() {
699        let _ = state.flush_tx.send(Arc::new(snapshot));
700    }
701}
702
703struct MetricsContextResolver {
704    context_resolver: ContextResolver,
705    key_context_cache: FastHashMap<Key, Context>,
706}
707
708impl MetricsContextResolver {
709    fn new(resolver_interner_size_bytes: NonZeroUsize) -> Self {
710        Self {
711            // Set up our context resolver without caching, since we will be caching the contexts ourselves.
712            context_resolver: ContextResolverBuilder::from_name("core/internal_metrics")
713                .expect("resolver name is not empty")
714                .with_interner_capacity_bytes(resolver_interner_size_bytes)
715                .without_caching()
716                .build(),
717            key_context_cache: FastHashMap::default(),
718        }
719    }
720
721    fn resolve_from_key(&mut self, key: Key) -> Context {
722        static SELF_ORIGIN_INFO: LazyLock<RawOrigin<'static>> = LazyLock::new(|| {
723            let mut origin_info = RawOrigin::default();
724            origin_info.set_process_id(std::process::id());
725            origin_info
726        });
727
728        // Check the cache first.
729        if let Some(context) = self.key_context_cache.get(&key) {
730            return context.clone();
731        }
732
733        // We don't have the context cached, so we need to resolve it.
734        let tags = key
735            .labels()
736            .map(|l| Tag::from(format!("{}:{}", l.key(), l.value())))
737            .collect::<TagSet>();
738
739        let context = self
740            .context_resolver
741            .resolve(key.name(), &tags, Some(SELF_ORIGIN_INFO.clone()))
742            .expect("resolver should always allow falling back");
743
744        self.key_context_cache.insert(key, context.clone());
745        context
746    }
747
748    /// Removes a key's cached context, returning it if present.
749    ///
750    /// Returns `Some` only if the key had been resolved before (that is, the metric was emitted at
751    /// least once), which is what tells the flush loop whether a downstream eviction needs to be sent.
752    fn take(&mut self, key: &Key) -> Option<Context> {
753        self.key_context_cache.remove(key)
754    }
755}
756
757/// Initializes the metrics subsystem with the given metrics prefix and default filter level.
758///
759/// `default_level` sets the initial filter level for emitted metrics, and is also what the filter is restored to when
760/// [`FilterHandle::reset_filter`] is invoked. Metrics whose level is more verbose than this default are filtered out
761/// until a runtime override is applied via [`FilterHandle::override_filter`].
762///
763/// Returns a [`FilterHandle`] for adjusting the runtime metrics filter, plus a [`MetricsFlusherWorker`]
764/// that must be added to a [`Supervisor`][crate::runtime::Supervisor] in order to drive the periodic
765/// flush loop. Internal metrics aren't propagated to subscribers until the worker is running.
766///
767/// # Errors
768///
769/// If a global recorder was already installed, an error will be returned.
770pub async fn initialize_metrics(
771    metrics_prefix: String, default_level: Level,
772) -> Result<(FilterHandle, MetricsFlusherWorker), GenericError> {
773    let recorder = MetricsRecorder::new(metrics_prefix, default_level);
774    let filter_handle = recorder.filter_handle();
775    recorder.install()?;
776
777    Ok((filter_handle, MetricsFlusherWorker))
778}
779
780/// A worker that periodically flushes the internal metrics registry to broadcast subscribers.
781///
782/// Wraps the internal flush loop and runs it under a [`Supervisor`][crate::runtime::Supervisor]. Must
783/// only be added to a supervisor after [`initialize_metrics`] has been called -- the flush loop
784/// reads from the global recorder state set by that call.
785pub struct MetricsFlusherWorker;
786
787#[async_trait]
788impl Supervisable for MetricsFlusherWorker {
789    fn name(&self) -> &str {
790        "flusher"
791    }
792
793    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
794        Ok(Box::pin(async move {
795            select! {
796                _ = process_shutdown => {},
797                _ = flush_metrics() => {},
798            }
799
800            Ok(())
801        }))
802    }
803}
804
805/// Feeds `upserts` through a fresh [`AggregatedMetricsProcessor`] and returns the resulting
806/// [`AggregatedMetricsState`].
807#[cfg(test)]
808pub(crate) fn aggregate_upserts(upserts: Vec<Event>) -> AggregatedMetricsState {
809    let processor = AggregatedMetricsProcessor;
810    let state = processor.build_initial_state();
811    processor.process(
812        MetricsSnapshot {
813            upserts,
814            evictions: Vec::new(),
815        },
816        &state,
817    );
818    state
819}
820
821#[cfg(test)]
822mod tests {
823    use metrics::Label;
824
825    use super::*;
826
827    const HIGH_CARDINALITY_COUNTER_NAME: &str = "high_cardinality_counter";
828    const HIGH_CARDINALITY_COUNTERS: usize = 64;
829
830    // We keep a live receiver in each test so `flush_once` observes a listener and emits updates.
831    fn make_state(idle_evict_intervals: u32) -> (Arc<State>, Receiver<SharedMetricsSnapshot>) {
832        let (flush_tx, rx) = broadcast::channel(64);
833        let state = Arc::new(State {
834            registry: MetricsRegistry::default(),
835            flush_tx,
836            metrics_prefix: "test".to_string(),
837            default_level: Level::TRACE,
838            current_level: Mutex::new(Level::TRACE),
839            idle_evict_intervals,
840            flush_interval: FLUSH_INTERVAL,
841        });
842        (state, rx)
843    }
844
845    fn resolver() -> MetricsContextResolver {
846        MetricsContextResolver::new(INTERNAL_METRICS_INTERNER_SIZE)
847    }
848
849    // Mimics `MetricsRecorder::register_counter` against a raw key (no prefixing needed in tests).
850    fn register_counter(state: &State, name: &'static str) -> Counter {
851        state
852            .registry
853            .get_or_create_counter(&Key::from_name(name), Level::TRACE)
854    }
855
856    fn register_counter_with_origin(state: &State, name: &'static str, origin: &str) -> Counter {
857        let key = Key::from_parts(name, vec![Label::new("origin", origin.to_string())]);
858        state.registry.get_or_create_counter(&key, Level::TRACE)
859    }
860
861    fn register_gauge(state: &State, name: &'static str) -> Gauge {
862        state.registry.get_or_create_gauge(&Key::from_name(name), Level::TRACE)
863    }
864
865    fn register_histogram(state: &State, name: &'static str) -> Histogram {
866        state
867            .registry
868            .get_or_create_histogram(&Key::from_name(name), Level::TRACE)
869    }
870
871    fn counter_present(state: &State, name: &'static str) -> bool {
872        state
873            .registry
874            .maps
875            .lock()
876            .unwrap()
877            .counters
878            .contains_key(&Key::from_name(name))
879    }
880
881    fn counter_count(state: &State) -> usize {
882        state.registry.maps.lock().unwrap().counters.len()
883    }
884
885    fn gauge_present(state: &State, name: &'static str) -> bool {
886        state
887            .registry
888            .maps
889            .lock()
890            .unwrap()
891            .gauges
892            .contains_key(&Key::from_name(name))
893    }
894
895    fn histogram_present(state: &State, name: &'static str) -> bool {
896        state
897            .registry
898            .maps
899            .lock()
900            .unwrap()
901            .histograms
902            .contains_key(&Key::from_name(name))
903    }
904
905    fn drain(rx: &mut Receiver<SharedMetricsSnapshot>) -> Vec<MetricsSnapshot> {
906        let mut out = Vec::new();
907        while let Ok(batch) = rx.try_recv() {
908            out.push((*batch).clone());
909        }
910        out
911    }
912
913    fn evicted_names(snapshots: &[MetricsSnapshot]) -> Vec<String> {
914        snapshots
915            .iter()
916            .flat_map(|snapshot| snapshot.evictions.iter().map(|ctx| ctx.name().to_string()))
917            .collect()
918    }
919
920    fn metric_count(state: &AggregatedMetricsState, name: &str) -> usize {
921        let mut count = 0;
922        state.visit_metrics(|context, _| {
923            if context.name() == name {
924                count += 1;
925            }
926        });
927        count
928    }
929
930    #[test]
931    fn delete_counter_from_state_emits_pending_delta_before_eviction() {
932        let (state, _rx) = make_state(IDLE_EVICT_INTERVALS);
933        let key = Key::from_parts(
934            "deleted_counter",
935            vec![Label::new("origin", "container_id://deleted".to_string())],
936        );
937
938        let counter = state.registry.get_or_create_counter(&key, Level::TRACE);
939        counter.increment(7);
940        drop(counter);
941
942        let snapshot = delete_counter_from_state(&state, &key).expect("counter should be deleted");
943
944        assert!(!state.registry.maps.lock().unwrap().counters.contains_key(&key));
945        assert_eq!(snapshot.evictions.len(), 1);
946        assert_eq!(snapshot.evictions[0].name(), "deleted_counter");
947        assert!(snapshot.evictions[0].tags().has_tag("origin:container_id://deleted"));
948
949        assert_eq!(snapshot.upserts.len(), 1);
950        let Event::Metric(metric) = &snapshot.upserts[0] else {
951            panic!("delete should emit the pending counter delta");
952        };
953        assert_eq!(metric.context(), &snapshot.evictions[0]);
954        let MetricValues::Counter(points) = metric.values() else {
955            panic!("delete should emit a counter metric");
956        };
957        assert_eq!(points.into_iter().map(|(_, value)| value).sum::<f64>(), 7.0);
958    }
959
960    #[tokio::test]
961    async fn deleted_counters_retire_cached_contexts_on_next_flush() {
962        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
963        let mut resolver = resolver();
964        let mut flush_state = FlushState::default();
965        for i in 0..400 {
966            let key = Key::from_parts("deleted_counter", vec![Label::new("origin", i.to_string())]);
967            state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
968            flush_once(&state, &mut resolver, &mut flush_state);
969            assert_eq!(resolver.key_context_cache.len(), 1);
970            delete_counter_from_state(&state, &key).expect("counter should be deleted");
971        }
972        flush_once(&state, &mut resolver, &mut flush_state);
973        drain(&mut rx);
974        assert!(resolver.key_context_cache.is_empty());
975        assert!(state.registry.maps.lock().unwrap().deleted_counters.is_empty());
976    }
977
978    #[tokio::test]
979    async fn repeated_deletions_of_one_counter_between_flushes_are_queued_once() {
980        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
981        let mut resolver = resolver();
982        let mut flush_state = FlushState::default();
983        let key = Key::from_parts("churned_counter", vec![Label::new("origin", "container_id://churned")]);
984
985        // Publish the counter once so the resolver caches its context.
986        state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
987        flush_once(&state, &mut resolver, &mut flush_state);
988        assert_eq!(resolver.key_context_cache.len(), 1);
989
990        // Re-register and delete the same counter many times within a single flush interval.
991        for _ in 0..1_000 {
992            state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
993            delete_counter_from_state(&state, &key).expect("counter should be deleted");
994        }
995        assert_eq!(state.registry.maps.lock().unwrap().deleted_counters.len(), 1);
996
997        // The single queued entry still retires the cached context, and the queue is empty afterwards.
998        flush_once(&state, &mut resolver, &mut flush_state);
999        drain(&mut rx);
1000        assert!(resolver.key_context_cache.is_empty());
1001        assert!(state.registry.maps.lock().unwrap().deleted_counters.is_empty());
1002    }
1003
1004    #[tokio::test]
1005    async fn counter_republished_by_concurrent_flush_is_evicted_on_next_flush() {
1006        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
1007        let mut resolver = resolver();
1008        let mut flush_state = FlushState::default();
1009        let processor = AggregatedMetricsProcessor;
1010        let aggregated = processor.build_initial_state();
1011        let key = Key::from_name("raced_counter");
1012        state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
1013
1014        // The deletion's eviction overtakes the upsert of a flush that collected the counter first.
1015        flush_once(&state, &mut resolver, &mut flush_state);
1016        let in_flight = drain(&mut rx);
1017        processor.process(
1018            delete_counter_from_state(&state, &key).expect("counter should be deleted"),
1019            &aggregated,
1020        );
1021        for snapshot in in_flight {
1022            processor.process(snapshot, &aggregated);
1023        }
1024        assert_eq!(metric_count(&aggregated, "raced_counter"), 1);
1025
1026        flush_once(&state, &mut resolver, &mut flush_state);
1027        for snapshot in drain(&mut rx) {
1028            processor.process(snapshot, &aggregated);
1029        }
1030        assert_eq!(metric_count(&aggregated, "raced_counter"), 0);
1031    }
1032
1033    #[tokio::test]
1034    async fn counter_reregistered_after_delete_keeps_cached_context() {
1035        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
1036        let mut resolver = resolver();
1037        let mut flush_state = FlushState::default();
1038        let key = Key::from_name("reused_counter");
1039        state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
1040        flush_once(&state, &mut resolver, &mut flush_state);
1041        drain(&mut rx);
1042        delete_counter_from_state(&state, &key).expect("counter should be deleted");
1043        let counter = state.registry.get_or_create_counter(&key, Level::INFO);
1044        counter.increment(2);
1045        flush_once(&state, &mut resolver, &mut flush_state);
1046        assert!(drain(&mut rx).iter().all(|snapshot| snapshot.evictions.is_empty()));
1047        assert_eq!(resolver.key_context_cache.len(), 1);
1048    }
1049
1050    #[tokio::test]
1051    async fn deleted_counter_keeps_context_of_gauge_with_same_key() {
1052        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
1053        let mut resolver = resolver();
1054        let mut flush_state = FlushState::default();
1055        let key = Key::from_name("shared_key");
1056        state.registry.get_or_create_counter(&key, Level::INFO).increment(1);
1057        let gauge = state.registry.get_or_create_gauge(&key, Level::INFO);
1058        gauge.set(1.0);
1059        flush_once(&state, &mut resolver, &mut flush_state);
1060        drain(&mut rx);
1061        delete_counter_from_state(&state, &key).expect("counter should be deleted");
1062        flush_once(&state, &mut resolver, &mut flush_state);
1063        assert!(drain(&mut rx).iter().all(|snapshot| snapshot.evictions.is_empty()));
1064        assert_eq!(resolver.key_context_cache.len(), 1);
1065    }
1066
1067    #[tokio::test]
1068    async fn evicts_high_cardinality_counters_from_registry_and_aggregated_state() {
1069        let (state, mut rx) = make_state(IDLE_EVICT_INTERVALS);
1070        let mut resolver = resolver();
1071        let mut flush_state = FlushState::default();
1072        let agg_processor = AggregatedMetricsProcessor;
1073        let agg_state = agg_processor.build_initial_state();
1074        let mut expected_eviction_tags = FastHashSet::default();
1075        let mut observed_eviction_tags = FastHashSet::default();
1076
1077        for index in 0..HIGH_CARDINALITY_COUNTERS {
1078            let origin = format!("entity://source-{index}");
1079            expected_eviction_tags.insert(format!("origin:{origin}"));
1080
1081            let counter = register_counter_with_origin(&state, HIGH_CARDINALITY_COUNTER_NAME, &origin);
1082            counter.increment(1);
1083            drop(counter);
1084        }
1085
1086        assert_eq!(counter_count(&state), HIGH_CARDINALITY_COUNTERS);
1087
1088        for _ in 0..IDLE_EVICT_INTERVALS {
1089            flush_once(&state, &mut resolver, &mut flush_state);
1090
1091            for update in drain(&mut rx) {
1092                for context in &update.evictions {
1093                    if context.name() != HIGH_CARDINALITY_COUNTER_NAME {
1094                        continue;
1095                    }
1096
1097                    for tag in &expected_eviction_tags {
1098                        if context.tags().has_tag(tag) {
1099                            observed_eviction_tags.insert(tag.clone());
1100                        }
1101                    }
1102                }
1103
1104                agg_processor.process(update, &agg_state);
1105            }
1106        }
1107
1108        assert_eq!(counter_count(&state), 0);
1109        assert_eq!(metric_count(&agg_state, HIGH_CARDINALITY_COUNTER_NAME), 0);
1110        assert_eq!(observed_eviction_tags, expected_eviction_tags);
1111    }
1112
1113    #[tokio::test]
1114    async fn evicts_counter_within_bounded_time_after_handle_dropped() {
1115        let (state, mut rx) = make_state(3);
1116        let mut resolver = resolver();
1117        let mut flush_state = FlushState::default();
1118
1119        let counter = register_counter(&state, "dropped_counter");
1120        counter.increment(5);
1121
1122        // While the handle is held, the metric is retained and its delta is emitted.
1123        flush_once(&state, &mut resolver, &mut flush_state);
1124        assert!(counter_present(&state, "dropped_counter"));
1125
1126        // Drop the last handle; the metric must be reclaimed within `idle_evict_intervals` flushes.
1127        drop(counter);
1128        let _ = drain(&mut rx);
1129        for _ in 0..3 {
1130            flush_once(&state, &mut resolver, &mut flush_state);
1131        }
1132        assert!(!counter_present(&state, "dropped_counter"));
1133
1134        // The eviction is propagated downstream so the aggregated view drops it too.
1135        let updates = drain(&mut rx);
1136        assert!(evicted_names(&updates).iter().any(|n| n == "dropped_counter"));
1137    }
1138
1139    #[tokio::test]
1140    async fn does_not_evict_while_handle_is_held() {
1141        let (state, _rx) = make_state(3);
1142        let mut resolver = resolver();
1143        let mut flush_state = FlushState::default();
1144
1145        let counter = register_counter(&state, "held_counter");
1146
1147        // Idle well past the eviction threshold without dropping the handle.
1148        for _ in 0..8 {
1149            flush_once(&state, &mut resolver, &mut flush_state);
1150        }
1151
1152        assert!(
1153            counter_present(&state, "held_counter"),
1154            "a held metric must never be evicted"
1155        );
1156        drop(counter);
1157    }
1158
1159    #[tokio::test]
1160    async fn reregistration_keeps_uncached_metric_alive() {
1161        // Models the uncached-macro pattern: a fresh handle is registered (and dropped) every interval.
1162        // Re-registration resets the idle counter, so the metric is never churned out while in use.
1163        let (state, _rx) = make_state(3);
1164        let mut resolver = resolver();
1165        let mut flush_state = FlushState::default();
1166
1167        for _ in 0..8 {
1168            let counter = register_counter(&state, "uncached_counter");
1169            counter.increment(1);
1170            drop(counter);
1171            flush_once(&state, &mut resolver, &mut flush_state);
1172        }
1173        assert!(counter_present(&state, "uncached_counter"));
1174
1175        // Once it stops being re-registered, it is reclaimed within the idle threshold.
1176        for _ in 0..3 {
1177            flush_once(&state, &mut resolver, &mut flush_state);
1178        }
1179        assert!(!counter_present(&state, "uncached_counter"));
1180    }
1181
1182    #[tokio::test]
1183    async fn gauge_reset_to_same_value_is_not_evicted() {
1184        // A gauge re-set to the same value every interval (e.g. a backoff gauge that sits at 0.0) must
1185        // stay alive. Activity is driven by re-registration, not value comparison.
1186        let (state, _rx) = make_state(3);
1187        let mut resolver = resolver();
1188        let mut flush_state = FlushState::default();
1189
1190        for _ in 0..8 {
1191            let gauge = register_gauge(&state, "steady_gauge");
1192            gauge.set(0.0);
1193            drop(gauge);
1194            flush_once(&state, &mut resolver, &mut flush_state);
1195        }
1196        assert!(gauge_present(&state, "steady_gauge"));
1197    }
1198
1199    #[tokio::test]
1200    async fn final_counter_delta_reaches_downstream_before_eviction() {
1201        let (state, mut rx) = make_state(1);
1202        let mut resolver = resolver();
1203        let mut flush_state = FlushState::default();
1204
1205        let counter = register_counter(&state, "final_counter");
1206
1207        // Arm eviction by letting the idle counter reach the threshold while the handle is held.
1208        flush_once(&state, &mut resolver, &mut flush_state);
1209
1210        // Increment and drop the handle in the same inter-flush window. The next flush sees a non-zero
1211        // delta, so it must emit it and defer eviction by one interval (so the delta isn't lost).
1212        counter.increment(7);
1213        drop(counter);
1214        flush_once(&state, &mut resolver, &mut flush_state);
1215        assert!(
1216            counter_present(&state, "final_counter"),
1217            "must not evict in an interval that produced a delta"
1218        );
1219
1220        // The emitted delta must reach the downstream aggregated state.
1221        let agg_processor = AggregatedMetricsProcessor;
1222        let agg_state = agg_processor.build_initial_state();
1223        for update in drain(&mut rx) {
1224            agg_processor.process(update, &agg_state);
1225        }
1226        assert_eq!(agg_state.get_aggregated_with_tags("final_counter", &[]), 7.0);
1227
1228        // The following interval (no delta) finally evicts it.
1229        flush_once(&state, &mut resolver, &mut flush_state);
1230        assert!(!counter_present(&state, "final_counter"));
1231    }
1232
1233    #[tokio::test]
1234    async fn gauge_final_value_reaches_downstream_before_eviction() {
1235        let (state, mut rx) = make_state(1);
1236        let mut resolver = resolver();
1237        let mut flush_state = FlushState::default();
1238
1239        let gauge = register_gauge(&state, "final_gauge");
1240        gauge.set(1.0);
1241
1242        // Arm eviction by letting the idle counter reach the threshold while the handle is held.
1243        flush_once(&state, &mut resolver, &mut flush_state);
1244
1245        // Update to a NEW value and drop the handle in the same inter-flush window. Even though the
1246        // gauge is now orphaned and idle, the write must not be lost: the next flush sees the dirty flag,
1247        // emits the value, and defers eviction by one interval.
1248        gauge.set(42.0);
1249        drop(gauge);
1250        flush_once(&state, &mut resolver, &mut flush_state);
1251        assert!(
1252            gauge_present(&state, "final_gauge"),
1253            "must not evict in an interval that wrote a new value"
1254        );
1255
1256        // The final value must reach the downstream aggregated state.
1257        let agg_processor = AggregatedMetricsProcessor;
1258        let agg_state = agg_processor.build_initial_state();
1259        for update in drain(&mut rx) {
1260            agg_processor.process(update, &agg_state);
1261        }
1262        assert_eq!(agg_state.find_single_with_tags("final_gauge", &[]), Some(42.0));
1263
1264        // The following interval (no write) finally evicts it.
1265        flush_once(&state, &mut resolver, &mut flush_state);
1266        assert!(!gauge_present(&state, "final_gauge"));
1267    }
1268
1269    #[tokio::test]
1270    async fn histogram_final_samples_reach_downstream_before_eviction() {
1271        // Regression test for the histogram eviction race fixed in commit 3752c5ad1b
1272        // ("rework internal metrics registry to support evicting expired/idle metrics", #1947).
1273        //
1274        // The histogram branch of `flush_once` must read the Arc strong count first (Acquire-fencing
1275        // on the orphaned path) and only THEN drain the sample bucket, exactly like the counter and
1276        // gauge paths. If a final `record()` and the handle drop both land in the inter-flush window
1277        // where eviction is armed, the flush that observes the orphaned handle must still see and emit
1278        // that sample -- and defer eviction by one interval -- rather than dropping the samples along
1279        // with the evicted registry entry. That commit shipped the counter regression coverage
1280        // (`final_counter_delta_reaches_downstream_before_eviction` plus the loom model) but never the
1281        // symmetric histogram coverage; this is it.
1282        let (state, mut rx) = make_state(1);
1283        let mut resolver = resolver();
1284        let mut flush_state = FlushState::default();
1285
1286        let histogram = register_histogram(&state, "final_histogram");
1287
1288        // Arm eviction by letting the idle counter reach the threshold while the handle is held.
1289        flush_once(&state, &mut resolver, &mut flush_state);
1290
1291        // Record a sample and drop the handle in the same inter-flush window. The next flush observes
1292        // the recorded sample, so it must emit it and defer eviction by one interval.
1293        histogram.record(1.5);
1294        drop(histogram);
1295        flush_once(&state, &mut resolver, &mut flush_state);
1296        assert!(
1297            histogram_present(&state, "final_histogram"),
1298            "must not evict in an interval that recorded a sample"
1299        );
1300
1301        // The recorded sample must reach the downstream aggregated state.
1302        let agg_processor = AggregatedMetricsProcessor;
1303        let agg_state = agg_processor.build_initial_state();
1304        for update in drain(&mut rx) {
1305            agg_processor.process(update, &agg_state);
1306        }
1307
1308        let mut downstream_sample_count = None;
1309        agg_state.visit_metrics(|context, value| {
1310            if context.name() == "final_histogram" {
1311                if let AggregatedMetricValue::Histogram(histogram) = value {
1312                    downstream_sample_count = Some(histogram.count());
1313                }
1314            }
1315        });
1316        assert_eq!(
1317            downstream_sample_count,
1318            Some(1),
1319            "the final recorded sample must reach downstream before eviction"
1320        );
1321
1322        // The following interval (no samples) finally evicts it.
1323        flush_once(&state, &mut resolver, &mut flush_state);
1324        assert!(!histogram_present(&state, "final_histogram"));
1325    }
1326}
1327
1328// Loom model of the counter eviction path in `flush_once`.
1329//
1330// In `flush_once`, the registry `maps` lock is held during the drain, but the increment/drop path
1331// does not take that lock: `Counter::increment` writes straight through the `Arc<Handle>`, and
1332// dropping a caller's `Counter` only decrements the Arc strong count. A component holding a cached
1333// handle can therefore land a final increment and drop the handle while a flush is mid-pass over it.
1334//
1335// The model transcribes the counter branch with loom primitives instead of exercising the real types,
1336// which loom cannot instrument here:
1337//
1338// - The strong count is an explicit `AtomicUsize`. loom's `Arc::strong_count` does not reflect a
1339//   concurrent decrement from another thread (it models Arc's drop synchronization, not the observable
1340//   count value), so a flush reading it never sees the orphaned (`== 1`) state mid-race. The explicit
1341//   atomic matches `std`'s `Arc`: clone increments (Relaxed), drop decrements with `Release`,
1342//   observation is a `Relaxed` load -- the same shape as how `flush_once` reads `Arc::strong_count`.
1343// - The real `Handle` is wrapped by the `metrics` crate's `Counter`/`CounterFn`, which construct
1344//   `std::sync::Arc` internally. loom only instruments atomics and `Arc`s swapped to `loom::sync::*`
1345//   behind the `loom` cfg, not those inside a third-party crate.
1346//
1347// `flush_decision_consume_first` and `flush_decision_strong_count_first` mirror the two possible
1348// orderings of `flush_once`'s counter branch and must stay in lockstep with it.
1349#[cfg(all(test, feature = "loom"))]
1350mod loom_tests {
1351    use loom::sync::atomic::{fence, AtomicU64, AtomicUsize, Ordering};
1352    use loom::sync::Arc;
1353
1354    /// The shared state behind a counter handle: the accumulator the flush loop drains, and the Arc
1355    /// strong count it consults to decide whether the handle is orphaned.
1356    struct Shared {
1357        value: AtomicU64,
1358        strong: AtomicUsize,
1359    }
1360
1361    /// A component holding a cached handle lands one final increment, then drops the handle.
1362    fn caller_increment_then_drop(shared: &Arc<Shared>, amount: u64) {
1363        shared.value.fetch_add(amount, Ordering::Relaxed);
1364        shared.strong.fetch_sub(1, Ordering::Release); // Arc clone drop
1365    }
1366
1367    /// Consumes the value, then checks the strong count (value read before the liveness check).
1368    fn flush_decision_consume_first(shared: &Arc<Shared>) -> (u64, bool) {
1369        let delta = shared.value.swap(0, Ordering::Relaxed);
1370        let orphaned = shared.strong.load(Ordering::Relaxed) == 1;
1371        (delta, orphaned && delta == 0)
1372    }
1373
1374    /// Checks the strong count first; if orphaned, Acquire-fences to synchronize with the dropping
1375    /// thread's `Release`, then consumes the value.
1376    fn flush_decision_strong_count_first(shared: &Arc<Shared>) -> (u64, bool) {
1377        let orphaned = shared.strong.load(Ordering::Relaxed) == 1;
1378        if orphaned {
1379            fence(Ordering::Acquire);
1380        }
1381        let delta = shared.value.swap(0, Ordering::Relaxed);
1382        (delta, orphaned && delta == 0)
1383    }
1384
1385    fn model(decision: fn(&Arc<Shared>) -> (u64, bool)) {
1386        loom::model(move || {
1387            const FINAL: u64 = 7;
1388
1389            // strong count starts at 2: one ref in the registry map, one held by the caller.
1390            let shared = Arc::new(Shared {
1391                value: AtomicU64::new(0),
1392                strong: AtomicUsize::new(2),
1393            });
1394            let caller_shared = Arc::clone(&shared);
1395
1396            let caller = loom::thread::spawn(move || {
1397                caller_increment_then_drop(&caller_shared, FINAL);
1398            });
1399
1400            // The flush task evaluates this counter while the component races.
1401            let (delta, evicted) = decision(&shared);
1402            caller.join().unwrap();
1403
1404            // Invariant: a counter may only be evicted once everything it accumulated has been
1405            // emitted. If the flush evicts it, the delta it emitted downstream must already include
1406            // the final increment -- otherwise those counts are silently discarded with the handle.
1407            if evicted {
1408                assert_eq!(
1409                    delta,
1410                    FINAL,
1411                    "counter evicted while {} counts were never emitted -> permanently lost",
1412                    FINAL - delta
1413                );
1414            }
1415        });
1416    }
1417
1418    // Consuming the value before checking the strong count is lossy: loom finds an interleaving where
1419    // the handle is evicted while a final increment goes unemitted. `#[should_panic]` asserts loom
1420    // reaches that interleaving.
1421    #[test]
1422    #[should_panic(expected = "permanently lost")]
1423    fn consume_first_ordering_loses_a_final_increment() {
1424        model(flush_decision_consume_first);
1425    }
1426
1427    // Checking the strong count first (Acquire-fencing when orphaned) before consuming preserves every
1428    // increment across all interleavings loom explores.
1429    #[test]
1430    fn strong_count_first_ordering_preserves_a_final_increment() {
1431        model(flush_decision_strong_count_first);
1432    }
1433
1434    // The histogram branch of `flush_once` has the same race shape as the counter branch, and got the
1435    // same fix in commit 3752c5ad1b (#1947): `Histogram::record` pushes straight through the
1436    // `Arc<Handle>`'s sample bucket, and dropping a caller's `Histogram` only decrements the Arc strong
1437    // count, so a component can land a final sample and drop its handle while a flush is mid-pass over
1438    // that histogram. Reading the strong count first (Acquire-fencing when orphaned) before draining
1439    // guarantees the drain observes the dropping thread's final `record()`.
1440    //
1441    // As with the counter model, loom cannot instrument the real storage: histogram samples live in
1442    // `metrics_util`'s `AtomicBucket`, which loom does not rewrite behind the `loom` cfg. We transcribe
1443    // "number of un-drained samples" into the same loom `AtomicU64` accumulator (record => fetch_add(1),
1444    // drain => swap(0)); that is precisely the ordering that decides whether the drain sees the final
1445    // sample, so the two decision functions above -- `flush_decision_consume_first` (drain-first) and
1446    // `flush_decision_strong_count_first` -- model the histogram drain unchanged, just with a
1447    // single-sample final write.
1448    fn histogram_model(decision: fn(&Arc<Shared>) -> (u64, bool)) {
1449        loom::model(move || {
1450            const FINAL_SAMPLES: u64 = 1;
1451
1452            // strong count starts at 2: one ref in the registry map, one held by the caller.
1453            let shared = Arc::new(Shared {
1454                value: AtomicU64::new(0),
1455                strong: AtomicUsize::new(2),
1456            });
1457            let caller_shared = Arc::clone(&shared);
1458
1459            // A component holding a cached histogram handle records one final sample, then drops it.
1460            let caller = loom::thread::spawn(move || {
1461                caller_shared.value.fetch_add(FINAL_SAMPLES, Ordering::Relaxed); // Histogram::record
1462                caller_shared.strong.fetch_sub(1, Ordering::Release); // Arc clone drop
1463            });
1464
1465            // The flush task evaluates this histogram while the component races.
1466            let (drained, evicted) = decision(&shared);
1467            caller.join().unwrap();
1468
1469            // Invariant: a histogram may only be evicted once every recorded sample has been drained
1470            // (and thus emitted). If the flush evicts it, the drain it performed must have observed the
1471            // final sample -- otherwise that sample is discarded with the evicted registry entry.
1472            if evicted {
1473                assert_eq!(
1474                    drained,
1475                    FINAL_SAMPLES,
1476                    "histogram evicted while {} recorded sample(s) were never drained -> permanently lost",
1477                    FINAL_SAMPLES - drained
1478                );
1479            }
1480        });
1481    }
1482
1483    // Draining the sample bucket before checking the strong count is lossy: loom finds an interleaving
1484    // where the histogram is evicted while a final recorded sample goes undrained. `#[should_panic]`
1485    // asserts loom reaches that interleaving.
1486    #[test]
1487    #[should_panic(expected = "permanently lost")]
1488    fn histogram_drain_first_ordering_loses_a_final_sample() {
1489        histogram_model(flush_decision_consume_first);
1490    }
1491
1492    // Checking the strong count first (Acquire-fencing when orphaned) before draining preserves the
1493    // final recorded sample across all interleavings loom explores.
1494    #[test]
1495    fn histogram_strong_count_first_ordering_preserves_a_final_sample() {
1496        histogram_model(flush_decision_strong_count_first);
1497    }
1498}