Skip to main content

hyprstream_core/storage/
model_ref.rs

1//! Advanced model reference type for git-native model management
2
3use anyhow::{bail, Result};
4use serde::{Deserialize, Serialize};
5use std::fmt;
6use uuid::Uuid;
7
8// Re-export git2db's GitRef instead of duplicating
9pub use git2db::GitRef;
10
11/// Model reference with typed git references
12/// Examples:
13///   "llama3"          -> model "llama3" with GitRef::DefaultBranch
14///   "llama3:main"     -> model "llama3" with GitRef::Branch("main")
15///   "llama3:v2.0"     -> model "llama3" with GitRef::Tag("v2.0")
16///   "llama3:abc123"   -> model "llama3" with GitRef::Commit(oid)
17///   "llama3:HEAD~1"   -> model "llama3" with GitRef::Revspec("HEAD~1")
18#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct ModelRef {
20    /// Local registry name of the model (e.g. `Qwen3-0.6B`).
21    ///
22    /// # Deprecation notice (#395)
23    ///
24    /// The name layer is being retired in favor of federated `at://` / `did:`
25    /// ModelRefs (see `services::model::ModelService::resolve_model_ref`). New
26    /// code should treat a model's identity as its content-addressed CID, not its
27    /// local registry name. Use [`ModelRef::name`] for read access — direct field
28    /// access is `#[deprecated]` to mark the direction without breaking callers.
29    ///
30    /// The field itself stays `pub` (and the constructor / parser remain) so the
31    /// migration is opt-in: every existing caller keeps compiling. The name layer
32    /// dies when all callers have migrated to `at://`.
33    #[deprecated(
34        since = "0.1.0",
35        note = "prefer at:// / did: federated ModelRefs (#395); use ModelRef::name() for read access"
36    )]
37    pub model: String,
38    pub git_ref: GitRef,
39}
40
41impl ModelRef {
42    /// Create a new ModelRef with default branch
43    #[allow(deprecated)] // constructs via field init; the field itself carries the deprecation
44    pub fn new(model: String) -> Self {
45        Self {
46            model,
47            git_ref: GitRef::DefaultBranch,
48        }
49    }
50
51    /// Create a new ModelRef with a specific git reference
52    #[allow(deprecated)] // constructs via field init; the field itself carries the deprecation
53    pub fn with_ref(model: String, git_ref: GitRef) -> Self {
54        Self { model, git_ref }
55    }
56
57    /// Read the local registry name.
58    ///
59    /// Non-deprecated accessor for the [`ModelRef::model`] field so internal
60    /// callers (registry lookup, worktree paths) don't trip the field-level
61    /// `#[deprecated]` lint during the name-layer retirement (#395). External
62    /// consumers reading `.model` by name get the deprecation notice; this
63    /// accessor is the sanctioned read path until the name layer is removed.
64    #[allow(deprecated)]
65    pub fn name(&self) -> &str {
66        &self.model
67    }
68
69    /// Parse a model reference string
70    #[allow(deprecated)] // constructs via field init; the field itself carries the deprecation
71    pub fn parse(s: &str) -> Result<Self> {
72        // Still support UUID for backwards compatibility
73        if let Ok(uuid) = Uuid::parse_str(s) {
74            return Ok(ModelRef {
75                model: uuid.to_string(),
76                git_ref: GitRef::DefaultBranch,
77            });
78        }
79
80        // Parse model:ref format
81        let (model, git_ref) = match s.split_once(':') {
82            Some((m, r)) => {
83                // Use git2db's GitRef::parse() and convert error
84                let git_ref = GitRef::parse(r)
85                    .map_err(|e| anyhow::anyhow!("Failed to parse git ref '{}': {}", r, e))?;
86                (m.to_owned(), git_ref)
87            }
88            None => (s.to_owned(), GitRef::DefaultBranch),
89        };
90
91        // Validate model name
92        validate_model_name(&model)?;
93
94        Ok(ModelRef { model, git_ref })
95    }
96
97    /// Get the git reference as an option string (for compatibility)
98    pub fn git_ref_str(&self) -> Option<String> {
99        match &self.git_ref {
100            GitRef::DefaultBranch => None,
101            _ => Some(self.git_ref.display_name()),
102        }
103    }
104}
105
106// Note: impl Display for GitRef removed - git2db already provides it
107
108impl fmt::Display for ModelRef {
109    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110        match &self.git_ref {
111            GitRef::DefaultBranch => write!(f, "{}", self.name()),
112            _ => write!(f, "{}:{}", self.name(), self.git_ref.display_name()),
113        }
114    }
115}
116
117impl std::str::FromStr for ModelRef {
118    type Err = anyhow::Error;
119
120    fn from_str(s: &str) -> Result<Self> {
121        Self::parse(s)
122    }
123}
124
125/// Validate model name
126pub fn validate_model_name(name: &str) -> Result<()> {
127    // Don't validate UUIDs (backwards compatibility)
128    if Uuid::parse_str(name).is_ok() {
129        return Ok(());
130    }
131
132    const MAX_LEN: usize = 50;
133    const RESERVED: &[&str] = &["api", "system", "admin", "registry", "test"];
134
135    if name.is_empty() || name.len() > MAX_LEN {
136        bail!("Model name must be 1-{} characters", MAX_LEN);
137    }
138
139    // Follow Git reference naming rules (but adapted for model names)
140    // Reject characters that Git doesn't allow
141    if name.chars().any(
142        |c| {
143            c.is_ascii_control() ||    // ASCII control characters
144        c == ' ' ||                // Space
145        c == '~' ||                // Tilde
146        c == '^' ||                // Caret
147        c == ':' ||                // Colon
148        c == '?' ||                // Question mark
149        c == '*' ||                // Asterisk
150        c == '[' ||                // Open bracket
151        c == '\\' ||               // Backslash
152        c == '\t' ||               // Tab
153        c == '\n' ||               // Newline
154        c == '\r'
155        }, // Carriage return
156    ) {
157        bail!("Model name contains invalid characters (spaces, control chars, or Git-forbidden chars)");
158    }
159
160    // No consecutive dots (Git rule)
161    if name.contains("..") {
162        bail!("Model name cannot contain consecutive dots (..)");
163    }
164
165    // Cannot end with .lock (Git rule)
166    if name.ends_with(".lock") {
167        bail!("Model name cannot end with '.lock'");
168    }
169
170    // Cannot be just "@" (Git rule)
171    if name == "@" {
172        bail!("Model name cannot be '@'");
173    }
174
175    // Cannot contain @{ sequence (Git rule)
176    if name.contains("@{") {
177        bail!("Model name cannot contain '@{{' sequence");
178    }
179
180    // Cannot start or end with dot (adapted Git rule - no component can start with dot)
181    if name.starts_with('.') || name.ends_with('.') {
182        bail!("Model name cannot start or end with dot");
183    }
184
185    // Check reserved names
186    if RESERVED.contains(&name) {
187        bail!("Model name '{}' is reserved", name);
188    }
189
190    Ok(())
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[test]
198    #[allow(deprecated)] // asserts the deprecated `.model` field still carries the parsed name
199    fn test_parse_model_ref() -> Result<()> {
200        // Model only (default branch)
201        let ref1 = ModelRef::parse("llama3")?;
202        assert_eq!(ref1.model, "llama3");
203        assert_eq!(ref1.git_ref, GitRef::DefaultBranch);
204
205        // Model with branch
206        let ref2 = ModelRef::parse("llama3:main")?;
207        assert_eq!(ref2.model, "llama3");
208        assert_eq!(ref2.git_ref, GitRef::Branch("main".to_owned()));
209
210        // Model with tag (must use explicit tag syntax)
211        let ref3 = ModelRef::parse("llama3:tags/v2.0")?;
212        assert_eq!(ref3.model, "llama3");
213        assert_eq!(ref3.git_ref, GitRef::Tag("v2.0".to_owned()));
214
215        // Model with commit SHA
216        let ref4 = ModelRef::parse("llama3:1234567890abcdef1234567890abcdef12345678")?;
217        assert_eq!(ref4.model, "llama3");
218        assert!(
219            matches!(ref4.git_ref, GitRef::Commit(oid) if oid.to_string() == "1234567890abcdef1234567890abcdef12345678")
220        );
221
222        // Model with revspec
223        let ref5 = ModelRef::parse("llama3:HEAD~1")?;
224        assert_eq!(ref5.model, "llama3");
225        assert_eq!(ref5.git_ref, GitRef::Revspec("HEAD~1".to_owned()));
226
227        // UUID backwards compatibility
228        let uuid = "550e8400-e29b-41d4-a716-446655440000";
229        let ref6 = ModelRef::parse(uuid)?;
230        assert_eq!(ref6.model, uuid);
231        assert_eq!(ref6.git_ref, GitRef::DefaultBranch);
232        Ok(())
233    }
234
235    #[test]
236    fn test_git_ref_parsing() -> Result<()> {
237        // Test GitRef parsing (now using git2db's GitRef::parse)
238        assert_eq!(GitRef::parse("main")?, GitRef::Branch("main".to_owned()));
239        // Explicit tag syntax required
240        assert!(matches!(GitRef::parse("tags/v1.0.0")?, GitRef::Tag(_)));
241        assert!(matches!(
242            GitRef::parse("HEAD~1")?,
243            GitRef::Revspec(_) | GitRef::DefaultBranch
244        ));
245        assert!(matches!(GitRef::parse("main^2")?, GitRef::Revspec(_)));
246
247        // Full SHA
248        let sha = "1234567890abcdef1234567890abcdef12345678";
249        assert!(matches!(GitRef::parse(sha)?, GitRef::Commit(oid) if oid.to_string() == sha));
250
251        // Abbreviated SHA (should be treated as revspec)
252        assert!(matches!(GitRef::parse("1234567")?, GitRef::Revspec(_)));
253        Ok(())
254    }
255
256    #[test]
257    fn test_git_ref_display() -> Result<()> {
258        // Test display_name (git2db's API)
259        assert_eq!(GitRef::DefaultBranch.display_name(), "HEAD");
260        assert_eq!(GitRef::Branch("main".to_owned()).display_name(), "main");
261        // git2db's Tag display includes tags/ prefix
262        assert!(GitRef::Tag("v1.0".to_owned())
263            .display_name()
264            .contains("v1.0"));
265        assert_eq!(
266            GitRef::Revspec("HEAD~1".to_owned()).display_name(),
267            "HEAD~1"
268        );
269
270        let oid = git2db::Oid::from_str("1234567890abcdef1234567890abcdef12345678")?;
271        // display_name shows abbreviated SHA
272        assert!(GitRef::Commit(oid).display_name().contains("12345678"));
273        Ok(())
274    }
275
276    #[test]
277    fn test_model_ref_compatibility() -> Result<()> {
278        // Test that the new API provides backward compatibility
279        let model_ref = ModelRef::parse("llama3:main")?;
280
281        // Should have compatible git_ref_str method
282        assert_eq!(model_ref.git_ref_str(), Some("main".to_owned()));
283
284        // Should display the same as before
285        assert_eq!(model_ref.to_string(), "llama3:main");
286
287        // Default branch should show just the model name
288        let default_ref = ModelRef::parse("llama3")?;
289        assert_eq!(default_ref.to_string(), "llama3");
290        assert_eq!(default_ref.git_ref_str(), None);
291        Ok(())
292    }
293
294    #[test]
295    fn test_validate_model_name() {
296        // Valid names (Git-compliant)
297        assert!(validate_model_name("llama3").is_ok());
298        assert!(validate_model_name("gpt-2").is_ok());
299        assert!(validate_model_name("model-123").is_ok());
300        assert!(validate_model_name("Qwen3-4B").is_ok()); // HuggingFace mixed case
301        assert!(validate_model_name("GPT-4").is_ok()); // uppercase
302        assert!(validate_model_name("Model").is_ok()); // mixed case
303        assert!(validate_model_name("Qwen3-0.6B").is_ok()); // dots in version numbers
304        assert!(validate_model_name("model-v1.2.3").is_ok()); // dots in versions
305        assert!(validate_model_name("model_with_underscores").is_ok()); // underscores now allowed
306        assert!(validate_model_name("model/submodel").is_ok()); // slashes now allowed
307        assert!(validate_model_name("org-name_model.v1").is_ok()); // mixed separators
308        assert!(validate_model_name("123model").is_ok()); // starting with numbers
309        assert!(validate_model_name("model+special").is_ok()); // plus signs
310        assert!(validate_model_name("model=equals").is_ok()); // equals signs
311
312        // Invalid names (following Git rules)
313        assert!(validate_model_name("").is_err()); // empty
314        assert!(validate_model_name(".model").is_err()); // starts with dot
315        assert!(validate_model_name("model.").is_err()); // ends with dot
316        assert!(validate_model_name("model..name").is_err()); // consecutive dots
317        assert!(validate_model_name("model.lock").is_err()); // ends with .lock
318        assert!(validate_model_name("@").is_err()); // just @
319        assert!(validate_model_name("model@{ref}").is_err()); // contains @{
320        assert!(validate_model_name("api").is_err()); // reserved
321        assert!(validate_model_name("model with spaces").is_err()); // spaces not allowed
322        assert!(validate_model_name("model~1").is_err()); // tilde not allowed
323        assert!(validate_model_name("model^HEAD").is_err()); // caret not allowed
324        assert!(validate_model_name("model:tag").is_err()); // colon not allowed
325        assert!(validate_model_name("model?query").is_err()); // question mark not allowed
326        assert!(validate_model_name("model*glob").is_err()); // asterisk not allowed
327        assert!(validate_model_name("model[bracket]").is_err()); // bracket not allowed
328    }
329
330    #[test]
331    fn test_git_ref_validation() -> Result<()> {
332        // Test that git2db's GitRef parsing handles various git reference formats
333
334        // Simple branch names
335        assert!(matches!(GitRef::parse("main")?, GitRef::Branch(_)));
336        assert!(matches!(
337            GitRef::parse("feature/new-model")?,
338            GitRef::Branch(_)
339        ));
340
341        // Tags (explicit tag syntax required)
342        assert!(matches!(GitRef::parse("tags/v1.0.0")?, GitRef::Tag(_)));
343        assert!(matches!(GitRef::parse("refs/tags/v2.1")?, GitRef::Tag(_)));
344
345        // Revspecs or DefaultBranch
346        // Note: git2db treats "HEAD" as DefaultBranch, not Revspec
347        assert!(matches!(GitRef::parse("HEAD")?, GitRef::DefaultBranch));
348        assert!(matches!(GitRef::parse("main~1")?, GitRef::Revspec(_)));
349        assert!(matches!(GitRef::parse("HEAD^")?, GitRef::Revspec(_)));
350        assert!(matches!(
351            GitRef::parse("branch..other")?,
352            GitRef::Revspec(_)
353        ));
354        assert!(matches!(
355            GitRef::parse("branch@{HEAD}")?,
356            GitRef::Revspec(_)
357        ));
358
359        // Commits
360        assert!(matches!(
361            GitRef::parse("1234567890abcdef1234567890abcdef12345678")?,
362            GitRef::Commit(_)
363        ));
364
365        // Test libgit2 validation separately (for reference)
366        assert!(git2::Reference::is_valid_name("refs/heads/main"));
367        assert!(git2::Reference::is_valid_name("refs/tags/v1.0.0"));
368        assert!(git2::Reference::is_valid_name(
369            "refs/heads/feature/new-model"
370        ));
371        assert!(git2::Reference::is_valid_name("HEAD"));
372        Ok(())
373    }
374}