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#[derive(Debug, Clone, PartialEq)]
356#[non_exhaustive]
357pub enum EarlyHeader {
358    Gguf(GgufHeader),
359    Safetensors(SafetensorsHeader),
360}
361
362/// A reader over a prefix that notes whether a read reached its end.
363struct Prefix<'a> {
364    bytes: &'a [u8],
365    hit_end: bool,
366}
367
368impl Read for Prefix<'_> {
369    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
370        let n = self.bytes.read(buf)?;
371        if n < buf.len() {
372            self.hit_end = true;
373        }
374        Ok(n)
375    }
376}
377
378/// Checks a file's header from the first bytes received (`prefix`) of a file of `file_size`
379/// bytes named `path`, so a bad file is refused before the rest is sent. `Ok(None)` when more
380/// bytes are needed (or the file type has no header); an error when the header is bad.
381pub fn early_header(path: &str, prefix: &[u8], file_size: u64) -> Result<Option<EarlyHeader>> {
382    let lower = path.to_ascii_lowercase();
383    let complete = prefix.len() as u64 >= file_size;
384    if lower.ends_with(".gguf") {
385        let mut r = Prefix { bytes: prefix, hit_end: false };
386        return match gguf::read_header(&mut r) {
387            Ok(h) => Ok(Some(EarlyHeader::Gguf(h))),
388            Err(_) if r.hit_end && !complete => Ok(None),
389            Err(e) => Err(Error::Model(format!("{path}: {e}"))),
390        };
391    }
392    if lower.ends_with(".safetensors") {
393        let need = prefix.get(..8).map(|l| u64::from_le_bytes(l.try_into().expect("8 bytes")).saturating_add(8));
394        return match need {
395            Some(n) if n <= SAFETENSORS_HEADER_LIMIT + 8 && (prefix.len() as u64) < n && !complete => Ok(None),
396            None if !complete => Ok(None),
397            _ => read_safetensors(prefix, file_size).map(|h| Some(EarlyHeader::Safetensors(h))).map_err(|e| Error::Model(format!("{path}: {e}"))),
398        };
399    }
400    Ok(None)
401}
402
403/// Kind, format and what the headers say, before hashing.
404struct Classified {
405    kind: ArtifactKind,
406    format: ArtifactFormat,
407    architecture: Option<String>,
408    base_model: Option<String>,
409    info: Option<GgufInfo>,
410    rank: Option<u32>,
411    alpha: Option<f32>,
412    /// `files` reordered: split parts in order, else by path.
413    files: Vec<Found>,
414}
415
416fn classify(mut files: Vec<Found>) -> Result<Classified> {
417    files.sort_by(|a, b| a.rel.cmp(&b.rel));
418    let is = |f: &Found, ext: &str| f.rel.to_ascii_lowercase().ends_with(ext);
419    let ggufs = files.iter().filter(|f| is(f, ".gguf")).count();
420    if ggufs > 0 {
421        if ggufs != files.len() {
422            return Err(Error::Model("GGUF files come alone: give only the .gguf file or its split parts".into()));
423        }
424        return classify_gguf(files);
425    }
426    let root = |name: &str| files.iter().find(|f| f.rel == name).cloned();
427    if let Some(config) = root("adapter_config.json") {
428        let cfg = read_json(&config.abs)?;
429        let (rank, alpha, base) = peft_lora(&cfg).ok_or_else(|| Error::Model("adapter_config.json: only LoRA adapters are accepted".into()))?;
430        root("adapter_model.safetensors").ok_or_else(|| Error::Model("a PEFT adapter needs adapter_model.safetensors".into()))?;
431        for f in files.iter().filter(|f| is(f, ".safetensors")) {
432            safetensors_of(f)?;
433        }
434        return Ok(Classified {
435            kind: ArtifactKind::Adapter { format: AdapterFormat::Peft },
436            format: ArtifactFormat::Safetensors,
437            architecture: None,
438            base_model: base,
439            info: None,
440            rank,
441            alpha,
442            files,
443        });
444    }
445    if let Some(config) = root("config.json") {
446        let cfg = read_json(&config.abs)?;
447        let architecture = cfg["architectures"]
448            .as_array()
449            .and_then(|a| a.first())
450            .and_then(Value::as_str)
451            .filter(|a| !a.is_empty())
452            .ok_or_else(|| Error::Model("config.json has no architectures".into()))?
453            .to_string();
454        let shards: Vec<&Found> = files.iter().filter(|f| is(f, ".safetensors")).collect();
455        if shards.is_empty() {
456            return Err(Error::Model("a model directory needs its *.safetensors weights".into()));
457        }
458        let mut mlx = cfg.get("quantization").is_some_and(Value::is_object);
459        for s in &shards {
460            let h = safetensors_of(s)?;
461            mlx |= h.metadata.get("format").is_some_and(|f| f == "mlx");
462        }
463        let indexes: Vec<&Found> = files.iter().filter(|f| is(f, ".safetensors.index.json")).collect();
464        match indexes.as_slice() {
465            [] if shards.len() > 1 => return Err(Error::Model("several *.safetensors files need a *.safetensors.index.json".into())),
466            [] => {}
467            [index] => {
468                let map = read_json(&index.abs)?;
469                let named: BTreeSet<&str> = map["weight_map"]
470                    .as_object()
471                    .ok_or_else(|| Error::Model(format!("{}: no weight_map", index.rel)))?
472                    .values()
473                    .map(|v| v.as_str().ok_or_else(|| Error::Model(format!("{}: bad weight_map", index.rel))))
474                    .collect::<Result<_>>()?;
475                let dir = index.rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
476                let have: BTreeSet<String> = shards.iter().map(|s| s.rel.clone()).collect();
477                let want: BTreeSet<String> = named.iter().map(|n| format!("{dir}{n}")).collect();
478                if let Some(missing) = want.difference(&have).next() {
479                    return Err(Error::Model(format!("{}: names {missing}, which is missing", index.rel)));
480                }
481                if let Some(extra) = have.difference(&want).next() {
482                    return Err(Error::Model(format!("{extra} is not in {}", index.rel)));
483                }
484            }
485            _ => return Err(Error::Model("more than one *.safetensors.index.json".into())),
486        }
487        let base_model = cfg["_name_or_path"].as_str().filter(|b| check_repo(b).is_ok()).map(str::to_string);
488        return Ok(Classified {
489            kind: ArtifactKind::Model,
490            format: if mlx { ArtifactFormat::Mlx } else { ArtifactFormat::Safetensors },
491            architecture: Some(architecture),
492            base_model,
493            info: None,
494            rank: None,
495            alpha: None,
496            files,
497        });
498    }
499    Err(Error::Model(
500        "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(),
501    ))
502}
503
504fn classify_gguf(mut files: Vec<Found>) -> Result<Classified> {
505    let parts = if let [one] = files.as_slice() {
506        if let Some((_, part, of)) = split_part(&one.rel)
507            && (part, of) != (1, 1)
508        {
509            return Err(Error::Model(format!("{} is part {part} of {of}: give every part", one.rel)));
510        }
511        1
512    } else {
513        let mut seen: Vec<(u32, Found)> = Vec::new();
514        let mut set: Option<(String, u32)> = None;
515        for f in &files {
516            let (base, part, of) = split_part(&f.rel)
517                .ok_or_else(|| Error::Model("one model per upload: several GGUF files must be the parts of one split model".into()))?;
518            let dir = f.rel.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
519            let key = (format!("{dir}{base}"), of);
520            if set.get_or_insert_with(|| key.clone()) != &key {
521                return Err(Error::Model("one model per upload: the GGUF parts belong to different models".into()));
522            }
523            seen.push((part, f.clone()));
524        }
525        let of = set.map(|s| s.1).unwrap_or(0);
526        seen.sort_by_key(|(p, _)| *p);
527        if seen.len() as u32 != of || seen.iter().enumerate().any(|(i, (p, _))| *p != i as u32 + 1) {
528            return Err(Error::Model(format!("a split model needs all {of} parts, once each")));
529        }
530        files = seen.into_iter().map(|(_, f)| f).collect();
531        of
532    };
533    let first = &files[0];
534    let header =
535        gguf::read_header(std::io::BufReader::new(std::fs::File::open(&first.abs)?)).map_err(|e| Error::Model(format!("{}: {e}", first.rel)))?;
536    if let Some(info) = &header.info
537        && parts > 1
538        && info.split_count != parts as u64
539    {
540        return Err(Error::Model(format!("{}: the header says {} parts, not {parts}", first.rel, info.split_count)));
541    }
542    let (kind, alpha) = match &header.kind {
543        GgufKind::Model => (ArtifactKind::Model, None),
544        GgufKind::Adapter { alpha, .. } if header.kind.is_lora() => (ArtifactKind::Adapter { format: AdapterFormat::GgufLora }, *alpha),
545        GgufKind::Adapter { adapter_type, .. } => {
546            return Err(Error::Model(format!("{}: only LoRA adapters are accepted, not {adapter_type:?}", first.rel)));
547        }
548        GgufKind::Projector => (ArtifactKind::Projector, None),
549    };
550    if parts > 1 && kind != ArtifactKind::Model {
551        return Err(Error::Model(format!("{}: only models come in split parts", first.rel)));
552    }
553    Ok(Classified {
554        kind,
555        format: ArtifactFormat::Gguf { parts },
556        architecture: Some(header.architecture),
557        base_model: header.base_model,
558        info: header.info,
559        rank: None,
560        alpha,
561        files,
562    })
563}
564
565/// SHA-256 of `path`, read in chunks, adding to `done` and calling `progress` as it goes.
566fn hash_file(path: &Path, done: &mut u64, total: u64, progress: &mut dyn FnMut(Progress) -> bool) -> Result<String> {
567    let mut hasher = Sha256::new();
568    let mut file = std::fs::File::open(path)?;
569    let mut buf = vec![0; 1 << 20];
570    loop {
571        let n = file.read(&mut buf)?;
572        if n == 0 {
573            break;
574        }
575        hasher.update(&buf[..n]);
576        *done += n as u64;
577        if !progress(Progress { done: *done, total }) {
578            return Err(Error::Cancelled { done: crate::human(*done), total: crate::human(total) });
579        }
580    }
581    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
582}
583
584fn finish(c: Classified, progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
585    let total = c.files.iter().map(|f| f.size).sum();
586    let mut done = 0;
587    let mut files = Vec::with_capacity(c.files.len());
588    for f in &c.files {
589        let sha256 = hash_file(&f.abs, &mut done, total, progress)?;
590        files.push(ArtifactFile { path: f.rel.clone(), size: f.size, sha256 });
591    }
592    let revision = revision(&files);
593    Ok(Artifact {
594        kind: c.kind,
595        format: c.format,
596        architecture: c.architecture,
597        base_model: c.base_model,
598        info: c.info,
599        rank: c.rank,
600        alpha: c.alpha,
601        files,
602        revision,
603    })
604}
605
606/// Reads and hashes local model files: one directory, or files given one by one (a GGUF, every
607/// part of a split GGUF). Headers are checked before anything is hashed. See the module docs
608/// for what is accepted and refused.
609pub fn inspect(paths: &[PathBuf]) -> Result<Artifact> {
610    inspect_with(paths, &mut |_| true)
611}
612
613/// [`inspect`], calling `progress` while hashing; it returns `false` to cancel.
614pub fn inspect_with(paths: &[PathBuf], progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
615    finish(classify(gather(paths)?)?, progress)
616}
617
618/// Inspects files that were received into `dir` under their artifact paths (as an upload
619/// stages them) and checks each against `files`: present, a regular file, the same size and
620/// SHA-256. The headers are checked as [`inspect`] does.
621pub fn inspect_staged(dir: &Path, files: &[ArtifactFile], progress: &mut dyn FnMut(Progress) -> bool) -> Result<Artifact> {
622    if files.is_empty() {
623        return Err(Error::Model("no files".into()));
624    }
625    let mut found = Vec::with_capacity(files.len());
626    let mut names = BTreeSet::new();
627    for f in files {
628        check_name(&f.path)?;
629        if !names.insert(f.path.as_str()) {
630            return Err(Error::Model(format!("{} is listed twice", f.path)));
631        }
632        let abs = dir.join(&f.path);
633        let size = regular(&abs)?;
634        if size != f.size {
635            return Err(Error::Model(format!("{}: {size} bytes, expected {}", f.path, f.size)));
636        }
637        found.push(Found { rel: f.path.clone(), abs, size });
638    }
639    let artifact = finish(classify(found)?, progress)?;
640    for want in files {
641        let got = artifact.files.iter().find(|g| g.path == want.path).expect("every file is inspected");
642        if !got.sha256.eq_ignore_ascii_case(&want.sha256) {
643            return Err(Error::Checksum { name: want.path.clone(), got: got.sha256.clone() });
644        }
645    }
646    Ok(artifact)
647}
648
649/// [`Provenance::kind`].
650#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
651#[serde(rename_all = "snake_case")]
652#[non_exhaustive]
653pub enum ProvenanceKind {
654    #[default]
655    Model,
656    Adapter,
657    Projector,
658}
659
660/// [`Provenance::base`]: the model an artifact was made from or runs on.
661#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
662#[non_exhaustive]
663pub struct ProvenanceBase {
664    /// The base's id where it runs (a served or stored model id).
665    #[serde(default, skip_serializing_if = "Option::is_none")]
666    pub id: Option<String>,
667    /// Its Hub id (`owner/name`).
668    #[serde(default, skip_serializing_if = "Option::is_none")]
669    pub hub: Option<String>,
670    #[serde(default, skip_serializing_if = "Option::is_none")]
671    pub revision: Option<String>,
672    #[serde(default, skip_serializing_if = "Option::is_none")]
673    pub quant: Option<String>,
674    #[serde(default, skip_serializing_if = "Option::is_none")]
675    pub sha256: Option<String>,
676}
677
678/// [`Provenance::dataset`]: what it was trained on (hashes, counts and licenses; never rows).
679#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
680#[non_exhaustive]
681pub struct ProvenanceDataset {
682    /// The dataset manifest's format, such as an app's `name/1`.
683    #[serde(default, skip_serializing_if = "Option::is_none")]
684    pub format: Option<String>,
685    /// SHA-256 of the manifest.
686    #[serde(default, skip_serializing_if = "Option::is_none")]
687    pub sha256: Option<String>,
688    #[serde(default, skip_serializing_if = "Option::is_none")]
689    pub rows: Option<u64>,
690    /// Other counts by name.
691    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
692    pub counts: BTreeMap<String, u64>,
693    /// Licenses of the data (and of a teacher model's output, when one made it).
694    #[serde(default, skip_serializing_if = "Vec::is_empty")]
695    pub licenses: Vec<String>,
696}
697
698/// [`Provenance::trainer`]: what made it.
699#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
700#[non_exhaustive]
701pub struct ProvenanceTrainer {
702    #[serde(default, skip_serializing_if = "Option::is_none")]
703    pub name: Option<String>,
704    #[serde(default, skip_serializing_if = "Option::is_none")]
705    pub build: Option<String>,
706    #[serde(default, skip_serializing_if = "Option::is_none")]
707    pub run: Option<String>,
708}
709
710fn provenance_format() -> String {
711    PROVENANCE_FORMAT.into()
712}
713
714/// Where a model, adapter or projector came from, kept next to its files
715/// ([`PROVENANCE_FILE`]). It is what the uploader said, checked against the bytes where it
716/// can be (files, hashes and revision are set from them on import); it is signed by nobody and
717/// is not a trust anchor. Unknown fields (an app's own) are kept in [`Provenance::extra`] and
718/// written back.
719#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
720#[non_exhaustive]
721pub struct Provenance {
722    /// [`PROVENANCE_FORMAT`], or an app's own name.
723    #[serde(default = "provenance_format")]
724    pub format: String,
725    #[serde(default)]
726    pub kind: ProvenanceKind,
727    #[serde(default)]
728    pub id: String,
729    #[serde(default)]
730    pub files: Vec<ArtifactFile>,
731    /// See [`revision`].
732    #[serde(default)]
733    pub revision: String,
734    /// [`ORIGIN_UPLOAD`], [`ORIGIN_TRAIN`], [`ORIGIN_HUB`] or an app's own.
735    #[serde(default)]
736    pub origin: String,
737    /// An SPDX id, or `unknown` when the uploader said so explicitly.
738    #[serde(default, skip_serializing_if = "Option::is_none")]
739    pub license: Option<String>,
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub base: Option<ProvenanceBase>,
742    #[serde(default, skip_serializing_if = "Option::is_none")]
743    pub dataset: Option<ProvenanceDataset>,
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub trainer: Option<ProvenanceTrainer>,
746    /// The uploading device's label.
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    pub uploaded_by: Option<String>,
749    /// Unix time in milliseconds.
750    #[serde(default, skip_serializing_if = "Option::is_none")]
751    pub uploaded_ms: Option<u64>,
752    /// Any other fields.
753    #[serde(flatten)]
754    pub extra: BTreeMap<String, Value>,
755}
756
757impl Default for Provenance {
758    fn default() -> Self {
759        Self {
760            format: provenance_format(),
761            kind: ProvenanceKind::Model,
762            id: String::new(),
763            files: Vec::new(),
764            revision: String::new(),
765            origin: String::new(),
766            license: None,
767            base: None,
768            dataset: None,
769            trainer: None,
770            uploaded_by: None,
771            uploaded_ms: None,
772            extra: BTreeMap::new(),
773        }
774    }
775}
776
777impl Provenance {
778    /// A record with this origin ([`ORIGIN_UPLOAD`] and so on).
779    pub fn new(origin: impl Into<String>) -> Self {
780        Self { origin: origin.into(), ..Default::default() }
781    }
782
783    /// A record for `artifact` stored as `id`: its kind, files and revision, and its base
784    /// model's Hub id when the files name one.
785    pub fn for_artifact(artifact: &Artifact, id: impl Into<String>, origin: impl Into<String>) -> Self {
786        let mut p = Self::new(origin);
787        p.id = id.into();
788        p.kind = artifact.kind.provenance_kind();
789        p.files = artifact.files.clone();
790        p.revision = artifact.revision.clone();
791        if let Some(hub) = &artifact.base_model {
792            p.base = Some(ProvenanceBase { hub: Some(hub.clone()), ..Default::default() });
793        }
794        p
795    }
796
797    pub fn with_license(mut self, license: impl Into<String>) -> Self {
798        self.license = Some(license.into());
799        self
800    }
801
802    /// Bytes of the files it lists.
803    pub fn size(&self) -> u64 {
804        self.files.iter().map(|f| f.size).sum()
805    }
806
807    /// The record in `dir` ([`PROVENANCE_FILE`]), if there is a readable one.
808    pub fn read(dir: &Path) -> Option<Provenance> {
809        let path = dir.join(PROVENANCE_FILE);
810        regular(&path).ok()?;
811        serde_json::from_value(read_json(&path).ok()?).ok()
812    }
813
814    /// Writes the record to `dir` ([`PROVENANCE_FILE`]), replacing it atomically.
815    pub fn write(&self, dir: &Path) -> Result<()> {
816        let json = serde_json::to_vec_pretty(self).map_err(|e| Error::Model(e.to_string()))?;
817        let tmp = dir.join(format!(".{PROVENANCE_FILE}.tmp"));
818        std::fs::write(&tmp, json)?;
819        std::fs::rename(&tmp, dir.join(PROVENANCE_FILE))?;
820        Ok(())
821    }
822}
823
824#[cfg(test)]
825pub(crate) mod tests {
826    use super::*;
827    use serde_json::json;
828
829    /// A safetensors file with one F32 tensor of `n` elements and optional metadata.
830    pub(crate) fn safetensors(n: u64, metadata: Option<Value>) -> Vec<u8> {
831        let mut header = json!({"w": {"dtype": "F32", "shape": [n], "data_offsets": [0, n * 4]}});
832        if let Some(m) = metadata {
833            header["__metadata__"] = m;
834        }
835        let h = serde_json::to_vec(&header).unwrap();
836        let mut out = (h.len() as u64).to_le_bytes().to_vec();
837        out.extend(h);
838        out.extend(vec![7u8; (n * 4) as usize]);
839        out
840    }
841
842    /// A small llama GGUF model header, padded.
843    pub(crate) fn model_gguf(extra: &[(&str, Value)]) -> Vec<u8> {
844        let mut kv = vec![
845            ("general.architecture", json!("llama")),
846            ("llama.block_count", json!(2)),
847            ("llama.attention.head_count", json!(4)),
848            ("llama.attention.head_count_kv", json!(2)),
849            ("llama.attention.key_length", json!(8)),
850        ];
851        kv.extend(extra.iter().cloned());
852        let mut out = gguf::header(&kv);
853        out.extend([1u8; 100]);
854        out
855    }
856
857    fn write(dir: &Path, name: &str, body: &[u8]) -> PathBuf {
858        let p = dir.join(name);
859        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
860        std::fs::write(&p, body).unwrap();
861        p
862    }
863
864    #[test]
865    fn names_refuse_pickles_code_and_hidden_files() {
866        for ok in ["m.gguf", "config.json", "tokenizer.model", "d/model-00001-of-00002.safetensors", "LICENSE", "LICENSE.txt", "chat_template.jinja"]
867        {
868            check_name(ok).unwrap_or_else(|e| panic!("{ok}: {e}"));
869        }
870        for (bad, why) in [
871            ("pytorch_model.bin", "pickled"),
872            ("w.pt", "pickled"),
873            ("w.ckpt", "pickled"),
874            ("modeling.py", "code"),
875            (".hidden.json", "hidden"),
876            ("../x.gguf", "plain"),
877            ("/abs.gguf", "plain"),
878            ("a/b/c/d.json", "nested"),
879            ("x.exe", "code"),
880            ("x.zip", "not a model file"),
881        ] {
882            let e = check_name(bad).unwrap_err().to_string();
883            assert!(e.contains(why), "{bad}: {e}");
884        }
885    }
886
887    #[test]
888    fn a_gguf_model_is_read_hashed_and_given_a_revision() {
889        let tmp = tempfile::tempdir().unwrap();
890        let body = model_gguf(&[("general.base_model.0.repo_url", json!("https://huggingface.co/Org/Base"))]);
891        let p = write(tmp.path(), "tune-Q4_0.gguf", &body);
892        let mut calls = 0;
893        let a = inspect_with(std::slice::from_ref(&p), &mut |pr| {
894            calls += 1;
895            pr.total == body.len() as u64
896        })
897        .unwrap();
898        assert!(calls > 0);
899        assert_eq!((a.kind, a.format), (ArtifactKind::Model, ArtifactFormat::Gguf { parts: 1 }));
900        assert_eq!((a.architecture.as_deref(), a.base_model.as_deref()), (Some("llama"), Some("Org/Base")));
901        assert_eq!(a.info.as_ref().map(|i| i.layers), Some(2));
902        assert_eq!(a.files[0].sha256, crate::download::sha256_of(&p).unwrap());
903        assert_eq!(a.size(), body.len() as u64);
904        assert!(a.revision.starts_with("sha256:") && a.revision.len() == 23);
905        assert_eq!(a.revision, revision(&a.files), "stable");
906        assert!(matches!(inspect_with(&[p], &mut |_| false), Err(Error::Cancelled { .. })));
907    }
908
909    #[test]
910    fn revisions_ignore_order_but_not_paths() {
911        let f = |p: &str, h: &str| ArtifactFile { path: p.into(), size: 1, sha256: h.into() };
912        assert_eq!(revision(&[f("a", "1"), f("b", "2")]), revision(&[f("b", "2"), f("a", "1")]));
913        assert_ne!(revision(&[f("a", "1")]), revision(&[f("c", "1")]));
914    }
915
916    #[test]
917    fn split_ggufs_need_every_part() {
918        let tmp = tempfile::tempdir().unwrap();
919        let p1 = write(tmp.path(), "m-00001-of-00002.gguf", &model_gguf(&[("split.count", json!(2))]));
920        let p2 = write(tmp.path(), "m-00002-of-00002.gguf", &[0; 50]);
921        let a = inspect(&[p2.clone(), p1.clone()]).unwrap();
922        assert_eq!(a.format, ArtifactFormat::Gguf { parts: 2 });
923        assert_eq!(a.files.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), ["m-00001-of-00002.gguf", "m-00002-of-00002.gguf"]);
924        assert!(inspect(std::slice::from_ref(&p1)).unwrap_err().to_string().contains("give every part"));
925        let other = write(tmp.path(), "x.gguf", &model_gguf(&[]));
926        assert!(inspect(&[p1, other]).unwrap_err().to_string().contains("one model per upload"));
927    }
928
929    #[test]
930    fn gguf_adapters_and_projectors_are_told_apart() {
931        let tmp = tempfile::tempdir().unwrap();
932        let lora = write(tmp.path(), "tune-LoRA.gguf", &gguf::lora_header("llama"));
933        let a = inspect(&[lora]).unwrap();
934        assert_eq!(a.kind, ArtifactKind::Adapter { format: AdapterFormat::GgufLora });
935        assert_eq!((a.alpha, a.base_model.as_deref()), (Some(32.5), Some("Org/Base-8B")));
936        let mm = write(tmp.path(), "mmproj-F16.gguf", &gguf::header(&[("general.architecture", json!("clip")), ("general.type", json!("mmproj"))]));
937        assert_eq!(inspect(&[mm]).unwrap().kind, ArtifactKind::Projector);
938        let other = write(
939            tmp.path(),
940            "cv.gguf",
941            &gguf::header(&[("general.architecture", json!("llama")), ("general.type", json!("adapter")), ("adapter.type", json!("control_vector"))]),
942        );
943        assert!(inspect(&[other]).unwrap_err().to_string().contains("only LoRA"));
944        let junk = write(tmp.path(), "junk.gguf", b"not a gguf");
945        assert!(inspect(&[junk]).is_err());
946    }
947
948    #[test]
949    fn a_safetensors_directory_is_a_model_and_mlx_is_recognised() {
950        let tmp = tempfile::tempdir().unwrap();
951        let d = tmp.path().join("hf");
952        write(&d, "config.json", br#"{"architectures":["Qwen3ForCausalLM"],"_name_or_path":"Qwen/Qwen3-8B"}"#);
953        write(&d, "tokenizer.json", b"{}");
954        write(&d, "model.safetensors", &safetensors(4, None));
955        write(&d, ".gitattributes", b"skipped");
956        let a = inspect(std::slice::from_ref(&d)).unwrap();
957        assert_eq!((a.kind, a.format), (ArtifactKind::Model, ArtifactFormat::Safetensors));
958        assert_eq!((a.architecture.as_deref(), a.base_model.as_deref()), (Some("Qwen3ForCausalLM"), Some("Qwen/Qwen3-8B")));
959        assert_eq!(a.files.len(), 3, "hidden files are left out");
960
961        let m = tmp.path().join("mlx");
962        write(&m, "config.json", br#"{"architectures":["LlamaForCausalLM"]}"#);
963        write(&m, "model.safetensors", &safetensors(2, Some(json!({"format": "mlx"}))));
964        assert_eq!(inspect(&[m]).unwrap().format, ArtifactFormat::Mlx);
965        let q = tmp.path().join("mlxq");
966        write(&q, "config.json", br#"{"architectures":["LlamaForCausalLM"],"quantization":{"bits":4,"group_size":64}}"#);
967        write(&q, "model.safetensors", &safetensors(2, None));
968        assert_eq!(inspect(&[q]).unwrap().format, ArtifactFormat::Mlx);
969    }
970
971    #[test]
972    fn shards_must_match_their_index() {
973        let tmp = tempfile::tempdir().unwrap();
974        let d = tmp.path().join("m");
975        write(&d, "config.json", br#"{"architectures":["X"]}"#);
976        write(&d, "model-00001-of-00002.safetensors", &safetensors(2, None));
977        write(&d, "model-00002-of-00002.safetensors", &safetensors(2, None));
978        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("index"));
979        write(&d, "model.safetensors.index.json", br#"{"weight_map":{"a":"model-00001-of-00002.safetensors"}}"#);
980        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("not in"));
981        write(
982            &d,
983            "model.safetensors.index.json",
984            br#"{"weight_map":{"a":"model-00001-of-00002.safetensors","b":"model-00002-of-00002.safetensors"}}"#,
985        );
986        assert_eq!(inspect(&[d]).unwrap().files.len(), 4);
987    }
988
989    #[test]
990    fn peft_adapters_are_lora_only() {
991        let tmp = tempfile::tempdir().unwrap();
992        let d = tmp.path().join("peft");
993        write(&d, "adapter_config.json", br#"{"peft_type":"LORA","r":8,"lora_alpha":16,"base_model_name_or_path":"Org/B"}"#);
994        write(&d, "adapter_model.safetensors", &safetensors(3, None));
995        let a = inspect(std::slice::from_ref(&d)).unwrap();
996        assert_eq!((a.kind, a.format), (ArtifactKind::Adapter { format: AdapterFormat::Peft }, ArtifactFormat::Safetensors));
997        assert_eq!((a.rank, a.alpha, a.base_model.as_deref()), (Some(8), Some(16.0), Some("Org/B")));
998        write(&d, "adapter_config.json", br#"{"peft_type":"IA3"}"#);
999        assert!(inspect(std::slice::from_ref(&d)).unwrap_err().to_string().contains("only LoRA"));
1000        write(&d, "adapter_config.json", br#"{"peft_type":"LORA"}"#);
1001        write(&d, "adapter_model.bin", b"pickle");
1002        assert!(inspect(&[d]).unwrap_err().to_string().contains("pickled"));
1003    }
1004
1005    #[cfg(unix)]
1006    #[test]
1007    fn symlinks_are_refused() {
1008        let tmp = tempfile::tempdir().unwrap();
1009        let real = write(tmp.path(), "real.gguf", &model_gguf(&[]));
1010        let link = tmp.path().join("link.gguf");
1011        std::os::unix::fs::symlink(&real, &link).unwrap();
1012        assert!(inspect(&[link]).unwrap_err().to_string().contains("symlink"));
1013        let d = tmp.path().join("d");
1014        std::fs::create_dir(&d).unwrap();
1015        std::os::unix::fs::symlink(&real, d.join("m.gguf")).unwrap();
1016        assert!(inspect(&[d]).unwrap_err().to_string().contains("symlink"));
1017    }
1018
1019    #[test]
1020    fn bad_safetensors_headers_are_refused() {
1021        let good = safetensors(4, None);
1022        read_safetensors(&good[..], good.len() as u64).unwrap();
1023        assert!(read_safetensors(&good[..], good.len() as u64 + 1).unwrap_err().to_string().contains("cover"));
1024        let h = br#"{"w":{"dtype":"F32","shape":[4],"data_offsets":[0,8]}}"#;
1025        let mut short = (h.len() as u64).to_le_bytes().to_vec();
1026        short.extend(h);
1027        short.extend([0u8; 8]);
1028        assert!(read_safetensors(&short[..], short.len() as u64).unwrap_err().to_string().contains("needs 16"));
1029        let huge = (SAFETENSORS_HEADER_LIMIT + 1).to_le_bytes();
1030        assert!(read_safetensors(&huge[..], u64::MAX).unwrap_err().to_string().contains("larger"));
1031    }
1032
1033    #[test]
1034    fn early_headers_wait_for_enough_bytes_and_refuse_bad_ones() {
1035        let body = model_gguf(&[]);
1036        assert_eq!(early_header("m.gguf", &body[..10], 10_000).unwrap(), None);
1037        assert!(matches!(early_header("m.gguf", &body, 10_000).unwrap(), Some(EarlyHeader::Gguf(h)) if h.architecture == "llama"));
1038        assert!(early_header("m.gguf", b"NOPE and more bytes", 10_000).is_err());
1039        let st = safetensors(4, None);
1040        assert_eq!(early_header("model.safetensors", &st[..4], st.len() as u64).unwrap(), None);
1041        assert_eq!(early_header("model.safetensors", &st[..12], st.len() as u64).unwrap(), None);
1042        assert!(matches!(early_header("model.safetensors", &st, st.len() as u64).unwrap(), Some(EarlyHeader::Safetensors(h)) if h.tensors == 1));
1043        assert!(early_header("model.safetensors", &st, st.len() as u64 + 5).is_err());
1044        assert_eq!(early_header("config.json", b"{", 100).unwrap(), None);
1045    }
1046
1047    #[test]
1048    fn staged_files_must_match_the_offer() {
1049        let tmp = tempfile::tempdir().unwrap();
1050        let src = write(tmp.path(), "src/m.gguf", &model_gguf(&[]));
1051        let a = inspect(std::slice::from_ref(&src)).unwrap();
1052        let stage = tmp.path().join("stage");
1053        write(&stage, "m.gguf", &std::fs::read(&src).unwrap());
1054        assert_eq!(inspect_staged(&stage, &a.files, &mut |_| true).unwrap(), a);
1055        let mut wrong = a.files.clone();
1056        wrong[0].sha256 = "00".repeat(32);
1057        assert!(matches!(inspect_staged(&stage, &wrong, &mut |_| true), Err(Error::Checksum { .. })));
1058        wrong[0].size += 1;
1059        assert!(inspect_staged(&stage, &wrong, &mut |_| true).unwrap_err().to_string().contains("expected"));
1060    }
1061
1062    #[test]
1063    fn provenance_round_trips_with_app_fields() {
1064        let tmp = tempfile::tempdir().unwrap();
1065        let mut p = Provenance::new(ORIGIN_UPLOAD).with_license("apache-2.0");
1066        p.id = "tune".into();
1067        p.extra.insert("app_field".into(), json!({"x": 1}));
1068        p.write(tmp.path()).unwrap();
1069        let back = Provenance::read(tmp.path()).unwrap();
1070        assert_eq!(back, p);
1071        assert_eq!(back.format, PROVENANCE_FORMAT);
1072        let raw: Value = serde_json::from_slice(&std::fs::read(tmp.path().join(PROVENANCE_FILE)).unwrap()).unwrap();
1073        assert_eq!(raw["app_field"]["x"], 1, "app fields sit at the top level");
1074        assert!(raw.get("base").is_none(), "unset fields are left out");
1075        let app: Provenance = serde_json::from_value(json!({"format": "app-provenance/1", "kind": "adapter", "origin": "train"})).unwrap();
1076        assert_eq!((app.kind, app.origin.as_str()), (ProvenanceKind::Adapter, ORIGIN_TRAIN));
1077    }
1078}