llmman 0.1.689

Run any agent on any model, models stored as OCI images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Top-level HuggingFace pull — originally ported from the Go shim's
//! `pullHF`/`pullHFSafetensors`/`downloadHFBlob` (since deleted), and
//! writing straight into the local OCI layout without ever calling into
//! the Go shim.

use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;

use anyhow::{Context, Result};
use futures::stream::{self, StreamExt, TryStreamExt};

use super::api::{self, HfFile};
use super::download::{self, FetchRequest};
use super::oci::{self, Descriptor, ModelMeta};
use super::progress;
use crate::fsutil::HashingWriter;
use crate::xet_fetch::{self, XetFileRef};

/// Pulls `reference` (already stripped of any `hf://`/`huggingface://`
/// scheme prefix) into `layout_dir`. `progress_key` is the exact,
/// original ref the daemon's `/api/pull` handler was given, for
/// `progress::poll` — see that module's own doc comment.
pub async fn pull(reference: &str, layout_dir: &Path, progress_key: &str) -> Result<()> {
    pull_from(reference, layout_dir, progress_key, super::hf_endpoint).await
}

/// [`pull`] with the Hub resolved by `endpoint(host)` instead of the
/// environment, so a test can point a pull at a local mock hub without
/// touching the process-wide `MODEL_ENDPOINT`/`HF_ENDPOINT`.
async fn pull_from(
    reference: &str,
    layout_dir: &Path,
    progress_key: &str,
    endpoint: impl FnOnce(&str) -> String,
) -> Result<()> {
    let _guard = progress::DoneGuard(progress_key);
    let (host, owner, repo, tag) = api::parse_hf_ref(reference)?;

    oci::ensure_layout(layout_dir)?;
    if oci::report_cached(layout_dir, reference) {
        return Ok(());
    }

    let endpoint = endpoint(&host);
    let token = super::token();
    let api_client = super::api_client()?;
    let dl_client = super::download_client()?;
    let head_client = super::head_client()?;

    progress::set_status(progress_key, "pulling");
    let info =
        api::fetch_model_info(&api_client, &endpoint, &owner, &repo, token.as_deref()).await?;
    let commit = info.commit().to_string();
    // The recorded revision is the raw sha: "" when the Hub gives none,
    // never the "main" branch name the URLs fall back to.
    let revision = info.sha().to_string();
    let mut meta = ModelMeta {
        licenses: info.license().into_iter().collect(),
        ..Default::default()
    };

    let files = api::fetch_files(
        &api_client,
        &endpoint,
        &owner,
        &repo,
        &commit,
        token.as_deref(),
    )
    .await?;

    let diffusion = api::is_diffusion_repo(&files);
    let selected = if diffusion {
        api::select_diffusion_gguf(&files, &tag)
    } else {
        api::select_gguf(&files, &tag)
    };
    let manifest_desc = match selected {
        Ok(shards) if diffusion && shards.len() != 1 => {
            anyhow::bail!("{owner}/{repo}: split diffusion transformers are not supported");
        }
        Ok(shards) => {
            meta.format = "gguf".to_string();
            let filepath_annotation = if shards.len() == 1 {
                basename(&shards[0].path)
            } else {
                String::new()
            };
            let plan = diffusion.then(|| api::diffusion_plan(&files, &shards[0].path));
            let mmproj = if diffusion {
                None
            } else {
                api::select_mmproj(&files)
            };
            let license = api::select_license_file(&files);
            let wanted: Vec<&HfFile> = shards
                .iter()
                .chain(plan.iter().flat_map(|p| p.sidecars.iter().map(|(_, f)| f)))
                .chain(mmproj.iter())
                .chain(license.iter())
                .collect();
            ensure_room(reference, layout_dir, &wanted)?;

            let mut layers = Vec::new();
            for f in &shards {
                layers.push(
                    download_layer(
                        &dl_client,
                        &head_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        f,
                        token.as_deref(),
                        layout_dir,
                        progress_key,
                    )
                    .await?,
                );
            }
            if let Some(plan) = plan {
                meta.diffusion_outputs = plan.outputs;
                for (role, file) in &plan.sidecars {
                    let d = download_layer(
                        &dl_client,
                        &head_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        file,
                        token.as_deref(),
                        layout_dir,
                        progress_key,
                    )
                    .await?;
                    layers.push(api::sidecar_layer(d, file, role));
                }
                if let Some(te_ref) = plan.text_encoder {
                    let mut d = pull_text_encoder(
                        &api_client,
                        &dl_client,
                        &head_client,
                        &host,
                        te_ref,
                        token.as_deref(),
                        layout_dir,
                        progress_key,
                    )
                    .await?;
                    d.annotations
                        .get_or_insert_with(BTreeMap::new)
                        .insert(oci::ANNOTATION_ROLE.to_string(), "text_encoder".to_string());
                    layers.push(d);
                }
            } else if let Some(mmproj) = mmproj {
                layers.push(
                    download_layer(
                        &dl_client,
                        &head_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        &mmproj,
                        token.as_deref(),
                        layout_dir,
                        progress_key,
                    )
                    .await?,
                );
                meta.vision = true;
            }
            if let Some(lic) = license {
                let mut d = download_layer(
                    &dl_client,
                    &head_client,
                    &endpoint,
                    &owner,
                    &repo,
                    &commit,
                    &lic,
                    token.as_deref(),
                    layout_dir,
                    progress_key,
                )
                .await?;
                d.media_type = oci::MEDIA_TYPE_MODEL_DOC_RAW.to_string();
                layers.push(d);
            }
            oci::build_cncf_manifest(
                layout_dir,
                &meta,
                &format!("{owner}/{repo}"),
                &filepath_annotation,
                &revision,
                layers,
            )?
        }
        // Only fall back to safetensors when the repo has no GGUF files
        // at all — a user-requested tag/quant that doesn't exist should
        // be a hard error, not a silent format switch.
        Err(e) if !tag.is_empty() && tag != "latest" => return Err(e),
        Err(_) => {
            meta.format = "safetensors".to_string();
            let to_download = api::select_downloadable_hf_files(&files);
            if to_download.is_empty() {
                anyhow::bail!("no model files found in repository {owner}/{repo}");
            }
            ensure_room(
                reference,
                layout_dir,
                &to_download.iter().collect::<Vec<_>>(),
            )?;
            // Concurrent, bounded by LLMMAN_MAX_TRANSFER_STREAMS (the
            // GGUF branch above stays sequential). Indexed so `layers`'
            // order doesn't depend on finish order.
            let max_streams = super::max_transfer_streams();
            let mut indexed_layers: Vec<(usize, Descriptor)> =
                stream::iter(to_download.iter().enumerate())
                    .map(|(i, f)| {
                        let dl_client = &dl_client;
                        let head_client = &head_client;
                        let endpoint = &endpoint;
                        let owner = &owner;
                        let repo = &repo;
                        let commit = &commit;
                        let token = token.as_deref();
                        async move {
                            let mut d = download_layer(
                                dl_client,
                                head_client,
                                endpoint,
                                owner,
                                repo,
                                commit,
                                f,
                                token,
                                layout_dir,
                                progress_key,
                            )
                            .await?;
                            d.media_type = api::safetensors_media_type(&f.path).to_string();
                            d.annotations = Some(BTreeMap::from([(
                                oci::ANNOTATION_FILEPATH.to_string(),
                                f.path.clone(),
                            )]));
                            Ok::<(usize, Descriptor), anyhow::Error>((i, d))
                        }
                    })
                    .buffer_unordered(max_streams)
                    .try_collect()
                    .await?;
            indexed_layers.sort_by_key(|(i, _)| *i);
            let layers: Vec<Descriptor> = indexed_layers.into_iter().map(|(_, d)| d).collect();
            // A Diffusers pipeline (served by vLLM-Omni) generates media,
            // not text: say so in the config, as a GGUF diffusion pull does.
            if api::is_diffusers_repo(&files) {
                let class = api::diffusers_pipeline_class(layout_dir, &layers);
                meta.diffusion_outputs = api::diffusers_outputs(class.as_deref());
            }
            oci::build_cncf_manifest(
                layout_dir,
                &meta,
                &format!("{owner}/{repo}"),
                "",
                &revision,
                layers,
            )?
        }
    };

    oci::write_manifest_ref(layout_dir, reference, manifest_desc)
}

