Skip to main content

weirdnet_model/
store.rs

1//! Where model files live on disk, and which Hub they come from. LoRA adapters live apart, in
2//! `adapters/<id>/` ([`ModelStore::adapters`]), and are never listed as models.
3//!
4//! Files a person brings ([`ModelStore::import`]) land in their own directory with a
5//! [`Provenance`] record next to them: a GGUF model in `<id>/`, an adapter in `adapters/<id>/`,
6//! a projector in `projectors/<id>/`, a safetensors model in `safetensors/<id>/` and an MLX
7//! model in `mlx/<id>/` ([`ModelStore::dir_models`]).
8
9use std::path::{Path, PathBuf};
10
11use serde::{Deserialize, Serialize};
12
13use crate::artifact::{Artifact, ArtifactFormat, ArtifactKind, PROVENANCE_FILE, Provenance, ProvenanceKind, inspect_staged};
14use crate::catalog::ModelSpec;
15use crate::download::Progress;
16use crate::hf::{AdapterFormat, Hub, adapter_hint, split_part};
17use crate::token::HfToken;
18
19/// The store's subdirectory for adapters: one directory per adapter id.
20pub const ADAPTERS_DIR: &str = "adapters";
21/// What [`download_adapter`](crate::download::download_adapter) records next to an adapter's files.
22pub const ADAPTER_INFO: &str = "adapter.json";
23/// The store's subdirectory for multimodal projectors: one directory per projector id.
24pub const PROJECTORS_DIR: &str = "projectors";
25/// The store's subdirectory for safetensors model directories (vLLM), one per model id.
26pub const SAFETENSORS_DIR: &str = "safetensors";
27/// The store's subdirectory for MLX model directories (MLX-LM), one per model id.
28pub const MLX_DIR: &str = "mlx";
29/// Directories [`ModelStore::import`] works in while it places files; never listed.
30const IMPORTING: &str = ".import-";
31const REPLACED: &str = ".replaced-";
32
33/// The public Hugging Face Hub.
34pub const HUB: &str = "https://huggingface.co";
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct ModelStore {
38    dir: PathBuf,
39    hub: String,
40    token: Option<HfToken>,
41    /// The token goes to any hub, not only the public one (set by [`ModelStore::with_token`]).
42    token_any_hub: bool,
43}
44
45/// A model file (or split model) in the store, from [`ModelStore::list`].
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[non_exhaustive]
48pub struct StoredModel {
49    /// The file stem without the split suffix, as in [`RepoModel::id`](crate::hf::RepoModel::id).
50    pub id: String,
51    /// Paths relative to the store directory, first part first.
52    pub files: Vec<String>,
53    pub size: u64,
54    /// Every part of a split model is there.
55    pub complete: bool,
56    /// How its files are laid out: GGUF files (from [`ModelStore::list`]), or a safetensors or
57    /// MLX directory (from [`ModelStore::dir_models`]).
58    #[serde(default)]
59    pub layout: ModelLayout,
60    /// Where it came from, for models placed by [`ModelStore::import`].
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    pub provenance: Option<Provenance>,
63}
64
65/// [`StoredModel::layout`].
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68#[non_exhaustive]
69pub enum ModelLayout {
70    /// GGUF files, for llama.cpp.
71    #[default]
72    Gguf,
73    /// A safetensors directory (`safetensors/<id>/`), for vLLM.
74    Safetensors,
75    /// An MLX directory (`mlx/<id>/`), for MLX-LM.
76    Mlx,
77}
78
79/// A multimodal projector in the store, from [`ModelStore::projectors`].
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81#[non_exhaustive]
82pub struct StoredProjector {
83    /// Its directory's name under `projectors/`.
84    pub id: String,
85    /// The GGUF (llama.cpp `--mmproj`).
86    pub path: PathBuf,
87    pub size: u64,
88    /// The model it is for (its provenance's base), when known.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub for_model: Option<String>,
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub provenance: Option<Provenance>,
93}
94
95/// What [`ModelStore::import`] placed.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Imported {
100    Model(StoredModel),
101    Adapter(StoredAdapter),
102    Projector(StoredProjector),
103}
104
105impl Imported {
106    pub fn id(&self) -> &str {
107        match self {
108            Imported::Model(m) => &m.id,
109            Imported::Adapter(a) => &a.id,
110            Imported::Projector(p) => &p.id,
111        }
112    }
113
114    /// Bytes of its files.
115    pub fn size(&self) -> u64 {
116        match self {
117            Imported::Model(m) => m.size,
118            Imported::Adapter(a) => a.size,
119            Imported::Projector(p) => p.size,
120        }
121    }
122
123    pub fn provenance(&self) -> Option<&Provenance> {
124        match self {
125            Imported::Model(m) => m.provenance.as_ref(),
126            Imported::Adapter(a) => a.provenance.as_ref(),
127            Imported::Projector(p) => p.provenance.as_ref(),
128        }
129    }
130}
131
132/// Free and total bytes on the store's filesystem ([`ModelStore::disk_space`]).
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
134#[non_exhaustive]
135pub struct DiskSpace {
136    /// Bytes this process may still write.
137    pub free: u64,
138    pub total: u64,
139}
140
141/// A LoRA adapter in the store, from [`ModelStore::adapters`].
142#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
143#[non_exhaustive]
144pub struct StoredAdapter {
145    /// Its directory's name under `adapters/`.
146    pub id: String,
147    pub format: AdapterFormat,
148    /// The GGUF file (llama.cpp `--lora`), or the PEFT directory (vLLM `--lora-modules`).
149    pub path: PathBuf,
150    /// All its files together.
151    pub size: u64,
152    /// The base model as a Hub id, when known.
153    pub base_model: Option<String>,
154    /// `general.architecture` of a GGUF adapter.
155    pub architecture: Option<String>,
156    /// The Hub repo it was downloaded from, when known.
157    pub repo: Option<String>,
158    pub rank: Option<u32>,
159    pub alpha: Option<f32>,
160    /// Where it came from, for adapters placed by [`ModelStore::import`].
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub provenance: Option<Provenance>,
163}
164
165/// `adapter.json`: a [`StoredAdapter`] without machine paths (the file name only).
166#[derive(Debug, Clone, Serialize, Deserialize)]
167struct AdapterInfo {
168    id: String,
169    format: AdapterFormat,
170    /// The GGUF's file name; `None` for PEFT (the directory).
171    #[serde(default)]
172    file: Option<String>,
173    #[serde(default)]
174    base_model: Option<String>,
175    #[serde(default)]
176    architecture: Option<String>,
177    #[serde(default)]
178    repo: Option<String>,
179    #[serde(default)]
180    rank: Option<u32>,
181    #[serde(default)]
182    alpha: Option<f32>,
183}
184
185pub(crate) fn write_adapter_info(dir: &Path, a: &StoredAdapter) -> crate::Result<()> {
186    let file = match a.format {
187        AdapterFormat::GgufLora => a.path.file_name().map(|f| f.to_string_lossy().into_owned()),
188        _ => None,
189    };
190    let info = AdapterInfo {
191        id: a.id.clone(),
192        format: a.format,
193        file,
194        base_model: a.base_model.clone(),
195        architecture: a.architecture.clone(),
196        repo: a.repo.clone(),
197        rank: a.rank,
198        alpha: a.alpha,
199    };
200    let json = serde_json::to_vec_pretty(&info).map_err(|e| crate::Error::Model(e.to_string()))?;
201    std::fs::write(dir.join(ADAPTER_INFO), json)?;
202    Ok(())
203}
204
205/// A LoRA GGUF by its header.
206fn is_adapter_gguf(path: &Path) -> bool {
207    std::fs::File::open(path).ok().and_then(|f| crate::gguf::read_header(std::io::BufReader::new(f)).ok()).is_some_and(|h| h.kind.is_adapter())
208}
209
210/// Bytes of an entry's files in `dir`, subdirectories too (not `.part` or hidden files, nor
211/// `adapter.json` or `provenance.json`).
212fn dir_size(dir: &Path) -> u64 {
213    dir_files(dir, dir).iter().map(|(_, size)| size).sum()
214}
215
216/// An entry's files under `dir` (as in [`dir_size`]), as `/`-separated paths relative to `root`,
217/// sorted.
218fn dir_files(root: &Path, dir: &Path) -> Vec<(String, u64)> {
219    let mut out = Vec::new();
220    collect_files(root, dir, 0, &mut out);
221    out.sort();
222    out
223}
224
225fn collect_files(root: &Path, dir: &Path, depth: usize, out: &mut Vec<(String, u64)>) {
226    for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
227        let name = e.file_name().to_string_lossy().into_owned();
228        let Ok(ft) = e.file_type() else { continue };
229        if name.starts_with('.') || name.ends_with(".part") || name == ADAPTER_INFO || name == PROVENANCE_FILE {
230            continue;
231        }
232        if ft.is_dir() && depth < 3 {
233            collect_files(root, &e.path(), depth + 1, out);
234        } else if ft.is_file() {
235            let path = e.path();
236            let Ok(rel) = path.strip_prefix(root) else { continue };
237            let rel: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
238            out.push((rel.join("/"), e.metadata().map(|m| m.len()).unwrap_or(0)));
239        }
240    }
241}
242
243/// A directory [`ModelStore::import`] is working in.
244fn is_work_dir(name: &str) -> bool {
245    name.starts_with(IMPORTING) || name.starts_with(REPLACED)
246}
247
248/// Moves `from` to `to`: a rename, or a copy then delete across filesystems.
249fn move_file(from: &Path, to: &Path) -> std::io::Result<()> {
250    if std::fs::rename(from, to).is_ok() {
251        return Ok(());
252    }
253    std::fs::copy(from, to)?;
254    std::fs::File::open(to)?.sync_all()?;
255    std::fs::remove_file(from)
256}
257
258/// A name for a work directory next to the entry: unique within this process and time.
259fn work_name(prefix: &str, id: &str) -> String {
260    let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
261    format!("{prefix}{id}-{}-{nanos}", std::process::id())
262}
263
264impl ModelStore {
265    pub fn new(dir: impl Into<PathBuf>) -> Self {
266        Self { dir: dir.into(), hub: HUB.into(), token: None, token_any_hub: false }
267    }
268
269    /// `$WEIRDNET_MODELS_DIR`, else `<user data dir>/weirdnet/models`; the Hub from
270    /// `$WEIRDNET_HF_URL` (a mirror) when set; this node's Hugging Face token
271    /// ([`HfToken::from_env`]), which is sent only to the public Hub, never to a mirror.
272    pub fn from_env() -> Self {
273        let dir = std::env::var_os("WEIRDNET_MODELS_DIR")
274            .filter(|d| !d.is_empty())
275            .map(PathBuf::from)
276            .unwrap_or_else(|| dirs::data_dir().unwrap_or_else(std::env::temp_dir).join("weirdnet").join("models"));
277        let mut store = Self::new(dir);
278        if let Some(hub) = std::env::var("WEIRDNET_HF_URL").ok().filter(|u| !u.trim().is_empty()) {
279            store.hub = hub.trim_end_matches('/').to_string();
280        }
281        store.token = HfToken::from_env();
282        store
283    }
284
285    /// Sends `token` to this store's Hub, whichever it is (a mirror too).
286    pub fn with_token(mut self, token: Option<HfToken>) -> Self {
287        self.token = token;
288        self.token_any_hub = true;
289        self
290    }
291
292    /// The token requests to this store's Hub carry, if any.
293    pub(crate) fn token(&self) -> Option<&HfToken> {
294        self.token.as_ref().filter(|_| self.token_any_hub || self.hub == HUB)
295    }
296
297    /// Whether requests to the Hub carry a token.
298    pub fn has_token(&self) -> bool {
299        self.token().is_some()
300    }
301
302    /// A [`Hub`] client for this store's Hub, with the token when it may go there.
303    pub fn hub_client(&self) -> Hub {
304        Hub::new(&self.hub).with_token(self.token().cloned())
305    }
306
307    /// Use another Hub (a mirror, or a local server in tests).
308    pub fn with_hub(mut self, hub: impl Into<String>) -> Self {
309        self.hub = hub.into().trim_end_matches('/').to_string();
310        self
311    }
312
313    pub fn dir(&self) -> &Path {
314        &self.dir
315    }
316
317    pub fn hub(&self) -> &str {
318        &self.hub
319    }
320
321    /// Where `spec`'s file goes.
322    pub fn path(&self, spec: &ModelSpec) -> PathBuf {
323        self.dir.join(&spec.file)
324    }
325
326    /// Downloaded and complete: the size matches (the checksum was checked when it finished).
327    pub fn installed(&self, spec: &ModelSpec) -> bool {
328        std::fs::metadata(self.path(spec)).is_ok_and(|m| m.len() == spec.size)
329    }
330
331    /// Bytes of a partial download, if any.
332    pub fn partial_bytes(&self, spec: &ModelSpec) -> u64 {
333        std::fs::metadata(self.part_path(spec)).map(|m| m.len()).unwrap_or(0)
334    }
335
336    pub(crate) fn part_path(&self, spec: &ModelSpec) -> PathBuf {
337        self.dir.join(format!("{}.part", spec.file))
338    }
339
340    /// Deletes the file and any partial download. Returns whether a file was removed.
341    pub fn remove(&self, spec: &ModelSpec) -> bool {
342        let _ = std::fs::remove_file(self.part_path(spec));
343        std::fs::remove_file(self.path(spec)).is_ok()
344    }
345
346    /// The GGUF models in the store (split parts grouped; projector, draft and `.part` files
347    /// left out), sorted by id. Adapters are not models: `adapters/` is skipped, and so is a
348    /// GGUF whose name hints at an adapter ([`adapter_hint`]) when its header says it is one.
349    pub fn list(&self) -> Vec<StoredModel> {
350        let mut files = Vec::new();
351        walk(&self.dir, &self.dir, 0, &mut files);
352        files.retain(|(rel, _)| !(adapter_hint(rel) && is_adapter_gguf(&self.dir.join(rel))));
353        let mut out: std::collections::BTreeMap<String, (Vec<Part>, u32)> = Default::default();
354        for (rel, size) in files {
355            let (key, part, of) = match split_part(&rel) {
356                Some((base, part, of)) => {
357                    let dir = rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
358                    (format!("{dir}{base}"), part, of)
359                }
360                None => (rel.strip_suffix(".gguf").or_else(|| rel.strip_suffix(".GGUF")).unwrap_or(&rel).to_string(), 1, 1),
361            };
362            let e = out.entry(key).or_default();
363            e.0.push((part, rel, size));
364            e.1 = of;
365        }
366        let mut models: Vec<StoredModel> = out
367            .into_iter()
368            .map(|(key, (mut parts, of))| {
369                parts.sort();
370                let complete = parts.len() as u32 == of && parts[0].0 == 1;
371                let mut id = key.rsplit('/').next().unwrap_or(&key).to_string();
372                let provenance = self.provenance_of(&parts[0].1);
373                if let Some(p) = &provenance {
374                    id = p.id.clone();
375                }
376                StoredModel {
377                    id,
378                    size: parts.iter().map(|p| p.2).sum(),
379                    files: parts.into_iter().map(|p| p.1).collect(),
380                    complete,
381                    layout: ModelLayout::Gguf,
382                    provenance,
383                }
384            })
385            .collect();
386        models.sort_by(|a, b| a.id.cmp(&b.id).then_with(|| a.files.cmp(&b.files)));
387        models
388    }
389
390    /// The provenance record next to stored GGUF file `rel` (in its own directory, not the store
391    /// root) when the record lists that file.
392    fn provenance_of(&self, rel: &str) -> Option<Provenance> {
393        let (dir, file) = rel.rsplit_once('/')?;
394        let p = Provenance::read(&self.dir.join(dir))?;
395        (p.kind == ProvenanceKind::Model && !p.id.is_empty() && p.files.iter().any(|f| f.path == file)).then_some(p)
396    }
397
398    /// Deletes a listed model's files (and their `.part` files) and the directories that leaves
399    /// empty (with a provenance record left alone in one). Returns the bytes freed. Paths
400    /// outside the store are refused.
401    pub fn remove_local(&self, model: &StoredModel) -> crate::Result<u64> {
402        let mut freed = 0;
403        for rel in &model.files {
404            crate::hf::check_file(rel)?;
405        }
406        for rel in &model.files {
407            let path = self.dir.join(rel);
408            let _ = std::fs::remove_file(self.dir.join(format!("{rel}.part")));
409            if let Ok(m) = std::fs::metadata(&path) {
410                std::fs::remove_file(&path)?;
411                freed += m.len();
412            }
413        }
414        for rel in &model.files {
415            let path = self.dir.join(rel);
416            if let Some(d) = path.parent().filter(|d| *d != self.dir)
417                && std::fs::read_dir(d).is_ok_and(|mut e| e.all(|e| e.is_ok_and(|e| e.file_name() == PROVENANCE_FILE)))
418            {
419                let _ = std::fs::remove_file(d.join(PROVENANCE_FILE));
420            }
421            let mut dir = path.parent().map(Path::to_path_buf);
422            while let Some(d) = dir.filter(|d| d.starts_with(&self.dir) && *d != self.dir) {
423                if std::fs::remove_dir(&d).is_err() {
424                    break;
425                }
426                dir = d.parent().map(Path::to_path_buf);
427            }
428        }
429        Ok(freed)
430    }
431}
432
433impl ModelStore {
434    /// Where adapter `id` goes: `<store>/adapters/<id>`. The id must be one plain path part.
435    pub fn adapter_dir(&self, id: &str) -> crate::Result<PathBuf> {
436        if id.contains('/') || crate::hf::check_file(id).is_err() {
437            return Err(crate::Error::Model(format!("{id:?} is not an adapter id")));
438        }
439        Ok(self.dir.join(ADAPTERS_DIR).join(id))
440    }
441
442    /// The complete LoRA adapters under `adapters/`, sorted by id: from `adapter.json` when
443    /// [`download_adapter`](crate::download::download_adapter) wrote one, else a LoRA GGUF (by
444    /// its header) or a PEFT directory (`adapter_config.json` and its weights) found there.
445    pub fn adapters(&self) -> Vec<StoredAdapter> {
446        let mut out: Vec<StoredAdapter> = std::fs::read_dir(self.dir.join(ADAPTERS_DIR))
447            .into_iter()
448            .flatten()
449            .flatten()
450            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.'))
451            .filter_map(|e| Self::adapter_in(&e.path(), &e.file_name().to_string_lossy()))
452            .collect();
453        out.sort_by(|a, b| a.id.cmp(&b.id));
454        out
455    }
456
457    fn adapter_in(dir: &Path, id: &str) -> Option<StoredAdapter> {
458        let info: Option<AdapterInfo> = std::fs::read(dir.join(ADAPTER_INFO)).ok().and_then(|b| serde_json::from_slice(&b).ok());
459        let peft_weights = ["adapter_model.safetensors", "adapter_model.bin"].iter().any(|w| dir.join(w).is_file());
460        let peft_config = || -> Option<serde_json::Value> { serde_json::from_slice(&std::fs::read(dir.join("adapter_config.json")).ok()?).ok() };
461        let gguf = || {
462            std::fs::read_dir(dir)
463                .ok()?
464                .flatten()
465                .map(|e| e.path())
466                .find(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("gguf")) && p.is_file() && is_adapter_gguf(p))
467        };
468        let mut a = StoredAdapter {
469            id: id.to_string(),
470            format: AdapterFormat::Peft,
471            path: dir.to_path_buf(),
472            size: dir_size(dir),
473            base_model: None,
474            architecture: None,
475            repo: None,
476            rank: None,
477            alpha: None,
478            provenance: Provenance::read(dir).filter(|p| p.kind == ProvenanceKind::Adapter),
479        };
480        match info {
481            Some(i) => {
482                a.format = i.format;
483                (a.base_model, a.architecture, a.repo, a.rank, a.alpha) = (i.base_model, i.architecture, i.repo, i.rank, i.alpha);
484                match i.format {
485                    AdapterFormat::GgufLora => {
486                        let file = dir.join(i.file.filter(|f| !f.contains('/') && !f.contains('\\'))?);
487                        if !file.is_file() {
488                            return None;
489                        }
490                        a.path = file;
491                    }
492                    _ if !(peft_weights && dir.join("adapter_config.json").is_file()) => return None,
493                    _ => {}
494                }
495            }
496            None if peft_weights => {
497                let (rank, alpha, base) = crate::hf::peft_lora(&peft_config()?)?;
498                (a.rank, a.alpha, a.base_model) = (rank, alpha, base);
499            }
500            None => {
501                let file = gguf()?;
502                let h = crate::gguf::read_header(std::io::BufReader::new(std::fs::File::open(&file).ok()?)).ok()?;
503                a.format = AdapterFormat::GgufLora;
504                a.alpha = match h.kind {
505                    crate::gguf::GgufKind::Adapter { alpha, .. } => alpha,
506                    _ => None,
507                };
508                (a.architecture, a.base_model, a.path) = (Some(h.architecture), h.base_model, file);
509            }
510        }
511        Some(a)
512    }
513
514    /// Deletes a stored adapter's directory. Returns the bytes freed. Ids that are not one plain
515    /// path part are refused.
516    pub fn remove_adapter(&self, adapter: &StoredAdapter) -> crate::Result<u64> {
517        let dir = self.adapter_dir(&adapter.id)?;
518        if !dir.exists() {
519            return Ok(0);
520        }
521        let freed = dir_size(&dir);
522        std::fs::remove_dir_all(&dir)?;
523        let _ = std::fs::remove_dir(self.dir.join(ADAPTERS_DIR));
524        Ok(freed)
525    }
526}
527
528impl ModelStore {
529    /// The safetensors (`safetensors/<id>/`) and MLX (`mlx/<id>/`) model directories, sorted by
530    /// id. [`ModelStore::list`] has the GGUF models. A directory is complete when it has its
531    /// `config.json`.
532    pub fn dir_models(&self) -> Vec<StoredModel> {
533        let mut out = Vec::new();
534        for (sub, layout) in [(SAFETENSORS_DIR, ModelLayout::Safetensors), (MLX_DIR, ModelLayout::Mlx)] {
535            for e in std::fs::read_dir(self.dir.join(sub)).into_iter().flatten().flatten() {
536                let name = e.file_name().to_string_lossy().into_owned();
537                if name.starts_with('.') || !e.file_type().is_ok_and(|t| t.is_dir()) {
538                    continue;
539                }
540                let files = dir_files(&self.dir, &e.path());
541                if files.is_empty() {
542                    continue;
543                }
544                out.push(StoredModel {
545                    id: name,
546                    size: files.iter().map(|f| f.1).sum(),
547                    complete: e.path().join("config.json").is_file(),
548                    files: files.into_iter().map(|f| f.0).collect(),
549                    layout,
550                    provenance: Provenance::read(&e.path()).filter(|p| p.kind == ProvenanceKind::Model),
551                });
552            }
553        }
554        out.sort_by(|a, b| a.id.cmp(&b.id).then_with(|| a.files.cmp(&b.files)));
555        out
556    }
557
558    /// Where an imported model of `layout` with id `id` goes: `<id>/` for GGUF,
559    /// `safetensors/<id>/` or `mlx/<id>/`. The id must be one plain path part.
560    pub fn model_dir(&self, layout: ModelLayout, id: &str) -> crate::Result<PathBuf> {
561        check_id(id)?;
562        Ok(match layout {
563            ModelLayout::Gguf => self.dir.join(id),
564            ModelLayout::Safetensors => self.dir.join(SAFETENSORS_DIR).join(id),
565            ModelLayout::Mlx => self.dir.join(MLX_DIR).join(id),
566        })
567    }
568
569    /// Where projector `id` goes: `<store>/projectors/<id>`.
570    pub fn projector_dir(&self, id: &str) -> crate::Result<PathBuf> {
571        check_id(id)?;
572        Ok(self.dir.join(PROJECTORS_DIR).join(id))
573    }
574
575    /// The projectors under `projectors/`, sorted by id: each directory's GGUF.
576    pub fn projectors(&self) -> Vec<StoredProjector> {
577        let mut out: Vec<StoredProjector> = std::fs::read_dir(self.dir.join(PROJECTORS_DIR))
578            .into_iter()
579            .flatten()
580            .flatten()
581            .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()) && !e.file_name().to_string_lossy().starts_with('.'))
582            .filter_map(|e| {
583                let dir = e.path();
584                let path = std::fs::read_dir(&dir)
585                    .ok()?
586                    .flatten()
587                    .map(|f| f.path())
588                    .find(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("gguf")) && p.is_file())?;
589                let provenance = Provenance::read(&dir).filter(|p| p.kind == ProvenanceKind::Projector);
590                Some(StoredProjector {
591                    id: e.file_name().to_string_lossy().into_owned(),
592                    size: dir_size(&dir),
593                    for_model: provenance.as_ref().and_then(|p| p.base.as_ref()).and_then(|b| b.id.clone()),
594                    path,
595                    provenance,
596                })
597            })
598            .collect();
599        out.sort_by(|a, b| a.id.cmp(&b.id));
600        out
601    }
602
603    /// Deletes a stored projector's directory. Returns the bytes freed.
604    pub fn remove_projector(&self, projector: &StoredProjector) -> crate::Result<u64> {
605        let dir = self.projector_dir(&projector.id)?;
606        if !dir.exists() {
607            return Ok(0);
608        }
609        let freed = dir_size(&dir);
610        std::fs::remove_dir_all(&dir)?;
611        let _ = std::fs::remove_dir(self.dir.join(PROJECTORS_DIR));
612        Ok(freed)
613    }
614
615    /// The store's directory, or its nearest existing parent.
616    fn existing_dir(&self) -> PathBuf {
617        let mut d = self.dir.clone();
618        while !d.exists() {
619            match d.parent() {
620                Some(p) => d = p.to_path_buf(),
621                None => break,
622            }
623        }
624        d
625    }
626
627    /// Free and total bytes on the filesystem the store is on (or would be on, before it
628    /// exists).
629    pub fn disk_space(&self) -> crate::Result<DiskSpace> {
630        let d = self.existing_dir();
631        Ok(DiskSpace { free: fs4::available_space(&d)?, total: fs4::total_space(&d)? })
632    }
633
634    /// Bytes this process may still write on the store's filesystem (0 when that can't be read,
635    /// so callers checking for room refuse rather than overfill).
636    pub fn free_bytes(&self) -> u64 {
637        self.disk_space().map(|d| d.free).unwrap_or(0)
638    }
639
640    /// Bytes of everything stored (models, model directories, adapters and projectors) whose
641    /// provenance has this origin ([`ORIGIN_UPLOAD`](crate::artifact::ORIGIN_UPLOAD) and so on).
642    pub fn bytes_by_origin(&self, origin: &str) -> u64 {
643        let of = |p: Option<&Provenance>| p.is_some_and(|p| p.origin == origin);
644        let models: u64 = self.list().iter().chain(self.dir_models().iter()).filter(|m| of(m.provenance.as_ref())).map(|m| m.size).sum();
645        let adapters: u64 = self.adapters().iter().filter(|a| of(a.provenance.as_ref())).map(|a| a.size).sum();
646        let projectors: u64 = self.projectors().iter().filter(|p| of(p.provenance.as_ref())).map(|p| p.size).sum();
647        models + adapters + projectors
648    }
649
650    /// Places files received into `staged` (under their artifact paths, as an upload stages them;
651    /// keep `staged` outside the store) into the store as `id`, with `provenance` next to them.
652    ///
653    /// The staged files are checked first: each must be in `artifact.files` with the same size
654    /// and SHA-256, and their headers must say what `artifact` says. The record's id, kind, files
655    /// and revision are then set from the bytes. Files are moved (copied across filesystems)
656    /// into a work directory next to the target, which is renamed into place last, so the entry
657    /// appears whole or not at all. An adapter also gets its `adapter.json`.
658    ///
659    /// Where it goes: a GGUF model in `<id>/`, an adapter in `adapters/<id>/`, a projector in
660    /// `projectors/<id>/`, a safetensors model in `safetensors/<id>/`, an MLX model in
661    /// `mlx/<id>/`. An id already in use is refused; see [`ModelStore::import_replacing`].
662    pub fn import(&self, staged: &Path, artifact: &Artifact, provenance: &Provenance, id: &str) -> crate::Result<Imported> {
663        self.import_with(staged, artifact, provenance, id, false, &mut |_| true)
664    }
665
666    /// [`ModelStore::import`], replacing an entry this store imported before under the same id
667    /// (models in the store's own GGUF files are never replaced).
668    pub fn import_replacing(&self, staged: &Path, artifact: &Artifact, provenance: &Provenance, id: &str) -> crate::Result<Imported> {
669        self.import_with(staged, artifact, provenance, id, true, &mut |_| true)
670    }
671
672    /// [`ModelStore::import`] with `replace` and a `progress` callback for the hash check
673    /// (`false` cancels).
674    pub fn import_with(
675        &self,
676        staged: &Path,
677        artifact: &Artifact,
678        provenance: &Provenance,
679        id: &str,
680        replace: bool,
681        progress: &mut dyn FnMut(Progress) -> bool,
682    ) -> crate::Result<Imported> {
683        check_id(id)?;
684        let dest = self.dest(artifact, id)?;
685        self.check_free(artifact, id, &dest, replace)?;
686        let found = inspect_staged(staged, &artifact.files, progress)?;
687        if (found.kind, found.format, &found.revision) != (artifact.kind, artifact.format, &artifact.revision) {
688            return Err(crate::Error::Model(format!("{id}: the staged files are not what was described")));
689        }
690        self.place(staged, &found, provenance, id, replace)
691    }
692
693    /// [`ModelStore::import_with`] for files known only by their list (an upload's offer): what
694    /// they are comes from their headers, read once with the hash check. The entry's kind and
695    /// format are in the returned [`Imported`].
696    pub fn import_files(
697        &self,
698        staged: &Path,
699        files: &[crate::artifact::ArtifactFile],
700        provenance: &Provenance,
701        id: &str,
702        replace: bool,
703        progress: &mut dyn FnMut(Progress) -> bool,
704    ) -> crate::Result<Imported> {
705        check_id(id)?;
706        let found = inspect_staged(staged, files, progress)?;
707        self.place(staged, &found, provenance, id, replace)
708    }
709
710    /// Moves checked staged files into place (see [`ModelStore::import`]).
711    fn place(&self, staged: &Path, found: &Artifact, provenance: &Provenance, id: &str, replace: bool) -> crate::Result<Imported> {
712        let dest = self.dest(found, id)?;
713        self.check_free(found, id, &dest, replace)?;
714        let mut record = provenance.clone();
715        record.id = id.to_string();
716        record.kind = found.kind.provenance_kind();
717        record.files = found.files.clone();
718        record.revision = found.revision.clone();
719
720        let parent = dest.parent().ok_or_else(|| crate::Error::Model(format!("{id}: no parent directory")))?;
721        std::fs::create_dir_all(parent)?;
722        let work = parent.join(work_name(IMPORTING, id));
723        let placed = (|| -> crate::Result<()> {
724            std::fs::create_dir(&work)?;
725            for f in &found.files {
726                let to = work.join(&f.path);
727                if let Some(d) = to.parent() {
728                    std::fs::create_dir_all(d)?;
729                }
730                move_file(&staged.join(&f.path), &to)?;
731            }
732            record.write(&work)?;
733            if let ArtifactKind::Adapter { format } = found.kind {
734                let mut a = self.adapter_record(found, format, id, &work);
735                a.path = match format {
736                    AdapterFormat::GgufLora => dest.join(&found.files[0].path),
737                    _ => dest.clone(),
738                };
739                write_adapter_info(&work, &a)?;
740            }
741            Ok(())
742        })();
743        if let Err(e) = placed {
744            // Give the staged files back so the upload can be retried without sending them again.
745            for f in &found.files {
746                let at = work.join(&f.path);
747                if at.exists() {
748                    let _ = move_file(&at, &staged.join(&f.path));
749                }
750            }
751            let _ = std::fs::remove_dir_all(&work);
752            return Err(e);
753        }
754        let old = parent.join(work_name(REPLACED, id));
755        let had_old = replace && dest.exists();
756        if had_old {
757            std::fs::rename(&dest, &old)?;
758        }
759        if let Err(e) = std::fs::rename(&work, &dest) {
760            if had_old {
761                let _ = std::fs::rename(&old, &dest);
762            }
763            let _ = std::fs::remove_dir_all(&work);
764            return Err(e.into());
765        }
766        if had_old {
767            let _ = std::fs::remove_dir_all(&old);
768        }
769        Ok(self.imported(found, id, &dest, record))
770    }
771
772    /// Where an artifact stored as `id` goes.
773    fn dest(&self, artifact: &Artifact, id: &str) -> crate::Result<PathBuf> {
774        match (artifact.kind, artifact.format) {
775            (ArtifactKind::Adapter { .. }, _) => self.adapter_dir(id),
776            (ArtifactKind::Projector, _) => self.projector_dir(id),
777            (_, ArtifactFormat::Safetensors) => self.model_dir(ModelLayout::Safetensors, id),
778            (_, ArtifactFormat::Mlx) => self.model_dir(ModelLayout::Mlx, id),
779            _ => self.model_dir(ModelLayout::Gguf, id),
780        }
781    }
782
783    /// Refuses an id in use (unless `replace` and the entry at `dest` was imported) and a
784    /// target that a model's own GGUF files are in.
785    fn check_free(&self, artifact: &Artifact, id: &str, dest: &Path, replace: bool) -> crate::Result<()> {
786        let taken = |what: &str| crate::Error::Model(format!("{id} exists ({what}); remove it first or replace it"));
787        let imported_here = Provenance::read(dest).is_some();
788        if dest.exists() && !(replace && imported_here) {
789            return Err(taken("its directory is in use"));
790        }
791        let model = artifact.kind == ArtifactKind::Model;
792        if model
793            && self.list().iter().chain(self.dir_models().iter()).any(|m| m.id == id && !m.files.iter().all(|f| self.dir.join(f).starts_with(dest)))
794        {
795            return Err(taken("a stored model has that id"));
796        }
797        Ok(())
798    }
799
800    fn adapter_record(&self, found: &Artifact, format: AdapterFormat, id: &str, dir: &Path) -> StoredAdapter {
801        StoredAdapter {
802            id: id.to_string(),
803            format,
804            path: dir.to_path_buf(),
805            size: found.size(),
806            base_model: found.base_model.clone(),
807            architecture: found.architecture.clone(),
808            repo: None,
809            rank: found.rank,
810            alpha: found.alpha,
811            provenance: None,
812        }
813    }
814
815    fn imported(&self, found: &Artifact, id: &str, dest: &Path, record: Provenance) -> Imported {
816        let rel = |f: &str| {
817            let full = dest.join(f);
818            let rel: Vec<String> =
819                full.strip_prefix(&self.dir).unwrap_or(&full).components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
820            rel.join("/")
821        };
822        match found.kind {
823            ArtifactKind::Adapter { format } => {
824                let mut a = self.adapter_record(found, format, id, dest);
825                if format == AdapterFormat::GgufLora {
826                    a.path = dest.join(&found.files[0].path);
827                }
828                a.provenance = Some(record);
829                Imported::Adapter(a)
830            }
831            ArtifactKind::Projector => Imported::Projector(StoredProjector {
832                id: id.to_string(),
833                path: dest.join(&found.files[0].path),
834                size: found.size(),
835                for_model: record.base.as_ref().and_then(|b| b.id.clone()),
836                provenance: Some(record),
837            }),
838            _ => Imported::Model(StoredModel {
839                id: id.to_string(),
840                files: found.files.iter().map(|f| rel(&f.path)).collect(),
841                size: found.size(),
842                complete: true,
843                layout: match found.format {
844                    ArtifactFormat::Safetensors => ModelLayout::Safetensors,
845                    ArtifactFormat::Mlx => ModelLayout::Mlx,
846                    _ => ModelLayout::Gguf,
847                },
848                provenance: Some(record),
849            }),
850        }
851    }
852}
853
854/// An entry id: one plain path part, not hidden.
855fn check_id(id: &str) -> crate::Result<()> {
856    if id.contains('/') || id.starts_with('.') || crate::hf::check_file(id).is_err() {
857        return Err(crate::Error::Model(format!("{id:?} is not a valid id (one plain name, no '/', not hidden)")));
858    }
859    Ok(())
860}
861
862/// A file of a stored model: part number, path relative to the store, size.
863type Part = (u32, String, u64);
864
865/// Model GGUFs under `dir`, as `/`-separated paths relative to `root` (four levels deep at most).
866fn walk(root: &Path, dir: &Path, depth: usize, out: &mut Vec<(String, u64)>) {
867    let Ok(entries) = std::fs::read_dir(dir) else { return };
868    for e in entries.flatten() {
869        let Ok(ft) = e.file_type() else { continue };
870        let path = e.path();
871        let skip = [ADAPTERS_DIR, PROJECTORS_DIR, SAFETENSORS_DIR, MLX_DIR];
872        if ft.is_dir() && ((depth == 0 && skip.iter().any(|d| e.file_name() == *d)) || is_work_dir(&e.file_name().to_string_lossy())) {
873            continue;
874        } else if ft.is_dir() && depth < 4 {
875            walk(root, &path, depth + 1, out);
876        } else if ft.is_file() {
877            let name = e.file_name().to_string_lossy().to_ascii_lowercase();
878            if !name.ends_with(".gguf") || name.starts_with("mmproj") || name.starts_with("mtp-") {
879                continue;
880            }
881            let Ok(rel) = path.strip_prefix(root) else { continue };
882            let rel: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
883            out.push((rel.join("/"), e.metadata().map(|m| m.len()).unwrap_or(0)));
884        }
885    }
886}
887
888#[cfg(test)]
889mod tests {
890    use super::*;
891    use crate::catalog;
892
893    #[test]
894    fn paths_follow_the_file_name_and_remove_clears_parts() {
895        let tmp = tempfile::tempdir().unwrap();
896        let store = ModelStore::new(tmp.path());
897        let spec = catalog::default_for(catalog::Device::Phone);
898        assert_eq!(store.path(&spec), tmp.path().join("gemma-4-E2B-it-Q4_0.gguf"));
899        assert!(!store.installed(&spec));
900        std::fs::write(store.part_path(&spec), b"abc").unwrap();
901        assert_eq!(store.partial_bytes(&spec), 3);
902        assert!(!store.remove(&spec));
903        assert_eq!(store.partial_bytes(&spec), 0);
904    }
905
906    #[test]
907    fn lists_and_removes_models_with_their_parts() {
908        let tmp = tempfile::tempdir().unwrap();
909        let store = ModelStore::new(tmp.path());
910        let w = |rel: &str, n: usize| {
911            let p = tmp.path().join(rel);
912            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
913            std::fs::write(p, vec![0u8; n]).unwrap();
914        };
915        w("a-Q4_0.gguf", 3);
916        w("mmproj-a.gguf", 1);
917        w("b.gguf.part", 1);
918        w("Q8_0/b-Q8_0-00001-of-00002.gguf", 5);
919        w("Q8_0/b-Q8_0-00002-of-00002.gguf", 6);
920        w("c-00002-of-00002.gguf", 2);
921        let list = store.list();
922        assert_eq!(
923            list.iter().map(|m| (m.id.as_str(), m.size, m.complete)).collect::<Vec<_>>(),
924            [("a-Q4_0", 3, true), ("b-Q8_0", 11, true), ("c", 2, false)]
925        );
926        assert_eq!(list[1].files, ["Q8_0/b-Q8_0-00001-of-00002.gguf", "Q8_0/b-Q8_0-00002-of-00002.gguf"]);
927        w("Q8_0/b-Q8_0-00002-of-00002.gguf.part", 1);
928        assert_eq!(store.remove_local(&list[1]).unwrap(), 11);
929        assert!(!tmp.path().join("Q8_0").exists(), "the emptied directory goes too");
930        assert_eq!(store.list().len(), 2);
931        let mut evil = list[0].clone();
932        evil.files = vec!["../x.gguf".into()];
933        assert!(store.remove_local(&evil).is_err());
934    }
935
936    #[test]
937    fn adapters_are_found_without_adapter_json_and_never_listed_as_models() {
938        let tmp = tempfile::tempdir().unwrap();
939        let store = ModelStore::new(tmp.path());
940        let w = |rel: &str, b: &[u8]| {
941            let p = tmp.path().join(rel);
942            std::fs::create_dir_all(p.parent().unwrap()).unwrap();
943            std::fs::write(p, b).unwrap();
944        };
945        w("m-Q4_0.gguf", b"GGUF....");
946        w("stray-LoRA-F16.gguf", &crate::gguf::lora_header("qwen3"));
947        w("lora-merged-Q4_0.gguf", b"not an adapter header");
948        w("adapters/hand/hand.gguf", &crate::gguf::lora_header("llama"));
949        let config = br#"{"peft_type":"LORA","r":4,"lora_alpha":8,"base_model_name_or_path":"Org/B"}"#;
950        w("adapters/peft/adapter_config.json", config);
951        w("adapters/peft/adapter_model.safetensors", &[1; 10]);
952        w("adapters/half/adapter_config.json", br#"{"peft_type":"LORA"}"#);
953        w("adapters/ia3/adapter_config.json", br#"{"peft_type":"IA3"}"#);
954        w("adapters/ia3/adapter_model.safetensors", &[1; 10]);
955        assert_eq!(store.list().iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["lora-merged-Q4_0", "m-Q4_0"], "the header decides");
956        let a = store.adapters();
957        assert_eq!(
958            a.iter().map(|a| (a.id.as_str(), a.format)).collect::<Vec<_>>(),
959            [("hand", AdapterFormat::GgufLora), ("peft", AdapterFormat::Peft)]
960        );
961        assert_eq!((a[0].architecture.as_deref(), a[0].path.clone()), (Some("llama"), tmp.path().join("adapters/hand/hand.gguf")));
962        assert_eq!((a[1].rank, a[1].alpha, a[1].base_model.as_deref(), a[1].size), (Some(4), Some(8.0), Some("Org/B"), 10 + config.len() as u64));
963        assert!(store.adapter_dir("a/b").is_err() && store.adapter_dir("..").is_err());
964        let mut evil = a[0].clone();
965        evil.id = "../m-Q4_0.gguf".into();
966        assert!(store.remove_adapter(&evil).is_err());
967        assert!(tmp.path().join("m-Q4_0.gguf").exists());
968    }
969
970    #[test]
971    fn tokens_go_to_the_public_hub_or_where_they_were_set() {
972        let t = HfToken::new("hf_x");
973        let mut store = ModelStore::new("/x");
974        store.token = t.clone();
975        assert!(store.has_token() && store.hub_client().has_token());
976        let mirror = store.clone().with_hub("http://mirror");
977        assert!(!mirror.has_token(), "an environment token never goes to a mirror");
978        assert!(mirror.with_token(t).has_token());
979        assert!(format!("{store:?}").contains("<redacted>"));
980    }
981
982    #[test]
983    fn a_mirror_loses_its_trailing_slash() {
984        assert_eq!(ModelStore::new("/x").with_hub("http://127.0.0.1:1/").hub(), "http://127.0.0.1:1");
985    }
986
987    mod import {
988        use super::*;
989        use crate::artifact::tests::{model_gguf, safetensors};
990        use crate::artifact::{ORIGIN_TRAIN, ORIGIN_UPLOAD, ProvenanceBase, inspect};
991
992        fn stage(dir: &Path, files: &[(&str, Vec<u8>)]) -> Artifact {
993            for (name, body) in files {
994                let p = dir.join(name);
995                std::fs::create_dir_all(p.parent().unwrap()).unwrap();
996                std::fs::write(p, body).unwrap();
997            }
998            let paths: Vec<PathBuf> =
999                if files.len() == 1 && !files[0].0.contains('/') { vec![dir.join(files[0].0)] } else { vec![dir.to_path_buf()] };
1000            inspect(&paths).unwrap()
1001        }
1002
1003        #[test]
1004        fn a_gguf_model_lands_in_its_own_directory_with_provenance() {
1005            let tmp = tempfile::tempdir().unwrap();
1006            let store = ModelStore::new(tmp.path().join("store"));
1007            let staged = tmp.path().join("up");
1008            let a = stage(&staged, &[("tune-Q4_0.gguf", model_gguf(&[]))]);
1009            let p = Provenance::new(ORIGIN_UPLOAD).with_license("apache-2.0");
1010            let got = store.import(&staged, &a, &p, "support-r3").unwrap();
1011            let Imported::Model(m) = &got else { panic!("{got:?}") };
1012            assert_eq!(
1013                (m.id.as_str(), m.files.as_slice(), m.layout),
1014                ("support-r3", &["support-r3/tune-Q4_0.gguf".to_string()][..], ModelLayout::Gguf)
1015            );
1016            assert!(!staged.join("tune-Q4_0.gguf").exists(), "moved, not copied");
1017            let listed = store.list();
1018            assert_eq!(listed.len(), 1);
1019            assert_eq!(&listed[0], m, "list reads the same entry back");
1020            let rec = listed[0].provenance.as_ref().unwrap();
1021            assert_eq!((rec.revision.as_str(), rec.license.as_deref(), rec.kind), (a.revision.as_str(), Some("apache-2.0"), ProvenanceKind::Model));
1022            assert_eq!(store.bytes_by_origin(ORIGIN_UPLOAD), a.size());
1023            assert_eq!(store.bytes_by_origin(ORIGIN_TRAIN), 0);
1024
1025            let again = tmp.path().join("again");
1026            let b = stage(&again, &[("tune-Q4_0.gguf", model_gguf(&[("general.name", serde_json::json!("v2"))]))]);
1027            assert!(store.import(&again, &b, &p, "support-r3").unwrap_err().to_string().contains("exists"));
1028            assert!(again.join("tune-Q4_0.gguf").exists(), "a refusal keeps the staged files");
1029            let replaced = store.import_replacing(&again, &b, &p, "support-r3").unwrap();
1030            assert_eq!(replaced.provenance().unwrap().revision, b.revision);
1031            assert_eq!(store.list().len(), 1);
1032
1033            assert_eq!(store.remove_local(&store.list()[0]).unwrap(), b.size());
1034            assert!(!tmp.path().join("store/support-r3").exists(), "the provenance record goes with the files");
1035        }
1036
1037        #[test]
1038        fn an_id_used_by_a_stored_model_or_bad_ids_are_refused() {
1039            let tmp = tempfile::tempdir().unwrap();
1040            let store = ModelStore::new(tmp.path().join("store"));
1041            std::fs::create_dir_all(store.dir()).unwrap();
1042            std::fs::write(store.dir().join("m-Q4_0.gguf"), model_gguf(&[])).unwrap();
1043            let staged = tmp.path().join("up");
1044            let a = stage(&staged, &[("x.gguf", model_gguf(&[]))]);
1045            let p = Provenance::new(ORIGIN_UPLOAD);
1046            assert!(store.import_replacing(&staged, &a, &p, "m-Q4_0").unwrap_err().to_string().contains("exists"));
1047            for bad in ["a/b", "..", ".hidden", ""] {
1048                assert!(store.import(&staged, &a, &p, bad).is_err(), "{bad}");
1049            }
1050        }
1051
1052        #[test]
1053        fn files_known_by_their_list_are_classified_from_their_headers() {
1054            let tmp = tempfile::tempdir().unwrap();
1055            let store = ModelStore::new(tmp.path().join("store"));
1056            let staged = tmp.path().join("up");
1057            let a = stage(&staged, &[("tune-LoRA.gguf", crate::gguf::lora_header("llama"))]);
1058            let got = store.import_files(&staged, &a.files, &Provenance::new(ORIGIN_UPLOAD), "tune", false, &mut |_| true).unwrap();
1059            assert!(matches!(&got, Imported::Adapter(ad) if ad.format == AdapterFormat::GgufLora));
1060            assert_eq!(got.provenance().unwrap().kind, ProvenanceKind::Adapter);
1061        }
1062
1063        #[test]
1064        fn tampered_staged_files_are_refused() {
1065            let tmp = tempfile::tempdir().unwrap();
1066            let store = ModelStore::new(tmp.path().join("store"));
1067            let staged = tmp.path().join("up");
1068            let a = stage(&staged, &[("x.gguf", model_gguf(&[]))]);
1069            let mut body = std::fs::read(staged.join("x.gguf")).unwrap();
1070            *body.last_mut().unwrap() ^= 1;
1071            std::fs::write(staged.join("x.gguf"), body).unwrap();
1072            assert!(matches!(store.import(&staged, &a, &Provenance::new(ORIGIN_UPLOAD), "x"), Err(crate::Error::Checksum { .. })));
1073            assert!(store.list().is_empty());
1074        }
1075
1076        #[test]
1077        fn adapters_get_adapter_json_and_their_size_leaves_provenance_out() {
1078            let tmp = tempfile::tempdir().unwrap();
1079            let store = ModelStore::new(tmp.path().join("store"));
1080            let staged = tmp.path().join("up");
1081            let a = stage(&staged, &[("tune-LoRA.gguf", crate::gguf::lora_header("llama"))]);
1082            let mut p = Provenance::new(ORIGIN_TRAIN);
1083            p.base = Some(ProvenanceBase { id: Some("qwen3-8b".into()), ..Default::default() });
1084            let got = store.import(&staged, &a, &p, "tune").unwrap();
1085            let Imported::Adapter(ad) = got else { panic!() };
1086            assert_eq!((ad.format, ad.architecture.as_deref(), ad.alpha), (AdapterFormat::GgufLora, Some("llama"), Some(32.5)));
1087            let listed = store.adapters();
1088            assert_eq!(listed.len(), 1);
1089            assert_eq!(listed[0].path, store.dir().join("adapters/tune/tune-LoRA.gguf"));
1090            assert_eq!(listed[0].size, a.size(), "adapter.json and provenance.json are not counted");
1091            assert_eq!(listed[0].provenance.as_ref().unwrap().base.as_ref().unwrap().id.as_deref(), Some("qwen3-8b"));
1092            assert!(store.dir().join("adapters/tune/adapter.json").is_file());
1093            assert!(store.list().is_empty(), "adapters are not models");
1094
1095            let peft = tmp.path().join("peft");
1096            let b = stage(
1097                &peft,
1098                &[
1099                    ("adapter_config.json", br#"{"peft_type":"LORA","r":8,"lora_alpha":16,"base_model_name_or_path":"Org/B"}"#.to_vec()),
1100                    ("adapter_model.safetensors", safetensors(3, None)),
1101                ],
1102            );
1103            store.import(&peft, &b, &Provenance::new(ORIGIN_UPLOAD), "peft").unwrap();
1104            let peft = store.adapters().into_iter().find(|a| a.id == "peft").unwrap();
1105            assert_eq!((peft.format, peft.rank, peft.path.clone()), (AdapterFormat::Peft, Some(8), store.dir().join("adapters/peft")));
1106        }
1107
1108        #[test]
1109        fn safetensors_and_mlx_directories_and_projectors_have_their_own_layouts() {
1110            let tmp = tempfile::tempdir().unwrap();
1111            let store = ModelStore::new(tmp.path().join("store"));
1112            let hf = tmp.path().join("hf");
1113            let a = stage(&hf, &[("config.json", br#"{"architectures":["X"]}"#.to_vec()), ("model.safetensors", safetensors(2, None))]);
1114            store.import(&hf, &a, &Provenance::new(ORIGIN_UPLOAD), "x-st").unwrap();
1115            let mlx = tmp.path().join("mlx");
1116            let b = stage(
1117                &mlx,
1118                &[
1119                    ("config.json", br#"{"architectures":["X"]}"#.to_vec()),
1120                    ("model.safetensors", safetensors(2, Some(serde_json::json!({"format":"mlx"})))),
1121                ],
1122            );
1123            store.import(&mlx, &b, &Provenance::new(ORIGIN_UPLOAD), "x-mlx").unwrap();
1124            let dirs = store.dir_models();
1125            assert_eq!(
1126                dirs.iter().map(|m| (m.id.as_str(), m.layout, m.complete)).collect::<Vec<_>>(),
1127                [("x-mlx", ModelLayout::Mlx, true), ("x-st", ModelLayout::Safetensors, true)]
1128            );
1129            assert_eq!(dirs[1].files, ["safetensors/x-st/config.json", "safetensors/x-st/model.safetensors"]);
1130            assert!(store.list().is_empty(), "GGUF list only");
1131
1132            let mm = tmp.path().join("mm");
1133            let c = stage(&mm, &[("mmproj-F16.gguf", crate::gguf::header(&[("general.architecture", serde_json::json!("clip"))]))]);
1134            let mut p = Provenance::new(ORIGIN_UPLOAD);
1135            p.base = Some(ProvenanceBase { id: Some("x-st".into()), ..Default::default() });
1136            store.import(&mm, &c, &p, "vision").unwrap();
1137            let proj = store.projectors();
1138            assert_eq!((proj[0].id.as_str(), proj[0].for_model.as_deref()), ("vision", Some("x-st")));
1139            assert_eq!(store.remove_projector(&proj[0]).unwrap(), c.size());
1140            assert_eq!(store.remove_local(&dirs[0]).unwrap(), b.size());
1141            assert!(!store.dir().join("mlx/x-mlx").exists());
1142            assert_eq!(store.bytes_by_origin(ORIGIN_UPLOAD), a.size());
1143        }
1144
1145        #[test]
1146        fn disk_space_is_read_before_the_store_exists() {
1147            let tmp = tempfile::tempdir().unwrap();
1148            let store = ModelStore::new(tmp.path().join("not/yet"));
1149            let d = store.disk_space().unwrap();
1150            assert!(d.total >= d.free && d.total > 0);
1151            assert!(store.free_bytes() > 0);
1152        }
1153    }
1154}