Skip to main content

dynamo_runtime/
metrics.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Metrics registry trait and implementation for Prometheus metrics
5//!
6//! This module provides a trait-based interface for creating and managing Prometheus metrics
7//! with automatic label injection and hierarchical naming support.
8
9pub mod frontend_perf;
10pub mod otlp_export;
11pub mod prom_typed;
12pub mod prometheus_names;
13pub mod quic_response;
14pub mod request_plane;
15pub mod tokio_perf;
16pub mod transport_metrics;
17pub mod work_handler_perf;
18pub mod work_handler_pool;
19
20use parking_lot::Mutex;
21use std::collections::HashSet;
22use std::sync::Arc;
23
24use crate::component::ComponentBuilder;
25use anyhow;
26use anyhow::Context as _;
27use once_cell::sync::Lazy;
28use regex::Regex;
29use std::any::Any;
30use std::collections::HashMap;
31
32// Import commonly used items to avoid verbose prefixes
33use prometheus_names::{
34    build_metric_name, labels, name_prefix, sanitize_prometheus_label, sanitize_prometheus_name,
35    work_handler,
36};
37
38// Pipeline imports for endpoint creation
39use crate::pipeline::{
40    AsyncEngine, AsyncEngineContextProvider, Error, ManyOut, ResponseStream, SingleIn, async_trait,
41    network::Ingress,
42};
43use crate::protocols::annotated::Annotated;
44use crate::stream;
45use crate::stream::StreamExt;
46
47// Prometheus imports
48use prometheus::Encoder;
49
50/// Validate that a label slice has no duplicate keys.
51/// Returns Ok(()) when all keys are unique; otherwise returns an error naming the duplicate key.
52fn validate_no_duplicate_label_keys(labels: &[(&str, &str)]) -> anyhow::Result<()> {
53    let mut seen_keys = std::collections::HashSet::new();
54    for (key, _) in labels {
55        if !seen_keys.insert(*key) {
56            return Err(anyhow::anyhow!(
57                "Duplicate label key '{}' found in labels",
58                key
59            ));
60        }
61    }
62    Ok(())
63}
64
65/// ==============================
66/// Prometheus section
67/// ==============================
68/// Trait that defines common behavior for Prometheus metric types
69pub trait PrometheusMetric: prometheus::core::Collector + Clone + Send + Sync + 'static {
70    /// Create a new metric with the given options
71    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error>
72    where
73        Self: Sized;
74
75    /// Create a new metric with histogram options and custom buckets
76    /// This is a default implementation that will panic for non-histogram metrics
77    fn with_histogram_opts_and_buckets(
78        _opts: prometheus::HistogramOpts,
79        _buckets: Option<Vec<f64>>,
80    ) -> Result<Self, prometheus::Error>
81    where
82        Self: Sized,
83    {
84        panic!("with_histogram_opts_and_buckets is not implemented for this metric type");
85    }
86
87    /// Create a histogram vector with custom buckets and label names.
88    fn with_histogram_opts_buckets_and_label_names(
89        _opts: prometheus::HistogramOpts,
90        _buckets: Option<Vec<f64>>,
91        _label_names: &[&str],
92    ) -> Result<Self, prometheus::Error>
93    where
94        Self: Sized,
95    {
96        panic!(
97            "with_histogram_opts_buckets_and_label_names is not implemented for this metric type"
98        );
99    }
100
101    /// Create a new metric with counter options and label names (for CounterVec)
102    /// This is a default implementation that will panic for non-countervec metrics
103    fn with_opts_and_label_names(
104        _opts: prometheus::Opts,
105        _label_names: &[&str],
106    ) -> Result<Self, prometheus::Error>
107    where
108        Self: Sized,
109    {
110        panic!("with_opts_and_label_names is not implemented for this metric type");
111    }
112}
113
114// Implement the trait for Counter, IntCounter, and Gauge
115impl PrometheusMetric for prometheus::Counter {
116    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
117        prometheus::Counter::with_opts(opts)
118    }
119}
120
121impl PrometheusMetric for prometheus::IntCounter {
122    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
123        prometheus::IntCounter::with_opts(opts)
124    }
125}
126
127impl PrometheusMetric for prometheus::Gauge {
128    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
129        prometheus::Gauge::with_opts(opts)
130    }
131}
132
133impl PrometheusMetric for prometheus::IntGauge {
134    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
135        prometheus::IntGauge::with_opts(opts)
136    }
137}
138
139impl PrometheusMetric for prometheus::GaugeVec {
140    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
141        Err(prometheus::Error::Msg(
142            "GaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
143        ))
144    }
145
146    fn with_opts_and_label_names(
147        opts: prometheus::Opts,
148        label_names: &[&str],
149    ) -> Result<Self, prometheus::Error> {
150        prometheus::GaugeVec::new(opts, label_names)
151    }
152}
153
154impl PrometheusMetric for prometheus::IntGaugeVec {
155    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
156        Err(prometheus::Error::Msg(
157            "IntGaugeVec requires label names, use with_opts_and_label_names instead".to_string(),
158        ))
159    }
160
161    fn with_opts_and_label_names(
162        opts: prometheus::Opts,
163        label_names: &[&str],
164    ) -> Result<Self, prometheus::Error> {
165        prometheus::IntGaugeVec::new(opts, label_names)
166    }
167}
168
169impl PrometheusMetric for prometheus::IntCounterVec {
170    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
171        Err(prometheus::Error::Msg(
172            "IntCounterVec requires label names, use with_opts_and_label_names instead".to_string(),
173        ))
174    }
175
176    fn with_opts_and_label_names(
177        opts: prometheus::Opts,
178        label_names: &[&str],
179    ) -> Result<Self, prometheus::Error> {
180        prometheus::IntCounterVec::new(opts, label_names)
181    }
182}
183
184// Implement the trait for Histogram
185impl PrometheusMetric for prometheus::Histogram {
186    fn with_opts(opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
187        // Convert Opts to HistogramOpts
188        let histogram_opts = prometheus::HistogramOpts::new(opts.name, opts.help);
189        prometheus::Histogram::with_opts(histogram_opts)
190    }
191
192    fn with_histogram_opts_and_buckets(
193        mut opts: prometheus::HistogramOpts,
194        buckets: Option<Vec<f64>>,
195    ) -> Result<Self, prometheus::Error> {
196        if let Some(custom_buckets) = buckets {
197            opts = opts.buckets(custom_buckets);
198        }
199        prometheus::Histogram::with_opts(opts)
200    }
201}
202
203impl PrometheusMetric for prometheus::HistogramVec {
204    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
205        Err(prometheus::Error::Msg(
206            "HistogramVec requires histogram options and label names".to_string(),
207        ))
208    }
209
210    fn with_histogram_opts_buckets_and_label_names(
211        mut opts: prometheus::HistogramOpts,
212        buckets: Option<Vec<f64>>,
213        label_names: &[&str],
214    ) -> Result<Self, prometheus::Error> {
215        if let Some(custom_buckets) = buckets {
216            opts = opts.buckets(custom_buckets);
217        }
218        prometheus::HistogramVec::new(opts, label_names)
219    }
220}
221
222// Implement the trait for CounterVec
223impl PrometheusMetric for prometheus::CounterVec {
224    fn with_opts(_opts: prometheus::Opts) -> Result<Self, prometheus::Error> {
225        // This will panic - CounterVec needs label names
226        panic!("CounterVec requires label names, use with_opts_and_label_names instead");
227    }
228
229    fn with_opts_and_label_names(
230        opts: prometheus::Opts,
231        label_names: &[&str],
232    ) -> Result<Self, prometheus::Error> {
233        prometheus::CounterVec::new(opts, label_names)
234    }
235}
236
237/// ==============================
238/// Metrics section
239/// ==============================
240/// Public helper function to create metrics - accessible for Python bindings
241pub fn create_metric<T: PrometheusMetric, H: MetricsHierarchy + ?Sized>(
242    hierarchy: &H,
243    metric_name: &str,
244    metric_desc: &str,
245    labels: &[(&str, &str)],
246    buckets: Option<Vec<f64>>,
247    const_labels: Option<&[&str]>,
248) -> anyhow::Result<T> {
249    create_metric_with_options(
250        hierarchy,
251        MetricOptions::default(),
252        metric_name,
253        metric_desc,
254        labels,
255        buckets,
256        const_labels,
257    )
258}
259
260/// How [`create_metric_with_options`] names and registers a metric. The
261/// default is what [`create_metric`] does.
262#[derive(Clone, Copy, Debug)]
263pub struct MetricOptions {
264    /// The metric is named `{prefix}_{metric_name}`. Only this prefix is ever
265    /// used: none is inferred from the metric name.
266    pub prefix: &'static str,
267    /// When the hierarchy's registry refuses the metric, log a warning and
268    /// return it unregistered, still usable but not exposed, instead of
269    /// failing.
270    pub warn_on_registration_failure: bool,
271}
272
273impl Default for MetricOptions {
274    fn default() -> Self {
275        Self {
276            prefix: name_prefix::COMPONENT,
277            warn_on_registration_failure: false,
278        }
279    }
280}
281
282/// [`create_metric`] under explicit [`MetricOptions`]: the same validation,
283/// auto-labels from the hierarchy, construction and registration.
284pub fn create_metric_with_options<T: PrometheusMetric, H: MetricsHierarchy + ?Sized>(
285    hierarchy: &H,
286    options: MetricOptions,
287    metric_name: &str,
288    metric_desc: &str,
289    labels: &[(&str, &str)],
290    buckets: Option<Vec<f64>>,
291    const_labels: Option<&[&str]>,
292) -> anyhow::Result<T> {
293    // Validate that user-provided labels don't have duplicate keys
294    validate_no_duplicate_label_keys(labels)?;
295    // Note: stored labels functionality has been removed
296
297    let basename = hierarchy.basename();
298    let parent_hierarchies = hierarchy.parent_hierarchies();
299
300    // Build hierarchy path as vector of strings: parent names + [basename]
301    let mut hierarchy_names: Vec<String> =
302        parent_hierarchies.iter().map(|p| p.basename()).collect();
303    hierarchy_names.push(basename.clone());
304
305    let metric_name = build_metric_name(options.prefix, metric_name);
306
307    // Build updated_labels: auto-labels first, then `labels` + stored labels
308    let mut updated_labels: Vec<(String, String)> = Vec::new();
309
310    // Auto-label injection: Always add dynamo_namespace, dynamo_component, dynamo_endpoint labels
311    // based on the hierarchy. Label constants defined in prometheus_names.rs labels module.
312    //
313    // Python counterpart: components/src/dynamo/common/utils/prometheus.py register_engine_metrics_callback()
314
315    // Validate that user-provided labels don't conflict with auto-generated labels
316    for (key, _) in labels {
317        if *key == labels::NAMESPACE
318            || *key == labels::COMPONENT
319            || *key == labels::ENDPOINT
320            || *key == labels::WORKER_ID
321        {
322            return Err(anyhow::anyhow!(
323                "Label '{}' is automatically added by auto-label injection and cannot be manually set",
324                key
325            ));
326        }
327    }
328
329    // Also validate that vector label names (const_labels) don't collide with auto-injected
330    // const labels. A variable label named "worker_id" would conflict with the auto-injected
331    // worker_id const label, causing a prometheus registration error or ambiguous output.
332    if let Some(label_names) = const_labels {
333        for name in label_names.iter() {
334            if *name == labels::NAMESPACE
335                || *name == labels::COMPONENT
336                || *name == labels::ENDPOINT
337                || *name == labels::WORKER_ID
338            {
339                return Err(anyhow::anyhow!(
340                    "Variable label name '{}' conflicts with auto-injected const label and cannot be used",
341                    name
342                ));
343            }
344        }
345    }
346
347    // Add auto-generated labels with sanitized values
348    // Hierarchy: [drt, namespace, component, endpoint]
349    if hierarchy_names.len() > 1 {
350        let namespace = &hierarchy_names[1];
351        if !namespace.is_empty() {
352            let valid_namespace = sanitize_prometheus_label(namespace)?;
353            if !valid_namespace.is_empty() {
354                updated_labels.push((labels::NAMESPACE.to_string(), valid_namespace));
355            }
356        }
357    }
358    if hierarchy_names.len() > 2 {
359        let component = &hierarchy_names[2];
360        if !component.is_empty() {
361            let valid_component = sanitize_prometheus_label(component)?;
362            if !valid_component.is_empty() {
363                updated_labels.push((labels::COMPONENT.to_string(), valid_component));
364            }
365        }
366    }
367    if hierarchy_names.len() > 3 {
368        let endpoint = &hierarchy_names[3];
369        if !endpoint.is_empty() {
370            let valid_endpoint = sanitize_prometheus_label(endpoint)?;
371            if !valid_endpoint.is_empty() {
372                updated_labels.push((labels::ENDPOINT.to_string(), valid_endpoint));
373            }
374        }
375    }
376
377    // Auto-inject worker_id label from the hierarchy's connection_id (discovery instance ID).
378    // This provides a stable per-worker identity label so metrics from different workers
379    // serving the same endpoint can be distinguished without relying on Kubernetes labels.
380    if let Some(conn_id) = hierarchy.connection_id() {
381        updated_labels.push((labels::WORKER_ID.to_string(), format!("{:x}", conn_id)));
382    }
383
384    // Add user labels
385    updated_labels.extend(
386        labels
387            .iter()
388            .map(|(k, v)| ((*k).to_string(), (*v).to_string())),
389    );
390    // Note: stored labels functionality has been removed
391
392    // Handle different metric types
393    let prometheus_metric = if std::any::TypeId::of::<T>()
394        == std::any::TypeId::of::<prometheus::CounterVec>()
395    {
396        // Special handling for CounterVec with label names
397        // const_labels parameter is required for CounterVec
398        if buckets.is_some() {
399            return Err(anyhow::anyhow!(
400                "buckets parameter is not valid for CounterVec"
401            ));
402        }
403        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
404        for (key, value) in &updated_labels {
405            opts = opts.const_label(key.clone(), value.clone());
406        }
407        let label_names = const_labels
408            .ok_or_else(|| anyhow::anyhow!("CounterVec requires const_labels parameter"))?;
409        T::with_opts_and_label_names(opts, label_names)?
410    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::GaugeVec>() {
411        // Special handling for GaugeVec with label names
412        // const_labels parameter is required for GaugeVec
413        if buckets.is_some() {
414            return Err(anyhow::anyhow!(
415                "buckets parameter is not valid for GaugeVec"
416            ));
417        }
418        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
419        for (key, value) in &updated_labels {
420            opts = opts.const_label(key.clone(), value.clone());
421        }
422        let label_names = const_labels
423            .ok_or_else(|| anyhow::anyhow!("GaugeVec requires const_labels parameter"))?;
424        T::with_opts_and_label_names(opts, label_names)?
425    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::HistogramVec>() {
426        let mut opts = prometheus::HistogramOpts::new(&metric_name, metric_desc);
427        for (key, value) in &updated_labels {
428            opts = opts.const_label(key.clone(), value.clone());
429        }
430        let label_names = const_labels
431            .ok_or_else(|| anyhow::anyhow!("HistogramVec requires const_labels parameter"))?;
432        T::with_histogram_opts_buckets_and_label_names(opts, buckets, label_names)?
433    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::Histogram>() {
434        // Special handling for Histogram with custom buckets
435        // buckets parameter is valid for Histogram, const_labels is not used
436        if const_labels.is_some() {
437            return Err(anyhow::anyhow!(
438                "const_labels parameter is not valid for Histogram"
439            ));
440        }
441        let mut opts = prometheus::HistogramOpts::new(&metric_name, metric_desc);
442        for (key, value) in &updated_labels {
443            opts = opts.const_label(key.clone(), value.clone());
444        }
445        T::with_histogram_opts_and_buckets(opts, buckets)?
446    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntCounterVec>() {
447        // Special handling for IntCounterVec with label names
448        // const_labels parameter is required for IntCounterVec
449        if buckets.is_some() {
450            return Err(anyhow::anyhow!(
451                "buckets parameter is not valid for IntCounterVec"
452            ));
453        }
454        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
455        for (key, value) in &updated_labels {
456            opts = opts.const_label(key.clone(), value.clone());
457        }
458        let label_names = const_labels
459            .ok_or_else(|| anyhow::anyhow!("IntCounterVec requires const_labels parameter"))?;
460        T::with_opts_and_label_names(opts, label_names)?
461    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<prometheus::IntGaugeVec>() {
462        // Special handling for IntGaugeVec with label names
463        // const_labels parameter is required for IntGaugeVec
464        if buckets.is_some() {
465            return Err(anyhow::anyhow!(
466                "buckets parameter is not valid for IntGaugeVec"
467            ));
468        }
469        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
470        for (key, value) in &updated_labels {
471            opts = opts.const_label(key.clone(), value.clone());
472        }
473        let label_names = const_labels
474            .ok_or_else(|| anyhow::anyhow!("IntGaugeVec requires const_labels parameter"))?;
475        T::with_opts_and_label_names(opts, label_names)?
476    } else {
477        // Standard handling for Counter, IntCounter, Gauge, IntGauge
478        // buckets and const_labels parameters are not valid for these types
479        if buckets.is_some() {
480            return Err(anyhow::anyhow!(
481                "buckets parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
482            ));
483        }
484        if const_labels.is_some() {
485            return Err(anyhow::anyhow!(
486                "const_labels parameter is not valid for Counter, IntCounter, Gauge, or IntGauge"
487            ));
488        }
489        let mut opts = prometheus::Opts::new(&metric_name, metric_desc);
490        for (key, value) in &updated_labels {
491            opts = opts.const_label(key.clone(), value.clone());
492        }
493        T::with_opts(opts)?
494    };
495
496    let collector: Box<dyn prometheus::core::Collector> = Box::new(prometheus_metric.clone());
497    let registry = hierarchy.get_metrics_registry();
498    if options.warn_on_registration_failure {
499        registry.add_metric_or_warn(collector, &metric_name);
500    } else {
501        registry.add_metric(collector)?;
502    }
503
504    Ok(prometheus_metric)
505}
506
507/// Wrapper struct that provides access to metrics functionality
508/// This struct is accessed via the `.metrics()` method on DistributedRuntime, Namespace, Component, and Endpoint
509pub struct Metrics<H: MetricsHierarchy> {
510    hierarchy: H,
511}
512
513impl<H: MetricsHierarchy> Metrics<H> {
514    pub fn new(hierarchy: H) -> Self {
515        Self { hierarchy }
516    }
517
518    // TODO: Add support for additional Prometheus metric types:
519    // - Counter: ✅ IMPLEMENTED - create_counter()
520    // - CounterVec: ✅ IMPLEMENTED - create_countervec()
521    // - Gauge: ✅ IMPLEMENTED - create_gauge()
522    // - GaugeVec: ✅ IMPLEMENTED - create_gaugevec()
523    // - GaugeHistogram: create_gauge_histogram() - for gauge histograms
524    // - Histogram: ✅ IMPLEMENTED - create_histogram()
525    // - HistogramVec: ✅ IMPLEMENTED - create_histogramvec()
526    // - Info: create_info() - for info metrics with labels
527    // - IntCounter: ✅ IMPLEMENTED - create_intcounter()
528    // - IntCounterVec: ✅ IMPLEMENTED - create_intcountervec()
529    // - IntGauge: ✅ IMPLEMENTED - create_intgauge()
530    // - IntGaugeVec: ✅ IMPLEMENTED - create_intgaugevec()
531    // - Stateset: create_stateset() - for state-based metrics
532    // - Summary: create_summary() - for quantiles and sum/count metrics
533    // - SummaryVec: create_summary_vec() - for labeled summaries
534    // - Untyped: create_untyped() - for untyped metrics
535    //
536    // NOTE: The order of create_* methods below is mirrored in lib/bindings/python/rust/lib.rs::Metrics
537    // Keep them synchronized when adding new metric types
538
539    /// Create a Counter metric
540    pub fn create_counter(
541        &self,
542        name: &str,
543        description: &str,
544        labels: &[(&str, &str)],
545    ) -> anyhow::Result<prometheus::Counter> {
546        create_metric(&self.hierarchy, name, description, labels, None, None)
547    }
548
549    /// Create a CounterVec metric with label names (for dynamic labels)
550    pub fn create_countervec(
551        &self,
552        name: &str,
553        description: &str,
554        const_labels: &[&str],
555        const_label_values: &[(&str, &str)],
556    ) -> anyhow::Result<prometheus::CounterVec> {
557        create_metric(
558            &self.hierarchy,
559            name,
560            description,
561            const_label_values,
562            None,
563            Some(const_labels),
564        )
565    }
566
567    /// Create a Gauge metric
568    pub fn create_gauge(
569        &self,
570        name: &str,
571        description: &str,
572        labels: &[(&str, &str)],
573    ) -> anyhow::Result<prometheus::Gauge> {
574        create_metric(&self.hierarchy, name, description, labels, None, None)
575    }
576
577    /// Create a GaugeVec metric with label names (for dynamic labels)
578    pub fn create_gaugevec(
579        &self,
580        name: &str,
581        description: &str,
582        const_labels: &[&str],
583        const_label_values: &[(&str, &str)],
584    ) -> anyhow::Result<prometheus::GaugeVec> {
585        create_metric(
586            &self.hierarchy,
587            name,
588            description,
589            const_label_values,
590            None,
591            Some(const_labels),
592        )
593    }
594
595    /// Create a Histogram metric with custom buckets
596    pub fn create_histogram(
597        &self,
598        name: &str,
599        description: &str,
600        labels: &[(&str, &str)],
601        buckets: Option<Vec<f64>>,
602    ) -> anyhow::Result<prometheus::Histogram> {
603        create_metric(&self.hierarchy, name, description, labels, buckets, None)
604    }
605
606    /// Create a HistogramVec metric with custom buckets and label names.
607    pub fn create_histogramvec(
608        &self,
609        name: &str,
610        description: &str,
611        label_names: &[&str],
612        labels: &[(&str, &str)],
613        buckets: Option<Vec<f64>>,
614    ) -> anyhow::Result<prometheus::HistogramVec> {
615        create_metric(
616            &self.hierarchy,
617            name,
618            description,
619            labels,
620            buckets,
621            Some(label_names),
622        )
623    }
624
625    /// Create an IntCounter metric
626    pub fn create_intcounter(
627        &self,
628        name: &str,
629        description: &str,
630        labels: &[(&str, &str)],
631    ) -> anyhow::Result<prometheus::IntCounter> {
632        create_metric(&self.hierarchy, name, description, labels, None, None)
633    }
634
635    /// Create an IntCounterVec metric with label names (for dynamic labels)
636    pub fn create_intcountervec(
637        &self,
638        name: &str,
639        description: &str,
640        const_labels: &[&str],
641        const_label_values: &[(&str, &str)],
642    ) -> anyhow::Result<prometheus::IntCounterVec> {
643        create_metric(
644            &self.hierarchy,
645            name,
646            description,
647            const_label_values,
648            None,
649            Some(const_labels),
650        )
651    }
652
653    /// Create an IntGauge metric
654    pub fn create_intgauge(
655        &self,
656        name: &str,
657        description: &str,
658        labels: &[(&str, &str)],
659    ) -> anyhow::Result<prometheus::IntGauge> {
660        create_metric(&self.hierarchy, name, description, labels, None, None)
661    }
662
663    /// Create an IntGaugeVec metric with label names (for dynamic labels)
664    pub fn create_intgaugevec(
665        &self,
666        name: &str,
667        description: &str,
668        const_labels: &[&str],
669        const_label_values: &[(&str, &str)],
670    ) -> anyhow::Result<prometheus::IntGaugeVec> {
671        create_metric(
672            &self.hierarchy,
673            name,
674            description,
675            const_label_values,
676            None,
677            Some(const_labels),
678        )
679    }
680
681    /// Get metrics in Prometheus text format
682    pub fn prometheus_expfmt(&self) -> anyhow::Result<String> {
683        self.hierarchy
684            .get_metrics_registry()
685            .prometheus_expfmt_combined()
686    }
687}
688
689/// This trait should be implemented by all metric registries, including Prometheus, Envy, OpenTelemetry, and others.
690/// It offers a unified interface for creating and managing metrics, organizing sub-registries, and
691/// generating output in Prometheus text format.
692use crate::traits::DistributedRuntimeProvider;
693
694pub trait MetricsHierarchy: Send + Sync {
695    // ========================================================================
696    // Required methods - must be implemented by all types
697    // ========================================================================
698
699    /// Get the name of this hierarchy (without any hierarchy prefix)
700    fn basename(&self) -> String;
701
702    /// Get the parent hierarchies as actual objects (not strings)
703    /// Returns a vector of hierarchy references, ordered from root to immediate parent.
704    /// For example, an Endpoint would return [DRT, Namespace, Component].
705    fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy>;
706
707    /// Get a reference to this hierarchy's metrics registry
708    fn get_metrics_registry(&self) -> &MetricsRegistry;
709
710    // ========================================================================
711    // Provided methods - have default implementations
712    // ========================================================================
713
714    /// Get the connection ID (discovery instance ID) for this hierarchy level.
715    ///
716    /// Returns `Some(id)` when the hierarchy has access to the DistributedRuntime
717    /// (e.g. Namespace, Component, Endpoint). Used by `create_metric()` to auto-inject
718    /// the `worker_id` label. Returns `None` by default.
719    fn connection_id(&self) -> Option<u64> {
720        None
721    }
722
723    /// Access the metrics interface for this hierarchy
724    /// This is a provided method that works for any type implementing MetricsHierarchy
725    fn metrics(&self) -> Metrics<&Self>
726    where
727        Self: Sized,
728    {
729        Metrics::new(self)
730    }
731}
732
733// Blanket implementation for references to types that implement MetricsHierarchy
734impl<T: MetricsHierarchy + ?Sized> MetricsHierarchy for &T {
735    fn basename(&self) -> String {
736        (**self).basename()
737    }
738
739    fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
740        (**self).parent_hierarchies()
741    }
742
743    fn get_metrics_registry(&self) -> &MetricsRegistry {
744        (**self).get_metrics_registry()
745    }
746
747    fn connection_id(&self) -> Option<u64> {
748        (**self).connection_id()
749    }
750}
751
752/// Type alias for runtime callback functions to reduce complexity
753///
754/// This type represents an Arc-wrapped callback function that can be:
755/// - Shared efficiently across multiple threads and contexts
756/// - Cloned without duplicating the underlying closure
757/// - Used in generic contexts requiring 'static lifetime
758///
759/// The Arc wrapper is included in the type to make sharing explicit.
760pub type PrometheusUpdateCallback = Arc<dyn Fn() -> anyhow::Result<()> + Send + Sync + 'static>;
761
762/// One collection: the merged families, plus the UNIT metadata that came with
763/// the typed ones.
764///
765/// Kept beside the families because `prometheus::proto::MetricFamily` has no
766/// unit field, and the compatibility spec requires the unit reach OTLP when the
767/// source declares one.
768pub struct CollectedFamilies {
769    pub families: Vec<prometheus::proto::MetricFamily>,
770    /// Family name -> Prometheus unit word, for families that declared one.
771    pub units: HashMap<String, String>,
772    /// Family name -> Prometheus type word. Carried because the proto model has
773    /// no Info variant: an Info family arrives here as a gauge, and the spec
774    /// converts it to a non-monotonic Sum rather than a Gauge.
775    pub prom_types: HashMap<String, String>,
776}
777
778/// Type alias for exposition text callback functions that return Prometheus text
779pub type PrometheusExpositionFormatCallback =
780    Arc<dyn Fn() -> anyhow::Result<String> + Send + Sync + 'static>;
781
782/// Returns already-built families, so engine metrics reach the structured
783/// path without being rendered to text and parsed back.
784pub type PrometheusTypedCallback = Arc<
785    dyn Fn() -> anyhow::Result<Vec<crate::metrics::prom_typed::BuiltFamily>>
786        + Send
787        + Sync
788        + 'static,
789>;
790
791/// Structure to hold Prometheus registries and associated callbacks for a given hierarchy.
792///
793/// All fields are Arc-wrapped, so cloning shares state. This ensures metrics registered
794/// on cloned instances (e.g., cloned Client/Endpoint) are visible to the original.
795#[derive(Clone)]
796pub struct MetricsRegistry {
797    /// The Prometheus registry for this hierarchy.
798    /// Arc-wrapped so clones share the same registry (metrics registered on clones are visible everywhere).
799    pub prometheus_registry: Arc<std::sync::RwLock<prometheus::Registry>>,
800
801    /// Child registries included when emitting combined `/metrics` output.
802    ///
803    /// Why this exists:
804    /// - Previously, `create_metric()` registered every collector into *all* parent registries
805    ///   (Endpoint → Component → Namespace → DRT) so scraping the root registry included everything.
806    /// - That fan-out caused Prometheus collisions when different endpoints tried to register the
807    ///   same metric name with different const-labels (descriptor mismatch).
808    ///
809    /// We now register metrics only into the local hierarchy registry to avoid collisions.
810    /// `child_registries` rebuilds “what to scrape” as a tree of registries so `/metrics` can:
811    /// - traverse registries recursively,
812    /// - merge metric families into one exposition payload,
813    /// - warn/drop exact duplicate series, while allowing same metric name with different labels.
814    child_registries: Arc<std::sync::RwLock<Vec<MetricsRegistry>>>,
815
816    /// Update callbacks invoked before metrics are scraped.
817    /// Wrapped in Arc to preserve callbacks across clones (prevents callback loss when MetricsRegistry is cloned).
818    pub prometheus_update_callbacks: Arc<std::sync::RwLock<Vec<PrometheusUpdateCallback>>>,
819
820    /// Callbacks returning engine exposition text; these feed `/metrics` only.
821    #[allow(clippy::type_complexity)]
822    pub prometheus_expfmt_callbacks:
823        Arc<std::sync::RwLock<Vec<PrometheusExpositionFormatCallback>>>,
824
825    /// Callbacks returning engine metric families; these feed OTLP only.
826    /// Wrapped in Arc to preserve callbacks across clones (e.g. vLLM callbacks
827    /// registered at Endpoint remain reachable at DRT).
828    pub prometheus_typed_callbacks: Arc<std::sync::RwLock<Vec<PrometheusTypedCallback>>>,
829}
830
831impl std::fmt::Debug for MetricsRegistry {
832    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833        f.debug_struct("MetricsRegistry")
834            .field("prometheus_registry", &"<RwLock<Registry>>")
835            .field(
836                "prometheus_update_callbacks",
837                &format!(
838                    "<RwLock<Vec<Callback>>> with {} callbacks",
839                    self.prometheus_update_callbacks.read().unwrap().len()
840                ),
841            )
842            .field(
843                "prometheus_expfmt_callbacks",
844                &format!(
845                    "<RwLock<Vec<Callback>>> with {} callbacks",
846                    self.prometheus_expfmt_callbacks.read().unwrap().len()
847                ),
848            )
849            .field(
850                "prometheus_typed_callbacks",
851                &format!(
852                    "<RwLock<Vec<Callback>>> with {} callbacks",
853                    self.prometheus_typed_callbacks.read().unwrap().len()
854                ),
855            )
856            .finish()
857    }
858}
859
860impl MetricsRegistry {
861    /// Create a new metrics registry with an empty Prometheus registry and callback lists
862    pub fn new() -> Self {
863        Self {
864            prometheus_registry: Arc::new(std::sync::RwLock::new(prometheus::Registry::new())),
865            child_registries: Arc::new(std::sync::RwLock::new(Vec::new())),
866            prometheus_update_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
867            prometheus_expfmt_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
868            prometheus_typed_callbacks: Arc::new(std::sync::RwLock::new(Vec::new())),
869        }
870    }
871
872    /// Add a child registry to be included in combined /metrics output.
873    ///
874    /// Dedup is by underlying Prometheus registry pointer, so repeated registration via clones is safe.
875    pub fn add_child_registry(&self, child: &MetricsRegistry) {
876        let child_ptr = Arc::as_ptr(&child.prometheus_registry);
877        let mut guard = self.child_registries.write().unwrap();
878        if guard
879            .iter()
880            .any(|r| Arc::as_ptr(&r.prometheus_registry) == child_ptr)
881        {
882            return;
883        }
884        guard.push(child.clone());
885    }
886
887    fn registries_for_combined_scrape(&self) -> Vec<MetricsRegistry> {
888        // Traverse child registries recursively so `prometheus_expfmt()` on any hierarchy
889        // (DRT/namespace/component/endpoint) includes metrics from its descendants.
890        //
891        // Dedup by underlying Prometheus registry pointer so multiple paths (e.g. also registering
892        // directly on the root) won't duplicate output.
893        fn visit(
894            registry: &MetricsRegistry,
895            out: &mut Vec<MetricsRegistry>,
896            seen: &mut HashSet<*const std::sync::RwLock<prometheus::Registry>>,
897        ) {
898            let ptr = Arc::as_ptr(&registry.prometheus_registry);
899            if !seen.insert(ptr) {
900                return;
901            }
902
903            out.push(registry.clone());
904
905            let children: Vec<MetricsRegistry> = registry
906                .child_registries
907                .read()
908                .unwrap()
909                .iter()
910                .cloned()
911                .collect();
912            for child in children {
913                visit(&child, out, seen);
914            }
915        }
916
917        let mut out = Vec::new();
918        let mut seen: HashSet<*const std::sync::RwLock<prometheus::Registry>> = HashSet::new();
919        visit(self, &mut out, &mut seen);
920        out
921    }
922
923    /// Combine metrics across this registry and all registered children into one Prometheus exposition output.
924    ///
925    /// Engine metrics are appended as the text the engine produced. This is the
926    /// scrape path and is deliberately independent of the typed path that feeds
927    /// OTLP: `/metrics` output stays byte-for-byte what the engine emitted.
928    ///
929    /// - Families are merged by name; HELP and TYPE must match.
930    /// - Multiple series for the same name are allowed if labels differ.
931    /// - Exact duplicate series (same name + identical label pairs) are warned and dropped.
932    pub fn prometheus_expfmt_combined(&self) -> anyhow::Result<String> {
933        let registries = self.registries_for_combined_scrape();
934        run_update_callbacks(&registries);
935
936        let merged = FamilyMerger::from_gathered(&registries)?.into_sorted();
937
938        let encoder = prometheus::TextEncoder::new();
939        let mut buffer = Vec::new();
940        encoder.encode(&merged, &mut buffer)?;
941        let mut result = String::from_utf8(buffer)?;
942
943        // Append expfmt callbacks deterministically in registry order.
944        let mut expfmt = String::new();
945        for registry in &registries {
946            let text = registry.execute_expfmt_callbacks();
947            if !text.is_empty() {
948                if !expfmt.is_empty() && !expfmt.ends_with('\n') {
949                    expfmt.push('\n');
950                }
951                expfmt.push_str(&text);
952            }
953        }
954
955        if !expfmt.is_empty() {
956            if !result.ends_with('\n') {
957                result.push('\n');
958            }
959            result.push_str(&expfmt);
960        }
961
962        Ok(result)
963    }
964
965    /// Every metric family: Dynamo's own from `gather()`, plus engine families
966    /// delivered typed. This is the OTLP export path.
967    ///
968    /// Engine metrics cross the binding as a structure rather than as
969    /// exposition text, so their name, type and help arrive authoritative
970    /// instead of being re-derived by a parser.
971    ///
972    /// Each call re-executes the typed callbacks, which cross into Python and
973    /// take the GIL, so callers should collect on a deliberate cadence.
974    pub fn metric_families_combined(&self) -> anyhow::Result<CollectedFamilies> {
975        let registries = self.registries_for_combined_scrape();
976        run_update_callbacks(&registries);
977
978        let mut merger = FamilyMerger::from_gathered(&registries)?;
979
980        // The unit travels beside the family, keyed by name: the proto model
981        // has no unit field, so it would otherwise be dropped here.
982        let mut units: HashMap<String, String> = HashMap::new();
983        let mut prom_types: HashMap<String, String> = HashMap::new();
984        for registry in &registries {
985            for built in registry.execute_typed_callbacks() {
986                let name = built.family.name().to_string();
987                // Publish the side metadata only once the family is accepted.
988                // The maps are keyed by name, so metadata from a family the
989                // merger rejects would otherwise be applied to the family that
990                // did survive under that name -- a rejected `info` could make a
991                // surviving gauge encode as a non-monotonic Sum.
992                if let Err(error) = merger.add_family(built.family) {
993                    tracing::warn!(metric_name = %name, %error, "skipping typed metric family");
994                    continue;
995                }
996                // First writer wins, matching how the merger itself resolves a
997                // conflict: the first family fixes help and type, and later
998                // ones must agree. A later family can be accepted and still
999                // have every sample dropped as a duplicate series, so letting
1000                // it overwrite the unit would label the surviving data with a
1001                // unit from a source that contributed none of it.
1002                if !built.unit.is_empty() {
1003                    units.entry(name.clone()).or_insert(built.unit);
1004                }
1005                prom_types.entry(name).or_insert(built.prom_type);
1006            }
1007        }
1008
1009        Ok(CollectedFamilies {
1010            families: merger.into_sorted(),
1011            units,
1012            prom_types,
1013        })
1014    }
1015
1016    /// Add a callback function that receives a reference to any MetricsHierarchy
1017    pub fn add_update_callback(&self, callback: PrometheusUpdateCallback) {
1018        self.prometheus_update_callbacks
1019            .write()
1020            .unwrap()
1021            .push(callback);
1022    }
1023
1024    /// Add an exposition text callback that returns Prometheus text.
1025    ///
1026    /// This feeds `/metrics` only. Engines that also want to be exported over
1027    /// OTLP must register a typed callback via [`Self::add_typed_callback`].
1028    pub fn add_expfmt_callback(&self, callback: PrometheusExpositionFormatCallback) {
1029        self.prometheus_expfmt_callbacks
1030            .write()
1031            .unwrap()
1032            .push(callback);
1033    }
1034
1035    /// Execute all exposition text callbacks and return their concatenated text
1036    pub fn execute_expfmt_callbacks(&self) -> String {
1037        // Snapshot under the lock, then invoke without it held; see
1038        // `execute_typed_callbacks` for why holding it across the calls
1039        // deadlocks against registration from Python.
1040        let callbacks: Vec<PrometheusExpositionFormatCallback> = self
1041            .prometheus_expfmt_callbacks
1042            .read()
1043            .unwrap()
1044            .iter()
1045            .cloned()
1046            .collect();
1047        let mut result = String::new();
1048        for callback in callbacks.iter() {
1049            match callback() {
1050                Ok(text) => {
1051                    if !text.is_empty() {
1052                        if !result.is_empty() && !result.ends_with('\n') {
1053                            result.push('\n');
1054                        }
1055                        result.push_str(&text);
1056                    }
1057                }
1058                Err(e) => {
1059                    tracing::error!("Error executing exposition text callback: {e}");
1060                }
1061            }
1062        }
1063        result
1064    }
1065
1066    /// Register a callback that returns typed families directly.
1067    ///
1068    /// This is how engine metrics reach OTLP.
1069    pub fn add_typed_callback(&self, callback: PrometheusTypedCallback) {
1070        self.prometheus_typed_callbacks
1071            .write()
1072            .unwrap()
1073            .push(callback);
1074    }
1075
1076    /// Collect from every typed callback, logging and skipping failures so one
1077    /// broken engine cannot empty the whole collection.
1078    pub fn execute_typed_callbacks(&self) -> Vec<crate::metrics::prom_typed::BuiltFamily> {
1079        // Snapshot under the lock, then invoke without it held. The callbacks
1080        // take the Python GIL, and registration arrives from Python holding the
1081        // GIL and blocking on `write()` -- holding the read lock across the
1082        // calls would deadlock those two against each other.
1083        let callbacks: Vec<PrometheusTypedCallback> = self
1084            .prometheus_typed_callbacks
1085            .read()
1086            .unwrap()
1087            .iter()
1088            .cloned()
1089            .collect();
1090
1091        callbacks
1092            .iter()
1093            .filter_map(|callback| match callback() {
1094                Ok(families) => Some(families),
1095                Err(error) => {
1096                    tracing::warn!(%error, "typed metrics callback failed");
1097                    None
1098                }
1099            })
1100            .flatten()
1101            .collect()
1102    }
1103
1104    /// Execute all update callbacks and return their results
1105    pub fn execute_update_callbacks(&self) -> Vec<anyhow::Result<()>> {
1106        // Snapshot before invoking, for the same reason as the typed and
1107        // exposition callbacks: a callback may take the Python GIL or register
1108        // another callback, and holding the read lock across the call deadlocks
1109        // against a registration that holds the GIL and wants the write lock.
1110        let callbacks: Vec<PrometheusUpdateCallback> = self
1111            .prometheus_update_callbacks
1112            .read()
1113            .unwrap()
1114            .iter()
1115            .cloned()
1116            .collect();
1117
1118        callbacks.iter().map(|callback| callback()).collect()
1119    }
1120
1121    /// Add a Prometheus metric collector to this registry
1122    pub fn add_metric(
1123        &self,
1124        collector: Box<dyn prometheus::core::Collector>,
1125    ) -> anyhow::Result<()> {
1126        self.prometheus_registry
1127            .write()
1128            .unwrap()
1129            .register(collector)
1130            .map_err(|e| anyhow::anyhow!("Failed to register metric: {}", e))
1131    }
1132
1133    /// Add a Prometheus metric collector, logging a warning on failure instead of returning an error.
1134    pub fn add_metric_or_warn(&self, collector: Box<dyn prometheus::core::Collector>, name: &str) {
1135        if let Err(e) = self.add_metric(collector) {
1136            tracing::warn!(error = %e, metric = name, "Failed to register metric");
1137        }
1138    }
1139
1140    /// Get a read guard to the Prometheus registry for scraping
1141    pub fn get_prometheus_registry(&self) -> std::sync::RwLockReadGuard<'_, prometheus::Registry> {
1142        self.prometheus_registry.read().unwrap()
1143    }
1144
1145    /// Returns true if a metric with the given name already exists in the Prometheus registry
1146    pub fn has_metric_named(&self, metric_name: &str) -> bool {
1147        self.prometheus_registry
1148            .read()
1149            .unwrap()
1150            .gather()
1151            .iter()
1152            .any(|mf| mf.name() == metric_name)
1153    }
1154}
1155
1156/// Run every registry's update callbacks, logging rather than propagating
1157/// failures so one broken callback cannot poison the whole collection.
1158fn run_update_callbacks(registries: &[MetricsRegistry]) {
1159    for registry in registries {
1160        for result in registry.execute_update_callbacks() {
1161            if let Err(error) = result {
1162                tracing::error!(%error, "metrics update callback failed");
1163            }
1164        }
1165    }
1166}
1167
1168/// Merges metric families from several sources under one set of rules.
1169///
1170/// Extracted so the text path (`prometheus_expfmt_combined`) and the structured
1171/// path (`metric_families_combined`) cannot drift: a series accepted by one must
1172/// be accepted by the other, or `/metrics` and OTLP would disagree.
1173struct FamilyMerger {
1174    by_name: HashMap<String, prometheus::proto::MetricFamily>,
1175    seen_series: HashSet<String>,
1176}
1177
1178impl FamilyMerger {
1179    fn from_gathered(registries: &[MetricsRegistry]) -> anyhow::Result<Self> {
1180        let mut merger = Self {
1181            by_name: HashMap::new(),
1182            seen_series: HashSet::new(),
1183        };
1184        for (idx, registry) in registries.iter().enumerate() {
1185            for family in registry.get_prometheus_registry().gather() {
1186                merger
1187                    .add_family(family)
1188                    .with_context(|| format!("gathering from registry {idx}"))?;
1189            }
1190        }
1191        Ok(merger)
1192    }
1193
1194    fn add_family(&mut self, mut family: prometheus::proto::MetricFamily) -> anyhow::Result<()> {
1195        let name = family.name().to_string();
1196
1197        let entry = self.by_name.entry(name.clone()).or_insert_with(|| {
1198            let mut out = prometheus::proto::MetricFamily::new();
1199            out.set_name(name.clone());
1200            out.set_help(family.help().to_string());
1201            out.set_field_type(family.get_field_type());
1202            out
1203        });
1204
1205        if entry.help() != family.help() || entry.get_field_type() != family.get_field_type() {
1206            return Err(anyhow::anyhow!(
1207                "Metric family '{}' has inconsistent help/type across sources",
1208                name
1209            ));
1210        }
1211
1212        for metric in family.take_metric() {
1213            let mut labels: Vec<(String, String)> = metric
1214                .get_label()
1215                .iter()
1216                .map(|lp| (lp.name().to_string(), lp.value().to_string()))
1217                .collect();
1218            labels.sort_by(|(ka, va), (kb, vb)| (ka, va).cmp(&(kb, vb)));
1219
1220            let key = format!(
1221                "{}|{}",
1222                name,
1223                labels
1224                    .iter()
1225                    .map(|(k, v)| format!("{}={}", k, v))
1226                    .collect::<Vec<_>>()
1227                    .join(",")
1228            );
1229
1230            if !self.seen_series.insert(key) {
1231                tracing::warn!(
1232                    metric_name = %name,
1233                    labels = ?labels,
1234                    "Duplicate Prometheus series while merging; dropping later sample"
1235                );
1236                continue;
1237            }
1238
1239            entry.mut_metric().push(metric);
1240        }
1241
1242        Ok(())
1243    }
1244
1245    fn into_sorted(self) -> Vec<prometheus::proto::MetricFamily> {
1246        let mut merged: Vec<prometheus::proto::MetricFamily> = self.by_name.into_values().collect();
1247        merged.sort_by(|a, b| a.name().cmp(b.name()));
1248        merged
1249    }
1250}
1251
1252impl Default for MetricsRegistry {
1253    fn default() -> Self {
1254        Self::new()
1255    }
1256}
1257
1258#[cfg(test)]
1259mod test_helpers {
1260    use super::prometheus_names::name_prefix;
1261    use super::*;
1262
1263    /// Base function to filter Prometheus output lines based on a predicate.
1264    /// Returns lines that match the predicate, converted to String.
1265    fn filter_prometheus_lines<F>(input: &str, mut predicate: F) -> Vec<String>
1266    where
1267        F: FnMut(&str) -> bool,
1268    {
1269        input
1270            .lines()
1271            .filter(|line| predicate(line))
1272            .map(|line| line.to_string())
1273            .collect::<Vec<_>>()
1274    }
1275
1276    /// Extracts all component metrics (excluding help text and type definitions).
1277    /// Returns only the actual metric lines with values.
1278    pub fn extract_metrics(input: &str) -> Vec<String> {
1279        filter_prometheus_lines(input, |line| {
1280            line.starts_with(&format!("{}_", name_prefix::COMPONENT))
1281                && !line.starts_with("#")
1282                && !line.trim().is_empty()
1283        })
1284    }
1285
1286    /// Parses a Prometheus metric line and extracts the name, labels, and value.
1287    /// Used instead of fetching metrics directly to test end-to-end results, not intermediate state.
1288    ///
1289    /// # Example
1290    /// ```
1291    /// let line = "http_requests_total{method=\"GET\"} 1234";
1292    /// let (name, labels, value) = parse_prometheus_metric(line).unwrap();
1293    /// assert_eq!(name, "http_requests_total");
1294    /// assert_eq!(labels.get("method"), Some(&"GET".to_string()));
1295    /// assert_eq!(value, 1234.0);
1296    /// ```
1297    pub fn parse_prometheus_metric(
1298        line: &str,
1299    ) -> Option<(String, std::collections::HashMap<String, String>, f64)> {
1300        if line.trim().is_empty() || line.starts_with('#') {
1301            return None;
1302        }
1303
1304        let parts: Vec<&str> = line.split_whitespace().collect();
1305        if parts.len() < 2 {
1306            return None;
1307        }
1308
1309        let metric_part = parts[0];
1310        let value: f64 = parts[1].parse().ok()?;
1311
1312        let (name, labels) = if metric_part.contains('{') {
1313            let brace_start = metric_part.find('{').unwrap();
1314            let brace_end = metric_part.rfind('}').unwrap_or(metric_part.len());
1315            let name = &metric_part[..brace_start];
1316            let labels_str = &metric_part[brace_start + 1..brace_end];
1317
1318            let mut labels = std::collections::HashMap::new();
1319            for pair in labels_str.split(',') {
1320                if let Some((k, v)) = pair.split_once('=') {
1321                    let v = v.trim_matches('"');
1322                    labels.insert(k.trim().to_string(), v.to_string());
1323                }
1324            }
1325            (name.to_string(), labels)
1326        } else {
1327            (metric_part.to_string(), std::collections::HashMap::new())
1328        };
1329
1330        Some((name, labels, value))
1331    }
1332
1333    /// Injects a `worker_id` label into Prometheus metric data lines.
1334    /// Prometheus places const labels (like worker_id) before special labels
1335    /// (like histogram `le`), so for histogram bucket lines we insert before
1336    /// `,le=`. For all other metric lines, we insert before the closing `}`.
1337    /// Comment lines and lines without labels are left unchanged.
1338    pub fn inject_worker_id(expected: &str, wid: &str) -> String {
1339        let wid_label = format!(",worker_id=\"{}\"", wid);
1340        expected
1341            .lines()
1342            .map(|line| {
1343                if line.starts_with('#') || line.trim().is_empty() || !line.contains('{') {
1344                    line.to_string()
1345                } else if let Some(le_pos) = line.find(",le=") {
1346                    // Histogram bucket lines: worker_id is a const label, `le` is special,
1347                    // so worker_id sorts before `le` in Prometheus output.
1348                    let mut s = line.to_string();
1349                    s.insert_str(le_pos, &wid_label);
1350                    s
1351                } else {
1352                    line.replacen("}", &format!("{}}}", wid_label), 1)
1353                }
1354            })
1355            .collect::<Vec<_>>()
1356            .join("\n")
1357    }
1358}
1359
1360#[cfg(test)]
1361mod test_metricsregistry_units {
1362    use super::prometheus_names::build_component_metric_name;
1363    use super::*;
1364
1365    #[test]
1366    fn test_build_component_metric_name_with_prefix() {
1367        // Test that build_component_metric_name correctly prepends the dynamo_component prefix
1368        let result = build_component_metric_name("requests");
1369        assert_eq!(result, "dynamo_component_requests");
1370
1371        let result = build_component_metric_name("counter");
1372        assert_eq!(result, "dynamo_component_counter");
1373    }
1374
1375    #[test]
1376    fn test_parse_prometheus_metric() {
1377        use super::test_helpers::parse_prometheus_metric;
1378        use std::collections::HashMap;
1379
1380        // Test parsing a metric with labels
1381        let line = "http_requests_total{method=\"GET\",status=\"200\"} 1234";
1382        let parsed = parse_prometheus_metric(line);
1383        assert!(parsed.is_some());
1384
1385        let (name, labels, value) = parsed.unwrap();
1386        assert_eq!(name, "http_requests_total");
1387
1388        let mut expected_labels = HashMap::new();
1389        expected_labels.insert("method".to_string(), "GET".to_string());
1390        expected_labels.insert("status".to_string(), "200".to_string());
1391        assert_eq!(labels, expected_labels);
1392
1393        assert_eq!(value, 1234.0);
1394
1395        // Test parsing a metric without labels
1396        let line = "cpu_usage 98.5";
1397        let parsed = parse_prometheus_metric(line);
1398        assert!(parsed.is_some());
1399
1400        let (name, labels, value) = parsed.unwrap();
1401        assert_eq!(name, "cpu_usage");
1402        assert!(labels.is_empty());
1403        assert_eq!(value, 98.5);
1404
1405        // Test parsing a metric with float value
1406        let line = "response_time{service=\"api\"} 0.123";
1407        let parsed = parse_prometheus_metric(line);
1408        assert!(parsed.is_some());
1409
1410        let (name, labels, value) = parsed.unwrap();
1411        assert_eq!(name, "response_time");
1412
1413        let mut expected_labels = HashMap::new();
1414        expected_labels.insert("service".to_string(), "api".to_string());
1415        assert_eq!(labels, expected_labels);
1416
1417        assert_eq!(value, 0.123);
1418
1419        // Test parsing invalid lines
1420        assert!(parse_prometheus_metric("").is_none()); // Empty line
1421        assert!(parse_prometheus_metric("# HELP metric description").is_none()); // Help text
1422        assert!(parse_prometheus_metric("# TYPE metric counter").is_none()); // Type definition
1423        assert!(parse_prometheus_metric("metric_name").is_none()); // No value
1424
1425        println!("✓ Prometheus metric parsing works correctly!");
1426    }
1427
1428    #[test]
1429    fn test_metrics_registry_entry_callbacks() {
1430        use crate::MetricsRegistry;
1431        use std::sync::atomic::{AtomicUsize, Ordering};
1432
1433        // Test 1: Basic callback execution with counter increments
1434        {
1435            let registry = MetricsRegistry::new();
1436            let counter = Arc::new(AtomicUsize::new(0));
1437
1438            // Add callbacks with different increment values
1439            for increment in [1, 10, 100] {
1440                let counter_clone = counter.clone();
1441                registry.add_update_callback(Arc::new(move || {
1442                    counter_clone.fetch_add(increment, Ordering::SeqCst);
1443                    Ok(())
1444                }));
1445            }
1446
1447            // Verify counter starts at 0
1448            assert_eq!(counter.load(Ordering::SeqCst), 0);
1449
1450            // First execution
1451            let results = registry.execute_update_callbacks();
1452            assert_eq!(results.len(), 3);
1453            assert!(results.iter().all(|r| r.is_ok()));
1454            assert_eq!(counter.load(Ordering::SeqCst), 111); // 1 + 10 + 100
1455
1456            // Second execution - callbacks should be reusable
1457            let results = registry.execute_update_callbacks();
1458            assert_eq!(results.len(), 3);
1459            assert_eq!(counter.load(Ordering::SeqCst), 222); // 111 + 111
1460
1461            // Test cloning - cloned entry shares callbacks (callbacks are Arc-wrapped)
1462            let cloned = registry.clone();
1463            assert_eq!(cloned.execute_update_callbacks().len(), 3);
1464            assert_eq!(counter.load(Ordering::SeqCst), 333); // 222 + 111
1465
1466            // Original still has callbacks and shares the same Arc
1467            registry.execute_update_callbacks();
1468            assert_eq!(counter.load(Ordering::SeqCst), 444); // 333 + 111
1469        }
1470
1471        // Test 2: Mixed success and error callbacks
1472        {
1473            let registry = MetricsRegistry::new();
1474            let counter = Arc::new(AtomicUsize::new(0));
1475
1476            // Successful callback
1477            let counter_clone = counter.clone();
1478            registry.add_update_callback(Arc::new(move || {
1479                counter_clone.fetch_add(1, Ordering::SeqCst);
1480                Ok(())
1481            }));
1482
1483            // Error callback
1484            registry.add_update_callback(Arc::new(|| Err(anyhow::anyhow!("Simulated error"))));
1485
1486            // Another successful callback
1487            let counter_clone = counter.clone();
1488            registry.add_update_callback(Arc::new(move || {
1489                counter_clone.fetch_add(10, Ordering::SeqCst);
1490                Ok(())
1491            }));
1492
1493            // Execute and verify mixed results
1494            let results = registry.execute_update_callbacks();
1495            assert_eq!(results.len(), 3);
1496            assert!(results[0].is_ok());
1497            assert!(results[1].is_err());
1498            assert!(results[2].is_ok());
1499
1500            // Verify error message
1501            assert_eq!(
1502                results[1].as_ref().unwrap_err().to_string(),
1503                "Simulated error"
1504            );
1505
1506            // Verify successful callbacks still executed
1507            assert_eq!(counter.load(Ordering::SeqCst), 11); // 1 + 10
1508
1509            // Execute again - errors should be consistent
1510            let results = registry.execute_update_callbacks();
1511            assert!(results[1].is_err());
1512            assert_eq!(counter.load(Ordering::SeqCst), 22); // 11 + 11
1513        }
1514
1515        // Test 3: Empty registry
1516        {
1517            let registry = MetricsRegistry::new();
1518            let results = registry.execute_update_callbacks();
1519            assert_eq!(results.len(), 0);
1520        }
1521    }
1522}
1523
1524#[cfg(test)]
1525mod test_create_metric_with_options {
1526    use super::*;
1527    use prometheus::core::Collector;
1528
1529    /// A hierarchy level without a runtime, with a registry of its own.
1530    struct Level {
1531        name: &'static str,
1532        parents: Vec<Level>,
1533        registry: MetricsRegistry,
1534        connection_id: Option<u64>,
1535    }
1536
1537    impl Level {
1538        fn new(name: &'static str, parents: Vec<Level>, connection_id: Option<u64>) -> Self {
1539            Self {
1540                name,
1541                parents,
1542                registry: MetricsRegistry::new(),
1543                connection_id,
1544            }
1545        }
1546
1547        /// Component `comp` of namespace `ns-1`, on connection `0x1a`.
1548        fn component() -> Self {
1549            let root = Self::new("", Vec::new(), None);
1550            let namespace = Self::new("ns-1", Vec::new(), None);
1551            Self::new("comp", vec![root, namespace], Some(0x1a))
1552        }
1553    }
1554
1555    impl MetricsHierarchy for Level {
1556        fn basename(&self) -> String {
1557            self.name.to_string()
1558        }
1559
1560        fn parent_hierarchies(&self) -> Vec<&dyn MetricsHierarchy> {
1561            self.parents
1562                .iter()
1563                .map(|parent| parent as &dyn MetricsHierarchy)
1564                .collect()
1565        }
1566
1567        fn get_metrics_registry(&self) -> &MetricsRegistry {
1568            &self.registry
1569        }
1570
1571        fn connection_id(&self) -> Option<u64> {
1572            self.connection_id
1573        }
1574    }
1575
1576    const CUSTOM: MetricOptions = MetricOptions {
1577        prefix: "dynamo_custom",
1578        warn_on_registration_failure: false,
1579    };
1580
1581    /// A metric's name and its constant labels, as sorted `name=value` pairs.
1582    fn described(metric: &impl Collector) -> (String, Vec<String>) {
1583        let desc = metric.desc()[0];
1584        let labels = desc
1585            .const_label_pairs
1586            .iter()
1587            .map(|pair| format!("{}={}", pair.name(), pair.value()))
1588            .collect();
1589        (desc.fq_name.clone(), labels)
1590    }
1591
1592    /// A prefix applies only when passed explicitly, and a metric named under
1593    /// one carries the same hierarchy labels as one named by default.
1594    #[test]
1595    fn an_explicit_prefix_names_the_metric_and_keeps_the_hierarchy_labels() {
1596        let component = Level::component();
1597        let custom: prometheus::IntCounterVec = create_metric_with_options(
1598            &component,
1599            CUSTOM,
1600            "requests_total",
1601            "help",
1602            &[],
1603            None,
1604            Some(&["dp_rank"]),
1605        )
1606        .unwrap();
1607        let default = component
1608            .metrics()
1609            .create_intcountervec("requests_total", "help", &["dp_rank"], &[])
1610            .unwrap();
1611        // A name that merely looks prefixed is still named by default.
1612        let lookalike: prometheus::IntCounter =
1613            create_metric(&component, "dynamo_custom_total", "help", &[], None, None).unwrap();
1614
1615        let (name, labels) = described(&custom);
1616        assert_eq!(name, "dynamo_custom_requests_total");
1617        assert_eq!(
1618            labels,
1619            [
1620                "dynamo_component=comp",
1621                "dynamo_namespace=ns_1",
1622                "worker_id=1a"
1623            ]
1624        );
1625        assert_eq!(
1626            described(&default),
1627            ("dynamo_component_requests_total".to_string(), labels)
1628        );
1629        assert_eq!(
1630            described(&lookalike).0,
1631            "dynamo_component_dynamo_custom_total"
1632        );
1633    }
1634
1635    /// Explicit options keep every label check, and choose what a registry's
1636    /// refusal does: fail, or keep the metric unregistered with a warning.
1637    #[test]
1638    fn explicit_options_keep_validation_and_choose_how_a_refusal_ends() {
1639        let component = Level::component();
1640        let gauge = |options, labels: &[(&str, &str)], label_names: &[&str]| {
1641            create_metric_with_options::<prometheus::IntGaugeVec, _>(
1642                &component,
1643                options,
1644                "depth",
1645                "help",
1646                labels,
1647                None,
1648                Some(label_names),
1649            )
1650        };
1651        assert!(gauge(CUSTOM, &[("worker_id", "7")], &["dp_rank"]).is_err());
1652        assert!(gauge(CUSTOM, &[], &["dynamo_namespace"]).is_err());
1653        assert!(gauge(CUSTOM, &[("a", "1"), ("a", "2")], &["dp_rank"]).is_err());
1654
1655        let first = gauge(CUSTOM, &[], &["dp_rank"]).unwrap();
1656        assert!(gauge(CUSTOM, &[], &["dp_rank"]).is_err());
1657        let warn = MetricOptions {
1658            warn_on_registration_failure: true,
1659            ..CUSTOM
1660        };
1661        let refused = gauge(warn, &[], &["dp_rank"]).unwrap();
1662        first.with_label_values(&["0"]).set(3);
1663        refused.with_label_values(&["0"]).set(5);
1664
1665        // The registry exposes only the first; the refused one still counts.
1666        let exposed = component.registry.prometheus_expfmt_combined().unwrap();
1667        let samples: Vec<&str> = exposed
1668            .lines()
1669            .filter(|line| !line.starts_with('#'))
1670            .collect();
1671        assert_eq!(
1672            samples,
1673            [
1674                r#"dynamo_custom_depth{dp_rank="0",dynamo_component="comp",dynamo_namespace="ns_1",worker_id="1a"} 3"#
1675            ]
1676        );
1677        assert_eq!(refused.with_label_values(&["0"]).get(), 5);
1678    }
1679}
1680
1681#[cfg(feature = "integration")]
1682#[cfg(test)]
1683mod test_metricsregistry_prefixes {
1684    use super::*;
1685    use crate::distributed::distributed_test_utils::create_test_drt_async;
1686    use prometheus::core::Collector;
1687
1688    #[tokio::test]
1689    async fn test_hierarchical_prefixes_and_parent_hierarchies() {
1690        let drt = create_test_drt_async().await;
1691
1692        const DRT_NAME: &str = "";
1693        const NAMESPACE_NAME: &str = "ns901";
1694        const COMPONENT_NAME: &str = "comp901";
1695        const ENDPOINT_NAME: &str = "ep901";
1696        let namespace = drt.namespace(NAMESPACE_NAME).unwrap();
1697        let component = namespace.component(COMPONENT_NAME).unwrap();
1698        let endpoint = component.endpoint(ENDPOINT_NAME);
1699
1700        // DRT
1701        assert_eq!(drt.basename(), DRT_NAME);
1702        assert_eq!(drt.parent_hierarchies().len(), 0);
1703        // DRT hierarchy is just its basename (empty string)
1704
1705        // Namespace
1706        assert_eq!(namespace.basename(), NAMESPACE_NAME);
1707        assert_eq!(namespace.parent_hierarchies().len(), 1);
1708        assert_eq!(namespace.parent_hierarchies()[0].basename(), DRT_NAME);
1709        // Namespace hierarchy is just its basename since parent is empty
1710
1711        // Component
1712        assert_eq!(component.basename(), COMPONENT_NAME);
1713        assert_eq!(component.parent_hierarchies().len(), 2);
1714        assert_eq!(component.parent_hierarchies()[0].basename(), DRT_NAME);
1715        assert_eq!(component.parent_hierarchies()[1].basename(), NAMESPACE_NAME);
1716        // Component hierarchy structure is validated by the individual assertions above
1717
1718        // Endpoint
1719        assert_eq!(endpoint.basename(), ENDPOINT_NAME);
1720        assert_eq!(endpoint.parent_hierarchies().len(), 3);
1721        assert_eq!(endpoint.parent_hierarchies()[0].basename(), DRT_NAME);
1722        assert_eq!(endpoint.parent_hierarchies()[1].basename(), NAMESPACE_NAME);
1723        assert_eq!(endpoint.parent_hierarchies()[2].basename(), COMPONENT_NAME);
1724        // Endpoint hierarchy structure is validated by the individual assertions above
1725
1726        // Relationships
1727        assert!(
1728            namespace
1729                .parent_hierarchies()
1730                .iter()
1731                .any(|h| h.basename() == drt.basename())
1732        );
1733        assert!(
1734            component
1735                .parent_hierarchies()
1736                .iter()
1737                .any(|h| h.basename() == namespace.basename())
1738        );
1739        assert!(
1740            endpoint
1741                .parent_hierarchies()
1742                .iter()
1743                .any(|h| h.basename() == component.basename())
1744        );
1745
1746        // Depth
1747        assert_eq!(drt.parent_hierarchies().len(), 0);
1748        assert_eq!(namespace.parent_hierarchies().len(), 1);
1749        assert_eq!(component.parent_hierarchies().len(), 2);
1750        assert_eq!(endpoint.parent_hierarchies().len(), 3);
1751
1752        // Invalid namespace behavior - sanitizes to "_123" and succeeds
1753        // @ryanolson intended to enable validation (see TODO comment in component.rs) but didn't turn it on,
1754        // so invalid characters are sanitized in MetricsRegistry rather than rejected.
1755        let invalid_namespace = drt.namespace("@@123").unwrap();
1756        let result =
1757            invalid_namespace
1758                .metrics()
1759                .create_counter("test_counter", "A test counter", &[]);
1760        assert!(result.is_ok());
1761        if let Ok(counter) = &result {
1762            // Verify the namespace was sanitized to "_123" in the label
1763            let desc = counter.desc();
1764            let namespace_label = desc[0]
1765                .const_label_pairs
1766                .iter()
1767                .find(|l| l.name() == "dynamo_namespace")
1768                .expect("Should have dynamo_namespace label");
1769            assert_eq!(namespace_label.value(), "_123");
1770        }
1771
1772        // Valid namespace works
1773        let valid_namespace = drt.namespace("ns567").unwrap();
1774        assert!(
1775            valid_namespace
1776                .metrics()
1777                .create_counter("test_counter", "A test counter", &[])
1778                .is_ok()
1779        );
1780    }
1781
1782    #[tokio::test]
1783    async fn test_typed_callback_only_registered_on_endpoint_is_collected_once() {
1784        // The registry tree is traversed once, so a callback registered on the
1785        // endpoint must not be collected again via its parents. Count
1786        // invocations rather than emitted series: the merger drops duplicate
1787        // series, so a double traversal would be invisible in the output.
1788        let drt = create_test_drt_async().await;
1789        let namespace = drt.namespace("ns_typed_ep_only").unwrap();
1790        let component = namespace.component("comp_typed_ep_only").unwrap();
1791        let endpoint = component.endpoint("ep_typed_ep_only");
1792
1793        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1794        let counter = calls.clone();
1795        let callback: PrometheusTypedCallback = Arc::new(move || {
1796            counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1797            let mut family = prometheus::proto::MetricFamily::new();
1798            family.set_name("dynamo_component_active_decode_blocks".to_string());
1799            family.set_field_type(prometheus::proto::MetricType::GAUGE);
1800            let mut metric = prometheus::proto::Metric::new();
1801            let mut label = prometheus::proto::LabelPair::new();
1802            label.set_name("dp_rank".to_string());
1803            label.set_value("0".to_string());
1804            metric.set_label(vec![label]);
1805            metric.set_gauge(prometheus::proto::Gauge::new());
1806            family.mut_metric().push(metric);
1807            Ok(vec![crate::metrics::prom_typed::BuiltFamily {
1808                family,
1809                unit: String::new(),
1810                prom_type: "gauge".to_string(),
1811            }])
1812        });
1813
1814        endpoint.get_metrics_registry().add_typed_callback(callback);
1815
1816        // Typed callbacks feed the OTLP collection, not the exposition path.
1817        let families = drt
1818            .get_metrics_registry()
1819            .metric_families_combined()
1820            .unwrap();
1821
1822        assert_eq!(
1823            calls.load(std::sync::atomic::Ordering::SeqCst),
1824            1,
1825            "endpoint-registered typed callback should be collected once"
1826        );
1827        assert!(
1828            families
1829                .families
1830                .iter()
1831                .any(|f| f.name() == "dynamo_component_active_decode_blocks"),
1832            "typed family missing from the combined collection"
1833        );
1834    }
1835
1836    #[tokio::test]
1837    async fn test_recursive_namespace() {
1838        // Create a distributed runtime for testing
1839        let drt = create_test_drt_async().await;
1840
1841        // Create a deeply chained namespace: ns1.ns2.ns3
1842        let ns1 = drt.namespace("ns1").unwrap();
1843        let ns2 = ns1.namespace("ns2").unwrap();
1844        let ns3 = ns2.namespace("ns3").unwrap();
1845
1846        // Create a component in the deepest namespace
1847        let component = ns3.component("test-component").unwrap();
1848
1849        // Verify the hierarchy structure
1850        assert_eq!(ns1.basename(), "ns1");
1851        assert_eq!(ns1.parent_hierarchies().len(), 1);
1852        assert_eq!(ns1.parent_hierarchies()[0].basename(), "");
1853        // ns1 hierarchy is just its basename since parent is empty
1854
1855        assert_eq!(ns2.basename(), "ns2");
1856        assert_eq!(ns2.parent_hierarchies().len(), 2);
1857        assert_eq!(ns2.parent_hierarchies()[0].basename(), "");
1858        assert_eq!(ns2.parent_hierarchies()[1].basename(), "ns1");
1859        // ns2 hierarchy structure validated by parent assertions above
1860
1861        assert_eq!(ns3.basename(), "ns3");
1862        assert_eq!(ns3.parent_hierarchies().len(), 3);
1863        assert_eq!(ns3.parent_hierarchies()[0].basename(), "");
1864        assert_eq!(ns3.parent_hierarchies()[1].basename(), "ns1");
1865        assert_eq!(ns3.parent_hierarchies()[2].basename(), "ns2");
1866        // ns3 hierarchy structure validated by parent assertions above
1867
1868        assert_eq!(component.basename(), "test-component");
1869        assert_eq!(component.parent_hierarchies().len(), 4);
1870        assert_eq!(component.parent_hierarchies()[0].basename(), "");
1871        assert_eq!(component.parent_hierarchies()[1].basename(), "ns1");
1872        assert_eq!(component.parent_hierarchies()[2].basename(), "ns2");
1873        assert_eq!(component.parent_hierarchies()[3].basename(), "ns3");
1874        // component hierarchy structure validated by parent assertions above
1875
1876        println!("✓ Chained namespace test passed - all prefixes correct");
1877    }
1878}
1879
1880#[cfg(feature = "integration")]
1881#[cfg(test)]
1882mod test_metricsregistry_prometheus_fmt_outputs {
1883    use super::prometheus_names::name_prefix;
1884    use super::*;
1885    use crate::distributed::distributed_test_utils::create_test_drt_async;
1886    use prometheus::Counter;
1887    use std::sync::Arc;
1888
1889    #[tokio::test]
1890    async fn test_prometheusfactory_using_metrics_registry_trait() {
1891        // Setup real DRT and registry using the test-friendly constructor
1892        let drt = create_test_drt_async().await;
1893
1894        // Use a simple constant namespace name
1895        let namespace_name = "ns345";
1896
1897        let namespace = drt.namespace(namespace_name).unwrap();
1898        let component = namespace.component("comp345").unwrap();
1899        let endpoint = component.endpoint("ep345");
1900
1901        // Test Counter creation
1902        let counter = endpoint
1903            .metrics()
1904            .create_counter("testcounter", "A test counter", &[])
1905            .unwrap();
1906        counter.inc_by(123.456789);
1907        let epsilon = 0.01;
1908        assert!((counter.get() - 123.456789).abs() < epsilon);
1909
1910        let endpoint_output_raw = endpoint.metrics().prometheus_expfmt().unwrap();
1911        println!("Endpoint output:");
1912        println!("{}", endpoint_output_raw);
1913
1914        // worker_id is runtime-generated (etcd lease ID), so we grab it from the DRT
1915        // and inject it into expected strings via the inject_worker_id helper.
1916        let wid = format!("{:x}", drt.connection_id());
1917        use super::test_helpers::inject_worker_id;
1918
1919        let expected_endpoint_output = inject_worker_id(
1920            r#"# HELP dynamo_component_testcounter A test counter
1921# TYPE dynamo_component_testcounter counter
1922dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789"#,
1923            &wid,
1924        );
1925
1926        assert_eq!(
1927            endpoint_output_raw.trim_end_matches('\n'),
1928            expected_endpoint_output.trim_end_matches('\n'),
1929            "\n=== ENDPOINT COMPARISON FAILED ===\n\
1930             Actual:\n{}\n\
1931             Expected:\n{}\n\
1932             ==============================",
1933            endpoint_output_raw,
1934            expected_endpoint_output
1935        );
1936
1937        // Test Gauge creation
1938        let gauge = component
1939            .metrics()
1940            .create_gauge("testgauge", "A test gauge", &[])
1941            .unwrap();
1942        gauge.set(50000.0);
1943        assert_eq!(gauge.get(), 50000.0);
1944
1945        // Test Prometheus format output for Component (gauge + histogram)
1946        let component_output_raw = component.metrics().prometheus_expfmt().unwrap();
1947        println!("Component output:");
1948        println!("{}", component_output_raw);
1949
1950        let expected_component_output = inject_worker_id(
1951            r#"# HELP dynamo_component_testcounter A test counter
1952# TYPE dynamo_component_testcounter counter
1953dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1954# HELP dynamo_component_testgauge A test gauge
1955# TYPE dynamo_component_testgauge gauge
1956dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000"#,
1957            &wid,
1958        );
1959
1960        assert_eq!(
1961            component_output_raw.trim_end_matches('\n'),
1962            expected_component_output.trim_end_matches('\n'),
1963            "\n=== COMPONENT COMPARISON FAILED ===\n\
1964             Actual:\n{}\n\
1965             Expected:\n{}\n\
1966             ==============================",
1967            component_output_raw,
1968            expected_component_output
1969        );
1970
1971        let intcounter = namespace
1972            .metrics()
1973            .create_intcounter("testintcounter", "A test int counter", &[])
1974            .unwrap();
1975        intcounter.inc_by(12345);
1976        assert_eq!(intcounter.get(), 12345);
1977
1978        // Test Prometheus format output for Namespace (int_counter + gauge + histogram)
1979        let namespace_output_raw = namespace.metrics().prometheus_expfmt().unwrap();
1980        println!("Namespace output:");
1981        println!("{}", namespace_output_raw);
1982
1983        let expected_namespace_output = inject_worker_id(
1984            r#"# HELP dynamo_component_testcounter A test counter
1985# TYPE dynamo_component_testcounter counter
1986dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
1987# HELP dynamo_component_testgauge A test gauge
1988# TYPE dynamo_component_testgauge gauge
1989dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
1990# HELP dynamo_component_testintcounter A test int counter
1991# TYPE dynamo_component_testintcounter counter
1992dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345"#,
1993            &wid,
1994        );
1995
1996        assert_eq!(
1997            namespace_output_raw.trim_end_matches('\n'),
1998            expected_namespace_output.trim_end_matches('\n'),
1999            "\n=== NAMESPACE COMPARISON FAILED ===\n\
2000             Actual:\n{}\n\
2001             Expected:\n{}\n\
2002             ==============================",
2003            namespace_output_raw,
2004            expected_namespace_output
2005        );
2006
2007        // Test IntGauge creation
2008        let intgauge = namespace
2009            .metrics()
2010            .create_intgauge("testintgauge", "A test int gauge", &[])
2011            .unwrap();
2012        intgauge.set(42);
2013        assert_eq!(intgauge.get(), 42);
2014
2015        // Test IntGaugeVec creation
2016        let intgaugevec = namespace
2017            .metrics()
2018            .create_intgaugevec(
2019                "testintgaugevec",
2020                "A test int gauge vector",
2021                &["instance", "status"],
2022                &[("service", "api")],
2023            )
2024            .unwrap();
2025        intgaugevec
2026            .with_label_values(&["server1", "active"])
2027            .set(10);
2028        intgaugevec
2029            .with_label_values(&["server2", "inactive"])
2030            .set(0);
2031
2032        // Test CounterVec creation
2033        let countervec = endpoint
2034            .metrics()
2035            .create_countervec(
2036                "testcountervec",
2037                "A test counter vector",
2038                &["method", "status"],
2039                &[("service", "api")],
2040            )
2041            .unwrap();
2042        countervec.with_label_values(&["GET", "200"]).inc_by(10.0);
2043        countervec.with_label_values(&["POST", "201"]).inc_by(5.0);
2044
2045        // Test Histogram creation
2046        let histogram = component
2047            .metrics()
2048            .create_histogram("testhistogram", "A test histogram", &[], None)
2049            .unwrap();
2050        histogram.observe(1.0);
2051        histogram.observe(2.5);
2052        histogram.observe(4.0);
2053
2054        // Test Prometheus format output for DRT (all metrics combined)
2055        let drt_output_raw = drt.metrics().prometheus_expfmt().unwrap();
2056        println!("DRT output:");
2057        println!("{}", drt_output_raw);
2058
2059        // The uptime_seconds value is dynamic (depends on elapsed wall-clock time),
2060        // so we check all other lines exactly and validate uptime separately.
2061        let expected_drt_output_without_uptime = inject_worker_id(
2062            r#"# HELP dynamo_component_testcounter A test counter
2063# TYPE dynamo_component_testcounter counter
2064dynamo_component_testcounter{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345"} 123.456789
2065# HELP dynamo_component_testcountervec A test counter vector
2066# TYPE dynamo_component_testcountervec counter
2067dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="GET",service="api",status="200"} 10
2068dynamo_component_testcountervec{dynamo_component="comp345",dynamo_endpoint="ep345",dynamo_namespace="ns345",method="POST",service="api",status="201"} 5
2069# HELP dynamo_component_testgauge A test gauge
2070# TYPE dynamo_component_testgauge gauge
2071dynamo_component_testgauge{dynamo_component="comp345",dynamo_namespace="ns345"} 50000
2072# HELP dynamo_component_testhistogram A test histogram
2073# TYPE dynamo_component_testhistogram histogram
2074dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.005"} 0
2075dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.01"} 0
2076dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.025"} 0
2077dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.05"} 0
2078dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.1"} 0
2079dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.25"} 0
2080dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="0.5"} 0
2081dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="1"} 1
2082dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="2.5"} 2
2083dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="5"} 3
2084dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="10"} 3
2085dynamo_component_testhistogram_bucket{dynamo_component="comp345",dynamo_namespace="ns345",le="+Inf"} 3
2086dynamo_component_testhistogram_sum{dynamo_component="comp345",dynamo_namespace="ns345"} 7.5
2087dynamo_component_testhistogram_count{dynamo_component="comp345",dynamo_namespace="ns345"} 3
2088# HELP dynamo_component_testintcounter A test int counter
2089# TYPE dynamo_component_testintcounter counter
2090dynamo_component_testintcounter{dynamo_namespace="ns345"} 12345
2091# HELP dynamo_component_testintgauge A test int gauge
2092# TYPE dynamo_component_testintgauge gauge
2093dynamo_component_testintgauge{dynamo_namespace="ns345"} 42
2094# HELP dynamo_component_testintgaugevec A test int gauge vector
2095# TYPE dynamo_component_testintgaugevec gauge
2096dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server1",service="api",status="active"} 10
2097dynamo_component_testintgaugevec{dynamo_namespace="ns345",instance="server2",service="api",status="inactive"} 0"#,
2098            &wid,
2099        );
2100
2101        // Split actual output into non-uptime lines and validate the uptime value line.
2102        // The uptime metric now carries a worker_id label, so we match on the metric name
2103        // prefix and extract the value as the last whitespace-delimited token.
2104        let mut non_uptime_lines = Vec::new();
2105        let mut saw_uptime_value = false;
2106        for line in drt_output_raw.trim_end_matches('\n').lines() {
2107            if line.starts_with("dynamo_component_uptime_seconds") && !line.starts_with('#') {
2108                let val_str = line.split_whitespace().last().unwrap();
2109                val_str.parse::<f64>().expect("uptime should be a float");
2110                saw_uptime_value = true;
2111            } else if line.starts_with("# HELP dynamo_component_uptime_seconds")
2112                || line.starts_with("# TYPE dynamo_component_uptime_seconds")
2113            {
2114                // Skip HELP/TYPE lines for uptime (we just verify it exists via the value)
2115            } else {
2116                non_uptime_lines.push(line);
2117            }
2118        }
2119        assert!(
2120            saw_uptime_value,
2121            "uptime_seconds metric should be present in initial scrape"
2122        );
2123
2124        let actual_without_uptime = non_uptime_lines.join("\n");
2125        assert_eq!(
2126            actual_without_uptime,
2127            expected_drt_output_without_uptime.trim_end_matches('\n'),
2128            "\n=== DRT COMPARISON FAILED (excluding uptime) ===\n\
2129             Expected:\n{}\n\
2130             Actual:\n{}\n\
2131             ==============================",
2132            expected_drt_output_without_uptime,
2133            actual_without_uptime
2134        );
2135
2136        // Wait briefly so the uptime gauge is clearly positive on the next scrape.
2137        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2138        let drt_output_after = drt.metrics().prometheus_expfmt().unwrap();
2139        let uptime_line = drt_output_after
2140            .lines()
2141            .find(|l| l.starts_with("dynamo_component_uptime_seconds") && !l.starts_with('#'))
2142            .expect("uptime_seconds metric should be present after sleep");
2143        let uptime_after: f64 = uptime_line
2144            .split_whitespace()
2145            .last()
2146            .unwrap()
2147            .parse()
2148            .expect("uptime should be a float");
2149        assert!(
2150            uptime_after > 0.0,
2151            "uptime_seconds should be > 0 after 10ms sleep, got {}",
2152            uptime_after
2153        );
2154
2155        println!("✓ All Prometheus format outputs verified successfully!");
2156    }
2157
2158    #[test]
2159    fn test_refactored_filter_functions() {
2160        // Test data with component metrics
2161        let test_input = r#"# HELP dynamo_component_requests Total requests
2162# TYPE dynamo_component_requests counter
2163dynamo_component_requests 42
2164# HELP dynamo_component_latency Response latency
2165# TYPE dynamo_component_latency histogram
2166dynamo_component_latency_bucket{le="0.1"} 10
2167dynamo_component_latency_bucket{le="0.5"} 25
2168dynamo_component_errors_total 5"#;
2169
2170        // Test extract_metrics (only actual metric lines, excluding help/type)
2171        let metrics_only = super::test_helpers::extract_metrics(test_input);
2172        assert_eq!(metrics_only.len(), 4); // 4 actual metric lines (excluding help/type)
2173        assert!(
2174            metrics_only
2175                .iter()
2176                .all(|line| line.starts_with("dynamo_component") && !line.starts_with("#"))
2177        );
2178
2179        println!("✓ All refactored filter functions work correctly!");
2180    }
2181
2182    #[tokio::test]
2183    async fn test_same_metric_name_different_endpoints() {
2184        // Test that the same metric name can exist in different endpoints without collision.
2185        // This validates the multi-registry approach: each endpoint has its own registry,
2186        // and metrics are merged at scrape time with distinct labels.
2187        let drt = create_test_drt_async().await;
2188        let namespace = drt.namespace("ns_test").unwrap();
2189        let component = namespace.component("comp_test").unwrap();
2190
2191        // Create two endpoints with the same metric name
2192        let ep1 = component.endpoint("ep1");
2193        let ep2 = component.endpoint("ep2");
2194
2195        let counter1 = ep1
2196            .metrics()
2197            .create_counter("requests_total", "Total requests", &[])
2198            .unwrap();
2199        counter1.inc_by(100.0);
2200
2201        let counter2 = ep2
2202            .metrics()
2203            .create_counter("requests_total", "Total requests", &[])
2204            .unwrap();
2205        counter2.inc_by(200.0);
2206
2207        // Get merged Prometheus output from component level
2208        let output = component.metrics().prometheus_expfmt().unwrap();
2209
2210        let wid = format!("{:x}", drt.connection_id());
2211        use super::test_helpers::inject_worker_id;
2212
2213        let expected_output = inject_worker_id(
2214            r#"# HELP dynamo_component_requests_total Total requests
2215# TYPE dynamo_component_requests_total counter
2216dynamo_component_requests_total{dynamo_component="comp_test",dynamo_endpoint="ep1",dynamo_namespace="ns_test"} 100
2217dynamo_component_requests_total{dynamo_component="comp_test",dynamo_endpoint="ep2",dynamo_namespace="ns_test"} 200"#,
2218            &wid,
2219        );
2220
2221        assert_eq!(
2222            output.trim_end_matches('\n'),
2223            expected_output.trim_end_matches('\n'),
2224            "\n=== MULTI-REGISTRY COMPARISON FAILED ===\n\
2225             Actual:\n{}\n\
2226             Expected:\n{}\n\
2227             ==============================",
2228            output,
2229            expected_output
2230        );
2231
2232        println!("✓ Multi-registry prevents Prometheus collisions!");
2233    }
2234
2235    #[tokio::test]
2236    async fn test_duplicate_series_warning() {
2237        // Test that duplicate series (same metric name + same labels) are detected and deduplicated.
2238        // This should log a warning and keep only one of the duplicate series.
2239        let drt = create_test_drt_async().await;
2240        let namespace = drt.namespace("ns_dup").unwrap();
2241        let component = namespace.component("comp_dup").unwrap();
2242
2243        // Create two endpoints with counters that will have identical labels when scraped
2244        let ep1 = component.endpoint("ep_same");
2245        let ep2 = component.endpoint("ep_same"); // Same endpoint name = duplicate labels
2246
2247        let counter1 = ep1
2248            .metrics()
2249            .create_counter("dup_metric", "Duplicate metric test", &[])
2250            .unwrap();
2251        counter1.inc_by(50.0);
2252
2253        let counter2 = ep2
2254            .metrics()
2255            .create_counter("dup_metric", "Duplicate metric test", &[])
2256            .unwrap();
2257        counter2.inc_by(75.0);
2258
2259        // Get merged output - duplicates should be deduplicated
2260        let output = component.metrics().prometheus_expfmt().unwrap();
2261
2262        let wid = format!("{:x}", drt.connection_id());
2263        use super::test_helpers::inject_worker_id;
2264
2265        let expected_output = inject_worker_id(
2266            r#"# HELP dynamo_component_dup_metric Duplicate metric test
2267# TYPE dynamo_component_dup_metric counter
2268dynamo_component_dup_metric{dynamo_component="comp_dup",dynamo_endpoint="ep_same",dynamo_namespace="ns_dup"} 50"#,
2269            &wid,
2270        );
2271
2272        assert_eq!(
2273            output.trim_end_matches('\n'),
2274            expected_output.trim_end_matches('\n'),
2275            "\n=== DEDUPLICATION COMPARISON FAILED ===\n\
2276             Actual:\n{}\n\
2277             Expected:\n{}\n\
2278             ==============================",
2279            output,
2280            expected_output
2281        );
2282
2283        println!("✓ Duplicate series detection and deduplication works!");
2284    }
2285}
2286
2287#[cfg(test)]
2288mod test_metric_families_combined {
2289    use super::*;
2290    use std::sync::Arc as StdArc;
2291
2292    fn gauge_family(name: &str, help: &str, value: f64) -> prometheus::proto::MetricFamily {
2293        let mut family = prometheus::proto::MetricFamily::new();
2294        family.set_name(name.to_string());
2295        family.set_help(help.to_string());
2296        family.set_field_type(prometheus::proto::MetricType::GAUGE);
2297        let mut metric = prometheus::proto::Metric::new();
2298        let mut gauge = prometheus::proto::Gauge::new();
2299        gauge.set_value(value);
2300        metric.set_gauge(gauge);
2301        family.mut_metric().push(metric);
2302        family
2303    }
2304
2305    fn registry() -> MetricsRegistry {
2306        let registry = MetricsRegistry::new();
2307        let counter = prometheus::IntCounter::new("dynamo_native_total", "Native counter").unwrap();
2308        counter.inc_by(7);
2309        registry
2310            .get_prometheus_registry()
2311            .register(Box::new(counter))
2312            .unwrap();
2313        registry.add_typed_callback(StdArc::new(|| {
2314            Ok(vec![crate::metrics::prom_typed::BuiltFamily {
2315                unit: String::new(),
2316                prom_type: "gauge".to_string(),
2317                family: gauge_family("vllm:num_requests_running", "Running requests", 4.0),
2318            }])
2319        }));
2320        registry
2321    }
2322
2323    fn names(fs: &[prometheus::proto::MetricFamily]) -> Vec<&str> {
2324        fs.iter().map(|f| f.name()).collect()
2325    }
2326
2327    #[test]
2328    fn typed_and_native_families_share_one_collection() {
2329        let collected = registry().metric_families_combined().expect("combined");
2330        assert!(names(&collected.families).contains(&"vllm:num_requests_running"));
2331        assert!(names(&collected.families).contains(&"dynamo_native_total"));
2332    }
2333
2334    /// `units` and `prom_types` are keyed by family name, so a family the
2335    /// merger rejects must not leave its metadata behind: it would then be
2336    /// applied to whichever family did survive under that name. Here the
2337    /// rejected entry claims `info`, which would flip the surviving gauge to a
2338    /// non-monotonic Sum on the OTLP side.
2339    /// The merger resolves a conflict first-writer-wins: the first family
2340    /// fixes help and type and later ones must agree. The metadata maps must
2341    /// resolve the same way. A later family can pass that check and still have
2342    /// every sample dropped as a duplicate series, so a last-writer-wins unit
2343    /// would label the surviving data with a unit from a source that
2344    /// contributed none of it.
2345    #[test]
2346    fn metadata_from_a_source_that_contributed_no_samples_does_not_win() {
2347        let registry = MetricsRegistry::new();
2348        registry.add_typed_callback(StdArc::new(|| {
2349            Ok(vec![
2350                crate::metrics::prom_typed::BuiltFamily {
2351                    unit: "bytes".to_string(),
2352                    prom_type: "gauge".to_string(),
2353                    family: gauge_family("vllm:probe", "Same help", 1.0),
2354                },
2355                // Same name, help and type, so the merger accepts it -- but the
2356                // labels match too, so every sample is dropped as a duplicate.
2357                crate::metrics::prom_typed::BuiltFamily {
2358                    unit: "seconds".to_string(),
2359                    prom_type: "gauge".to_string(),
2360                    family: gauge_family("vllm:probe", "Same help", 2.0),
2361                },
2362            ])
2363        }));
2364
2365        let collected = registry.metric_families_combined().expect("combined");
2366
2367        let family = collected
2368            .families
2369            .iter()
2370            .find(|f| f.name() == "vllm:probe")
2371            .expect("family");
2372        assert_eq!(
2373            family.get_metric()[0].get_gauge().value(),
2374            1.0,
2375            "the surviving sample should be the first source's"
2376        );
2377        assert_eq!(
2378            collected.units.get("vllm:probe").map(String::as_str),
2379            Some("bytes"),
2380            "unit came from a source whose samples were all dropped"
2381        );
2382    }
2383
2384    #[test]
2385    fn rejected_family_leaves_no_metadata_behind() {
2386        let registry = MetricsRegistry::new();
2387        registry.add_typed_callback(StdArc::new(|| {
2388            Ok(vec![
2389                crate::metrics::prom_typed::BuiltFamily {
2390                    unit: String::new(),
2391                    prom_type: "gauge".to_string(),
2392                    family: gauge_family("vllm:cache_usage", "Cache usage", 0.5),
2393                },
2394                // Same name, different help -> rejected by the merger.
2395                crate::metrics::prom_typed::BuiltFamily {
2396                    unit: "seconds".to_string(),
2397                    prom_type: "info".to_string(),
2398                    family: gauge_family("vllm:cache_usage", "A different help", 1.0),
2399                },
2400            ])
2401        }));
2402
2403        let collected = registry.metric_families_combined().expect("combined");
2404
2405        assert_eq!(
2406            collected
2407                .prom_types
2408                .get("vllm:cache_usage")
2409                .map(String::as_str),
2410            Some("gauge"),
2411            "the rejected family's type overwrote the accepted family's"
2412        );
2413        assert!(
2414            !collected.units.contains_key("vllm:cache_usage"),
2415            "the rejected family's unit was published for a family that has none"
2416        );
2417    }
2418
2419    /// The two surfaces are fed independently: typed callbacks reach OTLP,
2420    /// exposition-text callbacks reach `/metrics`. A registry that registers
2421    /// only one appears on only that surface -- which is why the Python
2422    /// helpers always register both.
2423    #[test]
2424    fn typed_callbacks_feed_otlp_and_not_the_scrape() {
2425        let registry = registry();
2426
2427        let text = registry.prometheus_expfmt_combined().expect("text");
2428        assert!(
2429            text.contains("dynamo_native_total"),
2430            "native metrics must still render on /metrics"
2431        );
2432        assert!(
2433            !text.contains("vllm:num_requests_running"),
2434            "typed callbacks feed OTLP only; /metrics is fed by expfmt callbacks"
2435        );
2436
2437        registry.add_expfmt_callback(StdArc::new(|| {
2438            Ok("# HELP vllm:num_requests_running Running requests\n\
2439                # TYPE vllm:num_requests_running gauge\n\
2440                vllm:num_requests_running 4\n"
2441                .to_string())
2442        }));
2443        let text = registry.prometheus_expfmt_combined().expect("text");
2444        assert!(
2445            text.contains("vllm:num_requests_running"),
2446            "engine exposition text must be appended verbatim"
2447        );
2448    }
2449
2450    /// Collection must not hold the callback lock while invoking callbacks.
2451    ///
2452    /// Registration arrives from Python holding the GIL and blocks on
2453    /// `write()`; a collection that held the read lock while calling into
2454    /// Python would deadlock the two against each other. Registering from
2455    /// inside a callback reproduces that ordering deterministically, without
2456    /// depending on a thread interleaving.
2457    ///
2458    /// Run on a worker thread with a deadline so a regression fails the test
2459    /// rather than hanging the suite forever.
2460    #[test]
2461    fn collection_does_not_hold_the_callback_lock() {
2462        for (name, collect) in [
2463            (
2464                "typed",
2465                Box::new(|r: &MetricsRegistry| {
2466                    r.execute_typed_callbacks();
2467                }) as Box<dyn Fn(&MetricsRegistry) + Send>,
2468            ),
2469            (
2470                "expfmt",
2471                Box::new(|r: &MetricsRegistry| {
2472                    r.execute_expfmt_callbacks();
2473                }),
2474            ),
2475        ] {
2476            let (tx, rx) = std::sync::mpsc::channel();
2477            std::thread::spawn(move || {
2478                let registry = MetricsRegistry::new();
2479                let reentrant = registry.clone();
2480                registry.add_typed_callback(StdArc::new(move || {
2481                    reentrant.add_typed_callback(StdArc::new(|| Ok(Vec::new())));
2482                    Ok(Vec::new())
2483                }));
2484                let reentrant = registry.clone();
2485                registry.add_expfmt_callback(StdArc::new(move || {
2486                    reentrant.add_expfmt_callback(StdArc::new(|| Ok(String::new())));
2487                    Ok(String::new())
2488                }));
2489                collect(&registry);
2490                let _ = tx.send(());
2491            });
2492
2493            assert!(
2494                rx.recv_timeout(std::time::Duration::from_secs(10)).is_ok(),
2495                "{name} collection deadlocked: the callback lock was held while a \
2496                 callback registered another"
2497            );
2498        }
2499    }
2500
2501    /// A failing engine callback is skipped, never fatal: one broken engine
2502    /// must not empty the collection for every other.
2503    #[test]
2504    fn failing_typed_callback_is_skipped() {
2505        let registry = MetricsRegistry::new();
2506        registry.add_typed_callback(StdArc::new(|| anyhow::bail!("engine exploded")));
2507        assert!(
2508            registry
2509                .metric_families_combined()
2510                .expect("collection survives")
2511                .families
2512                .is_empty()
2513        );
2514    }
2515}