/// Fails before anything downloads when `files` won't fit on the store's
/// disk; see [`bytes_missing`].
fn ensure_room(reference: &str, layout_dir: &Path, files: &[&HfFile]) -> Result<()> {
    let needed = bytes_missing(layout_dir, files);
    crate::fsutil::ensure_room(
        reference,
        layout_dir,
        needed,
        crate::fsutil::available_space(layout_dir),
    )
}

/// The bytes `files` still need in `layout_dir`. An LFS file already
/// stored as its blob (its `lfs.oid` is the sha256 that names it, and
/// `download_layer` reuses it) needs none, nor does a second file with
/// the same content. Each download lands in `blobs/tmp` and is renamed
/// into place on the same disk, so this is also the most it ever holds.
fn bytes_missing(layout_dir: &Path, files: &[&HfFile]) -> u64 {
    let blobs = layout_dir.join("blobs").join("sha256");
    let mut seen = std::collections::HashSet::new();
    let mut needed = 0u64;
    for f in files {
        let stored = f.lfs.as_ref().is_some_and(|lfs| {
            !seen.insert(lfs.oid.as_str())
                || std::fs::metadata(blobs.join(&lfs.oid))
                    .is_ok_and(|m| m.is_file() && m.len() as i64 == f.size)
        });
        if !stored {
            needed = needed.saturating_add(f.size.max(0) as u64);
        }
    }
    needed
}

