Skip to main content

modelexpress_server/metrics/
cache.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Cache and registry gauges, plus the eviction counter.
5//!
6//! # Why these are refreshed rather than collected at scrape time
7//!
8//! Counting registry entries means walking the keyspace: the Redis backend does a
9//! `SCAN` plus a pipelined per-key fetch, and the Kubernetes backend does an
10//! unpaginated `list` of every `ModelCacheEntry`. Registering that as a
11//! scrape-time collector would put a keyspace walk on the metadata store every
12//! fifteen seconds, and on Kubernetes it would put an unbounded list on the API
13//! server -- a cost paid forever for a number that changes slowly.
14//!
15//! So a background task recomputes them on its own interval and writes plain
16//! gauges; the scrape only encodes what is already in memory.
17//!
18//! # Why the task is not hosted on the cache-eviction interval
19//!
20//! The obvious home is [`crate::cache::CacheEvictionService`], and it is the wrong
21//! one twice over. Its interval defaults to an hour, which is far too coarse for a
22//! gauge, and the whole task is skipped when eviction is disabled -- which would
23//! make every gauge here permanently *absent* rather than merely stale. An absent
24//! gauge and a broken exporter look identical.
25
26use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
27use prometheus_client::metrics::counter::Counter;
28use prometheus_client::metrics::family::Family;
29use prometheus_client::metrics::gauge::Gauge;
30use prometheus_client::registry::Registry;
31
32use crate::cache::EvictionReason;
33use crate::metrics::registry::StatusLabel;
34
35impl EvictionReason {
36    /// Wire form of the eviction reason.
37    const fn as_metric_str(&self) -> &'static str {
38        match self {
39            Self::TimeThreshold => "time_threshold",
40            Self::CountLimit => "count_limit",
41            Self::DiskSpace => "disk_space",
42            Self::Manual => "manual",
43        }
44    }
45}
46
47impl EncodeLabelValue for EvictionReason {
48    fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
49        EncodeLabelValue::encode(&self.as_metric_str(), encoder)
50    }
51}
52
53/// Label set for the eviction counter.
54#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
55pub struct EvictionLabels {
56    /// Which rule selected the model.
57    pub reason: EvictionReason,
58}
59
60/// Label set for the registry-entry gauge.
61#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
62pub struct EntryStatusLabels {
63    /// Status of the counted entries.
64    pub status: StatusLabel,
65}
66
67/// Label set for the background-task heartbeat.
68#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
69pub struct TaskLabels {
70    /// Task name.
71    pub task: &'static str,
72}
73
74/// Label set for the in-process map gauge.
75#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
76pub struct MapLabels {
77    /// Which map is being reported.
78    pub map: &'static str,
79}
80
81/// Handles for the cache and registry gauges. Cloning shares the storage.
82#[derive(Clone)]
83pub struct CacheMetrics {
84    evictions: Family<EvictionLabels, Counter>,
85    registry_entries: Family<EntryStatusLabels, Gauge>,
86    state_entries: Family<MapLabels, Gauge>,
87    task_last_success: Family<TaskLabels, Gauge>,
88}
89
90impl CacheMetrics {
91    /// Register the families and return handles.
92    pub fn register(registry: &mut Registry) -> Self {
93        let evictions = Family::<EvictionLabels, Counter>::default();
94        let registry_entries = Family::<EntryStatusLabels, Gauge>::default();
95        let state_entries = Family::<MapLabels, Gauge>::default();
96        let task_last_success = Family::<TaskLabels, Gauge>::default();
97
98        let cache = registry.sub_registry_with_prefix("cache");
99        cache.register(
100            "evictions",
101            "Models evicted from the cache, by the rule that selected each one",
102            evictions.clone(),
103        );
104
105        let reg = registry.sub_registry_with_prefix("registry");
106        // Named "registry entries", not "models": one logical model can hold
107        // several entries at once -- one per revision, and separate ones for
108        // metadata-only downloads.
109        reg.register(
110            "entries",
111            "Registry entries by status, refreshed on the stats interval",
112            registry_entries.clone(),
113        );
114
115        registry.register(
116            "state_entries",
117            "Size of never-evicted in-process maps; the OOM early warning",
118            state_entries.clone(),
119        );
120        registry.register(
121            "task_last_success_timestamp_seconds",
122            "Unix time of each background task's last successful run",
123            task_last_success.clone(),
124        );
125
126        Self {
127            evictions,
128            registry_entries,
129            state_entries,
130            task_last_success,
131        }
132    }
133
134    /// Count one evicted model against the rule that selected it.
135    pub fn record_eviction(&self, reason: EvictionReason) {
136        self.evictions
137            .get_or_create(&EvictionLabels { reason })
138            .inc();
139    }
140
141    /// Publish the registry entry counts observed by a refresh pass.
142    pub fn set_registry_entries(&self, downloading: i64, downloaded: i64, errored: i64) {
143        for (status, count) in [
144            (StatusLabel::Downloading, downloading),
145            (StatusLabel::Downloaded, downloaded),
146            (StatusLabel::Error, errored),
147        ] {
148            self.registry_entries
149                .get_or_create(&EntryStatusLabels { status })
150                .set(count);
151        }
152    }
153
154    /// Publish the size of an in-process map.
155    pub fn set_state_entries(&self, map: &'static str, count: i64) {
156        self.state_entries
157            .get_or_create(&MapLabels { map })
158            .set(count);
159    }
160
161    /// Stamp a task's last successful run.
162    ///
163    /// Only on success. A task that starts failing leaves its previous timestamp
164    /// in place and the value goes stale, which is what makes
165    /// `time() - mx_task_last_success_timestamp_seconds` a usable liveness alert;
166    /// stamping unconditionally would report a wedged task as healthy.
167    pub fn stamp_task_success(&self, task: &'static str, unix_seconds: i64) {
168        self.task_last_success
169            .get_or_create(&TaskLabels { task })
170            .set(unix_seconds);
171    }
172}
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177    use crate::metrics::{encode_text, new_registry};
178
179    #[test]
180    fn the_count_limit_path_is_not_reported_as_a_time_threshold() {
181        let mut registry = new_registry();
182        let metrics = CacheMetrics::register(&mut registry);
183
184        metrics.record_eviction(EvictionReason::TimeThreshold);
185        metrics.record_eviction(EvictionReason::CountLimit);
186        metrics.record_eviction(EvictionReason::CountLimit);
187
188        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
189        assert!(
190            encoded.contains(r#"mx_cache_evictions_total{reason="time_threshold"} 1"#),
191            "{encoded}"
192        );
193        assert!(
194            encoded.contains(r#"mx_cache_evictions_total{reason="count_limit"} 2"#),
195            "{encoded}"
196        );
197        assert!(!encoded.contains("_total_total"), "{encoded}");
198    }
199
200    /// Every `EvictionReason` needs a wire form, not just the two the policy can
201    /// produce today: `Manual` is a live variant and `DiskSpace` is declared, and
202    /// a typo in either arm ships a label value no dashboard query matches.
203    ///
204    /// One increment per reason, so a collision between two arms shows up as a
205    /// series holding 2 and the expected one missing.
206    #[test]
207    fn every_eviction_reason_has_its_own_label_value() {
208        let mut registry = new_registry();
209        let metrics = CacheMetrics::register(&mut registry);
210
211        for (reason, expected) in [
212            (EvictionReason::TimeThreshold, "time_threshold"),
213            (EvictionReason::CountLimit, "count_limit"),
214            (EvictionReason::DiskSpace, "disk_space"),
215            (EvictionReason::Manual, "manual"),
216        ] {
217            metrics.record_eviction(reason);
218
219            let encoded =
220                encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
221            assert!(
222                encoded.contains(&format!(
223                    r#"mx_cache_evictions_total{{reason="{expected}"}} 1"#
224                )),
225                "{reason:?} did not encode as {expected}: {encoded}"
226            );
227        }
228    }
229
230    /// The three status gauges must not be cross-wired: a rotated argument list
231    /// publishes the error count under `status="downloading"`, which reads as a
232    /// plausible level and is what a wedged-download alert fires on. Distinct
233    /// values per status, so no rotation survives.
234    ///
235    /// Scope: the neighbouring invariant -- that a *failed* refresh leaves these
236    /// gauges at their previous values instead of zeroing them, since a zeroed
237    /// gauge and an empty registry are indistinguishable -- is a property of
238    /// `registry::stats_refresh::refresh_once`, not of this setter, and is not
239    /// checked here.
240    #[test]
241    fn registry_entry_gauges_are_set_per_status() {
242        let mut registry = new_registry();
243        let metrics = CacheMetrics::register(&mut registry);
244
245        metrics.set_registry_entries(2, 7, 1);
246        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
247        assert!(
248            encoded.contains(r#"mx_registry_entries{status="downloading"} 2"#),
249            "{encoded}"
250        );
251        assert!(
252            encoded.contains(r#"mx_registry_entries{status="downloaded"} 7"#),
253            "{encoded}"
254        );
255        assert!(
256            encoded.contains(r#"mx_registry_entries{status="error"} 1"#),
257            "{encoded}"
258        );
259    }
260
261    /// Stamped with the constant the production task actually publishes, not a
262    /// local copy of the string, so this exercises the same label value the
263    /// refresh task emits.
264    ///
265    /// That alone would go green on a rename, and a rename silently breaks every
266    /// dashboard and alert keyed on the old value -- hence the separate equality
267    /// on `TASK_NAME`, which pins the wire form as a contract.
268    #[test]
269    fn the_task_heartbeat_is_stamped_per_task() {
270        use crate::registry::stats_refresh::TASK_NAME;
271
272        let mut registry = new_registry();
273        let metrics = CacheMetrics::register(&mut registry);
274
275        assert_eq!(TASK_NAME, "registry_stats_refresh");
276
277        metrics.stamp_task_success(TASK_NAME, 1_760_000_000);
278        metrics.set_state_entries("download_waiters", 3);
279
280        let encoded = encode_text(&registry).unwrap_or_else(|_| String::from("<encode failed>"));
281        assert!(
282            encoded.contains(&format!(
283                r#"mx_task_last_success_timestamp_seconds{{task="{TASK_NAME}"}} 1760000000"#
284            )),
285            "{encoded}"
286        );
287        assert!(
288            encoded.contains(r#"mx_state_entries{map="download_waiters"} 3"#),
289            "{encoded}"
290        );
291    }
292}