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