pacha 0.2.5

Model, Data and Recipe Registry with full lineage tracking
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Remote registry client for Pacha
//!
//! Provides HTTP client for interacting with remote Pacha registries.
//! This module requires the `remote` feature to be enabled.
//!
//! # Example
//!
//! ```no_run
//! use pacha::remote::{RemoteRegistry, RegistryAuth};
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let registry = RemoteRegistry::new("https://registry.example.com")
//!     .with_auth(RegistryAuth::Token("my-token".to_string()));
//!
//! // Pull a model
//! let model = registry.pull_model("llama3", "1.0.0").await?;
//!
//! // List available models
//! let models = registry.list_models().await?;
//! # Ok(())
//! # }
//! ```

use crate::error::{PachaError, Result};
use crate::model::{Model, ModelVersion};
use serde::{Deserialize, Serialize};

// ============================================================================
// API Types
// ============================================================================

/// Remote registry API response for listing models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListModelsResponse {
    /// List of model names
    pub models: Vec<String>,
    /// Total count
    pub total: usize,
    /// Pagination cursor for next page
    pub next_cursor: Option<String>,
}

/// Remote registry API response for listing versions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListVersionsResponse {
    /// Model name
    pub model: String,
    /// List of versions
    pub versions: Vec<VersionInfo>,
}

/// Version information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionInfo {
    /// Version string (semver)
    pub version: String,
    /// Content hash (BLAKE3)
    pub hash: String,
    /// Size in bytes
    pub size: u64,
    /// Creation timestamp (ISO 8601)
    pub created_at: String,
    /// Stage (development, staging, production, archived)
    pub stage: String,
}

/// Remote registry API response for model metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelMetadataResponse {
    /// Model name
    pub name: String,
    /// Version
    pub version: String,
    /// Content hash
    pub hash: String,
    /// Size in bytes
    pub size: u64,
    /// Model card (description, metrics, etc.)
    pub card: Option<serde_json::Value>,
    /// Lineage information
    pub lineage: Option<LineageInfo>,
}

/// Lineage information from remote registry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineageInfo {
    /// Parent model (if derived)
    pub parent: Option<String>,
    /// Dataset used for training
    pub dataset: Option<String>,
    /// Recipe used
    pub recipe: Option<String>,
}

/// Push request body
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PushRequest {
    /// Model name
    pub name: String,
    /// Version
    pub version: String,
    /// Content hash (BLAKE3)
    pub hash: String,
    /// Model card
    pub card: Option<serde_json::Value>,
}

/// Push response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PushResponse {
    /// Upload URL for the artifact
    pub upload_url: String,
    /// Upload ID for tracking
    pub upload_id: String,
}

/// Authentication configuration
#[derive(Debug, Clone)]
pub enum RegistryAuth {
    /// No authentication
    None,
    /// Bearer token
    Token(String),
    /// Basic authentication
    Basic {
        /// Username
        username: String,
        /// Password
        password: String,
    },
    /// API key (header-based)
    ApiKey {
        /// Header name
        header: String,
        /// Key value
        key: String,
    },
}

impl Default for RegistryAuth {
    fn default() -> Self {
        Self::None
    }
}

// ============================================================================
// Remote Registry Client
// ============================================================================

/// Remote registry client
#[derive(Debug)]
pub struct RemoteRegistry {
    /// Base URL of the registry
    base_url: String,
    /// Authentication configuration
    auth: RegistryAuth,
    /// HTTP client (only available with `remote` feature)
    #[cfg(feature = "remote")]
    client: reqwest::Client,
}

impl RemoteRegistry {
    /// Create a new remote registry client
    #[must_use]
    pub fn new(base_url: impl Into<String>) -> Self {
        let base_url = base_url.into().trim_end_matches('/').to_string();

        Self {
            base_url,
            auth: RegistryAuth::None,
            #[cfg(feature = "remote")]
            client: reqwest::Client::builder()
                .user_agent(concat!("pacha/", env!("CARGO_PKG_VERSION")))
                .build()
                .expect("Failed to create HTTP client"),
        }
    }

    /// Set authentication
    #[must_use]
    pub fn with_auth(mut self, auth: RegistryAuth) -> Self {
        self.auth = auth;
        self
    }

    /// Get the base URL
    #[must_use]
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Check if authentication is configured
    #[must_use]
    pub fn has_auth(&self) -> bool {
        !matches!(self.auth, RegistryAuth::None)
    }

