Skip to main content

weirdnet_model/
download.rs

1//! Consent-gated download of one model file, or every part of a split model, or a LoRA adapter
2//! ([`download_adapter`]): resumes a `.part`, checks the size and the SHA-256, and only then
3//! renames it into place. Requests carry the
4//! store's Hugging Face token when it may go to the store's Hub (see [`ModelStore::from_env`]).
5
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8
9use sha2::{Digest, Sha256};
10
11use crate::catalog::{ModelSpec, human};
12use crate::hf::{AdapterFormat, RepoAdapter, check_file, check_repo};
13use crate::store::{ModelStore, StoredAdapter};
14use crate::{Error, Result};
15
16/// The user said yes to downloading this model. [`download`] needs one, so nothing downloads
17/// without an explicit OK. Create it only after showing [`ModelSpec::consent_text`].
18///
19/// A model under a restricting license ([`hw::restricted_license`](crate::hw::restricted_license),
20/// such as Fish Audio Drama 3 under [`FISH_AUDIO_COMMUNITY`](crate::speech::FISH_AUDIO_COMMUNITY))
21/// also needs the operator's explicit acceptance of that license:
22/// [`accepting_license`](Self::accepting_license).
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct Consent {
25    id: String,
26    adapter: bool,
27    license: Option<String>,
28}
29
30impl Consent {
31    pub fn given(spec: &ModelSpec) -> Self {
32        Self { id: spec.id.clone(), adapter: false, license: None }
33    }
34
35    /// The user said yes to downloading this adapter ([`download_adapter`]). It doesn't cover a
36    /// model of the same id, nor the other way round.
37    pub fn given_adapter(adapter: &RepoAdapter) -> Self {
38        Self { id: adapter.id.clone(), adapter: true, license: None }
39    }
40
41    /// The operator explicitly accepted `license` (by name, such as `fish-audio-community`, as
42    /// with Ymir's `--accept-license fish-audio-community`), which a restricted model's download
43    /// needs. Ask for it only after showing the license; it covers that license only. Since 0.5.5.
44    pub fn accepting_license(mut self, license: impl Into<String>) -> Self {
45        self.license = Some(license.into());
46        self
47    }
48
49    /// Whether this consent accepts `license`.
50    pub fn accepts_license(&self, license: &str) -> bool {
51        self.license.as_deref().is_some_and(|l| l.eq_ignore_ascii_case(license))
52    }
53}
54
55/// How far a download is.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct Progress {
58    pub done: u64,
59    pub total: u64,
60}
61
62impl Progress {
63    /// 0.0 to 1.0.
64    pub fn fraction(&self) -> f32 {
65        if self.total == 0 { 0.0 } else { (self.done as f64 / self.total as f64).min(1.0) as f32 }
66    }
67}
68
69/// Downloads `spec` into `store`. `progress` returns `false` to cancel (the `.part` is kept so a
70/// later call resumes). Returns the file's path; an already complete, matching file is kept.
71pub fn download(store: &ModelStore, spec: &ModelSpec, consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
72    if consent.adapter || consent.id != spec.id {
73        return Err(Error::Consent);
74    }
75    if let Some(license) = crate::hw::restricted_license(spec)
76        && !consent.accepts_license(license)
77    {
78        return Err(Error::Model(format!(
79            "{} is under the {license} license, which restricts how it may be used; download it only after the operator accepts that license explicitly",
80            spec.id
81        )));
82    }
83    if crate::hw::gated(spec) && !store.has_token() {
84        return Err(Error::Model(format!(
85            "{} is a gated Hugging Face repo ({}): accept its terms on the Hub, then set HF_TOKEN on this node",
86            spec.id, spec.repo
87        )));
88    }
89    check_file(&spec.file)?;
90    let file = File { url: spec.url(store.hub()), repo: &spec.repo, name: &spec.file, size: spec.size, sha256: spec.sha256.as_deref() };
91    fetch(store, &file, &store.path(spec), &store.part_path(spec), progress)
92}
93
94/// One file to fetch.
95struct File<'a> {
96    url: String,
97    repo: &'a str,
98    /// The name in the repo (for messages).
99    name: &'a str,
100    size: u64,
101    sha256: Option<&'a str>,
102}
103
104/// Fetches `file` to `dest` through `part`, resuming, checking the size and the hash.
105fn fetch(store: &ModelStore, file: &File<'_>, dest: &Path, part: &Path, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
106    let (dest, part) = (dest.to_path_buf(), part.to_path_buf());
107    std::fs::create_dir_all(dest.parent().unwrap_or(store.dir()))?;
108    let total = file.size;
109    if total > 0 && std::fs::metadata(&dest).is_ok_and(|m| m.len() == total) {
110        match &file.sha256 {
111            Some(want) if !sha256_of(&dest)?.eq_ignore_ascii_case(want) => std::fs::remove_file(&dest)?,
112            _ => {
113                progress(Progress { done: total, total });
114                return Ok(dest);
115            }
116        }
117    }
118    let have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
119    let mut done = have;
120    if have < total || total == 0 {
121        let mut req = store.hub_client().get(&file.url);
122        if have > 0 && have < total {
123            req = req.header("Range", format!("bytes={have}-"));
124        }
125        let mut resp = req.call().map_err(|e| Error::Http(e.to_string()))?;
126        let status = resp.status().as_u16();
127        done = match status {
128            206 => have,
129            200 => 0,
130            s @ (401 | 403) if !store.has_token() => {
131                return Err(Error::Http(format!("the Hub answered {s}; {} may be gated or private (set HF_TOKEN on this node)", file.repo)));
132            }
133            s => return Err(Error::Http(format!("the Hub answered {s}"))),
134        };
135        let mut file = std::fs::OpenOptions::new().create(true).write(true).append(done > 0).truncate(done == 0).open(&part)?;
136        let mut body = resp.body_mut().as_reader();
137        let mut buf = vec![0u8; 1 << 16];
138        loop {
139            if !progress(Progress { done, total }) {
140                return Err(Error::Cancelled { done: human(done), total: human(total) });
141            }
142            let n = body.read(&mut buf)?;
143            if n == 0 {
144                break;
145            }
146            file.write_all(&buf[..n])?;
147            done += n as u64;
148            if done > total {
149                break;
150            }
151        }
152        file.flush()?;
153    }
154    if done != total {
155        if done > total {
156            let _ = std::fs::remove_file(&part);
157        }
158        return Err(Error::Incomplete { done: human(done), total: human(total) });
159    }
160    if let Some(want) = &file.sha256 {
161        let got = sha256_of(&part)?;
162        if !got.eq_ignore_ascii_case(want) {
163            let _ = std::fs::remove_file(&part);
164            return Err(Error::Checksum { name: file.name.to_string(), got });
165        }
166    }
167    std::fs::rename(&part, &dest)?;
168    progress(Progress { done, total });
169    Ok(dest)
170}
171
172/// Downloads every part of a split model (or the one file of a single one), in order, with one
173/// [`Consent`] for the model: all `parts` must share its id (as
174/// [`RepoModel::specs`](crate::hf::RepoModel::specs) makes them). Progress counts all parts
175/// together. Returns the first part's path, which llama.cpp loads the whole model from.
176pub fn download_parts(store: &ModelStore, parts: &[ModelSpec], consent: &Consent, progress: &mut dyn FnMut(Progress) -> bool) -> Result<PathBuf> {
177    let first = parts.first().ok_or_else(|| Error::Model("no files to download".into()))?;
178    if parts.iter().any(|p| p.id != consent.id) {
179        return Err(Error::Consent);
180    }
181    let total: u64 = parts.iter().map(|p| p.size).sum();
182    let mut before = 0;
183    for p in parts {
184        download(store, p, consent, &mut |pr| progress(Progress { done: before + pr.done.min(p.size), total }))?;
185        before += p.size;
186    }
187    Ok(store.path(first))
188}
189
190/// Downloads a LoRA adapter of `repo` (from [`Hub::adapters`](crate::hf::Hub::adapters)) into
191/// `<store>/adapters/<id>/`, with the same resume, size and SHA-256 checks as [`download`], under
192/// a [`Consent::given_adapter`]. A GGUF adapter's header is checked once it is in place (deleted
193/// when it is not a LoRA adapter). Writes `adapter.json` next to the files, so
194/// [`ModelStore::adapters`] knows the repo, format and base model later. Returns the GGUF file,
195/// or the PEFT directory (what vLLM's `--lora-modules` takes).
196pub fn download_adapter(
197    store: &ModelStore,
198    repo: &str,
199    adapter: &RepoAdapter,
200    consent: &Consent,
201    progress: &mut dyn FnMut(Progress) -> bool,
202) -> Result<PathBuf> {
203    if !consent.adapter || consent.id != adapter.id {
204        return Err(Error::Consent);
205    }
206    check_repo(repo)?;
207    let dir = store.adapter_dir(&adapter.id)?;
208    if adapter.files.is_empty() {
209        return Err(Error::Model(format!("adapter {} has no files", adapter.id)));
210    }
211    let total: u64 = adapter.files.iter().map(|f| f.size).sum();
212    let mut before = 0;
213    let mut paths = Vec::new();
214    for f in &adapter.files {
215        check_file(&f.name)?;
216        let base = f.name.rsplit('/').next().unwrap_or(&f.name);
217        let dest = dir.join(base);
218        let part = dir.join(format!("{base}.part"));
219        let file =
220            File { url: format!("{}/{repo}/resolve/main/{}", store.hub(), f.name), repo, name: &f.name, size: f.size, sha256: f.sha256.as_deref() };
221        let size = f.size;
222        paths.push(fetch(store, &file, &dest, &part, &mut |p| progress(Progress { done: before + p.done.min(size), total }))?);
223        before += size;
224    }
225    let path = match adapter.format {
226        AdapterFormat::GgufLora => {
227            let gguf = paths[0].clone();
228            let header = crate::gguf::read_header(std::fs::File::open(&gguf)?);
229            if !header.as_ref().is_ok_and(|h| h.kind.is_lora()) {
230                let _ = std::fs::remove_dir_all(&dir);
231                return Err(Error::Model(format!("{} is not a LoRA adapter GGUF; it was deleted", adapter.files[0].name)));
232            }
233            gguf
234        }
235        _ => dir.clone(),
236    };
237    let info = StoredAdapter {
238        id: adapter.id.clone(),
239        format: adapter.format,
240        path: path.clone(),
241        size: total,
242        base_model: adapter.base_model.clone(),
243        architecture: adapter.architecture.clone(),
244        repo: Some(repo.to_string()),
245        rank: adapter.rank,
246        alpha: adapter.alpha,
247        provenance: None,
248    };
249    crate::store::write_adapter_info(&dir, &info)?;
250    Ok(path)
251}
252
253/// Lower-case hex SHA-256 of a file.
254pub fn sha256_of(path: &Path) -> Result<String> {
255    let mut hasher = Sha256::new();
256    std::io::copy(&mut std::fs::File::open(path)?, &mut hasher)?;
257    Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect())
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use crate::hf::AdapterFormat;
264    use crate::testing::MockHub;
265
266    fn body() -> Vec<u8> {
267        (0..2_000_000u32).map(|i| (i % 251) as u8).collect()
268    }
269
270    fn spec_for(body: &[u8]) -> ModelSpec {
271        let sum = Sha256::digest(body).iter().map(|b| format!("{b:02x}")).collect::<String>();
272        ModelSpec { id: "t".into(), label: "Test".into(), repo: "o/n".into(), file: "t.gguf".into(), size: body.len() as u64, sha256: Some(sum) }
273    }
274
275    #[test]
276    fn downloads_checks_and_renames() {
277        let b = body();
278        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
279        let tmp = tempfile::tempdir().unwrap();
280        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
281        let spec = spec_for(&b);
282        let mut last = 0.0;
283        let path = download(&store, &spec, &Consent::given(&spec), &mut |p| {
284            last = p.fraction();
285            true
286        })
287        .unwrap();
288        assert_eq!(std::fs::read(&path).unwrap(), b);
289        assert_eq!(last, 1.0);
290        assert!(store.installed(&spec));
291        assert_eq!(store.partial_bytes(&spec), 0);
292        // A second call keeps the verified file and makes no request.
293        let hits = hub.requests();
294        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
295        assert_eq!(hub.requests(), hits);
296    }
297
298    #[test]
299    fn a_gated_entry_needs_a_token_before_any_request() {
300        let e = crate::hw::find(crate::hw::COHERE_TRANSCRIBE_03_2026).unwrap();
301        let hub = MockHub::start("/nothing", b"x".to_vec());
302        let tmp = tempfile::tempdir().unwrap();
303        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
304        let err = download(&store, &e.spec, &Consent::given(&e.spec), &mut |_| true).unwrap_err().to_string();
305        assert!(err.contains("gated") && err.contains("HF_TOKEN"), "{err}");
306        assert_eq!(hub.requests(), 0);
307        // With a token the gate lets the request go (the mock has no such file).
308        let with = store.clone().with_token(crate::HfToken::new("hf_x"));
309        let err = download(&with, &e.spec, &Consent::given(&e.spec), &mut |_| true).unwrap_err().to_string();
310        assert!(!err.contains("gated"), "{err}");
311        assert_eq!(hub.requests(), 1);
312        // Another repo is not gated.
313        assert!(!crate::hw::gated(&spec_for(b"abc")));
314    }
315
316    #[test]
317    fn the_shards_of_one_entry_download_together_each_checked() {
318        let shards = [b"first shard bytes".to_vec(), b"second".to_vec()];
319        let sum = |b: &[u8]| Sha256::digest(b).iter().map(|x| format!("{x:02x}")).collect::<String>();
320        let files: Vec<ModelSpec> = shards
321            .iter()
322            .enumerate()
323            .map(|(i, b)| ModelSpec {
324                id: "sharded".into(),
325                label: "Sharded".into(),
326                repo: "o/n".into(),
327                file: format!("model-0000{}-of-00002.safetensors", i + 1),
328                size: b.len() as u64,
329                sha256: Some(sum(b)),
330            })
331            .collect();
332        let routes =
333            files.iter().zip(&shards).map(|(f, b)| (format!("/o/n/resolve/main/{}", f.file), "application/octet-stream", b.clone())).collect();
334        let hub = MockHub::start_with(routes);
335        let tmp = tempfile::tempdir().unwrap();
336        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
337        let mut last = 0.0;
338        let first = download_parts(&store, &files, &Consent::given(&files[0]), &mut |p| {
339            last = p.fraction();
340            true
341        })
342        .unwrap();
343        assert_eq!(first, store.path(&files[0]));
344        assert!(files.iter().all(|f| store.installed(f)));
345        assert_eq!(last, 1.0);
346        // A bad hash on any shard is refused and deleted.
347        let mut bad = files.clone();
348        bad[1].sha256 = Some("0".repeat(64));
349        store.remove(&bad[1]);
350        let err = download_parts(&store, &bad, &Consent::given(&bad[0]), &mut |_| true).unwrap_err();
351        assert!(matches!(err, Error::Checksum { .. }), "{err}");
352        assert!(!store.installed(&bad[1]));
353    }
354
355    #[test]
356    fn a_cancelled_download_resumes_with_a_range_request() {
357        let b = body();
358        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
359        let tmp = tempfile::tempdir().unwrap();
360        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
361        let spec = spec_for(&b);
362        let mut calls = 0;
363        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| {
364            calls += 1;
365            calls < 2
366        })
367        .unwrap_err();
368        assert!(matches!(err, Error::Cancelled { .. }), "{err}");
369        let kept = store.partial_bytes(&spec);
370        assert!(kept > 0 && kept < b.len() as u64, "kept {kept}");
371        download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap();
372        assert_eq!(std::fs::read(store.path(&spec)).unwrap(), b);
373        assert_eq!(hub.last_range(), Some(format!("bytes={kept}-")));
374    }
375
376    #[test]
377    fn a_wrong_checksum_deletes_the_part_and_names_the_file() {
378        let b = body();
379        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b.clone());
380        let tmp = tempfile::tempdir().unwrap();
381        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
382        let mut spec = spec_for(&b);
383        spec.sha256 = Some("0".repeat(64));
384        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
385        assert!(matches!(err, Error::Checksum { ref name, .. } if name == "t.gguf"), "{err}");
386        assert_eq!(store.partial_bytes(&spec), 0);
387        assert!(!store.installed(&spec));
388    }
389
390    #[test]
391    fn consent_for_another_model_is_refused_and_http_errors_are_reported() {
392        let b = body();
393        let hub = MockHub::start("/o/n/resolve/main/other.gguf", b.clone());
394        let tmp = tempfile::tempdir().unwrap();
395        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
396        let spec = spec_for(&b);
397        let mut other = spec.clone();
398        other.id = "other".into();
399        assert!(matches!(download(&store, &spec, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
400        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
401        assert!(matches!(err, Error::Http(ref m) if m.contains("404")), "{err}");
402    }
403
404    #[test]
405    fn split_models_download_every_part_into_their_directory() {
406        let (a, b) = (body(), body()[..500_000].to_vec());
407        let hub = MockHub::start_with(vec![
408            ("/o/n/resolve/main/Q8_0/m-00001-of-00002.gguf".into(), "application/octet-stream", a.clone()),
409            ("/o/n/resolve/main/Q8_0/m-00002-of-00002.gguf".into(), "application/octet-stream", b.clone()),
410        ]);
411        let tmp = tempfile::tempdir().unwrap();
412        let store = ModelStore::new(tmp.path()).with_hub(hub.url()).with_token(crate::HfToken::new("hf_t"));
413        let mut parts = Vec::new();
414        for (name, data) in [("Q8_0/m-00001-of-00002.gguf", &a), ("Q8_0/m-00002-of-00002.gguf", &b)] {
415            let mut s = spec_for(data);
416            (s.id, s.file) = ("m".into(), name.into());
417            parts.push(s);
418        }
419        let mut seen = Vec::new();
420        let path = download_parts(&store, &parts, &Consent::given(&parts[0]), &mut |p| {
421            seen.push(p);
422            true
423        })
424        .unwrap();
425        assert_eq!(path, tmp.path().join("Q8_0/m-00001-of-00002.gguf"));
426        assert_eq!(std::fs::read(tmp.path().join("Q8_0/m-00002-of-00002.gguf")).unwrap(), b);
427        let total = (a.len() + b.len()) as u64;
428        assert!(seen.iter().all(|p| p.total == total));
429        assert!(seen.windows(2).all(|w| w[0].done <= w[1].done), "progress only goes up");
430        assert_eq!(seen.last().unwrap().done, total);
431        assert!(hub.seen().iter().all(|s| s.auth.as_deref() == Some("Bearer hf_t")));
432        let mut other = parts[0].clone();
433        other.id = "x".into();
434        assert!(matches!(download_parts(&store, &parts, &Consent::given(&other), &mut |_| true), Err(Error::Consent)));
435        let mut evil = parts[0].clone();
436        evil.file = "../evil.gguf".into();
437        assert!(download(&store, &evil, &Consent::given(&evil), &mut |_| true).is_err());
438    }
439
440    #[test]
441    fn adapters_download_into_their_own_directory_with_consent() {
442        let hub = crate::testing::adapter_hub();
443        let tmp = tempfile::tempdir().unwrap();
444        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
445        let found = store.hub_client().adapters("o/n").unwrap();
446        let (gguf, peft) = (&found[0], &found[1]);
447        let spec =
448            ModelSpec { id: gguf.id.clone(), label: String::new(), repo: "o/n".into(), file: "m-LoRA-F16.gguf".into(), size: 1500, sha256: None };
449        assert!(matches!(download_adapter(&store, "o/n", gguf, &Consent::given(&spec), &mut |_| true), Err(Error::Consent)), "model consent");
450        assert!(matches!(download(&store, &spec, &Consent::given_adapter(gguf), &mut |_| true), Err(Error::Consent)), "adapter consent");
451        assert!(matches!(download_adapter(&store, "o/n", gguf, &Consent::given_adapter(peft), &mut |_| true), Err(Error::Consent)));
452
453        let path = download_adapter(&store, "o/n", gguf, &Consent::given_adapter(gguf), &mut |_| true).unwrap();
454        assert_eq!(path, tmp.path().join("adapters/m-LoRA-F16/m-LoRA-F16.gguf"));
455        let mut seen = Vec::new();
456        let dir = download_adapter(&store, "o/n", peft, &Consent::given_adapter(peft), &mut |p| {
457            seen.push(p);
458            true
459        })
460        .unwrap();
461        assert_eq!(dir, tmp.path().join("adapters/tune"));
462        assert!(dir.join("adapter_config.json").is_file() && dir.join("adapter_model.safetensors").is_file());
463        assert_eq!(seen.last().map(|p| (p.done, p.total)), Some((peft.size, peft.size)));
464        assert!(seen.windows(2).all(|w| w[0].done <= w[1].done));
465
466        let stored = store.adapters();
467        assert_eq!(
468            stored.iter().map(|a| (a.id.as_str(), a.format)).collect::<Vec<_>>(),
469            [("m-LoRA-F16", AdapterFormat::GgufLora), ("tune", AdapterFormat::Peft)]
470        );
471        assert_eq!((stored[0].path.clone(), stored[0].architecture.as_deref(), stored[0].repo.as_deref()), (path, Some("qwen3"), Some("o/n")));
472        assert_eq!((stored[1].base_model.as_deref(), stored[1].rank), (Some("Org/Base-8B"), Some(16)));
473        let info = std::fs::read_to_string(dir.join(crate::store::ADAPTER_INFO)).unwrap();
474        assert!(!info.contains(&tmp.path().display().to_string()), "adapter.json holds no machine paths: {info}");
475        assert!(store.list().is_empty(), "adapters are not models");
476
477        let mut evil = gguf.clone();
478        evil.id = "../x".into();
479        assert!(download_adapter(&store, "o/n", &evil, &Consent::given_adapter(&evil), &mut |_| true).is_err());
480        let mut bad = gguf.clone();
481        bad.files[0].sha256 = Some("0".repeat(64));
482        bad.id = "bad".into();
483        assert!(matches!(download_adapter(&store, "o/n", &bad, &Consent::given_adapter(&bad), &mut |_| true), Err(Error::Checksum { .. })));
484        assert!(store.adapters().iter().all(|a| a.id != "bad"), "an unfinished adapter is not listed");
485
486        assert_eq!(store.remove_adapter(&stored[1]).unwrap(), peft.size);
487        assert!(!dir.exists());
488        assert_eq!(store.adapters().len(), 1);
489    }
490
491    #[test]
492    fn a_model_gguf_is_not_kept_as_an_adapter() {
493        let hub = crate::testing::adapter_hub();
494        let tmp = tempfile::tempdir().unwrap();
495        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
496        let mut fake = store.hub_client().adapters("o/n").unwrap().remove(0);
497        fake.files[0].name = "m-Q4_0.gguf".into();
498        fake.files[0].size = 4000;
499        fake.files[0].sha256 = None;
500        let err = download_adapter(&store, "o/n", &fake, &Consent::given_adapter(&fake), &mut |_| true).unwrap_err();
501        assert!(err.to_string().contains("not a LoRA adapter"), "{err}");
502        assert!(!tmp.path().join("adapters/m-LoRA-F16").exists());
503    }
504
505    #[test]
506    fn a_short_body_is_incomplete_and_kept_for_resume() {
507        let b = body();
508        let hub = MockHub::start("/o/n/resolve/main/t.gguf", b[..1000].to_vec());
509        let tmp = tempfile::tempdir().unwrap();
510        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
511        let spec = spec_for(&b);
512        let err = download(&store, &spec, &Consent::given(&spec), &mut |_| true).unwrap_err();
513        assert!(matches!(err, Error::Incomplete { .. }), "{err}");
514        assert_eq!(store.partial_bytes(&spec), 1000);
515    }
516
517    #[test]
518    fn a_restricted_license_needs_explicit_acceptance() {
519        let b = body();
520        let mut spec = spec_for(&b);
521        spec.id = "my-drama".into();
522        spec.repo = "ggml-org/drama-3-GGUF".into();
523        let hub = MockHub::start("/ggml-org/drama-3-GGUF/resolve/main/t.gguf", b.clone());
524        let tmp = tempfile::tempdir().unwrap();
525        let store = ModelStore::new(tmp.path()).with_hub(hub.url());
526        for consent in [Consent::given(&spec), Consent::given(&spec).accepting_license("apache-2.0")] {
527            let err = download(&store, &spec, &consent, &mut |_| true).unwrap_err();
528            assert!(err.to_string().contains("fish-audio-community"), "{err}");
529        }
530        assert_eq!(hub.requests(), 0, "refused before any request");
531        let consent = Consent::given(&spec).accepting_license("Fish-Audio-Community");
532        assert!(consent.accepts_license(crate::speech::FISH_AUDIO_COMMUNITY));
533        let path = download(&store, &spec, &consent, &mut |_| true).unwrap();
534        assert_eq!(std::fs::read(path).unwrap(), b);
535        // Other models need no acceptance.
536        let free = spec_for(&b);
537        assert!(!Consent::given(&free).accepts_license("fish-audio-community"));
538    }
539}