fn basename(path: &str) -> String {
    path.rsplit('/').next().unwrap_or(path).to_string()
}

/// Downloads the text encoder GGUF of a diffusion model from its own
/// repository (`owner/repo[:quant]`) into the same blob store, returning
/// its layer descriptor. Blobs are content-addressed, so a text encoder
/// shared by several diffusion models is stored once.
#[allow(clippy::too_many_arguments)]
async fn pull_text_encoder(
    api_client: &reqwest::Client,
    dl_client: &reqwest::Client,
    head_client: &reqwest::Client,
    host: &str,
    reference: &str,
    token: Option<&str>,
    layout_dir: &Path,
    progress_key: &str,
) -> Result<Descriptor> {
    let (_, owner, repo, tag) = api::parse_hf_ref(&format!("{host}/{reference}"))?;
    let endpoint = super::hf_endpoint(host);
    let info = api::fetch_model_info(api_client, &endpoint, &owner, &repo, token)
        .await
        .with_context(|| format!("text encoder {reference}"))?;
    let commit = info.commit().to_string();
    let files = api::fetch_files(api_client, &endpoint, &owner, &repo, &commit, token)
        .await
        .with_context(|| format!("text encoder {reference}"))?;
    let shards = api::select_gguf(&files, &tag)?;
    if shards.len() != 1 {
        anyhow::bail!("text encoder {reference}: split GGUFs are not supported");
    }
    ensure_room(reference, layout_dir, &[&shards[0]])?;
    let mut d = download_layer(
        dl_client,
        head_client,
        &endpoint,
        &owner,
        &repo,
        &commit,
        &shards[0],
        token,
        layout_dir,
        progress_key,
    )
    .await?;
    d.annotations = Some(BTreeMap::from([(
        oci::ANNOTATION_FILEPATH.to_string(),
        basename(&shards[0].path),
    )]));
    Ok(d)
}

/// Deletes its `.part` path on drop unless [`disarm`](Self::disarm) was
/// called first — so a concurrent download cancelled mid-flight (a
/// sibling in the same `buffer_unordered` batch failing first) still
/// cleans up its temp file, not just a normal error return.
struct TmpFileGuard<'a>(&'a Path, bool);

impl TmpFileGuard<'_> {
    fn disarm(&mut self) {
        self.1 = false;
    }
}

impl Drop for TmpFileGuard<'_> {
    fn drop(&mut self) {
        if self.1 {
            let _ = std::fs::remove_file(self.0);
        }
    }
}

