faucet-core 1.13.2

Shared types, traits, and utilities for the faucet-stream ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Idempotent global installer for the Prometheus recorder and a
//! `tracing-subscriber`. Safe to call more than once; subsequent calls warn
//! and continue rather than panicking. Port-in-use becomes a typed error.

use thiserror::Error;

/// Configuration for `install_observability`. Either or both sections may be
/// `None`; unset sections install nothing.
#[derive(Debug, Clone, Default)]
pub struct ObservabilityConfig {
    pub prometheus: Option<PrometheusConfig>,
    pub tracing: Option<TracingConfig>,
    pub otel: Option<crate::observability::otel::OtelConfig>,
}

/// Which metrics recorder to install given which exporters are requested.
/// Only consulted by `install_observability`, which itself requires the recorder
/// machinery, so it's gated on the same feature.
#[cfg(feature = "observability-install")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MetricsMode {
    None,
    PrometheusOnly,
    OtelOnly,
    Fanout,
}

#[cfg(feature = "observability-install")]
impl MetricsMode {
    pub(crate) fn select(prometheus: bool, otel_metrics: bool) -> Self {
        match (prometheus, otel_metrics) {
            (true, true) => MetricsMode::Fanout,
            (true, false) => MetricsMode::PrometheusOnly,
            (false, true) => MetricsMode::OtelOnly,
            (false, false) => MetricsMode::None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct PrometheusConfig {
    /// `host:port` to bind a `/metrics` HTTP endpoint. Recommended:
    /// `127.0.0.1:9464`.
    pub listen: String,
    /// Histogram bucket overrides (in seconds). When `None`, sensible defaults
    /// apply (0.001..300s spanning sub-ms through five-minute durations).
    pub buckets: Option<Vec<f64>>,
}

#[derive(Debug, Clone)]
pub struct TracingConfig {
    /// `EnvFilter`-style directive, e.g. `"info"` or `"faucet_core=debug,info"`.
    pub level: String,
}

/// Report from `install_observability` so callers can log what actually
/// happened (recorder installed vs. already-installed vs. disabled).
#[derive(Debug, Clone, Default)]
pub struct InstallReport {
    pub prometheus_listen: Option<String>,
    pub prometheus_already_installed: bool,
    pub tracing_already_installed: bool,
    pub otel_installed: bool,
    pub otel_signals: Vec<&'static str>,
}

#[derive(Debug, Error)]
pub enum InstallError {
    #[error("failed to bind Prometheus listener at {listen}: {source}")]
    PrometheusBind {
        listen: String,
        #[source]
        source: std::io::Error,
    },
    #[error("failed to install Prometheus recorder: {0}")]
    PrometheusInstall(String),
}

/// Install observability if requested. Always returns; never panics.
///
/// Behavior:
/// - If `prometheus` is set, builds a `PrometheusBuilder` and installs the
///   recorder + HTTP `/metrics` endpoint at the configured listen address.
///   Already-installed recorder (typed `BuildError::FailedToSetGlobalRecorder`)
///   is logged via `tracing::warn!` and continues. Listen-address parse failures
///   and HTTP-listener bind failures (e.g. port-in-use, typed
///   `BuildError::FailedToCreateHTTPListener`) return `InstallError::PrometheusBind`.
/// - If `tracing` is set, installs a `tracing-subscriber` registry with the
///   given env-filter directive as the default subscriber. Already-set-default
///   is logged via `tracing::warn!` and continues.
/// - OTLP export (feature `otel`) needs a tokio runtime; called outside one it
///   is skipped with a warning.
#[cfg(feature = "observability-install")]
pub fn install_observability(cfg: &ObservabilityConfig) -> Result<InstallReport, InstallError> {
    let mut report = InstallReport::default();

    // The OTLP exporters (and the fanout's `/metrics` task) need a tokio
    // runtime; outside one, skip OTLP rather than panic.
    #[cfg(feature = "otel")]
    let without_otel;
    #[cfg(feature = "otel")]
    let cfg = if cfg.otel.is_some() && tokio::runtime::Handle::try_current().is_err() {
        tracing::warn!("OTLP export needs a tokio runtime; install_observability skips it");
        without_otel = ObservabilityConfig {
            otel: None,
            ..cfg.clone()
        };
        &without_otel
    } else {
        cfg
    };

    // Provider holders moved into the guard after both arms run; only populated
    // (and only referenced) when the `otel` feature is enabled.
    #[cfg(feature = "otel")]
    let mut otel_tracer: Option<opentelemetry_sdk::trace::SdkTracerProvider> = None;

    // --- Metrics ---
    #[cfg(feature = "otel")]
    let otel_metrics = cfg
        .otel
        .as_ref()
        .map(|o| o.exports(crate::observability::otel::OtelSignal::Metrics))
        .unwrap_or(false);
    #[cfg(not(feature = "otel"))]
    let otel_metrics = false;

    let mode = MetricsMode::select(cfg.prometheus.is_some(), otel_metrics);

    // Declared so the trace arm + guard step can move them; only used under otel.
    #[cfg(feature = "otel")]
    let mut otel_meter: Option<opentelemetry_sdk::metrics::SdkMeterProvider> = None;

    match mode {
        MetricsMode::None => {}
        MetricsMode::PrometheusOnly => {
            install_prometheus_only(cfg.prometheus.as_ref().unwrap(), &mut report)?;
        }
        #[cfg(feature = "otel")]
        MetricsMode::OtelOnly => {
            if let Some(otel) = cfg.otel.as_ref() {
                match crate::observability::otel::build_meter_provider(otel) {
                    Ok((mp, recorder)) => {
                        if metrics::set_global_recorder(recorder).is_err() {
                            tracing::warn!(
                                "metrics recorder already installed; OTLP metrics are not exported"
                            );
                        } else {
                            otel_meter = Some(mp);
                            report.otel_signals.push("metrics");
                        }
                    }
                    Err(e) => tracing::warn!("OTLP metrics exporter init failed; skipping: {e}"),
                }
            }
        }
        #[cfg(feature = "otel")]
        MetricsMode::Fanout => {
            install_fanout(
                cfg.prometheus.as_ref().unwrap(),
                cfg.otel.as_ref().unwrap(),
                &mut report,
                &mut otel_meter,
            )?;
        }
        #[cfg(not(feature = "otel"))]
        MetricsMode::OtelOnly | MetricsMode::Fanout => {
            unreachable!("otel metrics mode selected without the otel feature")
        }
    }

    // --- Traces ---
    #[cfg(feature = "otel")]
    let otel_traces = cfg
        .otel
        .as_ref()
        .is_some_and(|o| o.exports(crate::observability::otel::OtelSignal::Traces));
    #[cfg(not(feature = "otel"))]
    let otel_traces = false;
    if cfg.tracing.is_some() || otel_traces {
        use tracing_subscriber::EnvFilter;
        use tracing_subscriber::layer::SubscriberExt;
        use tracing_subscriber::util::SubscriberInitExt;

        let level = cfg.tracing.as_ref().map_or("info", |t| t.level.as_str());
        let make_filter = || EnvFilter::try_new(level).unwrap_or_else(|_| EnvFilter::new("info"));

        // Reassigned only in the `otel` branch below; without that feature the
        // `mut` is genuinely unused.
        #[cfg_attr(not(feature = "otel"), allow(unused_mut))]
        let mut installed = false;

        #[cfg(feature = "otel")]
        if let (true, Some(otel)) = (otel_traces, cfg.otel.as_ref()) {
            if crate::observability::otel::tracer_installed() {
                installed = true;
            } else {
                match crate::observability::otel::build_trace_provider(otel) {
                    Ok(tp) => {
                        use opentelemetry::trace::TracerProvider as _;
                        use tracing_subscriber::Layer as _;
                        let tracer = tp.tracer("faucet");
                        crate::observability::otel::install_propagator();
                        let layer: crate::observability::otel::TraceLayer = Box::new(
                            tracing_opentelemetry::layer()
                                .with_tracer(tracer)
                                .and_then(crate::observability::otel::OtelErrorCountLayer),
                        );
                        // A host that installed its own subscriber first (the CLI)
                        // registered a slot for exactly this layer.
                        match crate::observability::otel::fill_trace_slot(layer) {
                            Ok(()) => {
                                report.otel_signals.push("traces");
                                otel_tracer = Some(tp);
                            }
                            Err(layer) => {
                                let reg = tracing_subscriber::registry()
                                    .with(layer)
                                    .with(make_filter())
                                    .with(tracing_subscriber::fmt::layer());
                                if reg.try_init().is_err() {
                                    tracing::warn!(
                                        "tracing subscriber already installed and no trace \
                                         layer slot registered; OTLP traces are not exported"
                                    );
                                    report.tracing_already_installed = true;
                                    // No otel layer was installed, so DON'T store the
                                    // provider — let `tp` drop to shut its exporter down.
                                } else {
                                    report.otel_signals.push("traces");
                                    otel_tracer = Some(tp);
                                }
                            }
                        }
                        installed = true;
                    }
                    Err(e) => tracing::warn!("OTLP trace exporter init failed; logs-only: {e}"),
                }
            }
        }

        if !installed {
            // Install the OTLP export-error counter layer whenever ANY otel
            // signal is exported — not only when a trace layer was installed —
            // so `faucet_otel_export_failures_total` still fires under
            // `otel.export: [metrics]` (audit #321 L7). `Option<Layer>` is a
            // no-op when `None`, so this composes for the non-otel build too.
            #[cfg(feature = "otel")]
            let otel_error_layer = cfg
                .otel
                .as_ref()
                .map(|o| {
                    o.exports(crate::observability::otel::OtelSignal::Traces)
                        || o.exports(crate::observability::otel::OtelSignal::Metrics)
                })
                .unwrap_or(false)
                .then_some(crate::observability::otel::OtelErrorCountLayer);
            #[cfg(not(feature = "otel"))]
            let otel_error_layer: Option<tracing_subscriber::layer::Identity> = None;

            let reg = tracing_subscriber::registry()
                .with(make_filter())
                .with(tracing_subscriber::fmt::layer())
                .with(otel_error_layer);
            if reg.try_init().is_err() {
                // Some other code path has already set a global default. Log and
                // continue — observability still works through the previously-
                // installed subscriber.
                tracing::warn!("tracing subscriber already installed; continuing");
                report.tracing_already_installed = true;
            }
        }
    }

    // --- OTel guard + describe ---
    #[cfg(feature = "otel")]
    {
        if otel_tracer.is_some() || otel_meter.is_some() {
            crate::observability::otel::describe();
            let _ = crate::observability::otel::set_guard(crate::observability::otel::OtelGuard {
                tracer: otel_tracer,
                meter: otel_meter,
            });
            report.otel_installed = true;
        }
    }

    // Register metric HELP text + build_info after any Prometheus install
    // attempt — describe!()/set!() into a not-yet-installed recorder is a no-op,
    // so we order them last.
    crate::observability::resilience::describe();
    crate::observability::cleanup::describe();
    crate::observability::drift::describe();
    crate::observability::describe_roundtrip_metrics();
    register_build_info();

    Ok(report)
}

/// Install the Prometheus recorder + `/metrics` HTTP endpoint as the sole
/// global recorder. Extracted verbatim from the original metrics arm so the
/// fanout / otel-only paths can choose a different recorder.
#[cfg(feature = "observability-install")]
fn install_prometheus_only(
    p: &PrometheusConfig,
    report: &mut InstallReport,
) -> Result<(), InstallError> {
    use metrics_exporter_prometheus::{BuildError, PrometheusBuilder};

    let listen: std::net::SocketAddr =
        p.listen
            .parse()
            .map_err(|e: std::net::AddrParseError| InstallError::PrometheusBind {
                listen: p.listen.clone(),
                source: std::io::Error::new(std::io::ErrorKind::InvalidInput, e.to_string()),
            })?;

    const DEFAULT_BUCKETS: &[f64] = &[
        0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 30.0, 60.0, 300.0,
    ];
    let buckets = p.buckets.as_deref().unwrap_or(DEFAULT_BUCKETS);

    let builder = PrometheusBuilder::new()
        .with_http_listener(listen)
        .set_buckets(buckets)
        .map_err(|e| InstallError::PrometheusInstall(e.to_string()))?;

    match builder.install() {
        Ok(()) => report.prometheus_listen = Some(p.listen.clone()),
        // Match the TYPED `BuildError` variant rather than scraping its
        // Display string — the latter breaks silently if the upstream
        // wording changes.
        Err(e) => match e {
            // Recorder already installed (e.g. a prior `install` call or a
            // test harness). Idempotent: warn and continue.
            BuildError::FailedToSetGlobalRecorder(_) => {
                tracing::warn!("Prometheus recorder already installed; continuing");
                report.prometheus_already_installed = true;
            }
            // The HTTP `/metrics` listener could not bind. This is where a
            // genuine bind failure (e.g. EADDRINUSE / port-in-use) lands,
            // since the real `TcpListener::bind` happens inside `install()`,
            // not in the address parse above. Surface it as the dedicated
            // bind error so port-in-use is reported correctly.
            BuildError::FailedToCreateHTTPListener(msg) => {
                return Err(InstallError::PrometheusBind {
                    listen: p.listen.clone(),
                    source: std::io::Error::other(msg),
                });
            }
            other => return Err(InstallError::PrometheusInstall(other.to_string())),
        },
    }
    Ok(())
}

/// Install a `metrics-util` fanout recorder dispatching to BOTH a Prometheus
/// recorder (with its `/metrics` HTTP endpoint) and an OTLP metrics recorder,
/// so both coexist. If the OTLP exporter fails to build, falls back to a
/// Prometheus-only recorder so `/metrics` still works — export never fails the
/// process.
#[cfg(all(feature = "observability-install", feature = "otel"))]
fn install_fanout(
    p: &PrometheusConfig,
    otel: &crate::observability::otel::OtelConfig,
    report: &mut InstallReport,
    otel_meter: &mut Option<opentelemetry_sdk::metrics::SdkMeterProvider>,
) -> Result<(), InstallError> {
    use metrics_exporter_prometheus::{BuildError, PrometheusBuilder};
    use metrics_util::layers::FanoutBuilder;

    let listen: std::net::SocketAddr =
        p.listen
            .parse()
            .map_err(|e: std::net::AddrParseError| InstallError::PrometheusBind {
                listen: p.listen.clone(),
                source: std::io::Error::new(std::io::ErrorKind::InvalidInput, e.to_string()),
            })?;
    const DEFAULT_BUCKETS: &[f64] = &[
        0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 30.0, 60.0, 300.0,
    ];
    let buckets = p.buckets.as_deref().unwrap_or(DEFAULT_BUCKETS);

    // build() returns (recorder, /metrics exporter future) WITHOUT setting the
    // global recorder, so we can fan it out.
    let (prom_recorder, prom_exporter) = PrometheusBuilder::new()
        .with_http_listener(listen)
        .set_buckets(buckets)
        .map_err(|e| InstallError::PrometheusInstall(e.to_string()))?
        .build()
        .map_err(|e| match e {
            BuildError::FailedToCreateHTTPListener(msg) => InstallError::PrometheusBind {
                listen: p.listen.clone(),
                source: std::io::Error::other(msg),
            },
            other => InstallError::PrometheusInstall(other.to_string()),
        })?;

    match crate::observability::otel::build_meter_provider(otel) {
        Ok((mp, otel_recorder)) => {
            let fanout = FanoutBuilder::default()
                .add_recorder(prom_recorder)
                .add_recorder(otel_recorder)
                .build();
            if metrics::set_global_recorder(fanout).is_err() {
                tracing::warn!("metrics recorder already installed; continuing");
                report.prometheus_already_installed = true;
            } else {
                report.prometheus_listen = Some(p.listen.clone());
                report.otel_signals.push("metrics");
                *otel_meter = Some(mp);
                tokio::spawn(prom_exporter);
            }
        }
        Err(e) => {
            // OTLP metrics init failed — fall back to Prometheus-only so /metrics
            // still works; export never fails the process.
            tracing::warn!("OTLP metrics exporter init failed; Prometheus-only: {e}");
            if metrics::set_global_recorder(prom_recorder).is_err() {
                report.prometheus_already_installed = true;
            } else {
                report.prometheus_listen = Some(p.listen.clone());
                tokio::spawn(prom_exporter);
            }
        }
    }
    Ok(())
}

/// Install, as the global metrics recorder, a fanout to `prometheus` — a
/// recorder the host built (e.g. `PrometheusBuilder::build_recorder`) and
/// renders through its own handle — and an OTLP metrics exporter built from
/// `otel`. For a host such as an HTTP server that serves `/metrics` itself and
/// so cannot use [`install_observability`]'s listener.
///
/// Returns `Ok(true)` when OTLP metrics are exported, `Ok(false)` when the
/// exporter could not be built (the Prometheus recorder is installed alone, so
/// `/metrics` keeps working), and an error when a global recorder is already
/// installed. The meter provider lives for the process and is flushed by
/// [`shutdown_otel`](crate::observability::otel::shutdown_otel).
#[cfg(all(feature = "observability-install", feature = "otel"))]
pub fn install_prometheus_with_otel_metrics(
    prometheus: metrics_exporter_prometheus::PrometheusRecorder,
    otel: &crate::observability::otel::OtelConfig,
) -> Result<bool, InstallError> {
    use metrics_util::layers::FanoutBuilder;
    let already =
        || InstallError::PrometheusInstall("a metrics recorder is already installed".into());
    match crate::observability::otel::build_meter_provider(otel) {
        Ok((mp, otel_recorder)) => {
            let fanout = FanoutBuilder::default()
                .add_recorder(prometheus)
                .add_recorder(otel_recorder)
                .build();
            metrics::set_global_recorder(fanout).map_err(|_| already())?;
            crate::observability::otel::keep_meter_provider(mp);
            crate::observability::otel::describe();
            Ok(true)
        }
        Err(e) => {
            tracing::warn!("OTLP metrics exporter init failed; Prometheus-only: {e}");
            metrics::set_global_recorder(prometheus).map_err(|_| already())?;
            Ok(false)
        }
    }
}

/// Non-`observability-install` stub. Returns an empty report, never panics.
#[cfg(not(feature = "observability-install"))]
pub fn install_observability(_cfg: &ObservabilityConfig) -> Result<InstallReport, InstallError> {
    crate::observability::resilience::describe();
    crate::observability::cleanup::describe();
    crate::observability::drift::describe();
    crate::observability::describe_roundtrip_metrics();
    crate::observability::otel::describe();
    register_build_info();
    Ok(InstallReport::default())
}

/// The version [`register_build_info`] reports, when an application set one.
static BUILD_VERSION: std::sync::OnceLock<&'static str> = std::sync::OnceLock::new();

/// Set the version the `faucet_build_info{version}` gauge reports — call it
/// with the **binary's** own `env!("CARGO_PKG_VERSION")` before installing
/// observability. Without it the label is `faucet-core`'s version, which
/// differs from the binary's whenever only the binary was released (#832).
///
/// First call wins (a process has one build); returns `false` when a version
/// was already set. Re-registers the gauge so a recorder installed before
/// this call reports the new version too.
pub fn set_build_version(version: &'static str) -> bool {
    let first = BUILD_VERSION.set(version).is_ok();
    if first {
        register_build_info();
    }
    first
}

/// The version `faucet_build_info` reports: the one passed to
/// [`set_build_version`], else `faucet-core`'s `CARGO_PKG_VERSION`.
pub fn build_version() -> &'static str {
    BUILD_VERSION
        .get()
        .copied()
        .unwrap_or(env!("CARGO_PKG_VERSION"))
}

/// Register the `faucet_build_info{version}` gauge (set to 1) under the
/// currently-installed `metrics` recorder. Safe to call from any code path
/// that wants to ensure the gauge is set; `install_observability` invokes
/// this automatically. Gauges are naturally idempotent under the `metrics`
/// model — repeat calls just re-set the same value.
///
/// The version label is [`build_version`]: the application's version when it
/// called [`set_build_version`] (the `faucet` CLI does), else `faucet-core`'s.
/// Dashboards `group_left` the gauge onto every other metric to annotate
/// panels with the running version.
pub fn register_build_info() {
    metrics::gauge!(
        "faucet_build_info",
        "version" => build_version(),
    )
    .set(1.0);
}

#[cfg(all(test, feature = "observability-install"))]
mod tests {
    use super::*;
    use std::sync::Mutex;

    static LOCK: Mutex<()> = Mutex::new(());

    #[cfg(feature = "otel")]
    #[test]
    fn otlp_outside_a_runtime_is_skipped_not_a_panic() {
        let cfg = ObservabilityConfig {
            otel: Some(crate::observability::otel::OtelConfig::default()),
            ..Default::default()
        };
        let report = install_observability(&cfg).expect("no runtime is not an error");
        assert!(report.otel_signals.is_empty());
        assert!(!report.prometheus_already_installed);
    }

    #[test]
    fn metrics_mode_selection() {
        use super::MetricsMode;
        assert_eq!(MetricsMode::select(true, true), MetricsMode::Fanout);
        assert_eq!(
            MetricsMode::select(true, false),
            MetricsMode::PrometheusOnly
        );
        assert_eq!(MetricsMode::select(false, true), MetricsMode::OtelOnly);
        assert_eq!(MetricsMode::select(false, false), MetricsMode::None);
    }

    #[test]
    fn no_config_returns_empty_report() {
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let r = install_observability(&ObservabilityConfig::default()).unwrap();
        assert!(r.prometheus_listen.is_none());
        assert!(!r.prometheus_already_installed);
        assert!(!r.tracing_already_installed);
    }

    #[test]
    fn malformed_listen_returns_bind_error() {
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let cfg = ObservabilityConfig {
            prometheus: Some(PrometheusConfig {
                listen: "not-a-socket".into(),
                buckets: None,
            }),
            tracing: None,
            otel: None,
        };
        match install_observability(&cfg) {
            Err(InstallError::PrometheusBind { .. }) => {}
            other => panic!("expected PrometheusBind error, got {other:?}"),
        }
    }

    #[test]
    fn register_build_info_is_callable_and_idempotent() {
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Gauges are idempotent under the metrics model; repeat calls must not
        // panic regardless of which recorder (if any) is installed.
        register_build_info();
        register_build_info();
    }

    #[test]
    fn install_prometheus_and_tracing_returns_ok() {
        // Drive the full prometheus + tracing install path on an ephemeral
        // port. The recorder + subscriber are process-global: depending on
        // test ordering, the recorder either installs fresh (Ok path) or is
        // already installed (idempotent warn path). Either way the call must
        // return Ok and never panic, and the report must reflect what happened.
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let cfg = ObservabilityConfig {
            prometheus: Some(PrometheusConfig {
                listen: "127.0.0.1:0".into(),
                // Exercise the explicit-buckets branch.
                buckets: Some(vec![0.01, 0.1, 1.0]),
            }),
            tracing: Some(TracingConfig {
                level: "info".into(),
            }),
            otel: None,
        };
        let report = install_observability(&cfg).expect("install must return Ok");
        // Exactly one of: recorder installed (listen set) OR already installed.
        assert!(
            report.prometheus_listen.is_some() || report.prometheus_already_installed,
            "prometheus install must either bind or report already-installed"
        );
    }

    #[test]
    fn install_tracing_with_invalid_directive_falls_back_to_info() {
        // An unparseable EnvFilter directive must not error — it silently falls
        // back to "info". The call returns Ok regardless of subscriber state.
        let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let cfg = ObservabilityConfig {
            prometheus: None,
            tracing: Some(TracingConfig {
                // Garbage directive → try_new errors → fallback to info.
                level: "this is !!! not a valid filter".into(),
            }),
            otel: None,
        };
        install_observability(&cfg).expect("invalid tracing directive must not fail install");
    }
}