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
//! Top-level HuggingFace transfer.
//!
//! **`docker` build**: fetches each file (plain HTTP or `hf-xet`, as
//! [`super::pull`] does) and streams it straight into a registry push,
//! never touching local disk. The registry-push protocol itself still
//! runs in Go (only containerd speaks it) — see
//! [`crate::ffi::push_stream_open`]: Go creates the pipe and hands over
//! its write end's raw fd/HANDLE, so only that one integer crosses the
//! FFI boundary per file, not a callback per chunk.
//!
//! **`podman` build**: `copy.Image` works on whole images, not
//! individual blobs, so there's no per-blob streaming primitive to use.
//! Instead this pulls into a throwaway local OCI layout (via
//! [`super::pull`]) and pushes that with the existing `ffi::push`.

use anyhow::{Context, Result};

use crate::ffi::TransferOutcome;

/// Transfers `reference` (already stripped of any `hf://`/
/// `huggingface://` scheme prefix) directly to `destination`. Reports
/// what was pushed and the manifest digest that now sits at the
/// destination — mirrors `ffi::transfer`'s own contract.
pub async fn transfer(reference: &str, destination: &str) -> Result<TransferOutcome> {
    #[cfg(feature = "docker")]
    {
        docker::transfer(reference, destination).await
    }
    #[cfg(not(feature = "docker"))]
    {
        via_temp_pull(reference, destination).await
    }
}

/// The `podman`-build fallback: pull the whole model into a throwaway
/// local layout, then push that layout the ordinary way. `changed` is
/// always true on success — `ffi::push` (podman's `copy.Image`) doesn't
/// report whether the destination actually changed, unlike the docker
/// path's real per-blob answer.
#[cfg_attr(feature = "docker", allow(dead_code))]
async fn via_temp_pull(reference: &str, destination: &str) -> Result<TransferOutcome> {
    let tmp = std::env::temp_dir().join(format!(
        "llmman-hf-transfer-{}-{}",
        std::process::id(),
        rand_suffix()
    ));
    // pull() stages the manifest under `reference` itself, but
    // `ffi::push` resolves what to push by an *exact* ref lookup — so
    // the staged model has to also be findable under `destination`
    // before the push can find it at all.
    let result = super::pull::pull(reference, &tmp, "")
        .await
        .and_then(|()| super::oci::alias_manifest_ref(&tmp, reference, destination))
        .and_then(|()| {
            crate::ffi::push(
                tmp.to_str()
                    .context("temp layout path is not valid UTF-8")?,
                destination,
            )
        })
        // Read back from the staged layout rather than re-resolving the
        // destination tag: this is the manifest that was just pushed, so
        // it is what `--sign-key` must sign.
        .and_then(|()| super::oci::read_manifest_ref(&tmp, destination))
        .map(|desc| TransferOutcome::new(true, desc.digest));
    let _ = std::fs::remove_dir_all(&tmp);
    result
}

fn rand_suffix() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos() as u64
}

#[cfg(feature = "docker")]
mod docker {
    use std::io::Write;

    use anyhow::{Context, Result};
    use sha2::Digest as _;

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

