Skip to main content

weirdnet_model/
artifact.rs

1//! Model files a person brings themselves (a fine-tune made elsewhere, a trainer's output):
2//! [`inspect`] reads and hashes them, [`Provenance`] records where they came from, and
3//! [`ModelStore::import`](crate::ModelStore::import) places them in the store.
4//!
5//! Weights are data, never code: pickled weights (`.bin`, `.pt`, `.pth`, `.ckpt`, `.pkl`),
6//! Python files and other code are refused, and so are symlinks and anything that isn't a
7//! regular file. GGUF and safetensors files are read by their headers only, with size caps.
8//!
9//! What can be inspected:
10//!
11//! - GGUF files: one model, a split model (every `-0000k-of-0000n` part), a LoRA adapter or a
12//!   multimodal projector, told apart by the header ([`gguf::read_header`]).
13//! - A safetensors model directory (`config.json` with `architectures`, `*.safetensors`, an
14//!   index covering every shard when there are several, tokenizer files), for vLLM.
15//! - An MLX model directory (the same, saved by MLX-LM), for MLX-LM.
16//! - A PEFT LoRA adapter directory (`adapter_config.json`, `adapter_model.safetensors`), for vLLM.
17
18use std::collections::{BTreeMap, BTreeSet};
19use std::io::Read;
20use std::path::{Path, PathBuf};
21
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24use sha2::{Digest, Sha256};
25
26use crate::download::Progress;
27use crate::gguf::{self, GgufHeader, GgufInfo, GgufKind};
28use crate::hf::{AdapterFormat, check_file, check_repo, peft_lora, split_part};
29use crate::{Error, Result};
30
31/// Where [`ModelStore::import`](crate::ModelStore::import) writes an entry's [`Provenance`].
32pub const PROVENANCE_FILE: &str = "provenance.json";
33/// [`Provenance::format`] for records written by this crate.
34pub const PROVENANCE_FORMAT: &str = "weirdnet-provenance/1";
35/// [`Provenance::origin`]: sent from another machine.
36pub const ORIGIN_UPLOAD: &str = "upload";
37/// [`Provenance::origin`]: made by a training run.
38pub const ORIGIN_TRAIN: &str = "train";
39/// [`Provenance::origin`]: downloaded from a Hub.
40pub const ORIGIN_HUB: &str = "hub";
41/// The largest JSON file (`config.json`, `adapter_config.json`, an index, a provenance record)
42/// that is parsed.
43pub const JSON_LIMIT: u64 = 16 << 20;
44/// The largest safetensors header that is parsed (the format's own limit).
45pub const SAFETENSORS_HEADER_LIMIT: u64 = 100 << 20;
46/// File extensions that may be inspected (lower case). Anything else is refused.
47pub const ALLOWED_EXTENSIONS: &[&str] = &["gguf", "safetensors", "json", "txt", "model", "jinja", "tiktoken", "md"];
48/// File names without an allowed extension that may come along (license and readme files).
49pub const ALLOWED_NAMES: &[&str] = &["LICENSE", "NOTICE", "README", "USE_POLICY"];
50/// Pickled weights: they can run code when loaded, so they are never accepted.
51const PICKLES: &[&str] = &["bin", "pt", "pth", "ckpt", "pkl", "pickle", "joblib", "npy", "npz"];
52/// Code.
53const CODE: &[&str] = &["py", "pyc", "pyo", "pyx", "so", "dll", "dylib", "exe", "sh", "bat", "cmd", "ps1", "js"];
54/// Directories are read this many levels deep at most.
55const MAX_DEPTH: usize = 3;
56
57/// What an artifact is.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
59#[serde(rename_all = "snake_case")]
60#[non_exhaustive]
61pub enum ArtifactKind {
62    /// A full model.
63    Model,
64    /// A LoRA adapter for a base model.
65    Adapter { format: AdapterFormat },
66    /// A multimodal projector (llama.cpp `--mmproj`) for a model.
67    Projector,
68}
69
70impl ArtifactKind {
71    pub fn is_adapter(&self) -> bool {
72        matches!(self, ArtifactKind::Adapter { .. })
73    }
74
75    /// The [`ProvenanceKind`] for records about it.
76    pub fn provenance_kind(&self) -> ProvenanceKind {
77        match self {
78            ArtifactKind::Model => ProvenanceKind::Model,
79            ArtifactKind::Adapter { .. } => ProvenanceKind::Adapter,
80            ArtifactKind::Projector => ProvenanceKind::Projector,
81        }
82    }
83}
84
85/// How an artifact's weights are stored. A PEFT adapter is [`ArtifactFormat::Safetensors`]
86/// with [`ArtifactKind::Adapter`] of [`AdapterFormat::Peft`].
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89#[non_exhaustive]
90pub enum ArtifactFormat {
91    /// GGUF, in `parts` files (1 unless split).
92    Gguf { parts: u32 },
93    /// A safetensors directory (Hugging Face Transformers layout), for vLLM.
94    Safetensors,
95    /// An MLX directory (MLX-LM's layout), for MLX-LM.
96    Mlx,
97}
98
99/// One file of an artifact.
100#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
101pub struct ArtifactFile {
102    /// `/`-separated path relative to the artifact (a file name for single files).
103    pub path: String,
104    pub size: u64,
105    /// Lower-case hex SHA-256.
106    pub sha256: String,
107}
108
109/// What [`inspect`] found.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111#[non_exhaustive]
112pub struct Artifact {
113    pub kind: ArtifactKind,
114    pub format: ArtifactFormat,
115    /// GGUF `general.architecture`, or the first of `config.json`'s `architectures`. `None` for
116    /// PEFT adapters (their config doesn't say).
117    pub architecture: Option<String>,
118    /// The base model as a Hub id: the GGUF header's `general.base_model`, PEFT's
119    /// `base_model_name_or_path`, or `config.json`'s `_name_or_path`, when they name one.
120    pub base_model: Option<String>,
121    /// A GGUF model's KV shape, when its header has it.
122    pub info: Option<GgufInfo>,
123    /// PEFT `r`.
124    pub rank: Option<u32>,
125    /// GGUF `adapter.lora.alpha` or PEFT `lora_alpha`.
126    pub alpha: Option<f32>,
127    /// Split GGUF parts in order; otherwise sorted by path.
128    pub files: Vec<ArtifactFile>,
129    /// See [`revision`].
130    pub revision: String,
131}
132
133impl Artifact {
134    /// All files together.
135    pub fn size(&self) -> u64 {
136        self.files.iter().map(|f| f.size).sum()
137    }
138}
139
140/// A content revision for `files`: `sha256:` and the first 16 hex digits of the SHA-256 of the
141/// `path:sha256` lines, sorted by path. The same files give the same revision wherever they are.
142pub fn revision(files: &[ArtifactFile]) -> String {
143    let mut lines: Vec<String> = files.iter().map(|f| format!("{}:{}\n", f.path, f.sha256)).collect();
144    lines.sort();
145    let digest = Sha256::digest(lines.concat().as_bytes());
146    let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect();
147    format!("sha256:{}", &hex[..16])
148}
149
150/// Whether `path` may be part of an artifact: a relative, `/`-separated path of plain parts
151/// (no `..`, no hidden parts, at most three levels), with an allowed extension. Pickles, Python
152/// and other code are refused with the reason.
153pub fn check_name(path: &str) -> Result<()> {
154    check_file(path).map_err(|_| Error::Model(format!("{path:?} is not a plain relative file name")))?;
155    if path.split('/').any(|p| p.starts_with('.')) {
156        return Err(Error::Model(format!("{path}: hidden files are not accepted")));
157    }
158    if path.split('/').count() > MAX_DEPTH {
159        return Err(Error::Model(format!("{path}: nested more than {MAX_DEPTH} levels")));
160    }
161    let name = path.rsplit('/').next().unwrap_or(path);
162    let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
163    match ext.as_deref() {
164        Some(e) if PICKLES.contains(&e) => {
165            Err(Error::Model(format!("{path}: pickled weights can run code and are never accepted; convert them to safetensors or GGUF")))
166        }
167        Some(e) if CODE.contains(&e) => Err(Error::Model(format!("{path}: code is never accepted with model files"))),
168        Some(e) if ALLOWED_EXTENSIONS.contains(&e) => Ok(()),
169        _ if ALLOWED_NAMES.iter().any(|n| name.eq_ignore_ascii_case(n) || name.to_ascii_uppercase().starts_with(&format!("{n}."))) => Ok(()),
170        _ => Err(Error::Model(format!("{path}: not a model file type ({})", ALLOWED_EXTENSIONS.join(", ")))),
171    }
172}
173
174/// A file to inspect: its artifact path and where it is.
175#[derive(Debug, Clone)]
176struct Found {
177    rel: String,
178    abs: PathBuf,
179    size: u64,
180}
181
182/// A regular file, never a symlink or a device.
183fn regular(path: &Path) -> Result<u64> {
184    let m = std::fs::symlink_metadata(path).map_err(|e| Error::Model(format!("{}: {e}", path.display())))?;
185    if m.file_type().is_symlink() {
186        return Err(Error::Model(format!("{}: symlinks are not accepted", path.display())));
187    }
188    if !m.is_file() {
189        return Err(Error::Model(format!("{}: not a regular file", path.display())));
190    }
191    Ok(m.len())
192}
193
194fn walk(root: &Path, dir: &Path, depth: usize, out: &mut Vec<Found>) -> Result<()> {
195    let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<std::io::Result<_>>()?;
196    entries.sort_by_key(|e| e.file_name());
197    for e in entries {
198        let name = e.file_name().to_string_lossy().into_owned();
199        if name.starts_with('.') {
200            continue;
201        }
202        let path = e.path();
203        let ft = e.file_type()?;
204        if ft.is_symlink() {
205            return Err(Error::Model(format!("{}: symlinks are not accepted", path.display())));
206        } else if ft.is_dir() {
207            if depth + 1 >= MAX_DEPTH {
208                return Err(Error::Model(format!("{}: nested more than {MAX_DEPTH} levels", path.display())));
209            }
210            walk(root, &path, depth + 1, out)?;
211        } else if ft.is_file() {
212            let rel: Vec<String> =
213                path.strip_prefix(root).unwrap_or(&path).components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
214            let rel = rel.join("/");
215            check_name(&rel)?;
216            out.push(Found { rel, size: regular(&path)?, abs: path });
217        } else {
218            return Err(Error::Model(format!("{}: not a regular file", path.display())));
219        }
220    }
221    Ok(())
222}
223
224/// One directory (its files, recursively), or files given one by one (by file name).
225fn gather(paths: &[PathBuf]) -> Result<Vec<Found>> {
226    let mut out = Vec::new();
227    match paths {
228        [] => return Err(Error::Model("nothing to inspect".into())),
229        [one] if std::fs::symlink_metadata(one).is_ok_and(|m| m.is_dir()) => walk(one, one, 0, &mut out)?,
230        _ => {
231            for p in paths {
232                let size = regular(p)?;
233                let rel = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
234                check_name(&rel)?;
235                if out.iter().any(|f: &Found| f.rel == rel) {
236                    return Err(Error::Model(format!("{rel} is given twice")));
237                }
238                out.push(Found { rel, abs: p.clone(), size });
239            }
240        }
241    }
242    if out.is_empty() {
243        return Err(Error::Model("no files to inspect".into()));
244    }
245    Ok(out)
246}
247
248/// A JSON file, with [`JSON_LIMIT`].
249fn read_json(path: &Path) -> Result<Value> {
250    let mut buf = Vec::new();
251    std::fs::File::open(path)?.take(JSON_LIMIT + 1).read_to_end(&mut buf)?;
252    if buf.len() as u64 > JSON_LIMIT {
253        return Err(Error::Model(format!("{}: larger than {JSON_LIMIT} bytes", path.display())));
254    }
255    serde_json::from_slice(&buf).map_err(|e| Error::Model(format!("{}: not valid JSON: {e}", path.display())))
256}
257
258/// What a safetensors header says ([`read_safetensors`]).
259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260#[non_exhaustive]
261pub struct SafetensorsHeader {
262    /// The header's length in bytes (after the 8-byte length).
263    pub header_len: u64,
264    pub tensors: usize,
265    /// Bytes of tensor data after the header.
266    pub data_bytes: u64,
267    /// `__metadata__` (MLX-LM writes `format` = `mlx`).
268    pub metadata: BTreeMap<String, String>,
269}
270
271/// Bytes per element of a safetensors dtype, when it is a whole number of bytes.
272fn dtype_size(dtype: &str) -> Option<u64> {
273    Some(match dtype {
274        "BOOL" | "U8" | "I8" | "F8_E4M3" | "F8_E5M2" | "F8_E8M0" => 1,
275        "U16" | "I16" | "F16" | "BF16" => 2,
276        "U32" | "I32" | "F32" => 4,
277        "U64" | "I64" | "F64" | "C64" => 8,
278        _ => return None,
279    })
280}
281
282/// Reads and checks a safetensors header from the start of a file of `file_size` bytes: the
283/// 8-byte length, the JSON header (at most [`SAFETENSORS_HEADER_LIMIT`]), and the tensors'
284/// offsets, which must cover the data after the header exactly, with no gaps or overlaps, each
285/// as long as its dtype and shape say.
286pub fn read_safetensors(mut r: impl Read, file_size: u64) -> Result<SafetensorsHeader> {
287    let bad = |m: String| Error::Model(format!("safetensors: {m}"));
288    let mut len = [0u8; 8];
289    r.read_exact(&mut len).map_err(|e| bad(format!("header cut short: {e}")))?;
290    let header_len = u64::from_le_bytes(len);
291    if header_len > SAFETENSORS_HEADER_LIMIT {
292        return Err(bad(format!("header is larger than {SAFETENSORS_HEADER_LIMIT} bytes")));
293    }
294    if header_len.saturating_add(8) > file_size {
295        return Err(bad("header is longer than the file".into()));
296    }
297    let mut buf = vec![0; header_len as usize];
298    r.read_exact(&mut buf).map_err(|e| bad(format!("header cut short: {e}")))?;
299    let header: serde_json::Map<String, Value> = serde_json::from_slice(&buf).map_err(|e| bad(format!("header is not a JSON object: {e}")))?;
300    let data_bytes = file_size - 8 - header_len;
301    let mut metadata = BTreeMap::new();
302    let mut spans = Vec::new();
303    for (name, t) in &header {
304        if name == "__metadata__" {
305            for (k, v) in t.as_object().into_iter().flatten() {
306                metadata.insert(k.clone(), v.as_str().ok_or_else(|| bad(format!("metadata {k} is not a string")))?.to_string());
307            }
308            continue;
309        }
310        let dtype = t["dtype"].as_str().ok_or_else(|| bad(format!("{name} has no dtype")))?;
311        let shape: Vec<u64> = t["shape"]
312            .as_array()
313            .ok_or_else(|| bad(format!("{name} has no shape")))?
314            .iter()
315            .map(Value::as_u64)
316            .collect::<Option<_>>()
317            .ok_or_else(|| bad(format!("{name}: bad shape")))?;
318        let offsets: Vec<u64> = t["data_offsets"]
319            .as_array()
320            .filter(|a| a.len() == 2)
321            .and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
322            .ok_or_else(|| bad(format!("{name} has no data_offsets")))?;
323        let (start, end) = (offsets[0], offsets[1]);
324        if end < start {
325            return Err(bad(format!("{name}: offsets run backwards")));
326        }
327        if let Some(size) = dtype_size(dtype) {
328            let want = shape.iter().try_fold(size, |acc, d| acc.checked_mul(*d)).ok_or_else(|| bad(format!("{name}: shape overflows")))?;
329            if end - start != want {
330                return Err(bad(format!("{name}: {} bytes for {dtype} {shape:?}, which needs {want}", end - start)));
331            }
332        }
333        spans.push((start, end, name.clone()));
334    }
335    spans.sort();
336    let mut at = 0;
337    for (start, end, name) in &spans {
338        if *start != at {
339            return Err(bad(format!("{name} starts at {start}, not {at}: gaps and overlaps are not allowed")));
340        }
341        at = *end;
342    }
343    if at != data_bytes {
344        return Err(bad(format!("tensors cover {at} bytes; the file has {data_bytes} after the header")));
345    }
346    Ok(SafetensorsHeader { header_len, tensors: spans.len(), data_bytes, metadata })
347}
348
349fn safetensors_of(f: &Found) -> Result<SafetensorsHeader> {
350    let file = std::fs::File::open(&f.abs)?;
351    read_safetensors(std::io::BufReader::new(file), f.size).map_err(|e| Error::Model(format!("{}: {e}", f.rel)))
352}
353
354/// The header read so far from the start of a file being received ([`early_header`]).
355// A GGUF header (with a projector's figures) is larger than a safetensors one; boxing it would
356// change the public variant, and one header per upload is cheap either way.
357#[allow(clippy::large_enum_variant)]
358#[derive(Debug, Clone, PartialEq)]
359#[non_exhaustive]
360pub enum EarlyHeader {
361    Gguf(GgufHeader),
362    Safetensors(SafetensorsHeader),
363}
364
365/// A reader over a prefix that notes whether a read reached its end.
366struct Prefix<'a> {
367    bytes: &'a [u8],
368    hit_end: bool,
369}
370
371impl Read for Prefix<'_> {
372    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
373        let n = self.bytes.read(buf)?;
374        if n < buf.len() {
375            self.hit_end = true;
376        }
377        Ok(n)
378    }
379}
380
381/// Checks a file's header from the first bytes received (`prefix`) of a file of `file_size`
382/// bytes named `path`, so a bad file is refused before the rest is sent. `Ok(None)` when more
383/// bytes are needed (or the file type has no header); an error when the header is bad.
384pub fn early_header(path: &str, prefix: &[u8], file_size: u64) -> Result<Option<EarlyHeader>> {
385    let lower = path.to_ascii_lowercase();
386    let complete = prefix.len() as u64 >= file_size;
387    if lower.ends_with(".gguf") {
388        let mut r = Prefix { bytes: prefix, hit_end: false };
389        return match gguf::read_header(&mut r) {
390            Ok(h) => Ok(Some(EarlyHeader::Gguf(h))),
391            Err(_) if r.hit_end && !complete => Ok(None),
392            Err(e) => Err(Error::Model(format!("{path}: {e}"))),
393        };
394    }
395    if lower.ends_with(".safetensors") {
396        let need = prefix.get(..8).map(|l| u64::from_le_bytes(l.try_into().expect("8 bytes")).saturating_add(8));
397        return match need {
398            Some(n) if n <= SAFETENSORS_HEADER_LIMIT + 8 && (prefix.len() as u64) < n && !complete => Ok(None),
399            None if !complete => Ok(None),
400            _ => read_safetensors(prefix, file_size).map(|h| Some(EarlyHeader::Safetensors(h))).map_err(|e| Error::Model(format!("{path}: {e}"))),
401        };
402    }
403    Ok(None)
404}
405
406/// Kind, format and what the headers say, before hashing.
407struct Classified {
408    kind: ArtifactKind,
409    format: ArtifactFormat,
410    architecture: Option<String>,
411    base_model: Option<String>,
412    info: Option<GgufInfo>,
413    rank: Option<u32>,
414    alpha: Option<f32>,
415    /// `files` reordered: split parts in order, else by path.
416    files: Vec<Found>,
417}
418
419fn classify(mut files: Vec<Found>) -> Result<Classified> {
420    files.sort_by(|a, b| a.rel.cmp(&b.rel));
421    let is = |f: &Found, ext: &str| f.rel.to_ascii_lowercase().ends_with(ext);
422    let ggufs = files.iter().filter(|f| is(f, ".gguf")).count();
423    if ggufs > 0 {
424        if ggufs != files.len() {
425            return Err(Error::Model("GGUF files come alone: give only the .gguf file or its split parts".into()));
426        }
427        return classify_gguf(files);
428    }
429    let root = |name: &str| files.iter().find(|f| f.rel == name).cloned();
430    if let Some(config) = root("adapter_config.json") {
431        let cfg = read_json(&config.abs)?;
432        let (rank, alpha, base) = peft_lora(&cfg).ok_or_else(|| Error::Model("adapter_config.json: only LoRA adapters are accepted".into()))?;
433        root("adapter_model.safetensors").ok_or_else(|| Error::Model("a PEFT adapter needs adapter_model.safetensors".into()))?;
434        for f in files.iter().filter(|f| is(f, ".safetensors")) {
435            safetensors_of(f)?;
436        }
437        return Ok(Classified {
438            kind: ArtifactKind::Adapter { format: AdapterFormat::Peft },
439            format: ArtifactFormat::Safetensors,
440            architecture: None,
441            base_model: base,
442            info: None,
443            rank,
444            alpha,
445            files,
446        });
447    }
448    if let Some(config) = root("config.json") {
449        let cfg = read_json(&config.abs)?;
450        let architecture = cfg["architectures"]
451            .as_array()
452            .and_then(|a| a.first())
453            .and_then(Value::as_str)
454            .filter(|a| !a.is_empty())
455            .ok_or_else(|| Error::Model("config.json has no architectures".into()))?
456            .to_string();
457        let shards: Vec<&Found> = files.iter().filter(|f| is(f, ".safetensors")).collect();
458        if shards.is_empty() {
459            return Err(Error::Model("a model directory needs its *.safetensors weights".into()));
460        }
461        let mut mlx = cfg.get("quantization").is_some_and(Value::is_object);
462        for s in &shards {
463            let h = safetensors_of(s)?;
464            mlx |= h.metadata.get("format").is_some_and(|f| f == "mlx");
465        }
466        let indexes: Vec<&Found> = files.iter().filter(|f| is(f, ".safetensors.index.json")).collect();
467        match indexes.as_slice() {
468            [] if shards.len() > 1 => return Err(Error::Model("several *.safetensors files need a *.safetensors.index.json".into())),
469            [] => {}
470            [index] => {
471                let map = read_json(&index.abs)?;
472                let named: BTreeSet<&str> = map["weight_map"]
473                    .as_object()
474                    .ok_or_else(|| Error::Model(format!("{}: no weight_map", index.rel)))?
475                    .values()
476                    .map(|v| v.as_str().ok_or_else(|| Error::Model(format!("{}: bad weight_map", index.rel))))
477                    .collect::<Result<_>>()?;
478                let dir = index.rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
479                let have: BTreeSet<String> = shards.iter().map(|s| s.rel.clone()).collect();
480                let want: BTreeSet<String> = named.iter().map(|n| format!("{dir}{n}")).collect();
481                if let Some(missing) = want.difference(&have).next() {
482                    return Err(Error::Model(format!("{}: names {missing}, which is missing", index.rel)));
483                }
484                if let Some(extra) = have.difference(&want).next() {
485                    return Err(Error::Model(format!("{extra} is not in {}", index.rel)));
486                }
487            }
488            _ => return Err(Error::Model("more than one *.safetensors.index.json".into())),
489        }
490        let base_model = cfg["_name_or_path"].as_str().filter(|b| check_repo(b).is_ok()).map(str::to_string);
491        return Ok(Classified {
492            kind: ArtifactKind::Model,
493            format: if mlx { ArtifactFormat::Mlx } else { ArtifactFormat::Safetensors },
494            architecture: Some(architecture),
495            base_model,
496            info: None,
497            rank: None,
498            alpha: None,
499            files,
500        });
501    }
502    Err(Error::Model(
503        "not a model: give GGUF files, a safetensors or MLX model directory (config.json and *.safetensors), or a PEFT adapter directory (adapter_config.json)".into(),
504    ))
505}
506
507fn classify_gguf(mut files: Vec<Found>) -> Result<Classified> {
508    let parts = if let [one] = files.as_slice() {
509        if let Some((_, part, of)) = split_part(&one.rel)
510            && (part, of) != (1, 1)
511        {
512            return Err(Error::Model(format!("{} is part {part} of {of}: give every part", one.rel)));
513        }
514        1
515    } else {
516        let mut seen: Vec<(u32, Found)> = Vec::new();
517        let mut set: Option<(String, u32)> = None;
518        for f in &files {
519            let (base, part, of) = split_part(&f.rel)
520                .ok_or_else(|| Error::Model("one model per upload: several GGUF files must be the parts of one split model".into()))?;
521            let dir = f.rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
522            let key = (format!("{dir}{base}"), of);
523            if set.get_or_insert_with(|| key.clone()) != &key {
524                return Err(Error::Model("one model per upload: the GGUF parts belong to different models".into()));
525            }
526            seen.push((part, f.clone()));
527        }
528        let of = set.map(|s| s.1).unwrap_or(0);
529        seen.sort_by_key(|(p, _)| *p);
530        if seen.len() as u32 != of || seen.iter().enumerate().any(|(i, (p, _))| *p != i as u32 + 1) {
531            return Err(Error::Model(format!("a split model needs all {of} parts, once each")));
532        }
533        files = seen.into_iter().map(|(_, f)| f).collect();
534        of
535    };
536    let first = &files[0];
537    let header =
538        gguf::read_header(std::io::BufReader::new(std::fs::File::open(&first.abs)?)).map_err(|e| Error::Model(format!("{}: {e}", first.rel)))?;
539    if let Some(info) = &header.info
540        && parts > 1
541        && info.split_count != parts as u64
542    {
543        return Err(Error::Model(format!("{}: the header says {} parts, not {parts}", first.rel, info.split_count)));
544    }
545    let (kind, alpha) = match &header.kind {
546        GgufKind::Model => (ArtifactKind::Model, None),
547        GgufKind::Adapter { alpha, .. } if header.kind.is_lora() => (ArtifactKind::Adapter { format: AdapterFormat::GgufLora }, *alpha),
548        GgufKind::Adapter { adapter_type, .. } => {
549            return Err(Error::Model(format!("{}: only LoRA adapters are accepted, not {adapter_type:?}", first.rel)));
550        }
551        GgufKind::Projector => (ArtifactKind::Projector, None),
552    };
553    if parts > 1 && kind != ArtifactKind::Model {
554        return Err(Error::Model(format!("{}: only models come in split parts", first.rel)));
555    }
556    Ok(Classified {
557        kind,
558        format: ArtifactFormat::Gguf { parts },
559        architecture: Some(header.architecture),
560        base_model: header.base_model,
561        info: header.info,
562        rank: None,
563        alpha,
564        files,
565    })
566}
567
568/// SHA-256 of `path`, read in chunks, adding to `done` and calling `progress` as it goes.
569fn hash_file(path: &Path, done: &mut u64, total: u64, progress: &mut dyn FnMut(Progress) -> bool) -> Result<String> {
570    let mut hasher = Sha256::new();
571    let mut file = std::fs::File::open(path)?;
572    let mut buf = vec![0; 1 << 20];
573    loop {
574        let n = file.read(&mut buf)?;
575        if n == 0 {
576            break;
577        }
578        hasher.update(&buf[..n]);
579        *done += n as u64;
580        if !progress(Progress { done: *done, total }) {
581            return Err(Error::Cancelled { done: crate::human(*done), total: crate::human(total) });
582        }
583    }
584    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
585}
586
587fn finish(c: Classified, progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
588    let total = c.files.iter().map(|f| f.size).sum();
589    let mut done = 0;
590    let mut files = Vec::with_capacity(c.files.len());
591    for f in &c.files {
592        let sha256 = hash_file(&f.abs, &mut done, total, progress)?;
593        files.push(ArtifactFile { path: f.rel.clone(), size: f.size, sha256 });
594    }
595    let revision = revision(&files);
596    Ok(Artifact {
597        kind: c.kind,
598        format: c.format,
599        architecture: c.architecture,
600        base_model: c.base_model,
601        info: c.info,
602        rank: c.rank,
603        alpha: c.alpha,
604        files,
605        revision,
606    })
607}
608
609/// Reads and hashes local model files: one directory, or files given one by one (a GGUF, every
610/// part of a split GGUF). Headers are checked before anything is hashed. See the module docs
611/// for what is accepted and refused.
612pub fn inspect(paths: &[PathBuf]) -> Result<Artifact> {
613    inspect_with(paths, &mut |_| true)
614}
615
616/// [`inspect`], calling `progress` while hashing; it returns `false` to cancel.
617pub fn inspect_with(paths: &[PathBuf], progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
618    finish(classify(gather(paths)?)?, progress)
619}
620
621/// Inspects files that were received into `dir` under their artifact paths (as an upload
622/// stages them) and checks each against `files`: present, a regular file, the same size and
623/// SHA-256. The headers are checked as [`inspect`] does.
624pub fn inspect_staged(dir: &Path, files: &[ArtifactFile], progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
625    if files.is_empty() {
626        return Err(Error::Model("no files".into()));
627    }
628    let mut found = Vec::with_capacity(files.len());
629    let mut names = BTreeSet::new();
630    for f in files {
631        check_name(&f.path)?;
632        if !names.insert(f.path.as_str()) {
633            return Err(Error::Model(format!("{} is listed twice", f.path)));
634        }
635        let abs = dir.join(&f.path);
636        let size = regular(&abs)?;
637        if size != f.size {
638            return Err(Error::Model(format!("{}: {size} bytes, expected {}", f.path, f.size)));
639        }
640        found.push(Found { rel: f.path.clone(), abs, size });
641    }
642    let artifact = finish(classify(found)?, progress)?;
643    for want in files {
644        let got = artifact.files.iter().find(|g| g.path == want.path).expect("every file is inspected");
645        if !got.sha256.eq_ignore_ascii_case(&want.sha256) {
646            return Err(Error::Checksum { name: want.path.clone(), got: got.sha256.clone() });
647        }
648    }
649    Ok(artifact)
650}
651
652/// [`Provenance::kind`].
653#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
654#[serde(rename_all = "snake_case")]
655#[non_exhaustive]
656pub enum ProvenanceKind {
657    #[default]
658    Model,
659    Adapter,
660    Projector,
661}
662
663/// [`Provenance::base`]: the model an artifact was made from or runs on.
664#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
665#[non_exhaustive]
666pub struct ProvenanceBase {
667    /// The base's id where it runs (a served or stored model id).
668    #[serde(default, skip_serializing_if = "Option::is_none")]
669    pub id: Option<String>,
670    /// Its Hub id (`owner/name`).
671    #[serde(default, skip_serializing_if = "Option::is_none")]
672    pub hub: Option<String>,
673    #[serde(default, skip_serializing_if = "Option::is_none")]
674    pub revision: Option<String>,
675    #[serde(default, skip_serializing_if = "Option::is_none")]
676    pub quant: Option<String>,
677    #[serde(default, skip_serializing_if = "Option::is_none")]
678    pub sha256: Option<String>,
679}
680
681/// [`Provenance::dataset`]: what it was trained on (hashes, counts and licenses; never rows).
682#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
683#[non_exhaustive]
684pub struct ProvenanceDataset {
685    /// The dataset manifest's format, such as an app's `name/1`.
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub format: Option<String>,
688    /// SHA-256 of the manifest.
689    #[serde(default, skip_serializing_if = "Option::is_none")]
690    pub sha256: Option<String>,
691    #[serde(default, skip_serializing_if = "Option::is_none")]
692    pub rows: Option<u64>,
693    /// Other counts by name.
694    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
695    pub counts: BTreeMap<String, u64>,
696    /// Licenses of the data (and of a teacher model's output, when one made it).
697    #[serde(default, skip_serializing_if = "Vec::is_empty")]
698    pub licenses: Vec<String>,
699}
700
701/// [`Provenance::trainer`]: what made it.
702#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
703#[non_exhaustive]
704pub struct ProvenanceTrainer {
705    #[serde(default, skip_serializing_if = "Option::is_none")]
706    pub name: Option<String>,
707    #[serde(default, skip_serializing_if = "Option::is_none")]
708    pub build: Option<String>,
709    #[serde(default, skip_serializing_if = "Option::is_none")]
710    pub run: Option<String>,
711}
712
713fn provenance_format() -> String {
714    PROVENANCE_FORMAT.into()
715}
716
717/// Where a model, adapter or projector came from, kept next to its files
718/// ([`PROVENANCE_FILE`]). It is what the uploader said, checked against the bytes where it
719/// can be (files, hashes and revision are set from them on import); it is signed by nobody and
720/// is not a trust anchor. Unknown fields (an app's own) are kept in [`Provenance::extra`] and
721/// written back.
722#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
723#[non_exhaustive]
724pub struct Provenance {
725    /// [`PROVENANCE_FORMAT`], or an app's own name.
726    #[serde(default = "provenance_format")]
727    pub format: String,
728    #[serde(default)]
729    pub kind: ProvenanceKind,
730    #[serde(default)]
731    pub id: String,
732    #[serde(default)]
733    pub files: Vec<ArtifactFile>,
734    /// See [`revision`].
735    #[serde(default)]
736    pub revision: String,
737    /// [`ORIGIN_UPLOAD`], [`ORIGIN_TRAIN`], [`ORIGIN_HUB`] or an app's own.
738    #[serde(default)]
739    pub origin: String,
740    /// An SPDX id, or `unknown` when the uploader said so explicitly.
741    #[serde(default, skip_serializing_if = "Option::is_none")]
742    pub license: Option<String>,
743    #[serde(default, skip_serializing_if = "Option::is_none")]
744    pub base: Option<ProvenanceBase>,
745    #[serde(default, skip_serializing_if = "Option::is_none")]
746    pub dataset: Option<ProvenanceDataset>,
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub trainer: Option<ProvenanceTrainer>,
749    /// The uploading device's label.
750    #[serde(default, skip_serializing_if = "Option::is_none")]
751    pub uploaded_by: Option<String>,
752    /// Unix time in milliseconds.
753    #[serde(default, skip_serializing_if = "Option::is_none")]
754    pub uploaded_ms: Option<u64>,
755    /// Any other fields.
756    #[serde(flatten)]
757    pub extra: BTreeMap<String, Value>,
758}
759
760impl Default for Provenance {
761    fn default() -> Self {
762        Self {
763            format: provenance_format(),
764            kind: ProvenanceKind::Model,
765            id: String::new(),
766            files: Vec::new(),
767            revision: String::new(),
768            origin: String::new(),
769            license: None,
770            base: None,
771            dataset: None,
772            trainer: None,
773            uploaded_by: None,
774            uploaded_ms: None,
775            extra: BTreeMap::new(),
776        }
777    }
778}
779
780impl Provenance {
781    /// A record with this origin ([`ORIGIN_UPLOAD`] and so on).
782    pub fn new(origin: impl Into<String>) -> Self {
783        Self { origin: origin.into(), ..Default::default() }
784    }
785
786    /// A record for `artifact` stored as `id`: its kind, files and revision, and its base
787    /// model's Hub id when the files name one.
788    pub fn for_artifact(artifact: &Artifact, id: impl Into<String>, origin: impl Into<String>) -> Self {
789        let mut p = Self::new(origin);
790        p.id = id.into();
791        p.kind = artifact.kind.provenance_kind();
792        p.files = artifact.files.clone();
793        p.revision = artifact.revision.clone();
794        if let Some(hub) = &artifact.base_model {
795            p.base = Some(ProvenanceBase { hub: Some(hub.clone()), ..Default::default() });
796        }
797        p
798    }
799
800    pub fn with_license(mut self, license: impl Into<String>) -> Self {
801        self.license = Some(license.into());
802        self
803    }
804
805    /// Bytes of the files it lists.
806    pub fn size(&self) -> u64 {
807        self.files.iter().map(|f| f.size).sum()
808    }
809
810    /// The record in `dir` ([`PROVENANCE_FILE`]), if there is a readable one.
811    pub fn read(dir: &Path) -> Option<Provenance> {
812        let path = dir.join(PROVENANCE_FILE);
813        regular(&path).ok()?;
814        serde_json::from_value(read_json(&path).ok()?).ok()
815    }
816
817    /// Writes the record to `dir` ([`PROVENANCE_FILE`]), replacing it atomically.
818    pub fn write(&self, dir: &Path) -> Result<()> {
819        let json = serde_json::to_vec_pretty(self).map_err(|e| Error::Model(e.to_string()))?;
820        let tmp = dir.join(format!(".{PROVENANCE_FILE}.tmp"));
821        std::fs::write(&tmp, json)?;
822        std::fs::rename(&tmp, dir.join(PROVENANCE_FILE))?;
823        Ok(())
824    }
825}
826
827#[cfg(test)]
828pub(crate) mod tests {
829    use super::*;
830    use serde_json::json;
831
832    /// A safetensors file with one F32 tensor of `n` elements and optional metadata.
833    pub(crate) fn safetensors(n: u64, metadata: Option<Value>) -> Vec<u8> {
834        let mut header = json!({"w": {"dtype": "F32", "shape": [n], "data_offsets": [0, n * 4]}});
835        if let Some(m) = metadata {
836            header["__metadata__"] = m;
837        }
838        let h = serde_json::to_vec(&header).unwrap();
839        let mut out = (h.len() as u64).to_le_bytes().to_vec();
840        out.extend(h);
841        out.extend(vec![7u8; (n * 4) as usize]);
842        out
843    }
844
845    /// A small llama GGUF model header, padded.
846    pub(crate) fn model_gguf(extra: &[(&str, Value)]) -> Vec<u8> {
847        let mut kv = vec![
848            ("general.architecture", json!("llama")),
849            ("llama.block_count", json!(2)),
850            ("llama.attention.head_count", json!(4)),
851            ("llama.attention.head_count_kv", json!(2)),
852            ("llama.attention.key_length", json!(8)),
853        ];
854        kv.extend(extra.iter().cloned());
855        let mut out = gguf::header(&kv);
856        out.extend([1u8; 100]);
857        out
858    }
859
860    fn write(dir: &Path, name: &str, body: &[u8]) -> PathBuf {
861        let p = dir.join(name);
862        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
863        std::fs::write(&p, body).unwrap();
864        p
865    }
866
867    #[test]
868    fn names_refuse_pickles_code_and_hidden_files() {
869        for ok in ["m.gguf", "config.json", "tokenizer.model", "d/model-00001-of-00002.safetensors", "LICENSE", "LICENSE.txt", "chat_template.jinja"]
870        {
871            check_name(ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
872        }
873        for (bad, why) in [
874            ("pytorch_model.bin", "pickled"),
875            ("w.pt", "pickled"),
876            ("w.ckpt", "pickled"),
877            ("modeling.py", "code"),
878            (".hidden.json", "hidden"),
879            ("../x.gguf", "plain"),
880            ("/abs.gguf", "plain"),
881            ("a/b/c/d.json", "nested"),
882            ("x.exe", "code"),
883            ("x.zip", "not a model file"),
884        ] {
885            let e = check_name(bad).unwrap_err().to_string();
886            assert!(e.contains(why), "{bad}: {e}");
887        }
888    }
889
890    #[test]
891    fn a_gguf_model_is_read_hashed_and_given_a_revision() {
892        let tmp = tempfile::tempdir().unwrap();
893        let body = model_gguf(&[("general.base_model.0.repo_url", json!("https://huggingface.co/Org/Base"))]);
894        let p = write(tmp.path(), "tune-Q4_0.gguf", &body);
895        let mut calls = 0;
896        let a = inspect_with(std::slice::from_ref(&p), &mut |pr| {
897            calls += 1;
898            pr.total == body.len() as u64
899        })
900        .unwrap();
901        assert!(calls > 0);
902        assert_eq!((a.kind, a.format), (ArtifactKind::Model, ArtifactFormat::Gguf { parts: 1 }));
903        assert_eq!((a.architecture.as_deref(), a.base_model.as_deref()), (Some("llama"), Some("Org/Base")));
904        assert_eq!(a.info.as_ref().map(|i| i.layers), Some(2));
905        assert_eq!(a.files[0].sha256, crate::download::sha256_of(&p).unwrap());
906        assert_eq!(a.size(), body.len() as u64);
907        assert!(a.revision.starts_with("sha256:") && a.revision.len() == 23);
908        assert_eq!(a.revision, revision(&a.files), "stable");
909        assert!(matches!(inspect_with(&[p], &mut |_| false), Err(Error::Cancelled { .. })));
910    }
911
912    #[test]
913    fn revisions_ignore_order_but_not_paths() {
914        let f = |p: &str, h: &str| ArtifactFile { path: p.into(), size: 1, sha256: h.into() };
915        assert_eq!(revision(&[f("a", "1"), f("b", "2")]), revision(&[f("b", "2"), f("a", "1")]));
916        assert_ne!(revision(&[f("a", "1")]), revision(&[f("c", "1")]));
917    }
918
919    #[test]
920    fn split_ggufs_need_every_part() {
921        let tmp = tempfile::tempdir().unwrap();
922        let p1 = write(tmp.path(), "m-00001-of-00002.gguf", &model_gguf(&[("split.count", json!(2))]));
923        let p2 = write(tmp.path(), "m-00002-of-00002.gguf", &[0; 50]);
924        let a = inspect(&[p2.clone(), p1.clone()]).unwrap();
925        assert_eq!(a.format, ArtifactFormat::Gguf { parts: 2 });
926        assert_eq!(a.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["m-00001-of-00002.gguf", "m-00002-of-00002.gguf"]);
927        assert!(inspect(std::slice::from_ref(&p1)).unwrap_err().to_string().contains("give every part"));
928        let other = write(tmp.path(), "x.gguf", &model_gguf(&[]));
929        assert!(inspect(&[p1, other]).unwrap_err().to_string().contains("one model per upload"));
930    }
931
932    #[test]
933    fn gguf_adapters_and_projectors_are_told_apart() {
934        let tmp = tempfile::tempdir().unwrap();
935        let lora = write(tmp.path(), "tune-LoRA.gguf", &gguf::lora_header("llama"));
936        let a = inspect(&[lora]).unwrap();
937        assert_eq!(a.kind, ArtifactKind::Adapter { format: AdapterFormat::GgufLora });
938        assert_eq!((a.alpha, a.base_model.as_deref()), (Some(32.5), Some("Org/Base-8B")));
939        let mm = write(tmp.path(), "mmproj-F16.gguf", &gguf::header(&[("general.architecture", json!("clip")), ("general.type", json!("mmproj"))]));
940        assert_eq!(inspect(&[mm]).unwrap().kind, ArtifactKind::Projector);
941        let other = write(
942            tmp.path(),
943            "cv.gguf",
944            &gguf::header(&[("general.architecture", json!("llama")), ("general.type", json!("adapter")), ("adapter.type", json!("control_vector"))]),
945        );
946        assert!(inspect(&[other]).unwrap_err().to_string().contains("only LoRA"));
947        let junk = write(tmp.path(), "junk.gguf", b"not a gguf");
948        assert!(inspect(&[junk]).is_err());
949    }
950
951    #[test]
952    fn a_safetensors_directory_is_a_model_and_mlx_is_recognised() {
953        let tmp = tempfile::tempdir().unwrap();
954        let d = tmp.path().join("hf");
955        write(&d, "config.json", br#"{"architectures":["Qwen3ForCausalLM"],"_name_or_path":"Qwen/Qwen3-8B"}"#);
956        write(&d, "tokenizer.json", b"{}");
957        write(&d, "model.safetensors", &safetensors(4, None));
958        write(&d, ".gitattributes", b"skipped");
959        let a = inspect(std::slice::from_ref(&d)).unwrap();
960        assert_eq!((a.kind, a.format), (ArtifactKind::Model, ArtifactFormat::Safetensors));
961        assert_eq!((a.architecture.as_deref(), a.base_model.as_deref()), (Some("Qwen3ForCausalLM"), Some("Qwen/Qwen3-8B")));
962        assert_eq!(a.files.len(), 3, "hidden files are left out");
963
964        let m = tmp.path().join("mlx");
965        write(&m, "config.json", br#"{"architectures":["LlamaForCausalLM"]}"#);
966        write(&m, "model.safetensors", &safetensors(2, Some(json!({"format": "mlx"}))));
967        assert_eq!(inspect(&[m]).unwrap().format, ArtifactFormat::Mlx);
968        let q = tmp.path().join("mlxq");
969        write(&q, "config.json", br#"{"architectures":["LlamaForCausalLM"],"quantization":{"bits":4,"group_size":64}}"#);
970        write(&q, "model.safetensors", &safetensors(2, None));
971        assert_eq!(inspect(&[q]).unwrap().format, ArtifactFormat::Mlx);
972    }
973
974    #[test]
975    fn shards_must_match_their_index() {
976        let tmp = tempfile::tempdir().unwrap();
977        let d = tmp.path().join("m");
978        write(&d, "config.json", br#"{"architectures":["X"]}"#);
979        write(&d, "model-00001-of-00002.safetensors", &safetensors(2, None));
980        write(&d, "model-00002-of-00002.safetensors", &safetensors(2, None));
981        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("index"));
982        write(&d, "model.safetensors.index.json", br#"{"weight_map":{"a":"model-00001-of-00002.safetensors"}}"#);
983        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("not in"));
984        write(
985            &d,
986            "model.safetensors.index.json",
987            br#"{"weight_map":{"a":"model-00001-of-00002.safetensors","b":"model-00002-of-00002.safetensors"}}"#,
988        );
989        assert_eq!(inspect(&[d]).unwrap().files.len(), 4);
990    }
991
992    #[test]
993    fn peft_adapters_are_lora_only() {
994        let tmp = tempfile::tempdir().unwrap();
995        let d = tmp.path().join("peft");
996        write(&d, "adapter_config.json", br#"{"peft_type":"LORA","r":8,"lora_alpha":16,"base_model_name_or_path":"Org/B"}"#);
997        write(&d, "adapter_model.safetensors", &safetensors(3, None));
998        let a = inspect(std::slice::from_ref(&d)).unwrap();
999        assert_eq!((a.kind, a.format), (ArtifactKind::Adapter { format: AdapterFormat::Peft }, ArtifactFormat::Safetensors));
1000        assert_eq!((a.rank, a.alpha, a.base_model.as_deref()), (Some(8), Some(16.0), Some("Org/B")));
1001        write(&d, "adapter_config.json", br#"{"peft_type":"IA3"}"#);
1002        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("only LoRA"));
1003        write(&d, "adapter_config.json", br#"{"peft_type":"LORA"}"#);
1004        write(&d, "adapter_model.bin", b"pickle");
1005        assert!(inspect(&[d]).unwrap_err().to_string().contains("pickled"));
1006    }
1007
1008    #[cfg(unix)]
1009    #[test]
1010    fn symlinks_are_refused() {
1011        let tmp = tempfile::tempdir().unwrap();
1012        let real = write(tmp.path(), "real.gguf", &model_gguf(&[]));
1013        let link = tmp.path().join("link.gguf");
1014        std::os::unix::fs::symlink(&real, &link).unwrap();
1015        assert!(inspect(&[link]).unwrap_err().to_string().contains("symlink"));
1016        let d = tmp.path().join("d");
1017        std::fs::create_dir(&d).unwrap();
1018        std::os::unix::fs::symlink(&real, d.join("m.gguf")).unwrap();
1019        assert!(inspect(&[d]).unwrap_err().to_string().contains("symlink"));
1020    }
1021
1022    #[test]
1023    fn bad_safetensors_headers_are_refused() {
1024        let good = safetensors(4, None);
1025        read_safetensors(&good[..], good.len() as u64).unwrap();
1026        assert!(read_safetensors(&good[..], good.len() as u64 + 1).unwrap_err().to_string().contains("cover"));
1027        let h = br#"{"w":{"dtype":"F32","shape":[4],"data_offsets":[0,8]}}"#;
1028        let mut short = (h.len() as u64).to_le_bytes().to_vec();
1029        short.extend(h);
1030        short.extend([0u8; 8]);
1031        assert!(read_safetensors(&short[..], short.len() as u64).unwrap_err().to_string().contains("needs 16"));
1032        let huge = (SAFETENSORS_HEADER_LIMIT + 1).to_le_bytes();
1033        assert!(read_safetensors(&huge[..], u64::MAX).unwrap_err().to_string().contains("larger"));
1034    }
1035
1036    #[test]
1037    fn early_headers_wait_for_enough_bytes_and_refuse_bad_ones() {
1038        let body = model_gguf(&[]);
1039        assert_eq!(early_header("m.gguf", &body[..10], 10_000).unwrap(), None);
1040        assert!(matches!(early_header("m.gguf", &body, 10_000).unwrap(), Some(EarlyHeader::Gguf(h)) if h.architecture == "llama"));
1041        assert!(early_header("m.gguf", b"NOPE and more bytes", 10_000).is_err());
1042        let st = safetensors(4, None);
1043        assert_eq!(early_header("model.safetensors", &st[..4], st.len() as u64).unwrap(), None);
1044        assert_eq!(early_header("model.safetensors", &st[..12], st.len() as u64).unwrap(), None);
1045        assert!(matches!(early_header("model.safetensors", &st, st.len() as u64).unwrap(), Some(EarlyHeader::Safetensors(h)) if h.tensors == 1));
1046        assert!(early_header("model.safetensors", &st, st.len() as u64 + 5).is_err());
1047        assert_eq!(early_header("config.json", b"{", 100).unwrap(), None);
1048    }
1049
1050    #[test]
1051    fn staged_files_must_match_the_offer() {
1052        let tmp = tempfile::tempdir().unwrap();
1053        let src = write(tmp.path(), "src/m.gguf", &model_gguf(&[]));
1054        let a = inspect(std::slice::from_ref(&src)).unwrap();
1055        let stage = tmp.path().join("stage");
1056        write(&stage, "m.gguf", &std::fs::read(&src).unwrap());
1057        assert_eq!(inspect_staged(&stage, &a.files, &mut |_| true).unwrap(), a);
1058        let mut wrong = a.files.clone();
1059        wrong[0].sha256 = "00".repeat(32);
1060        assert!(matches!(inspect_staged(&stage, &wrong, &mut |_| true), Err(Error::Checksum { .. })));
1061        wrong[0].size += 1;
1062        assert!(inspect_staged(&stage, &wrong, &mut |_| true).unwrap_err().to_string().contains("expected"));
1063    }
1064
1065    #[test]
1066    fn provenance_round_trips_with_app_fields() {
1067        let tmp = tempfile::tempdir().unwrap();
1068        let mut p = Provenance::new(ORIGIN_UPLOAD).with_license("apache-2.0");
1069        p.id = "tune".into();
1070        p.extra.insert("app_field".into(), json!({"x": 1}));
1071        p.write(tmp.path()).unwrap();
1072        let back = Provenance::read(tmp.path()).unwrap();
1073        assert_eq!(back, p);
1074        assert_eq!(back.format, PROVENANCE_FORMAT);
1075        let raw: Value = serde_json::from_slice(&std::fs::read(tmp.path().join(PROVENANCE_FILE)).unwrap()).unwrap();
1076        assert_eq!(raw["app_field"]["x"], 1, "app fields sit at the top level");
1077        assert!(raw.get("base").is_none(), "unset fields are left out");
1078        let app: Provenance = serde_json::from_value(json!({"format": "app-provenance/1", "kind": "adapter", "origin": "train"})).unwrap();
1079        assert_eq!((app.kind, app.origin.as_str()), (ProvenanceKind::Adapter, ORIGIN_TRAIN));
1080    }
1081}