/// Moves `tmp_path` to `dest` in the content-addressed blob store.
/// Returns `false` (not moved) if `dest` already had this content — a
/// concurrent sibling download of identical bytes can win the rename
/// first now that safetensors files download in parallel; POSIX
/// overwrites silently, but Windows can error, so `dest` is rechecked
/// rather than failing the whole pull over that race.
fn move_into_place(tmp_path: &Path, dest: &Path) -> Result<bool> {
    if dest.exists() {
        return Ok(false);
    }
    match std::fs::rename(tmp_path, dest) {
        Ok(()) => Ok(true),
        Err(_) if dest.exists() => Ok(false),
        Err(e) => Err(e).with_context(|| format!("move downloaded blob to {}", dest.display())),
    }
}

/// Downloads one file straight into `layout_dir`'s content-addressed
/// blob store, returning its descriptor — mirrors `downloadHFBlob`.
/// Unlike the Go version, a retry always restarts this file from byte
/// zero rather than resuming a local `.part` file; see this migration's
/// own PR description for why that trade-off was accepted.
#[allow(clippy::too_many_arguments)]
async fn download_layer(
    client: &reqwest::Client,
    head_client: &reqwest::Client,
    endpoint: &str,
    owner: &str,
    repo: &str,
    commit: &str,
    file: &HfFile,
    token: Option<&str>,
    layout_dir: &Path,
    progress_key: &str,
) -> Result<Descriptor> {
    let url = format!("{endpoint}{owner}/{repo}/resolve/{commit}/{}", file.path);
    let label = format!("Pulling {}", basename(&file.path));

    // Failure is tolerated (falls back to a plain, un-Xet'd GET
    // self-hashed after download).
    let meta = super::client::probe(&format!("HEAD {}", file.path), || {
        download::head_metadata(head_client, url.clone(), token)
    })
    .await
    .unwrap_or_default();
    // One size for both the progress total and the Xet download, so the
    // bytes download_to_path credits can never exceed what was added.
    let size = if meta.size > 0 { meta.size } else { file.size };
    let xet = meta.xet_hash.map(|hash| XetFileRef {
        endpoint: endpoint.to_string(),
        repo_type: "models".to_string(),
        owner_repo: format!("{owner}/{repo}"),
        revision: commit.to_string(),
        hash,
        size: size as u64,
        sha256: meta.digest.clone(),
        hf_token: token.map(str::to_string),
    });
    progress::add_total(progress_key, size);

    // The blob store is content-addressed and HF's X-Linked-Etag is the
    // file's sha256, so a blob already present (the same text encoder
    // shared by two diffusion models, a re-pull after a manifest change)
    // needs no download at all.
    if let Some(want) = &meta.digest {
        let dest = layout_dir.join("blobs").join("sha256").join(want);
        if std::fs::metadata(&dest)
            .map(|m| m.is_file() && m.len() as i64 == size)
            .unwrap_or(false)
        {
            progress::add_completed(progress_key, size);
            return Ok(Descriptor {
                media_type: oci::MEDIA_TYPE_MODEL_WEIGHT_RAW.to_string(),
                digest: format!("sha256:{want}"),
                size,
                annotations: Some(BTreeMap::from([(
                    oci::ANNOTATION_FILEPATH.to_string(),
                    basename(&file.path),
                )])),
                ..Default::default()
            });
        }
    }

    let tmp_dir = layout_dir.join("blobs").join("tmp");
    std::fs::create_dir_all(&tmp_dir)?;
    // pid + a per-call counter, not just pid: two concurrent pulls of
    // different repos that happen to share a filename (e.g. both have a
    // "model.safetensors") would otherwise share this same path.
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let unique = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let tmp_path = tmp_dir.join(format!(
        "hf-{}-{unique}-{}.part",
        std::process::id(),
        sanitize(&file.path)
    ));
    let mut tmp_guard = TmpFileGuard(&tmp_path, true);

    let req = FetchRequest {
        url,
        token,
        xet,
        label: label.clone(),
    };
    let mut last_err: Option<anyhow::Error> = None;
    let mut next_delay = None;
    let digest = 'attempts: {
        for attempt in 0..super::client::MAX_ATTEMPTS {
            if let Some(delay) = next_delay.take() {
                eprintln!(
                    "\n[llmman] retrying {label} (attempt {}/{}, wait {delay:?})",
                    attempt + 1,
                    super::client::MAX_ATTEMPTS
                );
                tokio::time::sleep(delay).await;
            }
            // A fresh file each attempt, not a reopen: File::create
            // truncates, so a partial write from an earlier failed
            // attempt can never linger underneath this one's bytes.
            // (Progress reporting isn't undone on a retry — a retried
            // file's bar may briefly look ahead of itself; a cosmetic
            // wrinkle only, not worth this migration's added complexity.)
            let got = match &req.xet {
                // Xet: hf-xet owns the file so progress tracks the wire
                // (see xet_fetch::download_to_path); hash it afterwards.
                Some(xet) => {
                    match xet_fetch::download_to_path(xet, &tmp_path, |n| {
                        progress::add_completed(progress_key, n as i64)
                    })
                    .await
                    .with_context(|| label.clone())
                    {
                        Ok(()) => sha256_of_file(&tmp_path).await,
                        Err(e) => Err(e),
                    }
                }
                None => {
                    let f = std::fs::File::create(&tmp_path)?;
                    let mut writer = HashingWriter::with_progress(f, |n| {
                        progress::add_completed(progress_key, n as i64)
                    });
                    download::fetch_once(client, &req, &mut writer)
                        .await
                        .and_then(|_| {
                            writer.flush()?;
                            Ok(format!("sha256:{}", writer.finish().1))
                        })
                }
            };
            // meta.digest (from X-Linked-Etag) is a trusted claim about
            // the content ahead of downloading it — worth checking the
            // bytes we actually got still match, in case of transient
            // corruption, same as a failed fetch.
            let result = got.and_then(|got| match &meta.digest {
                Some(want) if format!("sha256:{want}") != got => {
                    anyhow::bail!("digest mismatch: expected sha256:{want}, got {got}")
                }
                _ => Ok(got),
            });
            match result {
                Ok(digest) => break 'attempts digest,
                Err(e) => {
                    eprintln!("[llmman] {label} error: {e:#}");
                    match download::should_retry(&e, attempt + 1) {
                        Some(delay) => next_delay = Some(delay),
                        None => {
                            last_err = Some(e);
                            break;
                        }
                    }
                    last_err = Some(e);
                }
            }
        }
        // tmp_guard's drop removes tmp_path.
        return Err(last_err.unwrap()).with_context(|| {
            format!(
                "download {} failed after {} attempts",
                file.path,
                super::client::MAX_ATTEMPTS
            )
        });
    };

    let dest_dir = layout_dir.join("blobs").join("sha256");
    std::fs::create_dir_all(&dest_dir)?;
    let dest = dest_dir.join(digest.trim_start_matches("sha256:"));
    let total = std::fs::metadata(&tmp_path)?.len() as i64;
    if move_into_place(&tmp_path, &dest)? {
        tmp_guard.disarm(); // already moved away; nothing left to clean up
    }
    // else: same content already at `dest` — tmp_guard's drop removes
    // this now-redundant copy.

    Ok(Descriptor {
        media_type: oci::MEDIA_TYPE_MODEL_WEIGHT_RAW.to_string(),
        digest,
        size: total,
        annotations: Some(BTreeMap::from([(
            oci::ANNOTATION_FILEPATH.to_string(),
            basename(&file.path),
        )])),
        ..Default::default()
    })
}