    pub async fn transfer(reference: &str, destination: &str) -> Result<super::TransferOutcome> {
        let _guard = progress::DoneGuard(destination);
        let (host, owner, repo, tag) = api::parse_hf_ref(reference)?;
        let endpoint = super::super::hf_endpoint(&host);
        let token = super::super::token();
        let api_client = super::super::api_client()?;
        let dl_client = super::super::download_client()?;
        let head_client = super::super::head_client()?;

        // One resolver/pusher for every blob (and the manifest) in this
        // transfer — see push_stream.go's own doc comment for why
        // resolving a destination is too expensive to redo per blob.
        let session = crate::ffi::push_session_open(destination)?;

        progress::set_status(destination, "pushing");
        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 mut changed = false;
        let diffusion = api::is_diffusion_repo(&files);
        let selected = if diffusion {
            api::select_diffusion_gguf(&files, &tag)
        } else {
            api::select_gguf(&files, &tag)
        };
        let (layers, filepath_annotation) = 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 mut layers = Vec::new();
                for f in &shards {
                    layers.push(
                        transfer_layer(
                            &dl_client,
                            &head_client,
                            &endpoint,
                            &owner,
                            &repo,
                            &commit,
                            f,
                            token.as_deref(),
                            &session,
                            &mut changed,
                        )
                        .await?,
                    );
                }
                if diffusion {
                    let plan = api::diffusion_plan(&files, &shards[0].path);
                    meta.diffusion_outputs = plan.outputs;
                    for (role, file) in &plan.sidecars {
                        let d = transfer_layer(
                            &dl_client,
                            &head_client,
                            &endpoint,
                            &owner,
                            &repo,
                            &commit,
                            file,
                            token.as_deref(),
                            &session,
                            &mut changed,
                        )
                        .await?;
                        layers.push(api::sidecar_layer(d, file, role));
                    }
                    if let Some(te_ref) = plan.text_encoder {
                        let d = transfer_text_encoder(
                            &api_client,
                            &dl_client,
                            &head_client,
                            &host,
                            te_ref,
                            token.as_deref(),
                            &session,
                            &mut changed,
                        )
                        .await?;
                        layers.push(d);
                    }
                } else if let Some(mmproj) = api::select_mmproj(&files) {
                    layers.push(
                        transfer_layer(
                            &dl_client,
                            &head_client,
                            &endpoint,
                            &owner,
                            &repo,
                            &commit,
                            &mmproj,
                            token.as_deref(),
                            &session,
                            &mut changed,
                        )
                        .await?,
                    );
                    meta.vision = true;
                }
                if let Some(lic) = api::select_license_file(&files) {
                    let mut d = transfer_layer(
                        &dl_client,
                        &head_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        &lic,
                        token.as_deref(),
                        &session,
                        &mut changed,
                    )
                    .await?;
                    d.media_type = oci::MEDIA_TYPE_MODEL_DOC_RAW.to_string();
                    layers.push(d);
                }
                (layers, filepath_annotation)
            }
            // 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}");
                }
                let mut layers = Vec::new();
                for f in &to_download {
                    let mut d = transfer_layer(
                        &dl_client,
                        &head_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        f,
                        token.as_deref(),
                        &session,
                        &mut changed,
                    )
                    .await?;
                    d.media_type = api::safetensors_media_type(&f.path).to_string();
                    d.annotations = Some(std::collections::BTreeMap::from([(
                        oci::ANNOTATION_FILEPATH.to_string(),
                        f.path.clone(),
                    )]));
                    layers.push(d);
                }
                // See the same step in pull.rs.
                if api::is_diffusers_repo(&files) {
                    let class = api::fetch_diffusers_pipeline_class(
                        &api_client,
                        &endpoint,
                        &owner,
                        &repo,
                        &commit,
                        token.as_deref(),
                    )
                    .await;
                    meta.diffusion_outputs = api::diffusers_outputs(class.as_deref());
                }
                (layers, String::new())
            }
        };

        let manifest_digest = push_cncf_manifest(
            &session,
            &meta,
            &format!("{owner}/{repo}"),
            &filepath_annotation,
            &revision,
            layers,
            &mut changed,
        )
        .await?;
        Ok(super::TransferOutcome::new(changed, manifest_digest))
    }

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

    /// The text encoder GGUF from its own repository, as a `text_encoder` layer.
    #[allow(clippy::too_many_arguments)]
    async fn transfer_text_encoder(
        api_client: &reqwest::Client,
        dl_client: &reqwest::Client,
        head_client: &reqwest::Client,
        host: &str,
        reference: &str,
        token: Option<&str>,
        session: &crate::ffi::PushSession,
        changed: &mut bool,
    ) -> Result<Descriptor> {
        let (_, owner, repo, tag) = api::parse_hf_ref(&format!("{host}/{reference}"))?;
        let endpoint = super::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");
        }
        let mut d = transfer_layer(
            dl_client,
            head_client,
            &endpoint,
            &owner,
            &repo,
            &commit,
            &shards[0],
            token,
            session,
            changed,
        )
        .await?;
        d.annotations = Some(std::collections::BTreeMap::from([
            (
                oci::ANNOTATION_FILEPATH.to_string(),
                basename(&shards[0].path),
            ),
            (oci::ANNOTATION_ROLE.to_string(), "text_encoder".to_string()),
        ]));
        Ok(d)
    }

    /// Fetches one file and streams it directly into a registry push,
    /// setting `*changed` if anything was actually pushed for it.
    #[allow(clippy::too_many_arguments)]
    async fn transfer_layer(
        client: &reqwest::Client,
        head_client: &reqwest::Client,
        endpoint: &str,
        owner: &str,
        repo: &str,
        commit: &str,
        file: &HfFile,
        token: Option<&str>,
        session: &crate::ffi::PushSession,
        changed: &mut bool,
    ) -> Result<Descriptor> {
        let url = format!("{endpoint}{owner}/{repo}/resolve/{commit}/{}", file.path);
        let label = format!("Transferring {}", basename(&file.path));

        let meta = super::super::client::probe(&format!("HEAD {}", file.path), || {
            download::head_metadata(head_client, url.clone(), token)
        })
        .await
        .context("resolve file metadata")?;
        let size = if meta.size > 0 { meta.size } else { file.size };
        let annotations = Some(std::collections::BTreeMap::from([(
            oci::ANNOTATION_FILEPATH.to_string(),
            basename(&file.path),
        )]));

        let (desc, pushed) = match meta.digest {
            // Known digest ahead of time (LFS/Xet-tracked — effectively
            // every real weight file): stream straight through with no
            // buffering, however large.
            Some(digest) => {
                // A known digest with an unknown (0) size would push a
                // Descriptor claiming 0 bytes while the stream writes
                // the real body — the registry only notices the
                // mismatch after the whole upload finishes.
                if size <= 0 {
                    anyhow::bail!("{}: digest known but size unknown", file.path);
                }
                let xet = meta.xet_hash.map(|hash| XetFileRef {
                    endpoint: endpoint.trim_end_matches('/').to_string(),
                    repo_type: "models".to_string(),
                    owner_repo: format!("{owner}/{repo}"),
                    revision: commit.to_string(),
                    hash,
                    size: size as u64,
                    sha256: Some(digest.clone()),
                    hf_token: token.map(str::to_string),
                });
                // FileMetadata::digest is bare hex — an OCI Descriptor's
                // own digest field must carry the "sha256:" algorithm
                // prefix (see FileMetadata's own doc comment).
                let desc = Descriptor {
                    media_type: oci::MEDIA_TYPE_MODEL_WEIGHT_RAW.to_string(),
                    digest: format!("sha256:{digest}"),
                    size,
                    annotations,
                    ..Default::default()
                };
                let req = FetchRequest {
                    url,
                    token,
                    xet,
                    label,
                };
                let pushed = fetch_and_push_stream(client, &req, session, &desc).await?;
                (desc, pushed)
            }
            // No usable digest ahead of time (a small, plain git-blob
            // file — config.json, a tokenizer file, ...; the ETag there
            // is a git blob sha1, not a sha256 of the content): buffer
            // it in memory and hash it ourselves. These are always tiny,
            // so buffering costs nothing.
            None => {
                let req = FetchRequest {
                    url,
                    token,
                    xet: None,
                    label,
                };
                let mut buf = Vec::new();
                download::fetch_once(client, &req, &mut buf)
                    .await
                    .with_context(|| format!("download {}", file.path))?;
                let digest = format!("sha256:{:x}", sha2::Sha256::digest(&buf));
                let desc = Descriptor {
                    media_type: oci::MEDIA_TYPE_MODEL_WEIGHT_RAW.to_string(),
                    digest,
                    size: buf.len() as i64,
                    annotations,
                    ..Default::default()
                };
                let pushed = push_bytes(session, &desc, &buf).await?;
                (desc, pushed)
            }
        };
        *changed |= pushed;
        Ok(desc)
    }

    /// Builds the CNCF model-spec config+manifest referencing `layers`
    /// and pushes both directly, without ever writing them to a local
    /// layout — the same JSON `oci::build_cncf_manifest` writes, reached
    /// via a throwaway local layout purely to reuse its exact
    /// construction (config/manifest JSON is at most a few KB, so that
    /// local round trip costs nothing measurable), then pushing those two
    /// blobs via [`push_stream`] instead of leaving them on disk.
    ///
    /// Returns the manifest's digest, which is what `--sign-key` signs.
    async fn push_cncf_manifest(
        session: &crate::ffi::PushSession,
        meta: &ModelMeta,
        model_repo: &str,
        filepath_annotation: &str,
        commit: &str,
        layers: Vec<Descriptor>,
        changed: &mut bool,
    ) -> Result<String> {
        let tmp = std::env::temp_dir().join(format!(
            "llmman-hf-transfer-manifest-{}-{}",
            std::process::id(),
            super::rand_suffix()
        ));
        std::fs::create_dir_all(&tmp)?;
        let manifest_desc =
            oci::build_cncf_manifest(&tmp, meta, model_repo, filepath_annotation, commit, layers)?;
        let manifest_data = oci::read_blob(&tmp, &manifest_desc.digest)?;
        let config_digest = {
            let m: oci::Manifest = serde_json::from_slice(&manifest_data)?;
            m.config.digest
        };
        let config_data = oci::read_blob(&tmp, &config_digest)?;
        let _ = std::fs::remove_dir_all(&tmp);

        let config_desc = Descriptor {
            media_type: oci::MEDIA_TYPE_MODEL_CONFIG.to_string(),
            digest: config_digest,
            size: config_data.len() as i64,
            ..Default::default()
        };
        let pushed = push_bytes(session, &config_desc, &config_data)
            .await
            .context("push CNCF model config")?;
        *changed |= pushed;

        let pushed = push_bytes(session, &manifest_desc, &manifest_data)
            .await
            .context("push CNCF manifest")?;
        *changed |= pushed;
        if *changed {
            eprintln!("Writing manifest to image destination");
        }
        Ok(manifest_desc.digest)
    }

    /// Fetches `req` and streams it directly into a fresh push-stream,
    /// retrying the *whole* open-fetch-close-wait cycle (never reusing a
    /// pipe across attempts — see `download::fetch_once`'s own doc
    /// comment on why that would corrupt rather than actually retry).
    ///
    /// Returns `Ok(false)` without touching the source if the destination
    /// already has the blob.
    async fn fetch_and_push_stream(
        client: &reqwest::Client,
        req: &FetchRequest<'_>,
        session: &crate::ffi::PushSession,
        desc: &Descriptor,
    ) -> Result<bool> {
        retry_push(&req.label, |_| {
            stream_push(session, desc, |mut w| async move {
                download::fetch_once(client, req, &mut w).await.map(drop)
            })
        })
        .await
    }

    /// Pushes an in-memory blob, unless the destination already has it.
    async fn push_bytes(
        session: &crate::ffi::PushSession,
        desc: &Descriptor,
        data: &[u8],
    ) -> Result<bool> {
        retry_push("push blob", |_| {
            stream_push(session, desc, |mut w| async move {
                w.write_all(data).map_err(anyhow::Error::from)
            })
        })
        .await
    }

    /// One open-write-close-wait cycle on a fresh push stream. `write`
    /// gets the pipe and must finish (dropping it) before the wait, or
    /// the wait hangs on an EOF that never comes. `Ok(false)` without
    /// calling `write` if the destination already has the blob.
    async fn stream_push<F, Fut>(
        session: &crate::ffi::PushSession,
        desc: &Descriptor,
        write: F,
    ) -> Result<bool>
    where
        F: FnOnce(std::fs::File) -> Fut,
        Fut: std::future::Future<Output = Result<()>>,
    {
        let Some((writer, stream)) = open_push_stream(session, desc)? else {
            return Ok(false);
        };
        let write_result = write(writer).await;
        // The goroutine's error is more informative than a local write
        // symptom like "broken pipe", so it takes priority.
        let pushed = crate::ffi::push_stream_wait(stream)?;
        write_result?;
        Ok(pushed)
    }

    /// The push-side retry loop: retries `attempt` (the whole
    /// open-a-fresh-stream-and-push cycle) up to `client::MAX_ATTEMPTS`
    /// times, honoring `Retry-After`/exponential backoff between tries.
    /// It is its own loop rather than a shared helper because `attempt`
    /// needs the attempt number to seed the backoff (see
    /// `download::should_retry`); the metadata path's `client::probe`
    /// retries only a 429 and the blob-download loop lives in
    /// `download.rs`, so there is no shared retry helper to call here.
    async fn retry_push<F, Fut>(label: &str, mut attempt: F) -> Result<bool>
    where
        F: FnMut(u32) -> Fut,
        Fut: std::future::Future<Output = Result<bool>>,
    {
        let mut last_err: Option<anyhow::Error> = None;
        let mut next_delay = None;
        for i in 0..super::super::client::MAX_ATTEMPTS {
            if let Some(delay) = next_delay.take() {
                eprintln!(
                    "\n[llmman] retrying {label} (attempt {}/{}, wait {delay:?})",
                    i + 1,
                    super::super::client::MAX_ATTEMPTS
                );
                tokio::time::sleep(delay).await;
            }
            match attempt(i).await {
                Ok(pushed) => return Ok(pushed),
                Err(e) => {
                    eprintln!("[llmman] {label} error: {e:#}");
                    match download::should_retry(&e, i + 1) {
                        Some(delay) => next_delay = Some(delay),
                        None => {
                            last_err = Some(e);
                            break;
                        }
                    }
                    last_err = Some(e);
                }
            }
        }
        Err(last_err.unwrap()).with_context(|| {
            format!(
                "{label} failed after {} attempts",
                super::super::client::MAX_ATTEMPTS
            )
        })
    }

    /// Opens a Go-shim pipe for pushing one descriptor within `session`
    /// (see `ffi::push_stream_open`/this module's own top doc comment),
    /// returning its write end wrapped as a `File` to write the blob's
    /// content into. Once done, drop the returned `File` (closing it —
    /// this is what signals EOF to the registry-push goroutine reading
    /// the other end) *before* calling `ffi::push_stream_wait` with the
    /// returned handle, or that call hangs waiting for an EOF that will
    /// never come while this side is still holding its own end open.
    ///
    /// Returns `None` if the destination already has the blob: no pipe,
    /// nothing to wait on, and the caller must not fetch the content.
    fn open_push_stream(
        session: &crate::ffi::PushSession,
        desc: &Descriptor,
    ) -> Result<Option<(std::fs::File, crate::ffi::PushStream)>> {
        let annotations_json = match &desc.annotations {
            Some(a) if !a.is_empty() => serde_json::to_string(a)?,
            _ => String::new(),
        };
        let stream = match crate::ffi::push_stream_open(
            session,
            &desc.media_type,
            &desc.digest,
            desc.size,
            &annotations_json,
        )? {
            crate::ffi::PushStreamOpen::Exists => return Ok(None),
            crate::ffi::PushStreamOpen::Stream(stream) => stream,
        };

        // SAFETY: `stream.fd` is a fresh, valid, write-only fd/HANDLE
        // that Go just created via its own os.Pipe and handed to us as
        // its sole owner from this point on (see push_stream.go's own
        // doc comment) — nothing else in this process holds or will
        // ever touch it.
        #[cfg(unix)]
        let file = unsafe {
            <std::fs::File as std::os::unix::io::FromRawFd>::from_raw_fd(
                stream.fd as std::os::unix::io::RawFd,
            )
        };
        #[cfg(windows)]
        let file = unsafe {
            <std::fs::File as std::os::windows::io::FromRawHandle>::from_raw_handle(
                stream.fd as *mut std::ffi::c_void,
            )
        };

        Ok(Some((file, stream)))
    }

    /// Real Go push via FFI against axum mocks of the registry and HF.
    #[cfg(test)]
    mod tests {
        use std::sync::{Arc, Mutex};

        use axum::extract::Request;
        use axum::http::{header, Method, StatusCode};
        use axum::response::{IntoResponse, Response};
        use axum::Router;

        use super::*;

        type Log = Arc<Mutex<Vec<String>>>;

        fn count(log: &Log, method: &str, path_contains: &str) -> usize {
            log.lock()
                .unwrap()
                .iter()
                .filter(|r| r.starts_with(&format!("{method} ")) && r.contains(path_contains))
                .count()
        }

        async fn serve(app: Router) -> String {
            let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
            let addr = listener.local_addr().unwrap();
            tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
            addr.to_string()
        }

        /// A registry that either has every blob (`has_blobs`) or none, and
        /// accepts any upload.
        async fn mock_registry(has_blobs: bool) -> (String, Log) {
            let log = Log::default();
            let seen = log.clone();
            let app = Router::new().fallback(move |req: Request| {
                let seen = seen.clone();
                async move {
                    let (method, path) = (req.method().clone(), req.uri().path().to_string());
                    let query = req.uri().query().unwrap_or_default().to_string();
                    seen.lock().unwrap().push(format!("{method} {path}"));
                    let _ = axum::body::to_bytes(req.into_body(), usize::MAX).await;
                    match method {
                        Method::HEAD if path.contains("/blobs/") && has_blobs => {
                            StatusCode::OK.into_response()
                        }
                        Method::HEAD => StatusCode::NOT_FOUND.into_response(),
                        Method::POST => Response::builder()
                            .status(StatusCode::ACCEPTED)
                            .header(header::LOCATION, format!("{path}upload-1"))
                            .body(axum::body::Body::empty())
                            .unwrap(),
                        // containerd rejects (and retries) a commit that
                        // doesn't echo the digest back.
                        Method::PUT => {
                            let digest = query
                                .split('&')
                                .find_map(|kv| kv.strip_prefix("digest="))
                                .unwrap_or_default()
                                .replace("%3A", ":");
                            Response::builder()
                                .status(StatusCode::CREATED)
                                .header("Docker-Content-Digest", digest)
                                .body(axum::body::Body::empty())
                                .unwrap()
                        }
                        _ => StatusCode::CREATED.into_response(),
                    }
                }
            });
            (serve(app).await, log)
        }

        /// A stand-in for huggingface.co that answers every request with
        /// `body` and records it.
        async fn mock_source(body: &'static str) -> (String, Log) {
            let log = Log::default();
            let seen = log.clone();
            let app = Router::new().fallback(move |req: Request| {
                let seen = seen.clone();
                async move {
                    seen.lock()
                        .unwrap()
                        .push(format!("{} {}", req.method(), req.uri().path()));
                    body
                }
            });
            (serve(app).await, log)
        }

        fn session(registry: &str) -> crate::ffi::PushSession {
            // The test harness skips `main()`; windows-msvc needs this
            // before any Go call or the call hangs.
            crate::ffi::ensure_runtime_init();
            crate::ffi::push_session_open(&format!("{registry}/org/model:v1")).unwrap()
        }

        fn desc_of(data: &[u8]) -> Descriptor {
            Descriptor {
                media_type: oci::MEDIA_TYPE_MODEL_WEIGHT_RAW.to_string(),
                digest: format!("sha256:{:x}", sha2::Sha256::digest(data)),
                size: data.len() as i64,
                ..Default::default()
            }
        }

        fn request(source: &str) -> FetchRequest<'static> {
            FetchRequest {
                url: format!("http://{source}/org/model/resolve/abc/model.gguf"),
                token: None,
                xet: None,
                label: "Transferring model.gguf".to_string(),
            }
        }

        // Multi-thread: a blocking FFI call would starve the mock otherwise.
        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
        async fn open_push_stream_returns_none_for_a_blob_the_registry_has() {
            let (registry, reg_log) = mock_registry(true).await;
            let session = session(&registry);
            let opened = open_push_stream(&session, &desc_of(b"hello")).unwrap();
            assert!(opened.is_none(), "an existing blob must not open a pipe");
            assert_eq!(count(&reg_log, "HEAD", "/blobs/sha256:"), 1);
            assert_eq!(count(&reg_log, "POST", "/blobs/uploads/"), 0);
        }

        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
        async fn an_existing_blob_is_never_fetched_from_the_source() {
            let (registry, reg_log) = mock_registry(true).await;
            let (source, src_log) = mock_source("hello").await;
            let session = session(&registry);

            let pushed = fetch_and_push_stream(
                &reqwest::Client::new(),
                &request(&source),
                &session,
                &desc_of(b"hello"),
            )
            .await
            .unwrap();

            assert!(!pushed, "nothing changed at the destination");
            assert!(
                src_log.lock().unwrap().is_empty(),
                "the source must not be contacted: {:?}",
                src_log.lock().unwrap()
            );
            assert_eq!(count(&reg_log, "POST", "/blobs/uploads/"), 0);
        }

        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
        async fn a_missing_blob_is_fetched_once_and_uploaded() {
            let (registry, reg_log) = mock_registry(false).await;
            let (source, src_log) = mock_source("hello").await;
            let session = session(&registry);

            let pushed = fetch_and_push_stream(
                &reqwest::Client::new(),
                &request(&source),
                &session,
                &desc_of(b"hello"),
            )
            .await
            .unwrap();

            assert!(pushed);
            assert_eq!(count(&src_log, "GET", "/resolve/"), 1);
            assert_eq!(count(&reg_log, "POST", "/blobs/uploads/"), 1);
            assert!(
                count(&reg_log, "PUT", "/blobs/uploads/")
                    + count(&reg_log, "PATCH", "/blobs/uploads/")
                    >= 1
            );
        }

        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
        async fn push_bytes_skips_the_upload_for_a_blob_the_registry_has() {
            let (registry, reg_log) = mock_registry(true).await;
            let session = session(&registry);
            let pushed = push_bytes(&session, &desc_of(b"{}"), b"{}").await.unwrap();
            assert!(!pushed);
            assert_eq!(count(&reg_log, "POST", "/blobs/uploads/"), 0);
        }

        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
        async fn push_bytes_uploads_a_missing_blob() {
            let (registry, reg_log) = mock_registry(false).await;
            let session = session(&registry);
            let pushed = push_bytes(&session, &desc_of(b"{}"), b"{}").await.unwrap();
            assert!(pushed);
            assert_eq!(count(&reg_log, "POST", "/blobs/uploads/"), 1);
        }
    }
}