    // -------------------------------------------------------------------------
    // Read Operations
    // -------------------------------------------------------------------------

    /// List all models in the registry
    #[cfg(feature = "remote")]
    pub async fn list_models(&self) -> Result<ListModelsResponse> {
        let url = format!("{}/api/v1/models", self.base_url);
        let response = self
            .build_request(reqwest::Method::GET, &url)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        self.handle_response(response).await
    }

    /// List all models (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn list_models(&self) -> Result<ListModelsResponse> {
        Err(PachaError::UnsupportedOperation {
            operation: "list_models".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    /// List versions of a model
    #[cfg(feature = "remote")]
    pub async fn list_versions(&self, model: &str) -> Result<ListVersionsResponse> {
        let url = format!("{}/api/v1/models/{}/versions", self.base_url, model);
        let response = self
            .build_request(reqwest::Method::GET, &url)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        self.handle_response(response).await
    }

    /// List versions (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn list_versions(&self, _model: &str) -> Result<ListVersionsResponse> {
        Err(PachaError::UnsupportedOperation {
            operation: "list_versions".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    /// Get model metadata
    #[cfg(feature = "remote")]
    pub async fn get_metadata(&self, model: &str, version: &str) -> Result<ModelMetadataResponse> {
        let url = format!(
            "{}/api/v1/models/{}/versions/{}",
            self.base_url, model, version
        );
        let response = self
            .build_request(reqwest::Method::GET, &url)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        self.handle_response(response).await
    }

    /// Get metadata (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn get_metadata(
        &self,
        _model: &str,
        _version: &str,
    ) -> Result<ModelMetadataResponse> {
        Err(PachaError::UnsupportedOperation {
            operation: "get_metadata".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    /// Pull model artifact data
    #[cfg(feature = "remote")]
    pub async fn pull_model(&self, model: &str, version: &str) -> Result<Vec<u8>> {
        let url = format!(
            "{}/api/v1/models/{}/versions/{}/artifact",
            self.base_url, model, version
        );
        let response = self
            .build_request(reqwest::Method::GET, &url)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        response
            .bytes()
            .await
            .map(|b| b.to_vec())
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))
    }

    /// Pull model (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn pull_model(&self, _model: &str, _version: &str) -> Result<Vec<u8>> {
        Err(PachaError::UnsupportedOperation {
            operation: "pull_model".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    // -------------------------------------------------------------------------
    // Write Operations
    // -------------------------------------------------------------------------

    /// Initiate a push operation
    #[cfg(feature = "remote")]
    pub async fn init_push(&self, request: &PushRequest) -> Result<PushResponse> {
        let url = format!("{}/api/v1/models/{}/versions", self.base_url, request.name);
        let response = self
            .build_request(reqwest::Method::POST, &url)
            .json(request)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        self.handle_response(response).await
    }

    /// Init push (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn init_push(&self, _request: &PushRequest) -> Result<PushResponse> {
        Err(PachaError::UnsupportedOperation {
            operation: "init_push".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    /// Upload artifact data to the provided URL
    #[cfg(feature = "remote")]
    pub async fn upload_artifact(&self, upload_url: &str, data: Vec<u8>) -> Result<()> {
        let response = self
            .build_request(reqwest::Method::PUT, upload_url)
            .body(data)
            .send()
            .await
            .map_err(|e| PachaError::Io(std::io::Error::other(e.to_string())))?;

        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        Ok(())
    }

    /// Upload artifact (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn upload_artifact(&self, _upload_url: &str, _data: Vec<u8>) -> Result<()> {
        Err(PachaError::UnsupportedOperation {
            operation: "upload_artifact".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    /// Complete push operation (full workflow)
    #[cfg(feature = "remote")]
    pub async fn push_model(
        &self,
        name: &str,
        version: &ModelVersion,
        data: &[u8],
        card: Option<serde_json::Value>,
    ) -> Result<()> {
        let hash = blake3::hash(data).to_hex().to_string();

        let request = PushRequest {
            name: name.to_string(),
            version: version.to_string(),
            hash,
            card,
        };

        let response = self.init_push(&request).await?;
        self.upload_artifact(&response.upload_url, data.to_vec())
            .await
    }

    /// Push model (stub for non-remote builds)
    #[cfg(not(feature = "remote"))]
    pub async fn push_model(
        &self,
        _name: &str,
        _version: &ModelVersion,
        _data: &[u8],
        _card: Option<serde_json::Value>,
    ) -> Result<()> {
        Err(PachaError::UnsupportedOperation {
            operation: "push_model".to_string(),
            reason: "Remote feature not enabled. Rebuild with --features remote".to_string(),
        })
    }

    // -------------------------------------------------------------------------
    // Internal Helpers
    // -------------------------------------------------------------------------

    #[cfg(feature = "remote")]
    fn build_request(&self, method: reqwest::Method, url: &str) -> reqwest::RequestBuilder {
        let mut request = self.client.request(method, url);

        match &self.auth {
            RegistryAuth::None => {}
            RegistryAuth::Token(token) => {
                request = request.bearer_auth(token);
            }
            RegistryAuth::Basic { username, password } => {
                request = request.basic_auth(username, Some(password));
            }
            RegistryAuth::ApiKey { header, key } => {
                request = request.header(header.as_str(), key.as_str());
            }
        }

        request
    }

    #[cfg(feature = "remote")]
    async fn handle_response<T: serde::de::DeserializeOwned>(
        &self,
        response: reqwest::Response,
    ) -> Result<T> {
        if !response.status().is_success() {
            return Err(self.handle_error_response(response).await);
        }

        response.json().await.map_err(|e| {
            PachaError::Json(serde_json::Error::io(std::io::Error::other(e.to_string())))
        })
    }

    #[cfg(feature = "remote")]
    async fn handle_error_response(&self, response: reqwest::Response) -> PachaError {
        let status = response.status();
        let body = response.text().await.unwrap_or_default();

        if status == reqwest::StatusCode::NOT_FOUND {
            PachaError::NotFound {
                kind: "remote".to_string(),
                name: body,
                version: "unknown".to_string(),
            }
        } else if status == reqwest::StatusCode::UNAUTHORIZED
            || status == reqwest::StatusCode::FORBIDDEN
        {
            PachaError::Validation(format!("Authentication failed: {body}"))
        } else {
            PachaError::Io(std::io::Error::other(format!("HTTP {}: {}", status, body)))
        }
    }
}

// ============================================================================
// Resolver Integration
// ============================================================================

/// Pull a model from remote registry and optionally cache locally
pub async fn pull_to_local(
    remote: &RemoteRegistry,
    local: &crate::registry::Registry,
    model: &str,
    version: &str,
) -> Result<Model> {
    // Get metadata first
    let metadata = remote.get_metadata(model, version).await?;

    // Parse version
    let model_version = parse_version(&metadata.version)?;

    // Check if already cached locally
    if let Ok(local_model) = local.get_model(model, &model_version) {
        // Verify hash matches
        let local_artifact = local.get_model_artifact(model, &model_version)?;
        let local_hash = blake3::hash(&local_artifact).to_hex().to_string();

        if local_hash == metadata.hash {
            return Ok(local_model);
        }
        // Hash mismatch - need to re-pull
    }

    // Pull artifact
    let data = remote.pull_model(model, version).await?;

    // Verify hash
    let hash = blake3::hash(&data).to_hex().to_string();
    if hash != metadata.hash {
        return Err(PachaError::HashMismatch {
            expected: metadata.hash,
            actual: hash,
        });
    }

    // Register locally
    let card = metadata
        .card
        .and_then(|v| serde_json::from_value(v).ok())
        .unwrap_or_else(|| crate::model::ModelCard::new("Pulled from remote registry"));

    local.register_model(model, &model_version, &data, card)?;

    local.get_model(model, &model_version)
}

/// Push a local model to remote registry
pub async fn push_to_remote(
    local: &crate::registry::Registry,
    remote: &RemoteRegistry,
    model: &str,
    version: &ModelVersion,
) -> Result<()> {
    // Get local model and artifact
    let local_model = local.get_model(model, version)?;
    let data = local.get_model_artifact(model, version)?;

    // Convert card to JSON
    let card = serde_json::to_value(&local_model.card).ok();

    // Push to remote
    remote.push_model(model, version, &data, card).await
}

/// Parse version string into ModelVersion
fn parse_version(s: &str) -> Result<ModelVersion> {
    let parts: Vec<&str> = s.split('.').collect();
    if parts.len() == 3 {
        let major: u32 = parts[0]
            .parse()
            .map_err(|_| PachaError::InvalidVersion(s.to_string()))?;
        let minor: u32 = parts[1]
            .parse()
            .map_err(|_| PachaError::InvalidVersion(s.to_string()))?;
        let patch: u32 = parts[2]
            .parse()
            .map_err(|_| PachaError::InvalidVersion(s.to_string()))?;
        return Ok(ModelVersion::new(major, minor, patch));
    }
    Err(PachaError::InvalidVersion(s.to_string()))
}

// ============================================================================
// TESTS - EXTREME TDD
// ============================================================================

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

    // -------------------------------------------------------------------------
    // API Types Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_list_models_response_serialize() {
        let response = ListModelsResponse {
            models: vec!["llama3".to_string(), "mistral".to_string()],
            total: 2,
            next_cursor: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("llama3"));
        assert!(json.contains("mistral"));
    }

    #[test]
    fn test_list_models_response_deserialize() {
        let json = r#"{"models":["llama3"],"total":1,"next_cursor":null}"#;
        let response: ListModelsResponse = serde_json::from_str(json).unwrap();

        assert_eq!(response.models.len(), 1);
        assert_eq!(response.models[0], "llama3");
        assert_eq!(response.total, 1);
        assert!(response.next_cursor.is_none());
    }

    #[test]
    fn test_version_info_serialize() {
        let info = VersionInfo {
            version: "1.0.0".to_string(),
            hash: "abc123".to_string(),
            size: 1024,
            created_at: "2024-01-01T00:00:00Z".to_string(),
            stage: "production".to_string(),
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("1.0.0"));
        assert!(json.contains("abc123"));
    }

    #[test]
    fn test_version_info_deserialize() {
        let json = r#"{"version":"2.0.0","hash":"def456","size":2048,"created_at":"2024-06-01T00:00:00Z","stage":"staging"}"#;
        let info: VersionInfo = serde_json::from_str(json).unwrap();

        assert_eq!(info.version, "2.0.0");
        assert_eq!(info.hash, "def456");
        assert_eq!(info.size, 2048);
        assert_eq!(info.stage, "staging");
    }

    #[test]
    fn test_model_metadata_response() {
        let response = ModelMetadataResponse {
            name: "test-model".to_string(),
            version: "1.2.3".to_string(),
            hash: "hash123".to_string(),
            size: 4096,
            card: Some(serde_json::json!({"description": "Test model"})),
            lineage: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: ModelMetadataResponse = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.name, "test-model");
        assert_eq!(parsed.version, "1.2.3");
    }

    #[test]
    fn test_lineage_info() {
        let lineage = LineageInfo {
            parent: Some("base-model:1.0.0".to_string()),
            dataset: Some("training-data:1.0.0".to_string()),
            recipe: Some("fine-tune-recipe:1.0.0".to_string()),
        };

        let json = serde_json::to_string(&lineage).unwrap();
        assert!(json.contains("base-model"));
        assert!(json.contains("training-data"));
    }

    #[test]
    fn test_push_request() {
        let request = PushRequest {
            name: "new-model".to_string(),
            version: "0.1.0".to_string(),
            hash: "newhash".to_string(),
            card: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("new-model"));
        assert!(json.contains("0.1.0"));
    }

    #[test]
    fn test_push_response() {
        let json =
            r#"{"upload_url":"https://storage.example.com/upload/123","upload_id":"upload-123"}"#;
        let response: PushResponse = serde_json::from_str(json).unwrap();

        assert!(response.upload_url.contains("storage.example.com"));
        assert_eq!(response.upload_id, "upload-123");
    }

    // -------------------------------------------------------------------------
    // Authentication Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_registry_auth_default() {
        let auth = RegistryAuth::default();
        assert!(matches!(auth, RegistryAuth::None));
    }

    #[test]
    fn test_registry_auth_token() {
        let auth = RegistryAuth::Token("my-token".to_string());
        assert!(matches!(auth, RegistryAuth::Token(_)));
    }

    #[test]
    fn test_registry_auth_basic() {
        let auth = RegistryAuth::Basic {
            username: "user".to_string(),
            password: "pass".to_string(),
        };
        assert!(matches!(auth, RegistryAuth::Basic { .. }));
    }

    #[test]
    fn test_registry_auth_api_key() {
        let auth = RegistryAuth::ApiKey {
            header: "X-Api-Key".to_string(),
            key: "secret-key".to_string(),
        };
        assert!(matches!(auth, RegistryAuth::ApiKey { .. }));
    }

    // -------------------------------------------------------------------------
    // RemoteRegistry Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_remote_registry_new() {
        let registry = RemoteRegistry::new("https://registry.example.com");
        assert_eq!(registry.base_url(), "https://registry.example.com");
        assert!(!registry.has_auth());
    }

    #[test]
    fn test_remote_registry_trailing_slash() {
        let registry = RemoteRegistry::new("https://registry.example.com/");
        assert_eq!(registry.base_url(), "https://registry.example.com");
    }

    #[test]
    fn test_remote_registry_with_auth() {
        let registry = RemoteRegistry::new("https://registry.example.com")
            .with_auth(RegistryAuth::Token("token".to_string()));
        assert!(registry.has_auth());
    }

    #[test]
    fn test_remote_registry_no_auth() {
        let registry =
            RemoteRegistry::new("https://registry.example.com").with_auth(RegistryAuth::None);
        assert!(!registry.has_auth());
    }

    // -------------------------------------------------------------------------
    // Version Parsing Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_parse_version_valid() {
        let v = parse_version("1.2.3").unwrap();
        assert_eq!(v, ModelVersion::new(1, 2, 3));
    }

    #[test]
    fn test_parse_version_zeros() {
        let v = parse_version("0.0.0").unwrap();
        assert_eq!(v, ModelVersion::new(0, 0, 0));
    }

    #[test]
    fn test_parse_version_large() {
        let v = parse_version("100.200.300").unwrap();
        assert_eq!(v, ModelVersion::new(100, 200, 300));
    }

    #[test]
    fn test_parse_version_invalid_format() {
        assert!(parse_version("1.2").is_err());
        assert!(parse_version("1").is_err());
        assert!(parse_version("1.2.3.4").is_err());
    }

    #[test]
    fn test_parse_version_non_numeric() {
        assert!(parse_version("a.b.c").is_err());
        assert!(parse_version("1.x.0").is_err());
    }

    // -------------------------------------------------------------------------
    // Serialization Round-Trip Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_list_versions_response_roundtrip() {
        let response = ListVersionsResponse {
            model: "test".to_string(),
            versions: vec![
                VersionInfo {
                    version: "1.0.0".to_string(),
                    hash: "hash1".to_string(),
                    size: 100,
                    created_at: "2024-01-01T00:00:00Z".to_string(),
                    stage: "production".to_string(),
                },
                VersionInfo {
                    version: "2.0.0".to_string(),
                    hash: "hash2".to_string(),
                    size: 200,
                    created_at: "2024-06-01T00:00:00Z".to_string(),
                    stage: "staging".to_string(),
                },
            ],
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: ListVersionsResponse = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.model, "test");
        assert_eq!(parsed.versions.len(), 2);
    }

    #[test]
    fn test_metadata_with_lineage_roundtrip() {
        let response = ModelMetadataResponse {
            name: "derived-model".to_string(),
            version: "1.0.0".to_string(),
            hash: "hash".to_string(),
            size: 1000,
            card: Some(serde_json::json!({"description": "A derived model"})),
            lineage: Some(LineageInfo {
                parent: Some("base:1.0.0".to_string()),
                dataset: Some("data:1.0.0".to_string()),
                recipe: None,
            }),
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: ModelMetadataResponse = serde_json::from_str(&json).unwrap();

        assert!(parsed.lineage.is_some());
        let lineage = parsed.lineage.unwrap();
        assert_eq!(lineage.parent.unwrap(), "base:1.0.0");
    }

    // -------------------------------------------------------------------------
    // Edge Cases
    // -------------------------------------------------------------------------

    #[test]
    fn test_empty_models_list() {
        let response = ListModelsResponse {
            models: vec![],
            total: 0,
            next_cursor: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: ListModelsResponse = serde_json::from_str(&json).unwrap();

        assert!(parsed.models.is_empty());
        assert_eq!(parsed.total, 0);
    }

    #[test]
    fn test_pagination_cursor() {
        let response = ListModelsResponse {
            models: vec!["model1".to_string()],
            total: 100,
            next_cursor: Some("cursor-abc".to_string()),
        };

        let json = serde_json::to_string(&response).unwrap();
        let parsed: ListModelsResponse = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.next_cursor.unwrap(), "cursor-abc");
    }

    #[test]
    fn test_push_request_with_card() {
        let request = PushRequest {
            name: "model".to_string(),
            version: "1.0.0".to_string(),
            hash: "hash".to_string(),
            card: Some(serde_json::json!({
                "description": "Test model",
                "metrics": {"accuracy": 0.95}
            })),
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("accuracy"));
        assert!(json.contains("0.95"));
    }
}