Skip to main content

modelexpress_server/registry/
entry_key.rs

1// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Identity of a single registry entry.
5//!
6//! Registry backends key every record, lease, and claim on one string. A model name
7//! alone is not a sufficient key:
8//!
9//! - two revisions of the same model must not share a download lease, or a request for
10//!   one revision would coalesce onto a download of the other;
11//! - a metadata-only download (`ignore_weights`) must not satisfy a later full-weight
12//!   request, which would hand back a snapshot with no weights in it.
13//!
14//! [`EntryKey`] folds those three components into the single string the backends want
15//! and parses it back, so cache eviction can still recover the model name and revision
16//! it needs in order to delete the right files.
17//!
18//! An unpinned, full-weight entry encodes to the bare model name, so providers without
19//! a revision concept keep the keys they have always used.
20//!
21//! # Encoding
22//!
23//! Anything else encodes as `mx1:<revision>:<flags>:<model_name>`. The model name goes
24//! last because it is the only field with no character restrictions — a GCS object path
25//! accepts almost any byte, so a name like `gs://bucket/models/foo:m:bar` must not be
26//! able to impersonate the other fields. Putting it last means nothing after it needs
27//! parsing, and the round trip is exact for any name.
28//!
29//! The revision field does have to avoid `:`, which holds because it is always a commit
30//! identifier: Git forbids `:` in ref names, and resolved revisions are commit SHAs.
31
32use std::fmt::{Display, Formatter};
33
34/// Marks a key that carries a revision or weight mode. Versioned so the format can
35/// change without misreading old keys.
36const STRUCTURED_PREFIX: &str = "mx1:";
37/// Weight-mode field values.
38const METADATA_FLAG: &str = "m";
39const FULL_WEIGHT_FLAG: &str = "-";
40
41/// The components a registry key is built from.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct EntryKey {
44    /// Provider-canonical model name.
45    pub model_name: String,
46    /// Immutable revision the request resolved to, when the provider has one.
47    pub revision: Option<String>,
48    /// Whether the entry covers a weightless (config/tokenizer only) download.
49    pub metadata_only: bool,
50}
51
52impl EntryKey {
53    pub fn new(
54        model_name: impl Into<String>,
55        revision: Option<String>,
56        metadata_only: bool,
57    ) -> Self {
58        Self {
59            model_name: model_name.into(),
60            revision,
61            metadata_only,
62        }
63    }
64
65    /// Whether the key needs the structured form.
66    ///
67    /// A model name that happens to start with the prefix is encoded structurally even
68    /// when it carries no revision, so it can never be mistaken for a key we wrote.
69    fn needs_structured_form(&self) -> bool {
70        self.revision.is_some()
71            || self.metadata_only
72            || self.model_name.starts_with(STRUCTURED_PREFIX)
73    }
74
75    /// Recover the components of an encoded key.
76    ///
77    /// A key without the prefix parses back to an unpinned, full-weight entry, which is
78    /// how records written before revisions existed are read.
79    pub fn parse(key: &str) -> Self {
80        let Some(fields) = key.strip_prefix(STRUCTURED_PREFIX) else {
81            return Self::new(key, None, false);
82        };
83
84        // `splitn(3)` leaves the model name — the only field that may contain `:` —
85        // untouched in the final part.
86        let mut parts = fields.splitn(3, ':');
87        match (parts.next(), parts.next(), parts.next()) {
88            (Some(revision), Some(flags), Some(model_name)) => Self::new(
89                model_name,
90                (!revision.is_empty()).then(|| revision.to_string()),
91                flags == METADATA_FLAG,
92            ),
93            // Not a key this module produced; treat it as a plain model name.
94            _ => Self::new(key, None, false),
95        }
96    }
97
98    /// True when this entry belongs to `model_name`, whatever its revision or weight mode.
99    /// Drives "forget everything about this model" operations such as `model clear`.
100    pub fn belongs_to(&self, model_name: &str) -> bool {
101        self.model_name == model_name
102    }
103}
104
105impl Display for EntryKey {
106    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
107        if !self.needs_structured_form() {
108            return f.write_str(&self.model_name);
109        }
110
111        let flags = if self.metadata_only {
112            METADATA_FLAG
113        } else {
114            FULL_WEIGHT_FLAG
115        };
116        write!(
117            f,
118            "{STRUCTURED_PREFIX}{}:{flags}:{}",
119            self.revision.as_deref().unwrap_or(""),
120            self.model_name
121        )
122    }
123}
124
125#[cfg(test)]
126mod tests {
127    use super::*;
128
129    fn roundtrip(key: EntryKey) {
130        assert_eq!(EntryKey::parse(&key.to_string()), key);
131    }
132
133    #[test]
134    fn unpinned_full_weight_entry_encodes_to_the_bare_model_name() {
135        let key = EntryKey::new("google-t5/t5-small", None, false);
136        assert_eq!(key.to_string(), "google-t5/t5-small");
137        roundtrip(key);
138    }
139
140    #[test]
141    fn every_component_survives_a_roundtrip() {
142        roundtrip(EntryKey::new(
143            "org/model",
144            Some("abc123".to_string()),
145            false,
146        ));
147        roundtrip(EntryKey::new("org/model", None, true));
148        roundtrip(EntryKey::new("org/model", Some("abc123".to_string()), true));
149        roundtrip(EntryKey::new("gs://bucket/org/model/rev-1", None, false));
150    }
151
152    /// A GCS object path accepts almost any byte, so a model name is free to contain
153    /// whatever the encoding uses as structure. Misreading one would evict a different
154    /// model's files, so every shape has to round-trip exactly.
155    #[test]
156    fn a_model_name_cannot_impersonate_the_encoding() {
157        for name in [
158            "gs://bucket/models/foo:m:bar",
159            "gs://bucket/models/foo#metadata",
160            "gs://bucket/models/foo@rev:abc123",
161            "mx1:abc123:m:gs://bucket/models/foo",
162            "mx1:",
163            ":::",
164        ] {
165            roundtrip(EntryKey::new(name, None, false));
166            roundtrip(EntryKey::new(name, None, true));
167            roundtrip(EntryKey::new(name, Some("abc123".to_string()), false));
168        }
169    }
170
171    #[test]
172    fn a_name_that_looks_like_a_key_stays_distinct_from_the_key_it_mimics() {
173        // The literal name and the entry whose encoding it copies must not collide.
174        let mimic = EntryKey::new("mx1:abc123:m:org/model", None, false);
175        let real = EntryKey::new("org/model", Some("abc123".to_string()), true);
176        assert_ne!(mimic.to_string(), real.to_string());
177        assert_eq!(EntryKey::parse(&mimic.to_string()), mimic);
178        assert_eq!(EntryKey::parse(&real.to_string()), real);
179    }
180
181    #[test]
182    fn a_model_name_with_a_colon_keeps_its_revision_and_weight_mode() {
183        let key = EntryKey::new("ngc/org/model:1.0", Some("abc123".to_string()), true);
184        let parsed = EntryKey::parse(&key.to_string());
185        assert_eq!(parsed.model_name, "ngc/org/model:1.0");
186        assert_eq!(parsed.revision.as_deref(), Some("abc123"));
187        assert!(parsed.metadata_only);
188    }
189
190    #[test]
191    fn two_revisions_of_one_model_get_distinct_keys() {
192        let first = EntryKey::new("org/model", Some("abc123".to_string()), false).to_string();
193        let second = EntryKey::new("org/model", Some("def456".to_string()), false).to_string();
194        assert_ne!(first, second);
195    }
196
197    #[test]
198    fn metadata_only_and_full_weight_entries_do_not_collide() {
199        let revision = Some("abc123".to_string());
200        assert_ne!(
201            EntryKey::new("org/model", revision.clone(), true).to_string(),
202            EntryKey::new("org/model", revision, false).to_string()
203        );
204    }
205
206    #[test]
207    fn a_legacy_key_parses_as_unpinned_and_full_weight() {
208        let parsed = EntryKey::parse("meta-llama/Llama-3.1-70B");
209        assert_eq!(parsed.model_name, "meta-llama/Llama-3.1-70B");
210        assert!(parsed.revision.is_none());
211        assert!(!parsed.metadata_only);
212    }
213
214    #[test]
215    fn belongs_to_ignores_revision_and_weight_mode() {
216        let key = EntryKey::new("org/model", Some("abc123".to_string()), true);
217        assert!(key.belongs_to("org/model"));
218        assert!(!key.belongs_to("org/other"));
219    }
220}