use modelexpress_common::models::ModelStatus;
use prometheus_client::encoding::{EncodeLabelSet, EncodeLabelValue, LabelValueEncoder};
use prometheus_client::metrics::counter::Counter;
use prometheus_client::metrics::family::Family;
use prometheus_client::metrics::histogram::Histogram;
use prometheus_client::registry::Registry;
use super::buckets;
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum StatusLabel {
Absent,
Downloading,
Downloaded,
Error,
}
impl StatusLabel {
const fn as_str(self) -> &'static str {
match self {
Self::Absent => "absent",
Self::Downloading => "downloading",
Self::Downloaded => "downloaded",
Self::Error => "error",
}
}
}
impl From<ModelStatus> for StatusLabel {
fn from(status: ModelStatus) -> Self {
match status {
ModelStatus::DOWNLOADING => Self::Downloading,
ModelStatus::DOWNLOADED => Self::Downloaded,
ModelStatus::ERROR => Self::Error,
}
}
}
impl EncodeLabelValue for StatusLabel {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum ClaimResult {
Claimed,
Takeover,
AlreadyExists,
Error,
}
impl ClaimResult {
pub(crate) const ALL: [Self; 4] = [
Self::Claimed,
Self::Takeover,
Self::AlreadyExists,
Self::Error,
];
const fn as_str(self) -> &'static str {
match self {
Self::Claimed => "claimed",
Self::Takeover => "takeover",
Self::AlreadyExists => "already_exists",
Self::Error => "error",
}
}
}
impl EncodeLabelValue for ClaimResult {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum LeaseResult {
Renewed,
Lost,
Error,
}
impl LeaseResult {
pub(crate) const ALL: [Self; 3] = [Self::Renewed, Self::Lost, Self::Error];
const fn as_str(self) -> &'static str {
match self {
Self::Renewed => "renewed",
Self::Lost => "lost",
Self::Error => "error",
}
}
}
impl EncodeLabelValue for LeaseResult {
fn encode(&self, encoder: &mut LabelValueEncoder<'_>) -> Result<(), std::fmt::Error> {
EncodeLabelValue::encode(&self.as_str(), encoder)
}
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct TransitionLabels {
pub from: StatusLabel,
pub to: StatusLabel,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct ClaimLabels {
pub result: ClaimResult,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct LeaseLabels {
pub result: LeaseResult,
}
#[derive(Clone)]
pub struct RegistryMetrics {
transitions: Family<TransitionLabels, Counter>,
claims: Family<ClaimLabels, Counter>,
lease_refreshes: Family<LeaseLabels, Counter>,
}
impl RegistryMetrics {
const REACHABLE_TRANSITIONS: [(StatusLabel, StatusLabel); 6] = [
(StatusLabel::Absent, StatusLabel::Downloading),
(StatusLabel::Downloading, StatusLabel::Downloading),
(StatusLabel::Error, StatusLabel::Downloading),
(StatusLabel::Downloading, StatusLabel::Downloaded),
(StatusLabel::Downloading, StatusLabel::Error),
(StatusLabel::Downloading, StatusLabel::Absent),
];
pub fn register(registry: &mut Registry) -> Self {
let transitions = Family::<TransitionLabels, Counter>::default();
let claims = Family::<ClaimLabels, Counter>::default();
let lease_refreshes = Family::<LeaseLabels, Counter>::default();
let sub = registry.sub_registry_with_prefix("registry");
sub.register(
"status_transitions",
"Model registry status transitions observed on the claim lifecycle",
transitions.clone(),
);
let download = registry.sub_registry_with_prefix("download");
download.register(
"claims",
"Download claim attempts by outcome; takeover means the bytes are being pulled again",
claims.clone(),
);
download.register(
"lease_refresh",
"Download lease heartbeats by outcome; lost is the leading indicator of a duplicate download",
lease_refreshes.clone(),
);
for result in ClaimResult::ALL {
let _ = claims.get_or_create(&ClaimLabels { result });
}
for result in LeaseResult::ALL {
let _ = lease_refreshes.get_or_create(&LeaseLabels { result });
}
for (from, to) in Self::REACHABLE_TRANSITIONS {
let _ = transitions.get_or_create(&TransitionLabels { from, to });
}
Self {
transitions,
claims,
lease_refreshes,
}
}
pub fn record_claim(&self, result: ClaimResult) {
self.claims.get_or_create(&ClaimLabels { result }).inc();
let from = match result {
ClaimResult::Claimed => StatusLabel::Absent,
ClaimResult::Takeover => StatusLabel::Downloading,
ClaimResult::AlreadyExists | ClaimResult::Error => return,
};
self.record_transition(from, StatusLabel::Downloading);
}
pub fn record_lease_refresh(&self, result: LeaseResult) {
self.lease_refreshes
.get_or_create(&LeaseLabels { result })
.inc();
}
pub fn record_transition(&self, from: StatusLabel, to: StatusLabel) {
self.transitions
.get_or_create(&TransitionLabels { from, to })
.inc();
}
}
#[derive(Clone)]
pub struct DownloadMetrics {
seconds: Family<DownloadLabels, Histogram, fn() -> Histogram>,
}
#[derive(Clone, Debug, Hash, PartialEq, Eq, EncodeLabelSet)]
pub struct DownloadLabels {
pub outcome: StatusLabel,
}
fn xslow_histogram() -> Histogram {
Histogram::new(buckets::XSLOW)
}
impl DownloadMetrics {
const TERMINAL: [StatusLabel; 2] = [StatusLabel::Downloaded, StatusLabel::Error];
pub fn register(registry: &mut Registry) -> Self {
let seconds: Family<DownloadLabels, Histogram, fn() -> Histogram> =
Family::new_with_constructor(xslow_histogram as fn() -> Histogram);
let download = registry.sub_registry_with_prefix("download");
download.register(
"seconds",
"End-to-end model download duration by terminal status",
seconds.clone(),
);
for outcome in Self::TERMINAL {
let _ = seconds.get_or_create(&DownloadLabels { outcome });
}
Self { seconds }
}
pub fn observe(&self, outcome: StatusLabel, elapsed_seconds: f64) {
self.seconds
.get_or_create(&DownloadLabels { outcome })
.observe(elapsed_seconds);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrics::{encode_text, new_registry};
#[test]
fn each_claim_result_encodes_as_its_own_label_value() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
metrics.record_claim(ClaimResult::Claimed);
metrics.record_claim(ClaimResult::Takeover);
metrics.record_claim(ClaimResult::AlreadyExists);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_download_claims_total{result="claimed"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_claims_total{result="takeover"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_claims_total{result="already_exists"} 1"#),
"{encoded}"
);
assert!(!encoded.contains("_total_total"), "{encoded}");
}
#[test]
fn a_model_status_keeps_its_own_label_through_the_encoder() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
let downloads = DownloadMetrics::register(&mut registry);
for _ in 0..3 {
metrics.record_transition(StatusLabel::Absent, ModelStatus::DOWNLOADING.into());
}
metrics.record_transition(StatusLabel::Downloading, ModelStatus::DOWNLOADED.into());
for _ in 0..2 {
metrics.record_transition(StatusLabel::Downloading, ModelStatus::ERROR.into());
}
downloads.observe(ModelStatus::ERROR.into(), 1.0);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(
r#"mx_registry_status_transitions_total{from="absent",to="downloading"} 3"#
),
"{encoded}"
);
assert!(
encoded.contains(
r#"mx_registry_status_transitions_total{from="downloading",to="downloaded"} 1"#
),
"{encoded}"
);
assert!(
encoded.contains(
r#"mx_registry_status_transitions_total{from="downloading",to="error"} 2"#
),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_seconds_count{outcome="error"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_seconds_count{outcome="downloaded"} 0"#),
"a failed download must not be timed as a successful one: {encoded}"
);
}
#[test]
fn download_outcomes_are_exported_at_zero_before_any_download() {
let mut registry = new_registry();
let _downloads = DownloadMetrics::register(&mut registry);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
for outcome in ["downloaded", "error"] {
assert!(
encoded.contains(&format!(
r#"mx_download_seconds_count{{outcome="{outcome}"}} 0"#
)),
"{outcome} missing before any download: {encoded}"
);
}
for outcome in ["absent", "downloading"] {
assert!(
!encoded.contains(&format!(
r#"mx_download_seconds_count{{outcome="{outcome}"}}"#
)),
"{outcome} is not a terminal outcome: {encoded}"
);
}
}
fn in_flight(encoded: &str) -> i64 {
let mut arrivals: i64 = 0;
let mut departures: i64 = 0;
for line in encoded.lines() {
let Some((labels, value)) = line
.strip_prefix("mx_registry_status_transitions_total{")
.and_then(|rest| rest.split_once("} "))
else {
continue;
};
let count: i64 = value.trim().parse().unwrap_or_default();
if labels.contains(r#"to="downloading""#) {
arrivals = arrivals.saturating_add(count);
}
if labels.contains(r#"from="downloading""#) {
departures = departures.saturating_add(count);
}
}
arrivals.saturating_sub(departures)
}
#[test]
fn a_takeover_does_not_change_the_in_flight_level() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
metrics.record_claim(ClaimResult::Claimed);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(in_flight(&encoded), 1, "one download in flight");
metrics.record_claim(ClaimResult::Takeover);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(
in_flight(&encoded),
1,
"a takeover is not a second download"
);
metrics.record_transition(StatusLabel::Downloading, StatusLabel::Downloaded);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(in_flight(&encoded), 0, "the download finished");
}
#[test]
fn a_downloading_to_absent_transition_is_a_departure() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
metrics.record_claim(ClaimResult::Claimed);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(in_flight(&encoded), 1);
metrics.record_transition(StatusLabel::Downloading, StatusLabel::Absent);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(
in_flight(&encoded),
0,
"a deleted download must not stay counted as in flight: {encoded}"
);
}
#[test]
fn an_already_exists_claim_records_no_transition() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
metrics.record_claim(ClaimResult::Claimed);
metrics.record_claim(ClaimResult::AlreadyExists);
metrics.record_claim(ClaimResult::Error);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(
in_flight(&encoded),
1,
"waiters and errors must not move the level: {encoded}"
);
}
#[test]
fn a_lost_lease_is_recorded_distinctly() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
metrics.record_lease_refresh(LeaseResult::Renewed);
metrics.record_lease_refresh(LeaseResult::Lost);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_download_lease_refresh_total{result="renewed"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_lease_refresh_total{result="lost"} 1"#),
"{encoded}"
);
}
#[test]
fn the_download_histogram_uses_the_hour_scale_band() {
let mut registry = new_registry();
let metrics = DownloadMetrics::register(&mut registry);
metrics.observe(StatusLabel::Downloaded, 2400.0);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert!(
encoded.contains(r#"mx_download_seconds_count{outcome="downloaded"} 1"#),
"{encoded}"
);
assert!(
encoded.contains(r#"mx_download_seconds_bucket{le="3600.0",outcome="downloaded"} 1"#),
"a 40-minute download must land below the top boundary: {encoded}"
);
}
#[test]
fn alertable_counters_are_exported_at_zero_before_any_event() {
let mut registry = new_registry();
let _metrics = RegistryMetrics::register(&mut registry);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
for series in [
r#"mx_download_claims_total{result="takeover"} 0"#,
r#"mx_download_lease_refresh_total{result="lost"} 0"#,
r#"mx_registry_status_transitions_total{from="absent",to="downloading"} 0"#,
] {
assert!(
encoded.contains(series),
"missing {series}; a counter born at 1 leaves rate() blind to the first event: {encoded}"
);
}
}
#[test]
fn pre_creation_covers_exactly_the_declared_label_values() {
let mut registry = new_registry();
let _metrics = RegistryMetrics::register(&mut registry);
let encoded = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
let count = |prefix: &str| encoded.lines().filter(|l| l.starts_with(prefix)).count();
assert_eq!(
count("mx_download_claims_total{"),
ClaimResult::ALL.len(),
"{encoded}"
);
assert_eq!(
count("mx_download_lease_refresh_total{"),
LeaseResult::ALL.len(),
"{encoded}"
);
assert_eq!(
count("mx_registry_status_transitions_total{"),
RegistryMetrics::REACHABLE_TRANSITIONS.len(),
"{encoded}"
);
for (from, to) in [
(StatusLabel::Absent, StatusLabel::Absent),
(StatusLabel::Absent, StatusLabel::Downloaded),
(StatusLabel::Downloaded, StatusLabel::Error),
(StatusLabel::Error, StatusLabel::Downloaded),
] {
let needle =
format!(r#"mx_registry_status_transitions_total{{from="{from:?}",to="{to:?}"#)
.to_lowercase();
assert!(!encoded.to_lowercase().contains(&needle), "{encoded}");
}
}
#[test]
fn every_booked_transition_was_pre_created() {
let mut registry = new_registry();
let metrics = RegistryMetrics::register(&mut registry);
let before = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
let series = |text: &str| {
text.lines()
.filter(|l| l.starts_with("mx_registry_status_transitions_total{"))
.count()
};
let baseline = series(&before);
metrics.record_claim(ClaimResult::Claimed);
metrics.record_claim(ClaimResult::Takeover);
metrics.record_transition(StatusLabel::Error, StatusLabel::Downloading);
metrics.record_transition(StatusLabel::Downloading, StatusLabel::Downloaded);
metrics.record_transition(StatusLabel::Downloading, StatusLabel::Error);
metrics.record_transition(StatusLabel::Downloading, StatusLabel::Absent);
let after = encode_text(®istry).unwrap_or_else(|_| String::from("<encode failed>"));
assert_eq!(
series(&after),
baseline,
"a booked transition was not pre-created, so its first occurrence is \
invisible to increase(): {after}"
);
}
}