modelexpress-server 0.8.0

High-performance gRPC server for model serving and management
Documentation
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Kubernetes CRD types for the model registry.
//!
//! Defines `ModelCacheEntry` — a custom resource that holds model-download lifecycle
//! state (phase + timestamps + message) for one cached model. This is the registry
//! analogue of the P2P `ModelMetadata` CRD, kept in a separate Kind so cardinality,
//! lifecycle, and RBAC scopes stay independent.

use kube::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// ModelCacheEntry spec - desired state. One CR per cached model.
#[derive(CustomResource, Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[kube(
    group = "modelexpress.nvidia.com",
    version = "v1alpha1",
    kind = "ModelCacheEntry",
    plural = "modelcacheentries",
    shortname = "mxcache",
    namespaced,
    status = "ModelCacheEntryStatus",
    doc = "ModelExpress model-download lifecycle metadata",
    printcolumn = r#"{"name":"Model","type":"string","jsonPath":".spec.modelName"}"#,
    printcolumn = r#"{"name":"Phase","type":"string","jsonPath":".status.phase"}"#,
    printcolumn = r#"{"name":"LastUsed","type":"date","jsonPath":".status.lastUsedAt"}"#,
    printcolumn = r#"{"name":"Claim","type":"string","jsonPath":".status.claimId","priority":1}"#,
    printcolumn = r#"{"name":"Lease","type":"date","jsonPath":".status.leaseExpiresAt","priority":1}"#,
    printcolumn = r#"{"name":"Age","type":"date","jsonPath":".metadata.creationTimestamp"}"#
)]
pub struct ModelCacheEntrySpec {
    /// Full model name (e.g., `meta-llama/Llama-3.1-70B`). Preserved in spec so
    /// operators can recover the original name even when the CR's metadata.name is a
    /// sanitized/hashed form.
    #[serde(rename = "modelName")]
    pub model_name: String,

    /// Provider string — `"HuggingFace"`, `"Ngc"`, `"Gcs"`, or `"S3"`.
    #[schemars(with = "ProviderSchema")]
    pub provider: String,
}

/// ModelCacheEntry status - observed state.
#[derive(Clone, Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ModelCacheEntryStatus {
    /// One of `"Downloading"`, `"Downloaded"`, `"Error"`. Empty string on freshly-created
    /// records that haven't yet received a status patch.
    #[serde(default)]
    #[schemars(with = "PhaseSchema")]
    pub phase: String,

    /// RFC3339 timestamp of first write. Omitted until the first status patch.
    #[serde(rename = "createdAt", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub created_at: Option<String>,

    /// RFC3339 timestamp of most recent status write or touch.
    #[serde(rename = "lastUsedAt", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub last_used_at: Option<String>,

    /// Optional human-readable message (download progress, error reason).
    #[serde(default)]
    pub message: Option<String>,

    /// Opaque identity of the replica that currently owns a download.
    #[serde(rename = "claimId", default)]
    pub claim_id: Option<String>,

    /// Owner-generated RFC3339 heartbeat deadline. Observers use changes in this value
    /// to measure liveness locally instead of comparing clocks across replicas.
    #[serde(rename = "leaseExpiresAt", default)]
    #[schemars(with = "Option<chrono::DateTime<chrono::Utc>>")]
    pub lease_expires_at: Option<String>,
}

#[derive(JsonSchema)]
#[allow(dead_code)]
enum ProviderSchema {
    HuggingFace,
    Ngc,
    Gcs,
    S3,
}

#[derive(JsonSchema)]
#[allow(dead_code)]
enum PhaseSchema {
    #[schemars(rename = "")]
    Empty,
    Downloading,
    Downloaded,
    Error,
}

/// Phase strings used by the CRD. Match `ModelStatus` one-for-one.
pub mod phase {
    pub const DOWNLOADING: &str = "Downloading";
    pub const DOWNLOADED: &str = "Downloaded";
    pub const ERROR: &str = "Error";
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn spec_roundtrips_through_json() {
        let spec = ModelCacheEntrySpec {
            model_name: "meta-llama/Llama-3.1-70B".to_string(),
            provider: "HuggingFace".to_string(),
        };
        let json = serde_json::to_string(&spec).expect("serialize");
        assert!(json.contains("\"modelName\":\"meta-llama/Llama-3.1-70B\""));
        let back: ModelCacheEntrySpec = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back.model_name, spec.model_name);
        assert_eq!(back.provider, spec.provider);
    }

    #[test]
    fn status_default_is_empty() {
        let status = ModelCacheEntryStatus::default();
        assert_eq!(status.phase, "");
        assert!(status.created_at.is_none());
        assert!(status.last_used_at.is_none());
        assert!(status.message.is_none());
        assert!(status.claim_id.is_none());
        assert!(status.lease_expires_at.is_none());
    }
}