fn sanitize(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}

/// `sha256:<hex>` of `path`'s content, for the one download path
/// (`xet_fetch::download_to_path`) that bypasses [`HashingWriter`].
/// Off the async runtime: a full read of a possibly hundreds-of-GB file.
async fn sha256_of_file(path: &Path) -> Result<String> {
    let path = path.to_path_buf();
    let hex = tokio::task::spawn_blocking(move || crate::fsutil::sha256_of_file(&path))
        .await
        .context("sha256 hashing task panicked")??;
    Ok(format!("sha256:{hex}"))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lfs_file(path: &str, size: i64, oid: Option<&str>) -> HfFile {
        HfFile {
            path: path.to_string(),
            size,
            kind: "file".to_string(),
            lfs: oid.map(|oid| api::HfLfs {
                oid: oid.to_string(),
            }),
        }
    }

    /// Only what isn't already a blob of the right size counts, and a
    /// file whose content another one already brings counts once.
    #[test]
    fn bytes_missing_skips_stored_blobs_and_repeated_content() {
        let dir = tempfile::tempdir().unwrap();
        let blobs = dir.path().join("blobs").join("sha256");
        std::fs::create_dir_all(&blobs).unwrap();
        std::fs::write(blobs.join("aa"), [0u8; 100]).unwrap();
        std::fs::write(blobs.join("bb"), [0u8; 5]).unwrap();
        let stored = lfs_file("stored.gguf", 100, Some("aa"));
        let truncated = lfs_file("truncated.gguf", 200, Some("bb"));
        let absent = lfs_file("absent.gguf", 300, Some("cc"));
        let again = lfs_file("copy/absent.gguf", 300, Some("cc"));
        let config = lfs_file("config.json", 7, None);
        assert_eq!(
            bytes_missing(dir.path(), &[&stored, &truncated, &absent, &again, &config]),
            200 + 300 + 7
        );
    }

    /// Sizes come from the repository, so a sum that wraps must not read
    /// as small.
    #[test]
    fn bytes_missing_saturates_on_overflow() {
        let dir = tempfile::tempdir().unwrap();
        let files: Vec<HfFile> = ["a", "b", "c"]
            .iter()
            .map(|oid| lfs_file(oid, i64::MAX, Some(oid)))
            .collect();
        let files: Vec<&HfFile> = files.iter().collect();
        assert_eq!(bytes_missing(dir.path(), &files), u64::MAX);
    }

    #[test]
    fn tmp_file_guard_removes_the_file_on_drop_by_default() {
        let dir = std::env::temp_dir().join(format!("llmman-tmpguard-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("armed.part");
        std::fs::write(&path, b"partial").unwrap();

        {
            let _guard = TmpFileGuard(&path, true);
        }
        assert!(
            !path.exists(),
            "an armed guard must remove its file on drop"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn tmp_file_guard_leaves_the_file_alone_once_disarmed() {
        let dir = std::env::temp_dir().join(format!(
            "llmman-tmpguard-test-disarm-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("disarmed.part");
        std::fs::write(&path, b"done").unwrap();

        {
            let mut guard = TmpFileGuard(&path, true);
            guard.disarm();
        }
        assert!(path.exists(), "a disarmed guard must not remove its file");

        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn move_into_place_moves_the_file_when_dest_is_absent() {
        let dir = std::env::temp_dir().join(format!("llmman-move-test-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let tmp = dir.join("a.part");
        let dest = dir.join("dest");
        std::fs::write(&tmp, b"content").unwrap();

        assert!(move_into_place(&tmp, &dest).unwrap());
        assert!(!tmp.exists());
        assert!(dest.exists());

        std::fs::remove_dir_all(&dir).ok();
    }

    /// Regression test: a concurrent sibling download of identical
    /// content winning the rename first (`dest` already exists) must
    /// not be treated as an error — the caller's own `.part` file is
    /// just redundant, not a failure.
    #[test]
    fn move_into_place_tolerates_a_destination_that_already_exists() {
        let dir =
            std::env::temp_dir().join(format!("llmman-move-test-existing-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let tmp = dir.join("a.part");
        let dest = dir.join("dest");
        std::fs::write(&tmp, b"content").unwrap();
        std::fs::write(&dest, b"content").unwrap(); // a sibling already won

        assert!(!move_into_place(&tmp, &dest).unwrap());
        assert!(
            tmp.exists(),
            "move_into_place itself must leave the redundant tmp file for the caller's guard to clean up"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    const SHA: &str = "7ae557604adf67be50417f59c2c2f167def9a775";
    const WEIGHTS: &[u8] = b"not really a gguf";

    /// A Hub serving one GGUF repository `o/r` at `SHA`: the model info,
    /// the tree at `SHA`, and the one file.
    async fn mock_hub() -> String {
        mock_hub_at(format!("{{\"sha\":\"{SHA}\"}}"), SHA).await
    }

    /// A Hub whose `/api/models/o/r` answers `model`, serving the tree
    /// and the one file at `revision` (the sha, or "main" when the model
    /// info carries none).
    async fn mock_hub_at(model: String, revision: &str) -> String {
        let tree = || async {
            format!(
                "[{{\"type\":\"file\",\"path\":\"model.gguf\",\"size\":{}}}]",
                WEIGHTS.len()
            )
        };
        let app = axum::Router::new()
            .route(
                "/api/models/o/r",
                axum::routing::get(move || async move { model }),
            )
            .route(
                &format!("/api/models/o/r/tree/{revision}"),
                axum::routing::get(tree),
            )
            .route(
                &format!("/o/r/resolve/{revision}/model.gguf"),
                axum::routing::get(|| async { WEIGHTS }),
            );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let endpoint = format!("http://{}/", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        endpoint
    }

    #[tokio::test]
    async fn a_plain_pull_records_the_hub_sha_as_the_revision() {
        let endpoint = mock_hub().await;
        let dir = tempfile::tempdir().unwrap();
        pull_from(
            "hf.co/o/r:latest",
            dir.path(),
            "hf-pull-plain-revision",
            |_| endpoint.clone(),
        )
        .await
        .unwrap();

        let (manifest, config) = oci::read_manifest_and_config(dir.path(), "hf.co/o/r:latest");
        assert_eq!(
            manifest.annotations.as_ref().unwrap()[oci::ANNOTATION_REVISION],
            SHA
        );
        assert_eq!(config["descriptor"]["revision"], SHA);
    }

    #[tokio::test]
    async fn a_pull_from_a_hub_without_a_sha_records_no_revision() {
        // The URLs fall back to the "main" branch; the recorded revision
        // must not, since a branch name does not identify the weights.
        let endpoint = mock_hub_at("{}".to_string(), "main").await;
        let dir = tempfile::tempdir().unwrap();
        pull_from(
            "hf.co/o/r:latest",
            dir.path(),
            "hf-pull-no-sha-revision",
            |_| endpoint.clone(),
        )
        .await
        .unwrap();

        let (manifest, config) = oci::read_manifest_and_config(dir.path(), "hf.co/o/r:latest");
        assert!(manifest
            .annotations
            .as_ref()
            .is_none_or(|a| !a.contains_key(oci::ANNOTATION_REVISION)));
        assert!(config["descriptor"].get("revision").is_none());
    }

    #[tokio::test]
    async fn a_file_served_without_xet_is_hashed_and_counted_as_it_downloads() {
        use sha2::Digest as _;
        let body: Vec<u8> = (0..1_000_000u32).map(|i| (i % 251) as u8).collect();
        let hex = hex::encode(sha2::Sha256::digest(&body));
        // No `x-xet-hash` header, so the file downloads over plain HTTP.
        let headers = [
            ("x-linked-etag", format!("\"{hex}\"")),
            ("x-linked-size", body.len().to_string()),
        ];
        let served = body.clone();
        let app = axum::Router::new().route(
            "/o/r/resolve/c/model.gguf",
            axum::routing::get(move || {
                let (headers, served) = (headers.clone(), served.clone());
                async move { (headers, served) }
            }),
        );
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let endpoint = format!("http://{}/", listener.local_addr().unwrap());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

        let dir = tempfile::tempdir().unwrap();
        oci::ensure_layout(dir.path()).unwrap();
        let progress_key = "hf-pull-plain-http-download";
        progress::reset(progress_key, "pulling");
        let descriptor = download_layer(
            &crate::hf::download_client().unwrap(),
            &crate::hf::head_client().unwrap(),
            &endpoint,
            "o",
            "r",
            "c",
            &lfs_file("model.gguf", body.len() as i64, None),
            None,
            dir.path(),
            progress_key,
        )
        .await
        .unwrap();

        assert_eq!(descriptor.digest, format!("sha256:{hex}"));
        let blob = dir.path().join("blobs").join("sha256").join(&hex);
        assert_eq!(std::fs::read(blob).unwrap(), body);
        let progress = progress::poll(progress_key);
        let size = body.len() as i64;
        assert_eq!((progress.completed, progress.total), (size, size));
    }
}