Skip to main content

modelexpress_server/
metrics.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Prometheus exposition for the ModelExpress server.
5//!
6//! Before this module the server had no metrics surface at all, and the Helm
7//! chart's `prometheus.io/port` annotation pointed at the tonic gRPC listener.
8//! tonic speaks HTTP/2 only, so Prometheus's HTTP/1.1 `GET /metrics` could never
9//! succeed and every server pod reported `up == 0` permanently — worse than no
10//! annotation, because a permanently-down target is indistinguishable from a
11//! crashed pod. This module provides the listener that annotation should have
12//! been pointing at; [`crate::server::run_server`] starts it and the chart is
13//! repointed in the same change.
14//!
15//! A subsystem is added by adding a module under `metrics/` that takes a
16//! sub-registry (`registry.sub_registry_with_prefix("p2p")`) and registers its
17//! own families, so a module cannot emit a family name outside its segment.
18//!
19//! # Constraints this module is written against
20//!
21//! - The workspace denies `clippy::unwrap_used` and `clippy::expect_used`, which
22//!   rules out the `lazy_static! { register_int_counter!(..).unwrap() }` idiom of
23//!   the tikv `prometheus` crate. `prometheus_client`'s registration and
24//!   `get_or_create` are infallible, so nothing here needs to panic.
25//! - The workspace denies `clippy::mod_module_files`, so this is `metrics.rs`
26//!   plus a `metrics/` directory, never `metrics/mod.rs`.
27//! - Collection must never be scrape-time-expensive. Anything derived from a
28//!   Redis `SCAN` or a similar keyspace walk belongs in a refresh task that
29//!   writes a plain gauge; the scrape only encodes what is already in memory.
30
31pub mod backend;
32pub mod buckets;
33pub mod cache;
34pub mod exposition;
35pub mod grpc;
36pub mod registry;
37
38use prometheus_client::encoding::EncodeLabelSet;
39use prometheus_client::encoding::text::encode;
40use prometheus_client::metrics::family::Family;
41use prometheus_client::metrics::gauge::Gauge;
42use prometheus_client::registry::Registry;
43
44use crate::backend_config::BackendConfig;
45
46pub use exposition::serve;
47
48/// Content type for the OpenMetrics text exposition format written by
49/// `prometheus_client`. Prometheus negotiates OpenMetrics when offered it and
50/// falls back to its own text parser otherwise; that parser treats the trailing
51/// `# EOF` line as a comment, so this response is readable either way.
52pub const OPENMETRICS_CONTENT_TYPE: &str =
53    "application/openmetrics-text; version=1.0.0; charset=utf-8";
54
55/// Namespace prefix applied to every family the server exports.
56const NAMESPACE: &str = "mx";
57
58/// Create the server's registry, rooted at the `mx` namespace.
59///
60/// Populated during startup and then shared read-only with the exposition task,
61/// so a scrape only ever reads.
62#[must_use]
63pub fn new_registry() -> Registry {
64    Registry::with_prefix(NAMESPACE)
65}
66
67/// Encode the current values in the OpenMetrics text format.
68///
69/// # Errors
70/// Returns [`std::fmt::Error`] if the encoder fails to write into the buffer.
71pub fn encode_text(registry: &Registry) -> Result<String, std::fmt::Error> {
72    let mut buffer = String::new();
73    encode(&mut buffer, registry)?;
74    Ok(buffer)
75}
76
77/// Process constants carried by `mx_build_info`.
78///
79/// Every field is fixed for the lifetime of the process, so this family has
80/// exactly one series per pod.
81#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
82pub struct BuildInfoLabels {
83    /// Which half of ModelExpress is reporting: `server` here, `client` from the
84    /// Python collector. Component identity is carried by this label rather than
85    /// by a family-name suffix, so family names stay globally unique.
86    pub component: &'static str,
87    /// Crate version, from `CARGO_PKG_VERSION` at compile time.
88    pub version: &'static str,
89    /// Metadata backend in use: `redis`, `kubernetes`, or `memory`.
90    pub backend: String,
91    /// Benchmark run label from `MX_METRICS_SCHEME`; empty when unset.
92    pub scheme: String,
93}
94
95/// Register `mx_build_info` on `registry` and set it to 1.
96///
97/// Two jobs. It is the exporter's **proof of life** — registered unconditionally
98/// at startup, so a successful scrape shows the endpoint came up even on a
99/// server that has served no traffic. And it is the **join target** for the
100/// process constants (version, backend, scheme), which are therefore not labels
101/// on every other family.
102///
103/// A `Gauge` set to 1, deliberately not an `Info`: under `prometheus_client`
104/// multiprocess mode on the Python side an `Info` writes no file, exposes
105/// nothing, and raises nothing, so it would pass its own health check while
106/// silently emptying every `group_left` join. Keeping both halves on the same
107/// representation means one PromQL expression works against either.
108///
109/// Nothing is returned — the registry holds its own clone of the `Arc`-backed
110/// family, and every label is a process constant, so there is never a later
111/// update.
112pub fn register_build_info(registry: &mut Registry, backend: &BackendConfig) {
113    let family = Family::<BuildInfoLabels, Gauge>::default();
114    registry.register(
115        "build_info",
116        "Build and deployment constants for this process; always 1",
117        family.clone(),
118    );
119    family
120        .get_or_create(&BuildInfoLabels {
121            component: "server",
122            version: env!("CARGO_PKG_VERSION"),
123            backend: backend.to_string(),
124            scheme: modelexpress_common::envs::metrics_scheme(),
125        })
126        .set(1);
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132
133    #[test]
134    fn build_info_is_one_series_in_the_mx_namespace() {
135        let mut registry = new_registry();
136        register_build_info(
137            &mut registry,
138            &BackendConfig::Redis {
139                url: "redis://localhost:6379".to_string(),
140            },
141        );
142
143        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
144
145        // Gauge, never an Info -- see register_build_info.
146        assert!(
147            encoded.contains("# TYPE mx_build_info gauge"),
148            "expected an mx-prefixed gauge, got: {encoded}"
149        );
150        // Exactly one series, set to 1: every label is a process constant, so
151        // this family is capped at one series per pod.
152        let series: Vec<_> = encoded
153            .lines()
154            .filter(|line| line.starts_with("mx_build_info{"))
155            .collect();
156        assert_eq!(series.len(), 1, "expected one series, got: {encoded}");
157        assert!(
158            series[0].ends_with(" 1"),
159            "expected value 1, got: {series:?}"
160        );
161        assert!(series[0].contains(r#"component="server""#), "{series:?}");
162        assert!(series[0].contains(r#"backend="redis""#), "{series:?}");
163
164        assert!(encoded.trim_end().ends_with("# EOF"), "not OpenMetrics");
165    }
166}