Skip to main content

logit_loom_models/
lib.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2
3#![doc = include_str!("../README.md")]
4#![forbid(unsafe_code)]
5
6mod acquisition;
7
8use std::{
9    collections::HashSet,
10    fs::File,
11    io::{self, Read as _},
12    path::{Component, Path, PathBuf},
13};
14
15use serde::{Deserialize, Serialize};
16use sha2::{Digest as _, Sha256};
17use thiserror::Error;
18
19pub use acquisition::{
20    AcquisitionMethod, AcquisitionReport, AcquisitionReportError, AcquisitionStatus,
21    PendingArtifact, PendingReason, ProfileAcquisition,
22};
23
24/// Current serialized catalog schema.
25pub const CATALOG_SCHEMA_VERSION: u32 = 1;
26/// Identity domain for the interpretation of the embedded catalog.
27pub const CATALOG_IDENTITY_DOMAIN: &str = "logit-loom-model-catalog-v1";
28/// Stable ID of the small default Qwen text profile.
29pub const QWEN3_SMALL_PROFILE_ID: &str = "qwen3-0.6b-q8-0";
30/// Source ID containing the small Qwen GGUF.
31pub const QWEN3_SMALL_SOURCE_ID: &str = "qwen3-gguf";
32/// Source-relative path of the small Qwen `Q8_0` GGUF.
33pub const QWEN3_SMALL_ARTIFACT_PATH: &str = "Qwen3-0.6B-Q8_0.gguf";
34
35const CATALOG_BYTES: &[u8] = include_bytes!("../profiles.json");
36const DEFAULT_PROFILE_COUNT: usize = 3;
37const MAX_PROFILES: usize = 32;
38const MAX_SOURCES_PER_PROFILE: usize = 8;
39const MAX_FILES_PER_SOURCE: usize = 64;
40const MAX_TEXT_BYTES: usize = 2_048;
41const MAX_PATH_BYTES: usize = 512;
42const MAX_FILE_BYTES: u64 = 256 * 1024 * 1024 * 1024;
43const MAX_PROFILE_BYTES: u64 = 512 * 1024 * 1024 * 1024;
44const HASH_BUFFER_BYTES: usize = 1024 * 1024;
45const WEIGHT_SUFFIXES: &[&str] = &[
46    ".gguf",
47    ".safetensors",
48    ".onnx",
49    ".pt",
50    ".pth",
51    ".bin",
52    ".ckpt",
53];
54
55/// One validated model acquisition catalog.
56#[derive(Clone, Debug, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct Catalog {
59    schema_version: u32,
60    identity_domain: String,
61    default_profiles: Vec<String>,
62    profiles: Vec<Profile>,
63}
64
65impl Catalog {
66    /// Parses and validates the catalog embedded in this crate.
67    ///
68    /// # Errors
69    ///
70    /// Returns a parse or validation error if the packaged catalog is invalid.
71    pub fn embedded() -> Result<Self, CatalogError> {
72        Self::from_slice(CATALOG_BYTES)
73    }
74
75    /// Parses and validates a bounded catalog value.
76    ///
77    /// # Errors
78    ///
79    /// Returns a parse or validation error if the input is malformed.
80    pub fn from_slice(bytes: &[u8]) -> Result<Self, CatalogError> {
81        if bytes.len() > MAX_TEXT_BYTES * MAX_FILES_PER_SOURCE * MAX_PROFILES {
82            return Err(CatalogError::Invalid(
83                "serialized catalog exceeds the input bound".to_owned(),
84            ));
85        }
86        let catalog = serde_json::from_slice::<Self>(bytes).map_err(CatalogError::Parse)?;
87        catalog.validate()?;
88        Ok(catalog)
89    }
90
91    /// Returns the catalog schema version.
92    pub const fn schema_version(&self) -> u32 {
93        self.schema_version
94    }
95
96    /// Returns the interpretation domain for catalog identities.
97    pub fn identity_domain(&self) -> &str {
98        &self.identity_domain
99    }
100
101    /// Returns the SHA-256 identity of the exact packaged JSON bytes.
102    pub fn packaged_sha256(&self) -> String {
103        sha256_bytes(CATALOG_BYTES)
104    }
105
106    /// Returns the profile IDs selected as default experiment profiles.
107    pub fn default_profiles(&self) -> &[String] {
108        &self.default_profiles
109    }
110
111    /// Returns every catalog profile in declared order.
112    pub fn profiles(&self) -> &[Profile] {
113        &self.profiles
114    }
115
116    /// Finds one exact profile ID.
117    pub fn find_profile(&self, id: &str) -> Option<&Profile> {
118        self.profiles.iter().find(|profile| profile.id == id)
119    }
120
121    /// Validates catalog bounds, identities, and cross-field relationships.
122    ///
123    /// # Errors
124    ///
125    /// Returns the first invalid catalog invariant.
126    pub fn validate(&self) -> Result<(), CatalogError> {
127        if self.schema_version != CATALOG_SCHEMA_VERSION {
128            return invalid(format!(
129                "schema_version must be {CATALOG_SCHEMA_VERSION}, got {}",
130                self.schema_version
131            ));
132        }
133        if self.identity_domain != CATALOG_IDENTITY_DOMAIN {
134            return invalid(format!(
135                "identity_domain must be {CATALOG_IDENTITY_DOMAIN:?}"
136            ));
137        }
138        if self.profiles.is_empty() || self.profiles.len() > MAX_PROFILES {
139            return invalid(format!(
140                "profiles must contain between 1 and {MAX_PROFILES} entries"
141            ));
142        }
143        if self.default_profiles.len() != DEFAULT_PROFILE_COUNT {
144            return invalid(format!(
145                "default_profiles must contain exactly {DEFAULT_PROFILE_COUNT} entries"
146            ));
147        }
148
149        let mut profile_ids = HashSet::new();
150        for profile in &self.profiles {
151            if !profile_ids.insert(profile.id.as_str()) {
152                return invalid(format!("duplicate profile id {:?}", profile.id));
153            }
154            validate_profile(profile)?;
155        }
156
157        let mut default_ids = HashSet::new();
158        for id in &self.default_profiles {
159            if !default_ids.insert(id.as_str()) {
160                return invalid(format!("duplicate default profile id {id:?}"));
161            }
162            if !profile_ids.contains(id.as_str()) {
163                return invalid(format!("default profile {id:?} does not exist"));
164            }
165        }
166        Ok(())
167    }
168}
169
170/// One optional model and its exact acquisition contract.
171#[derive(Clone, Debug, Deserialize)]
172#[serde(deny_unknown_fields)]
173pub struct Profile {
174    id: String,
175    display_name: String,
176    modality: Modality,
177    role: Role,
178    integration_status: IntegrationStatus,
179    acceptance_status: AcceptanceStatus,
180    adapter_target: AdapterTarget,
181    requires_accelerator: bool,
182    remote_code_policy: RemoteCodePolicy,
183    notes: String,
184    sources: Vec<Source>,
185}
186
187impl Profile {
188    /// Returns the stable profile ID.
189    pub fn id(&self) -> &str {
190        &self.id
191    }
192
193    /// Returns the human-readable profile name.
194    pub fn display_name(&self) -> &str {
195        &self.display_name
196    }
197
198    /// Returns the profile modality.
199    pub const fn modality(&self) -> Modality {
200        self.modality
201    }
202
203    /// Returns the intended catalog role.
204    pub const fn role(&self) -> Role {
205        self.role
206    }
207
208    /// Returns the checked-in integration status.
209    pub const fn integration_status(&self) -> IntegrationStatus {
210        self.integration_status
211    }
212
213    /// Returns the checked-in model-backed acceptance status.
214    pub const fn acceptance_status(&self) -> AcceptanceStatus {
215        self.acceptance_status
216    }
217
218    /// Returns the maintained adapter family.
219    pub const fn adapter_target(&self) -> AdapterTarget {
220        self.adapter_target
221    }
222
223    /// Returns whether model-backed execution requires accelerator placement.
224    pub const fn requires_accelerator(&self) -> bool {
225        self.requires_accelerator
226    }
227
228    /// Returns the policy for executable code supplied by a model repository.
229    pub const fn remote_code_policy(&self) -> RemoteCodePolicy {
230        self.remote_code_policy
231    }
232
233    /// Returns the profile's mechanics-only description.
234    pub fn notes(&self) -> &str {
235        &self.notes
236    }
237
238    /// Returns exact acquisition sources in declared order.
239    pub fn sources(&self) -> &[Source] {
240        &self.sources
241    }
242
243    /// Returns the sum of catalogued file sizes.
244    pub fn total_bytes(&self) -> u64 {
245        self.sources
246            .iter()
247            .flat_map(|source| &source.files)
248            .fold(0_u64, |total, file| total.saturating_add(file.bytes))
249    }
250
251    /// Returns the number of exact files in this profile.
252    pub fn file_count(&self) -> usize {
253        self.sources.iter().map(|source| source.files.len()).sum()
254    }
255
256    /// Finds an exact source and artifact path.
257    pub fn find_artifact(&self, source_id: &str, path: &str) -> Option<(&Source, &ArtifactFile)> {
258        self.sources
259            .iter()
260            .find(|source| source.id == source_id)
261            .and_then(|source| {
262                source
263                    .files
264                    .iter()
265                    .find(|artifact| artifact.path == path)
266                    .map(|artifact| (source, artifact))
267            })
268    }
269
270    /// Verifies one caller-supplied local file against an exact catalog entry.
271    ///
272    /// The returned receipt deliberately excludes the local filesystem path.
273    ///
274    /// # Errors
275    ///
276    /// Returns an unknown-artifact, I/O, size, or digest error.
277    pub fn verify_artifact(
278        &self,
279        catalog_sha256: &str,
280        source_id: &str,
281        artifact_path: &str,
282        local_path: impl AsRef<Path>,
283    ) -> Result<VerifiedArtifact, ArtifactError> {
284        let (source, artifact) = self
285            .find_artifact(source_id, artifact_path)
286            .ok_or_else(|| ArtifactError::Unknown {
287                profile: self.id.clone(),
288                source_id: source_id.to_owned(),
289                path: artifact_path.to_owned(),
290            })?;
291        let local_path = local_path.as_ref();
292        let actual_bytes = std::fs::metadata(local_path)
293            .map_err(|source| ArtifactError::Metadata {
294                path: local_path.to_owned(),
295                source,
296            })?
297            .len();
298        if actual_bytes != artifact.bytes {
299            return Err(ArtifactError::Size {
300                path: local_path.to_owned(),
301                actual: actual_bytes,
302                expected: artifact.bytes,
303            });
304        }
305        let actual_sha256 = match &artifact.sha256 {
306            Some(expected) => {
307                let actual = sha256_file(local_path)?;
308                if &actual != expected {
309                    return Err(ArtifactError::Digest {
310                        path: local_path.to_owned(),
311                        actual,
312                        expected: expected.clone(),
313                    });
314                }
315                Some(actual)
316            }
317            None => None,
318        };
319        Ok(VerifiedArtifact {
320            local_path: local_path.to_owned(),
321            receipt: ArtifactReceipt {
322                catalog_domain: CATALOG_IDENTITY_DOMAIN.to_owned(),
323                catalog_sha256: catalog_sha256.to_owned(),
324                profile_id: self.id.clone(),
325                source_id: source.id.clone(),
326                repository: source.repository.clone(),
327                revision: source.revision.clone(),
328                artifact_path: artifact.path.clone(),
329                bytes: artifact.bytes,
330                sha256: actual_sha256,
331            },
332        })
333    }
334}
335
336/// Model modality.
337#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
338#[serde(rename_all = "kebab-case")]
339pub enum Modality {
340    /// Autoregressive text generation.
341    Text,
342    /// Iterative image generation.
343    Image,
344}
345
346impl Modality {
347    /// Returns the serialized spelling.
348    pub const fn as_str(self) -> &'static str {
349        match self {
350            Self::Text => "text",
351            Self::Image => "image",
352        }
353    }
354}
355
356/// Intended profile complexity.
357#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
358#[serde(rename_all = "kebab-case")]
359pub enum Role {
360    /// Small profile intended for short experiments.
361    Toy,
362    /// Larger profile exercising advanced mechanics.
363    Advanced,
364}
365
366impl Role {
367    /// Returns the serialized spelling.
368    pub const fn as_str(self) -> &'static str {
369        match self {
370            Self::Toy => "toy",
371            Self::Advanced => "advanced",
372        }
373    }
374}
375
376/// Maintained adapter family.
377#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
378#[serde(rename_all = "kebab-case")]
379pub enum AdapterTarget {
380    /// The llama.cpp text adapter.
381    Llamacpp,
382    /// The diffusion image adapter.
383    Diffusion,
384}
385
386/// Checked-in integration status.
387#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
388#[serde(rename_all = "kebab-case")]
389pub enum IntegrationStatus {
390    /// Exact acquisition metadata exists; maintained execution is not accepted.
391    Catalogued,
392    /// Maintained adapter, runbook, and acceptance evidence exist.
393    FirstClass,
394}
395
396impl IntegrationStatus {
397    /// Returns the serialized spelling.
398    pub const fn as_str(self) -> &'static str {
399        match self {
400            Self::Catalogued => "catalogued",
401            Self::FirstClass => "first-class",
402        }
403    }
404}
405
406/// Checked-in model-backed acceptance status.
407#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
408#[serde(rename_all = "kebab-case")]
409pub enum AcceptanceStatus {
410    /// No retained acceptance report exists for this revision.
411    NotRun,
412    /// A retained mechanics report passed its schema checks.
413    Passed,
414}
415
416impl AcceptanceStatus {
417    /// Returns the serialized spelling.
418    pub const fn as_str(self) -> &'static str {
419        match self {
420            Self::NotRun => "not-run",
421            Self::Passed => "passed",
422        }
423    }
424}
425
426/// Policy for executable code in remote model repositories.
427#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)]
428#[serde(rename_all = "kebab-case")]
429pub enum RemoteCodePolicy {
430    /// Remote repository code must not execute.
431    Forbidden,
432}
433
434/// One immutable repository source.
435#[derive(Clone, Debug, Deserialize)]
436#[serde(deny_unknown_fields)]
437pub struct Source {
438    id: String,
439    repository: String,
440    revision: String,
441    local_subdir: String,
442    files: Vec<ArtifactFile>,
443}
444
445impl Source {
446    /// Returns the source ID within its profile.
447    pub fn id(&self) -> &str {
448        &self.id
449    }
450
451    /// Returns the Hugging Face repository name.
452    pub fn repository(&self) -> &str {
453        &self.repository
454    }
455
456    /// Returns the exact immutable source revision.
457    pub fn revision(&self) -> &str {
458        &self.revision
459    }
460
461    /// Returns the profile-relative destination directory.
462    pub fn local_subdir(&self) -> &str {
463        &self.local_subdir
464    }
465
466    /// Returns exact files in declared order.
467    pub fn files(&self) -> &[ArtifactFile] {
468        &self.files
469    }
470}
471
472/// One exact file in an acquisition source.
473#[derive(Clone, Debug, Deserialize)]
474#[serde(deny_unknown_fields)]
475pub struct ArtifactFile {
476    path: String,
477    bytes: u64,
478    sha256: Option<String>,
479}
480
481impl ArtifactFile {
482    /// Returns the source-relative path.
483    pub fn path(&self) -> &str {
484        &self.path
485    }
486
487    /// Returns the exact expected byte count.
488    pub const fn bytes(&self) -> u64 {
489        self.bytes
490    }
491
492    /// Returns the expected SHA-256 digest, when recorded.
493    pub fn sha256(&self) -> Option<&str> {
494        self.sha256.as_deref()
495    }
496}
497
498/// Serializable evidence that one exact local artifact was verified.
499#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
500#[serde(deny_unknown_fields)]
501pub struct ArtifactReceipt {
502    /// Catalog interpretation domain.
503    pub catalog_domain: String,
504    /// SHA-256 of the exact packaged catalog JSON.
505    pub catalog_sha256: String,
506    /// Stable profile ID.
507    pub profile_id: String,
508    /// Stable source ID within the profile.
509    pub source_id: String,
510    /// Upstream repository.
511    pub repository: String,
512    /// Exact immutable upstream revision.
513    pub revision: String,
514    /// Source-relative artifact path.
515    pub artifact_path: String,
516    /// Exact artifact size.
517    pub bytes: u64,
518    /// Verified SHA-256 digest, when the catalog declares one.
519    pub sha256: Option<String>,
520}
521
522/// A verified artifact and its caller-local path.
523#[derive(Clone, Debug)]
524pub struct VerifiedArtifact {
525    local_path: PathBuf,
526    receipt: ArtifactReceipt,
527}
528
529impl VerifiedArtifact {
530    /// Returns the verified caller-local path.
531    pub fn path(&self) -> &Path {
532        &self.local_path
533    }
534
535    /// Returns the path-free verification receipt.
536    pub const fn receipt(&self) -> &ArtifactReceipt {
537        &self.receipt
538    }
539}
540
541/// Catalog parsing or invariant failure.
542#[derive(Debug, Error)]
543#[non_exhaustive]
544pub enum CatalogError {
545    /// JSON parsing failed.
546    #[error("failed to parse model catalog: {0}")]
547    Parse(serde_json::Error),
548    /// A bounded catalog invariant failed.
549    #[error("invalid model catalog: {0}")]
550    Invalid(String),
551}
552
553/// Local artifact verification failure.
554#[derive(Debug, Error)]
555#[non_exhaustive]
556pub enum ArtifactError {
557    /// The profile does not declare the requested source and artifact.
558    #[error("profile {profile:?} has no artifact {source_id:?}/{path:?}")]
559    Unknown {
560        /// Profile ID.
561        profile: String,
562        /// Source ID.
563        source_id: String,
564        /// Source-relative file path.
565        path: String,
566    },
567    /// File metadata could not be read.
568    #[error("failed to inspect artifact {path}: {source}")]
569    Metadata {
570        /// Caller-local file path.
571        path: PathBuf,
572        /// Underlying I/O failure.
573        source: io::Error,
574    },
575    /// File size differs from the catalog.
576    #[error("artifact {path} has {actual} bytes; expected {expected}")]
577    Size {
578        /// Caller-local file path.
579        path: PathBuf,
580        /// Observed bytes.
581        actual: u64,
582        /// Catalogued bytes.
583        expected: u64,
584    },
585    /// File contents could not be read.
586    #[error("failed to read artifact {path}: {source}")]
587    Read {
588        /// Caller-local file path.
589        path: PathBuf,
590        /// Underlying I/O failure.
591        source: io::Error,
592    },
593    /// File digest differs from the catalog.
594    #[error("artifact {path} has SHA-256 {actual}; expected {expected}")]
595    Digest {
596        /// Caller-local file path.
597        path: PathBuf,
598        /// Observed lowercase SHA-256.
599        actual: String,
600        /// Catalogued lowercase SHA-256.
601        expected: String,
602    },
603}
604
605fn validate_profile(profile: &Profile) -> Result<(), CatalogError> {
606    validate_slug("profile id", &profile.id)?;
607    validate_text("display_name", &profile.display_name)?;
608    validate_text("notes", &profile.notes)?;
609    if profile.integration_status == IntegrationStatus::FirstClass
610        && profile.acceptance_status != AcceptanceStatus::Passed
611    {
612        return invalid(format!(
613            "first-class profile {:?} must have passed acceptance status",
614            profile.id
615        ));
616    }
617    match (profile.modality, profile.adapter_target) {
618        (Modality::Text, AdapterTarget::Llamacpp) | (Modality::Image, AdapterTarget::Diffusion) => {
619        }
620        _ => {
621            return invalid(format!(
622                "profile {:?} has an adapter target inconsistent with its modality",
623                profile.id
624            ));
625        }
626    }
627    if profile.sources.is_empty() || profile.sources.len() > MAX_SOURCES_PER_PROFILE {
628        return invalid(format!(
629            "profile {:?} must contain between 1 and {MAX_SOURCES_PER_PROFILE} sources",
630            profile.id
631        ));
632    }
633
634    let mut source_ids = HashSet::new();
635    let mut local_subdirs = HashSet::new();
636    let mut total_bytes = 0_u64;
637    for source in &profile.sources {
638        if !source_ids.insert(source.id.as_str()) {
639            return invalid(format!(
640                "profile {:?} has duplicate source id {:?}",
641                profile.id, source.id
642            ));
643        }
644        if !local_subdirs.insert(source.local_subdir.as_str()) {
645            return invalid(format!(
646                "profile {:?} has duplicate source local_subdir {:?}",
647                profile.id, source.local_subdir
648            ));
649        }
650        total_bytes = total_bytes
651            .checked_add(validate_source(&profile.id, source)?)
652            .ok_or_else(|| {
653                CatalogError::Invalid(format!("profile {:?} size overflow", profile.id))
654            })?;
655    }
656    if total_bytes > MAX_PROFILE_BYTES {
657        return invalid(format!(
658            "profile {:?} exceeds the {MAX_PROFILE_BYTES}-byte bound",
659            profile.id
660        ));
661    }
662    Ok(())
663}
664
665fn validate_source(profile_id: &str, source: &Source) -> Result<u64, CatalogError> {
666    validate_slug("source id", &source.id)?;
667    validate_repository(&source.repository)?;
668    validate_revision(&source.revision)?;
669    validate_slug("local_subdir", &source.local_subdir)?;
670    if source.files.is_empty() || source.files.len() > MAX_FILES_PER_SOURCE {
671        return invalid(format!(
672            "source {:?} in profile {profile_id:?} must contain between 1 and \
673             {MAX_FILES_PER_SOURCE} files",
674            source.id
675        ));
676    }
677
678    let mut file_paths = HashSet::new();
679    let mut total_bytes = 0_u64;
680    for file in &source.files {
681        validate_relative_path(&file.path)?;
682        if !file_paths.insert(file.path.as_str()) {
683            return invalid(format!(
684                "source {:?} in profile {profile_id:?} has duplicate file path {:?}",
685                source.id, file.path
686            ));
687        }
688        if file.bytes == 0 || file.bytes > MAX_FILE_BYTES {
689            return invalid(format!(
690                "file {:?} in source {:?} has an invalid byte count",
691                file.path, source.id
692            ));
693        }
694        total_bytes = total_bytes.checked_add(file.bytes).ok_or_else(|| {
695            CatalogError::Invalid(format!("source {:?} size overflow", source.id))
696        })?;
697        if let Some(digest) = &file.sha256 {
698            validate_sha256(&file.path, digest)?;
699        } else if is_weight_file(&file.path) {
700            return invalid(format!(
701                "weight file {:?} in source {:?} requires a SHA-256 digest",
702                file.path, source.id
703            ));
704        }
705    }
706    Ok(total_bytes)
707}
708
709fn validate_slug(label: &str, value: &str) -> Result<(), CatalogError> {
710    if value.is_empty()
711        || value.len() > 64
712        || !value.bytes().all(|byte| {
713            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'.')
714        })
715        || !value
716            .as_bytes()
717            .first()
718            .is_some_and(u8::is_ascii_alphanumeric)
719        || !value
720            .as_bytes()
721            .last()
722            .is_some_and(u8::is_ascii_alphanumeric)
723    {
724        return invalid(format!("{label} {value:?} is not a bounded lowercase slug"));
725    }
726    Ok(())
727}
728
729fn validate_text(label: &str, value: &str) -> Result<(), CatalogError> {
730    if value.is_empty() || value.len() > MAX_TEXT_BYTES || value.contains('\0') {
731        return invalid(format!("{label} must be nonempty and bounded"));
732    }
733    Ok(())
734}
735
736fn validate_repository(value: &str) -> Result<(), CatalogError> {
737    if value.len() > 160 {
738        return invalid(format!("repository {value:?} is too long"));
739    }
740    let Some((owner, name)) = value.split_once('/') else {
741        return invalid(format!("repository {value:?} must contain one slash"));
742    };
743    if name.contains('/')
744        || owner.is_empty()
745        || name.is_empty()
746        || !owner.bytes().all(is_repository_byte)
747        || !name.bytes().all(is_repository_byte)
748    {
749        return invalid(format!("repository {value:?} has an invalid shape"));
750    }
751    Ok(())
752}
753
754const fn is_repository_byte(byte: u8) -> bool {
755    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')
756}
757
758fn validate_revision(value: &str) -> Result<(), CatalogError> {
759    if value.len() != 40
760        || !value
761            .bytes()
762            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
763    {
764        return invalid(format!(
765            "revision {value:?} must be a 40-character lowercase commit hash"
766        ));
767    }
768    Ok(())
769}
770
771fn validate_relative_path(value: &str) -> Result<(), CatalogError> {
772    if value.is_empty()
773        || value.len() > MAX_PATH_BYTES
774        || value.contains('\\')
775        || Path::new(value)
776            .components()
777            .any(|component| !matches!(component, Component::Normal(_)))
778    {
779        return invalid(format!(
780            "artifact path {value:?} must be a bounded relative path"
781        ));
782    }
783    Ok(())
784}
785
786fn validate_sha256(path: &str, value: &str) -> Result<(), CatalogError> {
787    if value.len() != 64
788        || !value
789            .bytes()
790            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
791    {
792        return invalid(format!("file {path:?} has an invalid SHA-256 digest"));
793    }
794    Ok(())
795}
796
797fn is_weight_file(path: &str) -> bool {
798    let path = path.to_ascii_lowercase();
799    WEIGHT_SUFFIXES.iter().any(|suffix| path.ends_with(suffix))
800}
801
802fn sha256_file(path: &Path) -> Result<String, ArtifactError> {
803    let mut file = File::open(path).map_err(|source| ArtifactError::Read {
804        path: path.to_owned(),
805        source,
806    })?;
807    let mut hasher = Sha256::new();
808    let mut buffer = vec![0_u8; HASH_BUFFER_BYTES];
809    loop {
810        let count = file
811            .read(&mut buffer)
812            .map_err(|source| ArtifactError::Read {
813                path: path.to_owned(),
814                source,
815            })?;
816        if count == 0 {
817            break;
818        }
819        hasher.update(&buffer[..count]);
820    }
821    let digest = hasher.finalize();
822    Ok(encode_lower_hex(digest.as_ref()))
823}
824
825fn sha256_bytes(bytes: &[u8]) -> String {
826    let digest = Sha256::digest(bytes);
827    encode_lower_hex(digest.as_ref())
828}
829
830fn encode_lower_hex(bytes: &[u8]) -> String {
831    const HEX: &[u8; 16] = b"0123456789abcdef";
832
833    let mut encoded = String::with_capacity(bytes.len().saturating_mul(2));
834    for byte in bytes {
835        encoded.push(char::from(HEX[usize::from(*byte >> 4)]));
836        encoded.push(char::from(HEX[usize::from(*byte & 0x0f)]));
837    }
838    encoded
839}
840
841fn invalid<T>(message: String) -> Result<T, CatalogError> {
842    Err(CatalogError::Invalid(message))
843}
844
845#[cfg(test)]
846mod tests {
847    use super::{
848        Catalog, CatalogError, QWEN3_SMALL_ARTIFACT_PATH, QWEN3_SMALL_PROFILE_ID,
849        QWEN3_SMALL_SOURCE_ID, sha256_bytes,
850    };
851
852    #[test]
853    fn sha256_encoding_is_exact_lowercase_hex() {
854        assert_eq!(
855            sha256_bytes(b"abc"),
856            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
857        );
858    }
859
860    #[test]
861    fn packaged_catalog_is_valid() {
862        let catalog = Catalog::embedded().expect("packaged catalog should be valid");
863        assert_eq!(catalog.schema_version(), 1);
864        assert_eq!(catalog.default_profiles().len(), 3);
865        assert_eq!(catalog.profiles().len(), 3);
866        assert!(
867            catalog
868                .find_profile(QWEN3_SMALL_PROFILE_ID)
869                .and_then(|profile| {
870                    profile.find_artifact(QWEN3_SMALL_SOURCE_ID, QWEN3_SMALL_ARTIFACT_PATH)
871                })
872                .is_some()
873        );
874    }
875
876    #[test]
877    fn duplicate_default_is_rejected() {
878        let mut catalog = Catalog::embedded().expect("fixture should load");
879        catalog.default_profiles[1] = catalog.default_profiles[0].clone();
880        assert!(matches!(
881            catalog.validate(),
882            Err(CatalogError::Invalid(message)) if message.contains("duplicate default")
883        ));
884    }
885
886    #[test]
887    fn parent_path_is_rejected() {
888        let mut catalog = Catalog::embedded().expect("fixture should load");
889        catalog.profiles[0].sources[0].files[0].path = "../model.gguf".to_owned();
890        assert!(matches!(
891            catalog.validate(),
892            Err(CatalogError::Invalid(message)) if message.contains("relative path")
893        ));
894    }
895
896    #[test]
897    fn weight_without_digest_is_rejected() {
898        let mut catalog = Catalog::embedded().expect("fixture should load");
899        catalog.profiles[0].sources[0].files[0].sha256 = None;
900        assert!(matches!(
901            catalog.validate(),
902            Err(CatalogError::Invalid(message)) if message.contains("requires a SHA-256")
903        ));
904    }
905
906    #[test]
907    fn first_class_profile_requires_passed_acceptance_status() {
908        let mut catalog = Catalog::embedded().expect("fixture should load");
909        catalog.profiles[0].acceptance_status = super::AcceptanceStatus::NotRun;
910        assert!(matches!(
911            catalog.validate(),
912            Err(CatalogError::Invalid(message)) if message.contains("must have passed")
913        ));
914    }
915}