Skip to main content

zlayer_registry/
client.rs

1//! OCI distribution client for pulling and pushing images
2
3use crate::cache::BlobCacheBackend;
4use crate::error::{RegistryError, Result};
5use crate::image_config::{ImageConfig, OciImageConfigRoot};
6use crate::wasm::{detect_artifact_type, extract_wasm_info, ArtifactType, WasmArtifactInfo};
7use futures_util::stream::{StreamExt, TryStreamExt};
8use oci_client::{
9    client::{ClientConfig, ClientProtocol},
10    manifest::{ImageIndexEntry, OciImageIndex, OciImageManifest, OciManifest},
11    secrets::RegistryAuth,
12    Reference, RegistryOperation,
13};
14use std::sync::Arc;
15use thiserror::Error;
16use tokio::sync::Semaphore;
17use tracing::instrument;
18
19/// Max layers of a SINGLE image fetched concurrently. `buffered` preserves
20/// order; real network concurrency is further bounded by the shared
21/// `concurrency_limit` semaphore acquired inside each blob fetch.
22const LAYER_PULL_CONCURRENCY: usize = 8;
23use zlayer_spec::PullPolicy;
24
25/// Hard ceiling on a single shared-S3-tier read on the image-resolution path.
26///
27/// The S3 tier is a best-effort *cache*, never a hard dependency: `ZLayer` can
28/// host its own S3 backend (e.g. an in-cluster `ZataStorage` reachable as a
29/// `*.service.local` name), so the endpoint may be unreachable, mid-restart, or
30/// not yet resolvable precisely while the daemon is booting and trying to
31/// resolve the very images that bring that backend up. A dead endpoint must
32/// degrade to a cache MISS, NOT hang resolution: the AWS SDK's own
33/// connect/read timeouts are not configured here and can stall for a long time
34/// on a black-holed host. We therefore bound every S3 *read* on the pull path
35/// with this short timeout and treat an elapsed deadline exactly like a miss
36/// (fall through to origin/local). Writes (cache propagation) stay best-effort
37/// without a wrapper — a slow write only delays the background warm, never the
38/// resolution result that has already been produced.
39const S3_TIER_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
40
41/// Shared completion slot for an in-flight image-warm. Carries the RESOLVED
42/// manifest (a pure, clonable value) — never any staging-dir paths. The leader
43/// resolves the manifest once AND downloads every layer blob into the shared
44/// blob cache; it then publishes `(manifest, digest)` here. Followers that await
45/// this slot skip both `pull_manifest_inner` (no duplicate manifest fetch, no
46/// per-follower mutable-tag HEAD revalidation) and the network download (the
47/// cache is already warm), and materialize layers into their OWN staging
48/// directory from the shared manifest — so a caller never receives another
49/// caller's staged files. The error is stringified because [`RegistryError`]
50/// is not `Clone`: every follower of a failed warm gets the same message and
51/// independently surfaces it as a [`RegistryError::Cache`].
52type WarmSlot = tokio::sync::OnceCell<std::result::Result<(OciImageManifest, String), String>>;
53
54/// Shared completion slot for an in-flight image-CONFIG fetch. Unlike
55/// [`WarmSlot`], the config is a pure owned value with no per-call staging
56/// state, so the parsed [`ImageConfig`] itself is shared by-clone among all
57/// followers — there is nothing caller-specific to keep separate. The error is
58/// stringified because [`RegistryError`] is not `Clone`.
59type ConfigSlot = tokio::sync::OnceCell<std::result::Result<ImageConfig, String>>;
60
61/// Process-global single-flight registry for image pulls, keyed by
62/// [`ImagePuller::pull_singleflight_key`]. The daemon constructs a FRESH
63/// [`ImagePuller`] per `CreateContainer` (see
64/// `crates/zlayer-agent/src/runtimes/youki.rs::pull_image_with_policy`), so a
65/// per-instance field would never be shared across the 8–10 concurrent creates
66/// of the same executor image that a CI burst produces. A `static` keyed by the
67/// blob-cache identity collapses those N independent network pulls into one.
68///
69/// The value is a [`Weak`] so the entry self-evicts once the leader and all its
70/// followers drop their `Arc<WarmSlot>` — a LATER pull of the same image then
71/// re-runs the real warm (re-validating mutable tags, refetching evicted blobs)
72/// instead of forever short-circuiting on a stale slot.
73static PULL_SINGLEFLIGHT: std::sync::OnceLock<
74    tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>>,
75> = std::sync::OnceLock::new();
76
77fn pull_singleflight(
78) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<WarmSlot>>> {
79    PULL_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
80}
81
82/// Process-global single-flight registry for image-CONFIG fetches, the sibling
83/// of [`PULL_SINGLEFLIGHT`]. In the daemon's create path the config fetch is a
84/// SEPARATE hot round-trip that follows the layer pull (it does its own
85/// `pull_blob` for the config descriptor), so a burst of N creates would each
86/// fetch the (tiny) config blob until one populates the cache. This collapses
87/// those into one fetch and shares the parsed result by-clone.
88static CONFIG_SINGLEFLIGHT: std::sync::OnceLock<
89    tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>>,
90> = std::sync::OnceLock::new();
91
92fn config_singleflight(
93) -> &'static tokio::sync::Mutex<std::collections::HashMap<String, std::sync::Weak<ConfigSlot>>> {
94    CONFIG_SINGLEFLIGHT.get_or_init(|| tokio::sync::Mutex::new(std::collections::HashMap::new()))
95}
96
97#[cfg(feature = "local")]
98use crate::wasm_export::WasmExportResult;
99
100/// Normalize an image reference to the canonical form used as the *stem* of
101/// every manifest cache key.
102///
103/// This is the load-bearing fix for the macOS image-OS-resolution bug. The
104/// pull path and the OS-inspect path receive the SAME image through different
105/// spellings: the VZ-Linux delegate pulls `docker.io/library/alpine:latest`
106/// (already qualified by the service layer) and writes the manifest under that
107/// key, while the composite runtime's `inspect_image_os` is invoked with the
108/// BARE `alpine:latest`. With a raw `format!("manifest:{image}")` key those two
109/// land in different cache slots, so the inspect misses the cached manifest and
110/// goes to the network — which then 429s under a Docker Hub rate-limit.
111///
112/// Normalizing both spellings through `oci_client::Reference` collapses them
113/// onto one canonical `registry/repository:tag` (or `…@sha256:…`) key, so the
114/// reader queries exactly what the writer wrote. Inputs that don't parse as a
115/// reference (should not happen for real images) fall back to the raw string so
116/// the key is still deterministic.
117#[must_use]
118fn canonical_manifest_ref(image: &str) -> String {
119    use std::str::FromStr;
120    match oci_client::Reference::from_str(image) {
121        Ok(reference) => reference.whole(),
122        Err(_) => image.to_string(),
123    }
124}
125
126/// Blob-cache key under which the OCI manifest body for `image` is stored.
127///
128/// Both the registry-side pull paths and the agent-side runtimes
129/// (`crates/zlayer-agent/src/runtimes/youki.rs`) must construct this key
130/// via this function — never via raw `format!("manifest:{image}")`. A
131/// drift between writer and reader silently breaks image lookup; we just
132/// burned one debugging session on exactly that bug class for the digest
133/// sidecar key (see [`manifest_digest_cache_key`]).
134///
135/// The key stem is the *canonical* reference (see [`canonical_manifest_ref`]),
136/// so a bare `alpine:latest` and a qualified `docker.io/library/alpine:latest`
137/// resolve to the SAME entry — the writer (pull, qualified) and the reader
138/// (OS inspect, bare) always agree.
139#[must_use]
140pub fn manifest_cache_key(image: &str) -> String {
141    format!("manifest:{}", canonical_manifest_ref(image))
142}
143
144/// Blob-cache key under which the registry's content-addressable manifest
145/// digest is stored alongside the manifest body. Both the registry-side
146/// pull paths and the agent-side runtimes (e.g. youki's `list_images`)
147/// must agree on this key — otherwise readers silently miss the digest
148/// and image-drift detection short-circuits to "no recreate."
149///
150/// Keyed on the canonical reference (see [`manifest_cache_key`]) so the digest
151/// sidecar tracks the manifest body across bare/qualified spellings.
152#[must_use]
153pub fn manifest_digest_cache_key(image: &str) -> String {
154    format!("manifest:digest-{}", canonical_manifest_ref(image))
155}
156
157/// Blob-cache key under which the user's ORIGINAL (as-typed) reference for a
158/// cached manifest is stored, so `list_images` can surface what the user typed
159/// (`alpine:latest`) rather than the canonical form used as the cache key
160/// (`docker.io/library/alpine:latest`).
161///
162/// The prefix is `manifest-orig:` (a hyphen, NOT `manifest:`) so it is NOT
163/// enumerated by `keys_with_prefix("manifest:")` in `list_images`. Keyed on the
164/// canonical ref (like [`manifest_cache_key`]) so writer and reader agree.
165#[must_use]
166pub fn manifest_orig_cache_key(image: &str) -> String {
167    format!("manifest-orig:{}", canonical_manifest_ref(image))
168}
169
170/// Errors that can occur during push operations
171#[derive(Debug, Error)]
172pub enum PushError {
173    /// Authentication failed for the registry
174    #[error("authentication failed for registry {registry}: {reason}")]
175    AuthenticationFailed {
176        /// Registry hostname
177        registry: String,
178        /// Reason for failure
179        reason: String,
180    },
181
182    /// Failed to upload a blob
183    #[error("failed to upload blob {digest}: {reason}")]
184    BlobUploadFailed {
185        /// Digest of the blob that failed to upload
186        digest: String,
187        /// Reason for failure
188        reason: String,
189    },
190
191    /// Failed to upload a manifest
192    #[error("failed to upload manifest: {reason}")]
193    ManifestUploadFailed {
194        /// Reason for failure
195        reason: String,
196    },
197
198    /// Network error during push
199    #[error("network error: {0}")]
200    NetworkError(String),
201
202    /// Invalid image reference
203    #[error("invalid image reference: {reference}")]
204    InvalidReference {
205        /// The invalid reference string
206        reference: String,
207    },
208
209    /// OCI distribution error
210    #[error("OCI distribution error: {0}")]
211    OciError(#[from] oci_client::errors::OciDistributionError),
212}
213
214/// Result of a successful push operation
215#[derive(Debug, Clone)]
216pub struct PushResult {
217    /// Digest of the pushed manifest (sha256:...)
218    pub manifest_digest: String,
219    /// List of blob digests that were pushed
220    pub blobs_pushed: Vec<String>,
221    /// Full reference to the pushed image
222    pub reference: String,
223}
224
225/// One layer to publish as part of a generic OCI artifact via
226/// [`ImagePuller::push_artifact`]. `data` must already be in its final
227/// (compressed) form; the digest is computed over exactly these bytes.
228#[cfg(feature = "local")]
229#[derive(Debug, Clone)]
230pub struct ArtifactLayer {
231    /// Raw layer bytes (already compressed, matching `media_type`).
232    pub data: Vec<u8>,
233    /// OCI media type for the layer (e.g.
234    /// `application/vnd.oci.image.layer.v1.tar+zstd`).
235    pub media_type: String,
236    /// Optional `org.opencontainers.image.title` annotation — a filename hint
237    /// surfaced to tooling that inspects the layer.
238    pub title: Option<String>,
239}
240
241/// Compute the `sha256:<hex>` content digest of a blob, as expected by the
242/// OCI distribution API.
243#[cfg(feature = "local")]
244#[must_use]
245pub fn oci_sha256_digest(bytes: &[u8]) -> String {
246    use sha2::{Digest, Sha256};
247    let mut hasher = Sha256::new();
248    hasher.update(bytes);
249    format!("sha256:{}", hex::encode(hasher.finalize()))
250}
251
252/// Map Rust architecture names to Go/OCI architecture names.
253pub(crate) fn go_arch_name() -> &'static str {
254    match std::env::consts::ARCH {
255        "x86_64" => "amd64",
256        "x86" => "amd",
257        "aarch64" => "arm64",
258        "powerpc64" => "ppc64le",
259        other => other,
260    }
261}
262
263/// Map Rust OS names to Go/OCI OS names.
264pub(crate) fn go_os_name() -> &'static str {
265    match std::env::consts::OS {
266        "macos" => "darwin",
267        other => other,
268    }
269}
270
271/// Returns true when the image reference uses a "mutable" tag whose meaning
272/// can change over time (e.g. `:latest`, `:dev`), so cached manifests for it
273/// must be revalidated against the registry rather than trusted forever.
274///
275/// Returns false for pinned tags (`:v1.2.3`), digest references
276/// (`image@sha256:...`), and anything else not in the known-mutable set.
277fn is_mutable_tag(image: &str) -> bool {
278    // Digest references are always immutable — strip anything from `@` onward
279    // and, if a digest was present, the reference is content-addressed.
280    let (without_digest, had_digest) = match image.find('@') {
281        Some(idx) => (&image[..idx], true),
282        None => (image, false),
283    };
284    if had_digest {
285        return false;
286    }
287
288    // Find the tag by looking at the LAST `:`. If everything after it contains
289    // a `/`, that colon was part of a registry host:port, not a tag separator.
290    let tag = match without_digest.rfind(':') {
291        Some(idx) => {
292            let candidate = &without_digest[idx + 1..];
293            if candidate.contains('/') {
294                // Colon belonged to a host:port, so there is no explicit tag.
295                None
296            } else {
297                Some(candidate)
298            }
299        }
300        None => None,
301    };
302
303    match tag {
304        // No tag at all — Docker defaults to `latest`, which is mutable.
305        // Empty tag (e.g. `nginx:`) is treated the same as a missing tag.
306        None | Some("") => true,
307        Some(t) => matches!(t, "latest" | "dev" | "edge" | "main" | "master"),
308    }
309}
310
311/// Generate candidate `(name, reference)` pairs to try against the local
312/// registry, in priority order.
313///
314/// `oci_client::Reference::from_str` normalizes bare names like
315/// `zarcrunner-executor:latest` into `docker.io/library/zarcrunner-executor:latest`,
316/// but locally-built images are stored under whatever name the user passed to
317/// `zlayer build`. To bridge that gap we probe several plausible name forms
318/// before giving up and falling through to a remote pull.
319///
320/// Returns candidates in this priority order (deduplicated, preserving the
321/// first occurrence):
322/// 1. The primary name as parsed.
323/// 2. With `docker.io/` prefix stripped.
324/// 3. With `docker.io/library/` prefix stripped.
325/// 4. With `library/` prefix stripped.
326/// 5. With `library/` prefix added (only when the primary name has no `/`).
327/// 6. The bare last path segment.
328#[cfg(feature = "local")]
329fn local_image_ref_candidates(image: &str) -> Vec<(String, String)> {
330    // Delegates to the shared, non-cfg helper in `zlayer-types` so the agent
331    // crate (VZ rootfs cross-spelling lookup) and the registry use identical
332    // candidate logic. See `zlayer_types::image_ref_candidates`.
333    zlayer_types::image_ref_candidates(image)
334}
335
336#[cfg(all(test, feature = "local"))]
337mod local_image_ref_candidates_tests {
338    use super::local_image_ref_candidates;
339
340    fn contains(candidates: &[(String, String)], name: &str, reference: &str) -> bool {
341        candidates.iter().any(|(n, r)| n == name && r == reference)
342    }
343
344    #[test]
345    fn bare_name_with_tag_produces_library_and_self() {
346        let c = local_image_ref_candidates("zarcrunner-executor:latest");
347        assert!(
348            contains(&c, "zarcrunner-executor", "latest"),
349            "missing bare candidate in {c:?}",
350        );
351        assert!(
352            contains(&c, "library/zarcrunner-executor", "latest"),
353            "missing library/ candidate in {c:?}",
354        );
355    }
356
357    #[test]
358    fn fully_qualified_docker_hub_strips_prefixes() {
359        let c = local_image_ref_candidates("docker.io/library/zarcrunner-executor:latest");
360        assert!(
361            contains(&c, "docker.io/library/zarcrunner-executor", "latest"),
362            "missing primary in {c:?}",
363        );
364        assert!(
365            contains(&c, "library/zarcrunner-executor", "latest"),
366            "missing docker.io-stripped form in {c:?}",
367        );
368        assert!(
369            contains(&c, "zarcrunner-executor", "latest"),
370            "missing docker.io/library-stripped form in {c:?}",
371        );
372    }
373
374    #[test]
375    fn ghcr_keeps_qualified_and_bare_segment_but_no_library_prefix() {
376        let c = local_image_ref_candidates("ghcr.io/team/svc:1.2");
377        assert!(
378            contains(&c, "ghcr.io/team/svc", "1.2"),
379            "missing primary in {c:?}",
380        );
381        assert!(
382            contains(&c, "svc", "1.2"),
383            "missing bare last-segment fallback in {c:?}",
384        );
385        // The `library/` prefix only applies to bare (slash-free) names. A
386        // fully-qualified non-docker-hub name must NOT acquire `library/...`.
387        assert!(
388            !c.iter().any(|(n, _)| n.starts_with("library/")),
389            "unexpected library/ prefix in {c:?}",
390        );
391    }
392
393    #[test]
394    fn digest_reference_is_preserved() {
395        let digest = "sha256:0000000000000000000000000000000000000000000000000000000000000000";
396        let input = format!("foo@{digest}");
397        let c = local_image_ref_candidates(&input);
398        assert!(
399            contains(&c, "foo", digest),
400            "missing foo@digest candidate in {c:?}",
401        );
402        assert!(
403            contains(&c, "library/foo", digest),
404            "missing library/foo@digest candidate in {c:?}",
405        );
406        // The reference column is always the digest, never "latest".
407        for (_, r) in &c {
408            assert_eq!(r, digest, "non-digest reference leaked into {c:?}");
409        }
410    }
411
412    #[test]
413    fn deterministic_input_has_no_duplicates() {
414        for input in [
415            "zarcrunner-executor:latest",
416            "docker.io/library/zarcrunner-executor:latest",
417            "ghcr.io/team/svc:1.2",
418            "foo",
419            "library/foo:1.0",
420            "foo@sha256:0000000000000000000000000000000000000000000000000000000000000000",
421        ] {
422            let c = local_image_ref_candidates(input);
423            let mut sorted: Vec<_> = c.clone();
424            sorted.sort();
425            let original_len = sorted.len();
426            sorted.dedup();
427            assert_eq!(
428                original_len,
429                sorted.len(),
430                "duplicate candidates produced for {input}: {c:?}",
431            );
432        }
433    }
434}
435
436/// Build a `platform_resolver` closure that picks manifests matching `target`.
437///
438/// When `target` is `Some`, the closure looks for the exact `{os}/{arch}` in
439/// the image index and ignores any host-specific fallback (the caller has
440/// asked for a specific platform, so respect that intent).
441///
442/// When `target` is `None`, the closure falls back to the process's runtime
443/// platform (via `go_os_name()` / `go_arch_name()`), preserving the previous
444/// hardcoded resolver's behavior — including the macOS-specific two-pass
445/// search that first tries `darwin/{arch}` (native zlayer sandbox images)
446/// and then `linux/{arch}` (standard Docker Hub images which run inside a
447/// Linux VM via Docker Desktop or similar).
448fn build_platform_resolver(
449    target: Option<zlayer_spec::TargetPlatform>,
450) -> impl Fn(&[ImageIndexEntry]) -> Option<String> + Send + Sync + 'static {
451    // Resolve once at construction time so env isn't read on every invocation.
452    //
453    // Windows multi-platform indexes distinguish Server/Desktop build families
454    // via `platform.os.version` (e.g. `10.0.26100.*` for Server 2025 / Win11
455    // 24H2, `10.0.20348.*` for Server 2022). When the caller pinned a target
456    // os_version, prefer manifest entries whose os.version equals the
457    // constraint OR shares the same `major.minor.build` prefix.
458    //
459    // Macos-fallback only applies when we're using the host's default
460    // (no explicit override) AND the host is macOS — an explicit
461    // `darwin/...` override from a caller should NOT silently match linux.
462    let has_target = target.is_some();
463    let (target_os, target_arch, target_os_version): (String, String, Option<String>) = match target
464    {
465        Some(tp) => (
466            tp.os.as_oci_str().to_string(),
467            tp.arch.as_oci_str().to_string(),
468            tp.os_version,
469        ),
470        None => (go_os_name().to_string(), go_arch_name().to_string(), None),
471    };
472    let use_macos_fallback = !has_target && cfg!(target_os = "macos");
473
474    move |manifests: &[ImageIndexEntry]| -> Option<String> {
475        // Pass 1a: Windows + pinned os_version — prefer an entry whose
476        // `os.version` matches exactly or shares the requested prefix.
477        if target_os == "windows" {
478            if let Some(want_version) = target_os_version.as_deref() {
479                if let Some(entry) = manifests.iter().find(|entry| {
480                    entry.platform.as_ref().is_some_and(|p| {
481                        p.os == target_os
482                            && p.architecture == target_arch
483                            && p.os_version
484                                .as_deref()
485                                .is_some_and(|v| v == want_version || v.starts_with(want_version))
486                    })
487                }) {
488                    return Some(entry.digest.clone());
489                }
490            }
491        }
492
493        // Pass 1: exact {os}/{arch} match (os.version ignored — back-compat,
494        // and used as the fallback when no Windows os.version match was found).
495        if let Some(entry) = manifests.iter().find(|entry| {
496            entry
497                .platform
498                .as_ref()
499                .is_some_and(|p| p.os == target_os && p.architecture == target_arch)
500        }) {
501            return Some(entry.digest.clone());
502        }
503
504        // Pass 2: macOS-only fallback to linux/{arch} (for Docker Hub images
505        // run inside a Linux VM). Only runs when we're using host defaults.
506        if use_macos_fallback {
507            return manifests
508                .iter()
509                .find(|entry| {
510                    entry
511                        .platform
512                        .as_ref()
513                        .is_some_and(|p| p.os == "linux" && p.architecture == target_arch)
514                })
515                .map(|entry| entry.digest.clone());
516        }
517
518        None
519    }
520}
521
522/// Parse stored manifest bytes as a concrete image manifest, treating an OCI
523/// image *index* (`application/vnd.oci.image.index.v1+json`) as a miss
524/// (`None`).
525///
526/// Used by the in-process and S3 cache read paths, which are only ever warmed
527/// with already-resolved [`OciImageManifest`] bytes (`warm_local_cache` /
528/// `propagate_manifest_down` serialize a resolved manifest). An index appearing
529/// there is unexpected, so we return `None` — a clean miss that makes the
530/// resolution chain fall through to the origin/local registry rather than
531/// erroring with `missing field config`, which is what `from_slice::<OciImageManifest>`
532/// did on an index body before.
533fn parse_image_manifest_only(data: &[u8]) -> Option<OciImageManifest> {
534    match serde_json::from_slice::<OciManifest>(data).ok()? {
535        OciManifest::Image(manifest) => Some(manifest),
536        OciManifest::ImageIndex(_) => None,
537    }
538}
539
540/// Build a [`ClientConfig`] with the zlayer platform resolver and sensible
541/// defaults for timeouts and protocol.
542///
543/// `target` overrides the platform used by the resolver; `None` preserves the
544/// historical behavior of matching the process's runtime platform (with the
545/// macOS `darwin → linux` fallback).
546fn build_client_config(target: Option<zlayer_spec::TargetPlatform>) -> ClientConfig {
547    ClientConfig {
548        protocol: ClientProtocol::Https,
549        connect_timeout: Some(std::time::Duration::from_secs(30)),
550        read_timeout: Some(std::time::Duration::from_secs(300)), // 5 minutes for large layers
551        platform_resolver: Some(Box::new(build_platform_resolver(target))),
552        ..Default::default()
553    }
554}
555
556/// OCI image puller with caching
557pub struct ImagePuller {
558    client: oci_client::Client,
559    cache: Arc<Box<dyn BlobCacheBackend>>,
560    concurrency_limit: Arc<Semaphore>,
561    /// Count of network round-trips actually issued against the remote registry
562    /// through `self.client`. Bumped by [`ImagePuller::note_network_call`] at
563    /// every method that talks to the registry over the wire. It exists so the
564    /// *local-only* resolution paths (`resolve_manifest_local_only`,
565    /// `image_os_in_cache_only`, `image_runtime_marker_in_cache_only`) can be
566    /// proven, in tests, to issue ZERO network calls even when the cache misses
567    /// — the macOS Docker-Hub-429 regression was precisely a "local-only" path
568    /// silently falling through to the network.
569    network_calls: Arc<std::sync::atomic::AtomicUsize>,
570    /// Optional SHARED/remote blob cache (typically S3) probed AFTER the
571    /// primary `cache` and BEFORE the network. A hit here is written through to
572    /// `cache` (warm) on the way out; a fresh network pull is propagated down
573    /// into it. `None` = no S3 tier (single-cache behavior, unchanged).
574    s3_cache: Option<Arc<Box<dyn BlobCacheBackend>>>,
575    /// Last-resort default registry host for bare/unqualified names found
576    /// nowhere in the chain (e.g. `docker.io`). `None` = a bare name resolves
577    /// nowhere → actionable error; `ZLayer` never silently invents docker.io.
578    default_registry: Option<String>,
579    /// Per-image override of the resolution chain order (default
580    /// [`zlayer_spec::SourcePolicy::LocalFirst`] = the full chain). Read once in
581    /// [`Self::pull_manifest_inner`].
582    source_policy: zlayer_spec::SourcePolicy,
583    /// The OCI platform this puller resolves multi-platform image indexes
584    /// against. `None` = the process's runtime platform (with the macOS
585    /// `darwin → linux` fallback), matching `build_platform_resolver(None)`;
586    /// set by [`ImagePuller::with_platform`]. Read by the local-registry
587    /// manifest read path (`resolve_stored_manifest`) so a stored image *index*
588    /// is resolved to its platform-specific manifest exactly the way the remote
589    /// (`oci_client`) path already does. That path is the field's ONLY reader,
590    /// so the field is gated on the same feature (without `local` the remote
591    /// path still honors the platform via `build_client_config`'s resolver).
592    #[cfg(feature = "local")]
593    target: Option<zlayer_spec::TargetPlatform>,
594    #[cfg(feature = "local")]
595    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
596}
597
598impl ImagePuller {
599    /// Create a new image puller with any cache backend.
600    ///
601    /// Pulls will target the process's runtime platform (with the historical
602    /// macOS `darwin → linux` fallback). To pull a specific platform, use
603    /// [`ImagePuller::with_platform`].
604    pub fn new<C: BlobCacheBackend + 'static>(cache: C) -> Self {
605        let client = oci_client::Client::new(build_client_config(None));
606
607        Self {
608            client,
609            cache: Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>),
610            concurrency_limit: Arc::new(Semaphore::new(3)),
611            network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
612            s3_cache: None,
613            default_registry: None,
614            source_policy: zlayer_spec::SourcePolicy::LocalFirst,
615            #[cfg(feature = "local")]
616            target: None,
617            #[cfg(feature = "local")]
618            local_registry: None,
619        }
620    }
621
622    /// Create a new image puller with boxed cache backend.
623    ///
624    /// Pulls will target the process's runtime platform (with the historical
625    /// macOS `darwin → linux` fallback). To pull a specific platform, use
626    /// [`ImagePuller::with_platform`].
627    #[must_use]
628    pub fn with_cache(cache: Arc<Box<dyn BlobCacheBackend>>) -> Self {
629        let client = oci_client::Client::new(build_client_config(None));
630
631        Self {
632            client,
633            cache,
634            concurrency_limit: Arc::new(Semaphore::new(3)),
635            network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
636            s3_cache: None,
637            default_registry: None,
638            source_policy: zlayer_spec::SourcePolicy::LocalFirst,
639            #[cfg(feature = "local")]
640            target: None,
641            #[cfg(feature = "local")]
642            local_registry: None,
643        }
644    }
645
646    /// Create a new image puller targeting a specific OCI platform.
647    ///
648    /// The puller's internal `oci-client` will select the manifest whose
649    /// `{os}/{arch}` matches `target` from a multi-platform image index.
650    /// Unlike [`ImagePuller::new`], no macOS `darwin → linux` fallback is
651    /// applied — an explicit target is respected exactly.
652    #[must_use]
653    pub fn with_platform(
654        cache: Arc<Box<dyn BlobCacheBackend>>,
655        target: zlayer_spec::TargetPlatform,
656    ) -> Self {
657        // Clone only when the `local` feature keeps a copy in `self.target`
658        // (the local-registry index-resolution path); otherwise the resolver
659        // consumes the value outright.
660        #[cfg(feature = "local")]
661        let client = oci_client::Client::new(build_client_config(Some(target.clone())));
662        #[cfg(not(feature = "local"))]
663        let client = oci_client::Client::new(build_client_config(Some(target)));
664
665        Self {
666            client,
667            cache,
668            concurrency_limit: Arc::new(Semaphore::new(3)),
669            network_calls: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
670            s3_cache: None,
671            default_registry: None,
672            source_policy: zlayer_spec::SourcePolicy::LocalFirst,
673            #[cfg(feature = "local")]
674            target: Some(target),
675            #[cfg(feature = "local")]
676            local_registry: None,
677        }
678    }
679
680    /// Record that a network round-trip is about to be issued against the
681    /// remote registry. Every method that calls `self.client` over the wire
682    /// must invoke this first so that the local-only paths can be *proven* (in
683    /// tests) to never reach the network. Cheap relaxed atomic increment.
684    fn note_network_call(&self) {
685        self.network_calls
686            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
687    }
688
689    /// Number of network round-trips issued against the remote registry so far.
690    /// Test-only spy used to assert that the local-only resolution paths stay
691    /// offline (see the `*_in_cache_only` regression tests).
692    #[cfg(test)]
693    fn network_call_count(&self) -> usize {
694        self.network_calls
695            .load(std::sync::atomic::Ordering::Relaxed)
696    }
697
698    /// Store authentication for a registry
699    ///
700    /// This ensures the client has auth credentials before attempting pulls.
701    async fn store_auth(&self, image: &str, auth: &RegistryAuth) -> Result<()> {
702        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
703            registry: "unknown".to_string(),
704            image: image.to_string(),
705        })?;
706
707        // Store auth in the client's internal cache
708        // This is called by pull_image_manifest, but we call it explicitly here
709        // to ensure auth is available for blob pulls
710        self.client
711            .store_auth_if_needed(reference.resolve_registry(), auth)
712            .await;
713
714        Ok(())
715    }
716
717    /// Set concurrency limit for blob downloads
718    #[must_use]
719    pub fn with_concurrency_limit(mut self, limit: usize) -> Self {
720        self.concurrency_limit = Arc::new(Semaphore::new(limit));
721        self
722    }
723
724    /// Attach a SHARED/remote blob cache (typically S3) as the write-through
725    /// tier probed after the primary cache and before the network. See the
726    /// `s3_cache` field. Build one from the environment with
727    /// [`crate::s3_cache_from_env`].
728    #[must_use]
729    pub fn with_s3_cache(mut self, s3: Arc<Box<dyn BlobCacheBackend>>) -> Self {
730        self.s3_cache = Some(s3);
731        self
732    }
733
734    /// Read `key` from the shared S3 tier as a strictly best-effort cache probe.
735    ///
736    /// This is the ONE chokepoint every image-resolution-path S3 read goes
737    /// through so the fail-soft contract is enforced in a single place: the S3
738    /// tier is a cache, never a hard dependency, so EVERY failure mode collapses
739    /// to the same outcome — `None`, i.e. a cache MISS that the caller falls
740    /// through on (to the local registry / origin), never a propagated error and
741    /// never an unbounded hang:
742    /// - transport error / unreachable endpoint / `NoSuchKey` → `None`
743    /// - the call exceeding [`S3_TIER_READ_TIMEOUT`] (e.g. a dead
744    ///   `*.service.local` host black-holing the connection) → `None`
745    ///
746    /// Returns `None` immediately when no S3 tier is configured.
747    async fn s3_tier_get(&self, key: &str) -> Option<Vec<u8>> {
748        let s3 = self.s3_cache.as_ref()?;
749        match tokio::time::timeout(S3_TIER_READ_TIMEOUT, s3.get(key)).await {
750            Ok(Ok(data)) => data,
751            Ok(Err(e)) => {
752                tracing::debug!(key = %key, error = %e, "S3 tier read failed; treating as cache miss");
753                None
754            }
755            Err(_elapsed) => {
756                tracing::warn!(
757                    key = %key,
758                    timeout_secs = S3_TIER_READ_TIMEOUT.as_secs(),
759                    "S3 tier read timed out (endpoint unreachable?); treating as cache miss and \
760                     falling through to origin/local"
761                );
762                None
763            }
764        }
765    }
766
767    /// Set the last-resort default registry host for bare/unqualified names
768    /// (e.g. `docker.io`). With no default set, a bare name found nowhere in the
769    /// chain is an error — `ZLayer` never silently invents docker.io.
770    #[must_use]
771    pub fn with_default_registry(mut self, registry: impl Into<String>) -> Self {
772        let host = registry.into();
773        self.default_registry = if host.trim().is_empty() {
774            None
775        } else {
776            Some(host)
777        };
778        self
779    }
780
781    /// Override the resolution chain order for this puller (per-image policy).
782    #[must_use]
783    pub fn with_source_policy(mut self, source: zlayer_spec::SourcePolicy) -> Self {
784        self.source_policy = source;
785        self
786    }
787
788    /// Central runtime-puller constructor: wraps `cache` and wires the shared S3
789    /// tier (`ZLAYER_S3_BUCKET`) + last-resort default registry
790    /// (`ZLAYER_DEFAULT_REGISTRY`) from the environment, plus the per-image
791    /// `source` policy. This is the SINGLE place runtimes get the full source
792    /// chain — they must not re-implement the env wiring. Callers add
793    /// `.with_local_registry(..)` afterward when they have one (it is
794    /// feature-gated, so it stays at the call site).
795    pub async fn from_env_for_runtime(
796        cache: Arc<Box<dyn BlobCacheBackend>>,
797        source: zlayer_spec::SourcePolicy,
798    ) -> Self {
799        let mut puller = Self::with_cache(cache).with_source_policy(source);
800        match crate::cache_config::s3_cache_from_env().await {
801            Ok(Some(s3)) => puller = puller.with_s3_cache(s3),
802            Ok(None) => {}
803            Err(e) => {
804                tracing::warn!(error = %e, "S3 cache tier configured but failed to initialize; continuing without it");
805            }
806        }
807        if let Some(default_registry) = crate::cache_config::default_registry_from_env() {
808            puller = puller.with_default_registry(default_registry);
809        }
810        puller
811    }
812
813    /// Set a local OCI registry for image resolution.
814    #[cfg(feature = "local")]
815    #[must_use]
816    pub fn with_local_registry(
817        mut self,
818        registry: std::sync::Arc<crate::local_registry::LocalRegistry>,
819    ) -> Self {
820        self.local_registry = Some(registry);
821        self
822    }
823
824    /// Pull a single blob and cache it
825    ///
826    /// Uses the provided authentication credentials to pull blobs from the registry.
827    ///
828    /// # Errors
829    ///
830    /// Returns an error if the blob cannot be pulled from the registry or cached.
831    ///
832    /// # Panics
833    ///
834    /// Panics if the concurrency semaphore is closed.
835    pub async fn pull_blob(
836        &self,
837        image: &str,
838        digest: &str,
839        auth: &RegistryAuth,
840    ) -> Result<Vec<u8>> {
841        self.pull_blob_with_urls(image, digest, auth, &[], None)
842            .await
843    }
844
845    /// Pull a blob, with foreign-layer `urls[]` redirect fallback on 404.
846    ///
847    /// Behaviour matches [`pull_blob`] for ordinary layers. For descriptors that
848    /// carry a non-empty `urls` list (typically Windows base layers with media
849    /// type `application/vnd.docker.image.rootfs.foreign.diff.tar.gzip` or the
850    /// OCI nondistributable layer types served by Microsoft Container Registry),
851    /// a primary-registry 404 triggers sequential `GET`s against each URL.
852    /// Each redirect response is digest-verified (and size-verified when
853    /// `expected_size` is provided); the first successful match is cached and
854    /// returned.
855    ///
856    /// At most the first `MAX_FOREIGN_LAYER_REDIRECTS` URLs are attempted; any
857    /// additional URLs are ignored to guard against circular redirect spam.
858    ///
859    /// # Errors
860    ///
861    /// Returns an error if the blob cannot be pulled from the primary registry
862    /// and every `urls[]` fallback also fails.
863    ///
864    /// # Panics
865    ///
866    /// Panics if the concurrency semaphore is closed.
867    pub async fn pull_blob_with_urls(
868        &self,
869        image: &str,
870        digest: &str,
871        auth: &RegistryAuth,
872        urls: &[String],
873        expected_size: Option<i64>,
874    ) -> Result<Vec<u8>> {
875        // Check the local cache first (now async).
876        if let Some(data) = self.cache.get(digest).await? {
877            tracing::debug!(digest = %digest, "blob found in cache");
878            return Ok(data);
879        }
880
881        // Then the shared S3 tier (digest-addressed → immutable, no
882        // revalidation). A hit warms the local cache so the next pull is local.
883        // Best-effort + bounded: a dead/unreachable S3 endpoint degrades to a
884        // miss (see `s3_tier_get`), never an error or a hang on the pull path.
885        if let Some(data) = self.s3_tier_get(digest).await {
886            tracing::debug!(digest = %digest, "blob found in S3 tier; warming local cache");
887            let _ = self.cache.put(digest, &data).await;
888            return Ok(data);
889        }
890
891        // Then the daemon-wide local OCI registry (`zlayer import` / `zlayer
892        // build` store). Blobs are digest-addressed → immutable, so a hit is
893        // authoritative; warm the local cache so subsequent pulls are pure
894        // cache hits. This is what lets an IMPORTED image's layers resolve
895        // without ever touching a remote registry (the manifest already
896        // resolves via `try_local_registry`).
897        #[cfg(feature = "local")]
898        if let Some(registry) = &self.local_registry {
899            if let Ok(data) = registry.get_blob(digest).await {
900                if !data.is_empty() {
901                    tracing::debug!(
902                        digest = %digest,
903                        "blob found in local registry; warming local cache"
904                    );
905                    let _ = self.cache.put(digest, &data).await;
906                    return Ok(data);
907                }
908            }
909        }
910
911        // Store auth before pulling blob
912        self.store_auth(image, auth).await?;
913
914        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
915            registry: "unknown".to_string(),
916            image: image.to_string(),
917        })?;
918
919        let _permit = self.concurrency_limit.acquire().await.unwrap();
920
921        tracing::debug!(digest = %digest, image = %image, "pulling blob from registry");
922
923        // Pull from registry into memory
924        // Note: We pass &mut buffer directly, not wrapped in BufWriter.
925        // Vec<u8> implements AsyncWrite and oci_client's pull_blob writes directly to it.
926        // Using BufWriter was causing data to not be flushed properly.
927        let mut buffer = Vec::new();
928        let primary_result = self.client.pull_blob(&reference, digest, &mut buffer).await;
929
930        let buffer = match primary_result {
931            Ok(()) => buffer,
932            Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
933                tracing::info!(
934                    digest = %digest,
935                    urls_count = urls.len(),
936                    "primary registry missed foreign layer; attempting urls[] redirects"
937                );
938                let mut last_err: Option<RegistryError> = None;
939                let mut recovered: Option<Vec<u8>> = None;
940                for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
941                    match fetch_blob_from_url(url, digest, expected_size).await {
942                        Ok(bytes) => {
943                            tracing::info!(url = %url, "foreign layer recovered via redirect");
944                            recovered = Some(bytes);
945                            break;
946                        }
947                        Err(e) => {
948                            tracing::warn!(url = %url, error = %e, "redirect attempt failed");
949                            last_err = Some(e);
950                        }
951                    }
952                }
953                if let Some(bytes) = recovered {
954                    bytes
955                } else {
956                    tracing::error!(
957                        digest = %digest,
958                        image = %image,
959                        "foreign layer redirect fallback exhausted"
960                    );
961                    return Err(last_err.unwrap_or(RegistryError::Oci(err)));
962                }
963            }
964            Err(err) => {
965                tracing::error!(error = %err, digest = %digest, image = %image, "failed to pull blob from registry");
966                return Err(RegistryError::Oci(err));
967            }
968        };
969
970        // Validate blob data is not empty
971        if buffer.is_empty() {
972            return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
973                format!("blob {digest} was empty after pulling from registry"),
974            )));
975        }
976
977        // Cache the blob locally (now async).
978        self.cache.put(digest, &buffer).await?;
979
980        // Propagate DOWN into the shared S3 tier so other nodes (and this node
981        // after a cold restart) can serve it without re-hitting the origin.
982        // Best-effort: an S3 write failure must not fail an otherwise-good pull.
983        if let Some(s3) = &self.s3_cache {
984            if let Err(e) = s3.put(digest, &buffer).await {
985                tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
986            }
987        }
988
989        tracing::debug!(digest = %digest, size = buffer.len(), "blob cached successfully");
990
991        Ok(buffer)
992    }
993
994    /// Pull a single blob to a file in `staging_dir`, returning the file path,
995    /// without ever holding the whole blob in memory.
996    ///
997    /// Resolution mirrors [`ImagePuller::pull_blob_with_urls`] but stays on disk:
998    /// a file-backed cache hit ([`BlobCacheBackend::get_path`]) is hardlinked into
999    /// the stage; a small inline / in-memory / S3 / local-registry hit is written
1000    /// out; otherwise the blob is streamed from the registry through a
1001    /// [`HashingFileWriter`] (inline SHA-256 verification) into a `.part` temp
1002    /// file that is fsynced, verified, atomically renamed into place, and then
1003    /// best-effort ingested into the cache via [`BlobCacheBackend::put_path`].
1004    ///
1005    /// # Errors
1006    ///
1007    /// Returns an error if every source (cache tiers, primary registry, and all
1008    /// `urls[]` foreign-layer fallbacks) fails, or the streamed bytes fail digest
1009    /// / size verification.
1010    ///
1011    /// # Panics
1012    ///
1013    /// Panics if the concurrency semaphore is closed.
1014    #[allow(clippy::too_many_lines)]
1015    pub async fn pull_blob_to_file(
1016        &self,
1017        image: &str,
1018        digest: &str,
1019        auth: &RegistryAuth,
1020        urls: &[String],
1021        expected_size: Option<i64>,
1022        staging_dir: &std::path::Path,
1023    ) -> Result<std::path::PathBuf> {
1024        tokio::fs::create_dir_all(staging_dir)
1025            .await
1026            .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1027        let dest = staging_dir.join(blob_staging_filename(digest));
1028
1029        // 1. File-backed local cache hit → hardlink into the stage (no RAM).
1030        if let Some(path) = self.cache.get_path(digest).await? {
1031            tracing::debug!(digest = %digest, "blob found in cache (file-backed); linking into stage");
1032            link_or_copy(&path, &dest).await?;
1033            return Ok(dest);
1034        }
1035
1036        // 2. Small inline / in-memory local cache hit → write bytes out.
1037        if let Some(data) = self.cache.get(digest).await? {
1038            tracing::debug!(digest = %digest, "blob found in cache (inline); writing into stage");
1039            tokio::fs::write(&dest, &data)
1040                .await
1041                .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1042            return Ok(dest);
1043        }
1044
1045        // 3. Shared S3 tier (digest-addressed; warm the local cache on hit).
1046        //    Best-effort + bounded: a dead/unreachable S3 endpoint degrades to a
1047        //    miss (see `s3_tier_get`), never an error or a hang on the pull path.
1048        if let Some(data) = self.s3_tier_get(digest).await {
1049            tracing::debug!(digest = %digest, "blob found in S3 tier; staging + warming local cache");
1050            tokio::fs::write(&dest, &data)
1051                .await
1052                .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1053            let _ = self.cache.put_path(digest, &dest).await;
1054            return Ok(dest);
1055        }
1056
1057        // 4. Daemon-wide local OCI registry (imported / built images).
1058        #[cfg(feature = "local")]
1059        if let Some(registry) = &self.local_registry {
1060            if let Ok(data) = registry.get_blob(digest).await {
1061                if !data.is_empty() {
1062                    tracing::debug!(digest = %digest, "blob found in local registry; staging + warming local cache");
1063                    tokio::fs::write(&dest, &data)
1064                        .await
1065                        .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1066                    let _ = self.cache.put_path(digest, &dest).await;
1067                    return Ok(dest);
1068                }
1069            }
1070        }
1071
1072        // 5. Stream from the registry into a `.part` temp file.
1073        self.store_auth(image, auth).await?;
1074        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
1075            registry: "unknown".to_string(),
1076            image: image.to_string(),
1077        })?;
1078        let _permit = self.concurrency_limit.acquire().await.unwrap();
1079        tracing::debug!(digest = %digest, image = %image, "streaming blob from registry to file");
1080
1081        let seq = BLOB_PART_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1082        let tmp = staging_dir.join(format!(
1083            "{}.part.{}.{}",
1084            blob_staging_filename(digest),
1085            std::process::id(),
1086            seq
1087        ));
1088
1089        let make_writer = || async {
1090            let file = tokio::fs::File::create(&tmp)
1091                .await
1092                .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1093            Ok::<_, RegistryError>(HashingFileWriter::new(file))
1094        };
1095
1096        let mut writer = make_writer().await?;
1097        let primary = self.client.pull_blob(&reference, digest, &mut writer).await;
1098
1099        let final_writer = match primary {
1100            Ok(()) => writer,
1101            Err(err) if is_blob_not_found(&err) && !urls.is_empty() => {
1102                tracing::info!(
1103                    digest = %digest,
1104                    urls_count = urls.len(),
1105                    "primary registry missed foreign layer; streaming urls[] redirects"
1106                );
1107                // Restart with a fresh (truncated) file + hasher per attempt.
1108                drop(writer);
1109                let mut recovered: Option<HashingFileWriter> = None;
1110                let mut last_err: Option<RegistryError> = None;
1111                for url in urls.iter().take(MAX_FOREIGN_LAYER_REDIRECTS) {
1112                    let mut w = make_writer().await?;
1113                    match fetch_blob_from_url_to_writer(url, expected_size, &mut w).await {
1114                        Ok(()) => {
1115                            tracing::info!(url = %url, "foreign layer recovered via redirect");
1116                            recovered = Some(w);
1117                            break;
1118                        }
1119                        Err(e) => {
1120                            tracing::warn!(url = %url, error = %e, "redirect attempt failed");
1121                            last_err = Some(e);
1122                        }
1123                    }
1124                }
1125                if let Some(w) = recovered {
1126                    w
1127                } else {
1128                    let _ = tokio::fs::remove_file(&tmp).await;
1129                    tracing::error!(digest = %digest, image = %image, "foreign layer redirect fallback exhausted");
1130                    return Err(last_err.unwrap_or(RegistryError::Oci(err)));
1131                }
1132            }
1133            Err(err) => {
1134                let _ = tokio::fs::remove_file(&tmp).await;
1135                tracing::error!(error = %err, digest = %digest, image = %image, "failed to stream blob from registry");
1136                return Err(RegistryError::Oci(err));
1137            }
1138        };
1139
1140        // Finalize: fsync + verify digest and size before publishing.
1141        let (actual_digest, written) = final_writer.finalize().await?;
1142        if written == 0 {
1143            let _ = tokio::fs::remove_file(&tmp).await;
1144            return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1145                format!("blob {digest} was empty after pulling from registry"),
1146            )));
1147        }
1148        if !actual_digest.eq_ignore_ascii_case(digest) {
1149            let _ = tokio::fs::remove_file(&tmp).await;
1150            return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1151                format!("digest mismatch: expected {digest}, got {actual_digest}"),
1152            )));
1153        }
1154        if let Some(expected) = expected_size {
1155            if let Ok(expected_u) = u64::try_from(expected) {
1156                if written != expected_u {
1157                    let _ = tokio::fs::remove_file(&tmp).await;
1158                    return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1159                        format!(
1160                            "blob {digest}: size mismatch (expected {expected}, got {written})"
1161                        ),
1162                    )));
1163                }
1164            }
1165        }
1166
1167        tokio::fs::rename(&tmp, &dest)
1168            .await
1169            .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
1170
1171        // Populate the local cache (persistent = hardlink into spill, no RAM).
1172        if let Err(e) = self.cache.put_path(digest, &dest).await {
1173            tracing::debug!(digest = %digest, error = %e, "failed to ingest streamed blob into cache");
1174        }
1175        // Propagate DOWN into the shared S3 tier (best-effort, streamed from file).
1176        if let Some(s3) = &self.s3_cache {
1177            if let Err(e) = s3.put_path(digest, &dest).await {
1178                tracing::debug!(digest = %digest, error = %e, "failed to propagate blob to S3 tier");
1179            }
1180        }
1181
1182        tracing::debug!(digest = %digest, size = written, "blob streamed to file successfully");
1183        Ok(dest)
1184    }
1185
1186    /// Pull every layer of an image to files in `staging_dir` (default
1187    /// [`PullPolicy::Newer`]), streaming each layer so no layer is ever fully
1188    /// held in memory. Returns `(layer_file_path, media_type)` in apply order.
1189    ///
1190    /// # Errors
1191    ///
1192    /// Returns an error if the manifest or any layer cannot be pulled.
1193    pub async fn pull_image_to_files(
1194        &self,
1195        image: &str,
1196        auth: &RegistryAuth,
1197        staging_dir: &std::path::Path,
1198    ) -> Result<Vec<(std::path::PathBuf, String)>> {
1199        self.pull_image_to_files_inner(image, auth, staging_dir, PullPolicy::Newer)
1200            .await
1201    }
1202
1203    /// Pull every layer of an image to files honoring an explicit [`PullPolicy`].
1204    ///
1205    /// # Errors
1206    ///
1207    /// Returns an error if the manifest or any layer cannot be pulled.
1208    pub async fn pull_image_to_files_with_policy(
1209        &self,
1210        image: &str,
1211        auth: &RegistryAuth,
1212        staging_dir: &std::path::Path,
1213        policy: PullPolicy,
1214    ) -> Result<Vec<(std::path::PathBuf, String)>> {
1215        self.pull_image_to_files_inner(image, auth, staging_dir, policy)
1216            .await
1217    }
1218
1219    /// Single-flight key for an image-warm. Two concurrent pulls collapse onto
1220    /// one leader iff they agree on every input that changes WHAT the warm
1221    /// downloads into the blob cache: the canonical image ref (the manifest
1222    /// cache-key stem), the [`PullPolicy`], the per-image [`SourcePolicy`], and
1223    /// the IDENTITY of the blob cache being warmed (its `Arc` address). The
1224    /// cache identity guards against false sharing between unrelated pullers
1225    /// (e.g. two tests, or two daemons-in-process) that happen to pull the same
1226    /// ref into DIFFERENT caches — only pullers warming the SAME cache should
1227    /// dedup. Auth is deliberately NOT in the key: it does not change which
1228    /// bytes land in the cache, and the leader's auth is what runs the pull.
1229    fn pull_singleflight_key(&self, image: &str, policy: PullPolicy) -> String {
1230        // `Arc<Box<dyn ..>>` → address of the inner `Box` is stable for the
1231        // lifetime of the shared cache and unique per distinct cache instance.
1232        let cache_id = Arc::as_ptr(&self.cache) as usize;
1233        format!(
1234            "{cache_id:x}|{:?}|{:?}|{}",
1235            policy,
1236            self.source_policy,
1237            canonical_manifest_ref(image),
1238        )
1239    }
1240
1241    /// Single-flight coordinator for the image-to-files pull.
1242    ///
1243    /// Under a CI burst, 8–10 concurrent `CreateContainer` of the SAME executor
1244    /// image each call here independently. Letting all N run the real pull would
1245    /// fire N manifest fetches + N concurrent blob downloads into the
1246    /// single-process, ZQL-mutex-serialized blob cache. Instead, the FIRST
1247    /// caller for a key becomes the LEADER: it resolves the manifest once and
1248    /// downloads every layer blob into the shared cache (materializing into its
1249    /// OWN `staging_dir` as a side effect), then publishes the resolved
1250    /// `(manifest, digest)` into the shared slot. Concurrent callers for the same
1251    /// key (FOLLOWERS) await that slot, then materialize layers into THEIR OWN
1252    /// `staging_dir` from the shared manifest against the now-warm cache.
1253    ///
1254    /// ## Why the seam is correct for per-call staging dirs
1255    ///
1256    /// The expensive work runs exactly once: `pull_manifest_inner` (network
1257    /// manifest fetch / mutable-tag HEAD revalidation) and `pull_blob_to_file`'s
1258    /// registry-streaming arm (download a blob into the blob cache) happen only
1259    /// on the leader. The shared slot carries the resolved `OciImageManifest`
1260    /// (a pure, clonable value), NEVER any `PathBuf` — so a follower never
1261    /// receives the leader's staged files. Each caller, leader and follower
1262    /// alike, runs [`Self::materialize_layers_to_files`] against ITS OWN
1263    /// `staging_dir`, so every returned `Vec<(PathBuf, String)>` points into the
1264    /// caller's own directory. A follower's materialize finds every layer in the
1265    /// cache (file-backed hardlink, inline, S3, or local-registry hit) and issues
1266    /// zero network calls; it also skips the manifest fetch and the per-follower
1267    /// mutable-tag HEAD revalidation entirely by reusing the leader's manifest.
1268    async fn pull_image_to_files_inner(
1269        &self,
1270        image: &str,
1271        auth: &RegistryAuth,
1272        staging_dir: &std::path::Path,
1273        policy: PullPolicy,
1274    ) -> Result<Vec<(std::path::PathBuf, String)>> {
1275        let key = self.pull_singleflight_key(image, policy);
1276
1277        // Acquire (or create) the shared warm slot for this key. Holding the
1278        // map lock only long enough to upsert keeps the registry contention-free
1279        // while the actual (slow) warm runs.
1280        let (slot, is_leader) = {
1281            let mut map = pull_singleflight().lock().await;
1282            if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
1283                (existing, false)
1284            } else {
1285                let fresh: Arc<WarmSlot> = Arc::new(tokio::sync::OnceCell::new());
1286                map.insert(key.clone(), Arc::downgrade(&fresh));
1287                (fresh, true)
1288            }
1289        };
1290
1291        // BOTH leader and followers resolve the manifest through the SAME
1292        // `OnceCell::get_or_init`, which guarantees exactly one initializer runs
1293        // — so `pull_manifest_inner` (and thus the manifest fetch + mutable-tag
1294        // HEAD revalidation) executes once, no matter how many callers race.
1295        // `is_leader` only decides who removes the map entry afterward.
1296        //
1297        // The leader's `get_or_init` future ALSO downloads every layer blob into
1298        // the shared cache by materializing into ITS staging dir as the
1299        // initializer's side effect, so by the time a follower observes a set
1300        // slot the cache is fully warm. We capture the leader's materialized
1301        // result out-of-band (the OnceCell can only hold the manifest, never the
1302        // per-call paths) via a local slot the closure writes.
1303        let mut leader_layers: Option<Result<Vec<(std::path::PathBuf, String)>>> = None;
1304        let shared = slot
1305            .get_or_init(|| async {
1306                match self.pull_manifest_inner(image, auth, policy).await {
1307                    Ok((manifest, digest)) => {
1308                        // Initializer side effect: warm the cache + produce the
1309                        // leader's own staged layers (its legitimate result).
1310                        leader_layers = Some(
1311                            self.materialize_layers_to_files(image, auth, staging_dir, &manifest)
1312                                .await,
1313                        );
1314                        Ok((manifest, digest))
1315                    }
1316                    Err(e) => Err(e.to_string()),
1317                }
1318            })
1319            .await;
1320
1321        // The map entry is only dropped by the caller that created it, once the
1322        // slot has resolved — so a later pull re-runs (mutable-tag revalidation,
1323        // evicted blobs) instead of forever short-circuiting on a stale slot.
1324        if is_leader {
1325            pull_singleflight().lock().await.remove(&key);
1326        }
1327
1328        // If WE were the initializer, return our own materialized result (it
1329        // points into OUR staging dir). Note: the initializer is whichever
1330        // caller's `get_or_init` closure actually ran — usually the leader, but
1331        // in the leader-dropped-early race it can be a follower.
1332        if let Some(result) = leader_layers {
1333            return result;
1334        }
1335
1336        match shared {
1337            Ok((manifest, _digest)) => {
1338                // The cache is warm; materialize layers into OUR OWN staging dir.
1339                // Every blob is now a local cache hit → no network call, no
1340                // manifest re-fetch, no per-follower HEAD revalidation.
1341                self.materialize_layers_to_files(image, auth, staging_dir, manifest)
1342                    .await
1343            }
1344            Err(msg) => {
1345                // The initializer's manifest resolution failed. Surface the same
1346                // failure rather than attempting our own (which would likely fail
1347                // identically and defeat the single-flight under a flapping
1348                // registry).
1349                Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
1350                    format!("image warm failed for {image}: {msg}"),
1351                )))
1352            }
1353        }
1354    }
1355
1356    /// Materialize the layers of an already-resolved `manifest` into
1357    /// `staging_dir` via [`Self::pull_blob_to_file`] (cache-hit hardlink/copy on
1358    /// the warm path, registry-streaming download on a cold miss). Shared by the
1359    /// single-flight leader and its followers — each passes its OWN
1360    /// `staging_dir`, so no caller ever receives another's staged files. See
1361    /// [`Self::pull_image_to_files_inner`].
1362    async fn materialize_layers_to_files(
1363        &self,
1364        image: &str,
1365        auth: &RegistryAuth,
1366        staging_dir: &std::path::Path,
1367        manifest: &OciImageManifest,
1368    ) -> Result<Vec<(std::path::PathBuf, String)>> {
1369        tracing::info!(
1370            image = %image,
1371            layer_count = manifest.layers.len(),
1372            "pulling image layers (streamed to files)"
1373        );
1374
1375        // Pull layers concurrently (bounded). `buffered` preserves submission
1376        // order, so the returned Vec stays in layer order (rootfs layers apply
1377        // in sequence). Network concurrency is additionally capped by the shared
1378        // `concurrency_limit` semaphore acquired inside `pull_blob_to_file`.
1379        // Snapshot the per-layer inputs into owned values FIRST, so the pull
1380        // futures capture only owned data plus `self` / `image` / `auth` /
1381        // `staging_dir`. A map closure taking `&OciDescriptor` and returning a
1382        // future trips an HRTB inference failure under the fn's `#[instrument]`.
1383        let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
1384            .layers
1385            .iter()
1386            .enumerate()
1387            .map(|(i, l)| {
1388                (
1389                    i,
1390                    l.digest.clone(),
1391                    l.media_type.clone(),
1392                    l.urls.clone().unwrap_or_default(),
1393                    l.size,
1394                )
1395            })
1396            .collect();
1397        let layers: Vec<(std::path::PathBuf, String)> =
1398            futures_util::stream::iter(layer_inputs.into_iter().map(
1399                |(i, digest, media_type, urls, size)| async move {
1400                    tracing::debug!(
1401                        layer = i,
1402                        digest = %digest,
1403                        media_type = %media_type,
1404                        size,
1405                        "streaming layer to file"
1406                    );
1407                    let path = self
1408                        .pull_blob_to_file(image, &digest, auth, &urls, Some(size), staging_dir)
1409                        .await?;
1410                    Ok::<(std::path::PathBuf, String), RegistryError>((path, media_type))
1411                },
1412            ))
1413            .buffered(LAYER_PULL_CONCURRENCY)
1414            .try_collect()
1415            .await?;
1416
1417        tracing::info!(image = %image, layers_pulled = layers.len(), "image pull complete (streamed)");
1418        Ok(layers)
1419    }
1420
1421    /// Fetch the current upstream manifest digest for `image` from the registry
1422    /// without pulling the manifest body. Uses `HEAD /v2/{repo}/manifests/{tag}`.
1423    ///
1424    /// Returns `Ok(Some(digest))` when the registry reports a current digest,
1425    /// `Ok(None)` when the image or tag is not found on the registry, and `Err`
1426    /// on transport / auth / protocol failures.
1427    ///
1428    /// This exists so [`pull_manifest`] can revalidate its cache entry against
1429    /// the live registry state for mutable tags (`:latest`, `:dev`, ...) without
1430    /// paying for a full manifest download on every pull.
1431    ///
1432    /// # Errors
1433    ///
1434    /// Returns an error if the image reference is invalid or the registry
1435    /// returns a transport, auth, or protocol-level failure.
1436    pub async fn remote_manifest_digest(
1437        &self,
1438        image: &str,
1439        auth: &RegistryAuth,
1440    ) -> Result<Option<String>> {
1441        let reference: Reference = image.parse().map_err(|_| RegistryError::NotFound {
1442            registry: "unknown".to_string(),
1443            image: image.to_string(),
1444        })?;
1445
1446        self.note_network_call();
1447        match self.client.fetch_manifest_digest(&reference, auth).await {
1448            Ok(digest) => Ok(Some(digest)),
1449            Err(oci_client::errors::OciDistributionError::ImageManifestNotFoundError(_)) => {
1450                tracing::debug!(image = %image, "remote manifest not found");
1451                Ok(None)
1452            }
1453            Err(e) => {
1454                tracing::warn!(error = %e, image = %image, "failed to fetch remote manifest digest");
1455                Err(RegistryError::Oci(e))
1456            }
1457        }
1458    }
1459
1460    /// Try to satisfy a manifest request from the persistent cache.
1461    ///
1462    /// Returns `Some((manifest, digest))` when the cached entry is usable
1463    /// (either because the image ref is pinned, or because a HEAD revalidation
1464    /// against the registry confirmed the cached digest is still current, or
1465    /// because the registry was unreachable and we're falling back to stale).
1466    /// Returns `None` when the caller should proceed to fetch the manifest
1467    /// fresh from the registry — i.e. there is no cached entry, the cached
1468    /// bytes could not be deserialized, or revalidation detected a newer
1469    /// digest and already invalidated the cache entries.
1470    async fn try_cached_manifest(
1471        &self,
1472        image: &str,
1473        auth: &RegistryAuth,
1474        cache_key: &str,
1475        digest_key: &str,
1476        policy: PullPolicy,
1477    ) -> Option<(OciImageManifest, String)> {
1478        let data = self.cache.get(cache_key).await.ok().flatten()?;
1479        let manifest = parse_image_manifest_only(&data)?;
1480
1481        let cached_digest = self
1482            .cache
1483            .get(digest_key)
1484            .await
1485            .ok()
1486            .flatten()
1487            .and_then(|bytes| String::from_utf8(bytes).ok());
1488
1489        // IfNotPresent / Never: cached manifest is good enough, regardless of mutable tag.
1490        if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) {
1491            let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1492            tracing::debug!(image = %image, "manifest cache hit (IfNotPresent/Never, no revalidation)");
1493            return Some((manifest, digest));
1494        }
1495
1496        // Pinned refs: trust the cache without revalidation.
1497        if !is_mutable_tag(image) {
1498            let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1499            tracing::debug!(image = %image, "manifest cache hit (pinned ref)");
1500            return Some((manifest, digest));
1501        }
1502
1503        // Mutable tag: revalidate against the registry.
1504        match self.remote_manifest_digest(image, auth).await {
1505            Ok(Some(remote_digest)) => {
1506                if let Some(cached) = cached_digest.as_deref() {
1507                    if cached == remote_digest {
1508                        tracing::debug!(image = %image, "manifest cache hit (revalidated)");
1509                        return Some((manifest, remote_digest));
1510                    }
1511                    tracing::info!(
1512                        image = %image,
1513                        cached = %cached,
1514                        remote = %remote_digest,
1515                        "cached manifest is stale, refetching"
1516                    );
1517                } else {
1518                    // Legacy pre-revalidation entry with no cached digest:
1519                    // treat as stale so we refetch once and populate both
1520                    // keys for future revalidations.
1521                    tracing::info!(
1522                        image = %image,
1523                        remote = %remote_digest,
1524                        "cached manifest has no stored digest, refetching"
1525                    );
1526                }
1527                if let Err(e) = self.cache.delete(cache_key).await {
1528                    tracing::warn!(
1529                        image = %image,
1530                        error = %e,
1531                        "failed to delete stale manifest cache entry"
1532                    );
1533                }
1534                if let Err(e) = self.cache.delete(digest_key).await {
1535                    tracing::warn!(
1536                        image = %image,
1537                        error = %e,
1538                        "failed to delete stale manifest digest cache entry"
1539                    );
1540                }
1541                None
1542            }
1543            Ok(None) => {
1544                tracing::warn!(image = %image, "remote manifest not found, using stale cache");
1545                let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1546                Some((manifest, digest))
1547            }
1548            Err(e) => {
1549                tracing::warn!(
1550                    image = %image,
1551                    error = %e,
1552                    "manifest revalidation failed, using stale cache"
1553                );
1554                let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
1555                Some((manifest, digest))
1556            }
1557        }
1558    }
1559
1560    /// Resolve stored manifest bytes from the local registry into a concrete
1561    /// platform image manifest, following an OCI image *index* when present.
1562    ///
1563    /// - A plain image manifest is returned as-is (digest = the stored bytes).
1564    /// - An image *index* (`application/vnd.oci.image.index.v1+json`) is
1565    ///   resolved to its platform-specific sub-manifest using the SAME platform
1566    ///   preference as the remote pull path (`build_platform_resolver(self.target)`,
1567    ///   including the macOS `darwin → linux` fallback for host-default pullers),
1568    ///   then that sub-manifest is fetched **by digest** from the same local
1569    ///   registry and parsed. This makes a locally-stored multi-arch image
1570    ///   usable instead of crashing the read with `missing field config`.
1571    ///
1572    /// Returns `None` when the bytes are neither a usable image manifest nor an
1573    /// index that names a matching platform whose sub-manifest is present
1574    /// locally — a clean miss the caller treats as "try the next candidate /
1575    /// resolve fresh".
1576    #[cfg(feature = "local")]
1577    async fn resolve_stored_manifest(
1578        &self,
1579        registry: &crate::local_registry::LocalRegistry,
1580        name: &str,
1581        data: &[u8],
1582    ) -> Option<(OciImageManifest, String)> {
1583        match serde_json::from_slice::<OciManifest>(data).ok()? {
1584            OciManifest::Image(manifest) => Some((manifest, crate::cache::compute_digest(data))),
1585            OciManifest::ImageIndex(index) => {
1586                let resolver = build_platform_resolver(self.target.clone());
1587                let selected = resolver(&index.manifests)?;
1588                let sub = registry.get_manifest(name, &selected).await.ok()?;
1589                let manifest = serde_json::from_slice::<OciImageManifest>(&sub).ok()?;
1590                tracing::debug!(
1591                    name = %name,
1592                    index_digest = %crate::cache::compute_digest(data),
1593                    selected = %selected,
1594                    "resolved stored OCI image index to its platform-specific manifest",
1595                );
1596                Some((manifest, crate::cache::compute_digest(&sub)))
1597            }
1598        }
1599    }
1600
1601    /// Try to resolve a manifest from the local registry.
1602    ///
1603    /// Probes every candidate `(name, reference)` form produced by
1604    /// [`local_image_ref_candidates`] in order, returning the first that
1605    /// resolves to a parseable `OciImageManifest`. This is what lets a
1606    /// deployment spec say `image: zarcrunner-executor:latest` and still hit
1607    /// a locally-built image, even though `oci_client::Reference` normalized
1608    /// the lookup name to `docker.io/library/zarcrunner-executor`.
1609    #[cfg(feature = "local")]
1610    async fn try_local_registry(&self, image: &str) -> Option<(OciImageManifest, String)> {
1611        let registry = self.local_registry.as_ref()?;
1612        let candidates = local_image_ref_candidates(image);
1613        let primary = candidates.first().map(|(n, _)| n.clone());
1614        for (name, reference) in candidates {
1615            // `Err` arm (miss on this candidate) is a no-op — we just try the
1616            // next form, so `if let Ok` is clearer than a `match` with a stub
1617            // `Err(_)` arm (clippy::single-match-else).
1618            if let Ok(data) = registry.get_manifest(&name, &reference).await {
1619                // Resolve the stored bytes, following an OCI image index to its
1620                // platform-specific sub-manifest when needed. `None` = this
1621                // candidate's bytes were unusable (unparseable, or an index with
1622                // no locally-present match) — keep probing the next form.
1623                if let Some((manifest, digest)) =
1624                    self.resolve_stored_manifest(registry, &name, &data).await
1625                {
1626                    if primary.as_deref() == Some(name.as_str()) {
1627                        tracing::debug!(
1628                            image = %image,
1629                            digest = %digest,
1630                            "manifest found in local registry",
1631                        );
1632                    } else {
1633                        tracing::debug!(
1634                            image = %image,
1635                            matched_name = %name,
1636                            digest = %digest,
1637                            "manifest found in local registry via name-form fallback",
1638                        );
1639                    }
1640                    return Some((manifest, digest));
1641                }
1642                tracing::warn!(
1643                    image = %image,
1644                    candidate = %name,
1645                    "local registry manifest parse/resolve failed",
1646                );
1647                // Keep probing — the next candidate may still resolve.
1648            }
1649        }
1650
1651        // Suffix-match fallback (§4.1): a locally-built/pushed image may be
1652        // stored under a FULLER name than any canonical candidate form — e.g.
1653        // `zarcrunner-executor:latest` stored as `…/library/zarcrunner-executor:latest`.
1654        // For an unqualified input that missed every candidate, scan the local
1655        // registry and match by final path segment (optionally under a
1656        // `library/` namespace), so the daemon resolves the local image instead
1657        // of falling through to a doomed Docker Hub pull.
1658        if zlayer_types::image_str_is_unqualified(image) {
1659            if let Some((want_name, want_ref)) =
1660                local_image_ref_candidates(image).into_iter().next()
1661            {
1662                let want_leaf = want_name
1663                    .rsplit('/')
1664                    .next()
1665                    .unwrap_or(&want_name)
1666                    .to_string();
1667                if let Ok(stored) = registry.list_images().await {
1668                    for s in stored {
1669                        let s_leaf = s.rsplit('/').next().unwrap_or(&s);
1670                        // Match the requested leaf either exactly, or as the
1671                        // leaf of a stored namespaced name (`…/<leaf>` /
1672                        // `…/library/<leaf>`). The tag must also resolve below,
1673                        // which guards against a same-leaf-different-tag miss.
1674                        if s_leaf != want_leaf {
1675                            continue;
1676                        }
1677                        if let Ok(data) = registry.get_manifest(&s, &want_ref).await {
1678                            if let Some((manifest, digest)) =
1679                                self.resolve_stored_manifest(registry, &s, &data).await
1680                            {
1681                                tracing::debug!(
1682                                    image = %image,
1683                                    matched_name = %s,
1684                                    reference = %want_ref,
1685                                    digest = %digest,
1686                                    "manifest found in local registry via unqualified suffix-match",
1687                                );
1688                                return Some((manifest, digest));
1689                            }
1690                        }
1691                    }
1692                }
1693            }
1694        }
1695
1696        None
1697    }
1698
1699    /// Pull an image manifest from the registry.
1700    ///
1701    /// Returns the manifest and its registry-reported digest. Manifests are
1702    /// cached to avoid repeated network requests for the same image reference.
1703    ///
1704    /// For mutable tags (`:latest`, `:dev`, `:edge`, `:main`, `:master`, or
1705    /// missing/empty tags), a cache hit triggers a `HEAD` revalidation against
1706    /// the upstream registry. If the cached digest still matches, the cached
1707    /// manifest is returned. If the remote digest differs, the cache entry is
1708    /// invalidated and the manifest is refetched. If the revalidation request
1709    /// itself fails (e.g. the registry is unreachable), the stale cached
1710    /// manifest is returned rather than failing the caller — serving stale
1711    /// beats crashing the deploy.
1712    ///
1713    /// Pinned tags (e.g. `:v1.2.3`) and digest references (`img@sha256:...`)
1714    /// are treated as immutable: a cache hit is returned without revalidation.
1715    ///
1716    /// # Errors
1717    ///
1718    /// Returns an error if the manifest cannot be pulled or the image reference is invalid.
1719    pub async fn pull_manifest(
1720        &self,
1721        image: &str,
1722        auth: &RegistryAuth,
1723    ) -> Result<(OciImageManifest, String)> {
1724        self.pull_manifest_inner(image, auth, PullPolicy::Newer)
1725            .await
1726    }
1727
1728    /// Internal manifest pull driven by an explicit [`PullPolicy`].
1729    ///
1730    /// `PullPolicy::IfNotPresent` and `PullPolicy::Never` short-circuit any
1731    /// remote revalidation when the manifest is already available locally
1732    /// (either in the blob cache or in the local registry). `PullPolicy::Newer`
1733    /// preserves the legacy behavior of revalidating mutable tags against the
1734    /// remote. `PullPolicy::Always` is handled at the `*_with_policy` entry
1735    /// points by invalidating the cache before delegating here.
1736    async fn pull_manifest_inner(
1737        &self,
1738        image: &str,
1739        auth: &RegistryAuth,
1740        policy: PullPolicy,
1741    ) -> Result<(OciImageManifest, String)> {
1742        use zlayer_spec::SourcePolicy;
1743        let cache_key = manifest_cache_key(image);
1744        let digest_key = manifest_digest_cache_key(image);
1745        let source = self.source_policy;
1746
1747        // The resolution chain — LOCAL store -> local CACHE -> shared S3 tier ->
1748        // the ref's own registry (URL) -> last-resort default registry. Lower
1749        // tiers are populated ("propagated down") from a higher-authority hit so
1750        // the chain stays consistent. Mutable tags revalidate against the ORIGIN;
1751        // on any upstream-check error we serve the copy we already have
1752        // (fail-safe — serving stale beats crashing a redeploy on a Docker Hub
1753        // 429). Pinned tags / digests are immutable and never re-checked.
1754        //
1755        // `source` (the per-image [`SourcePolicy`]) selects which tiers run:
1756        //   - LocalFirst (default): the full chain, local CACHE before S3.
1757        //   - S3First:    like LocalFirst but probe S3 BEFORE the local cache.
1758        //   - LocalOnly:  local store + cache only; never S3/network/fallback.
1759        //   - RemoteOnly: skip every local/cached/S3 source; go to origin.
1760        // The local in-process CACHE is probed before the network S3 tier under
1761        // LocalFirst (faster; byte-identical for immutable, both revalidate vs
1762        // origin for mutable).
1763        let use_local = !matches!(source, SourcePolicy::RemoteOnly);
1764        let use_s3 = matches!(source, SourcePolicy::LocalFirst | SourcePolicy::S3First);
1765        let use_origin = !matches!(source, SourcePolicy::LocalOnly);
1766
1767        // 1. LOCAL store — owned/built images via the local registry. Highest
1768        //    authority for "we already have THIS image".
1769        #[cfg(feature = "local")]
1770        if use_local {
1771            if let Some((manifest, digest)) = self.try_local_registry(image).await {
1772                // Owned images warm the LOCAL cache only — never propagate a
1773                // locally-built manifest up into the shared S3 tier.
1774                self.warm_local_cache(image, &cache_key, &digest_key, &manifest, &digest)
1775                    .await;
1776
1777                // Serve local unless we may AND should revalidate a mutable tag
1778                // against the origin (never under LocalOnly / IfNotPresent / Never
1779                // / a pinned ref).
1780                let revalidate = use_origin
1781                    && !matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never)
1782                    && is_mutable_tag(image);
1783                if !revalidate {
1784                    return Ok((manifest, digest));
1785                }
1786                match self.remote_manifest_digest(image, auth).await {
1787                    Ok(Some(remote_digest)) if remote_digest != digest => {
1788                        tracing::info!(
1789                            image = %image,
1790                            local = %digest,
1791                            remote = %remote_digest,
1792                            "remote has newer manifest, pulling fresh"
1793                        );
1794                        // Newer upstream — fall through to the origin pull.
1795                    }
1796                    Ok(Some(_) | None) => return Ok((manifest, digest)),
1797                    Err(e) => {
1798                        tracing::warn!(image = %image, error = %e, "remote check failed, using local manifest");
1799                        return Ok((manifest, digest));
1800                    }
1801                }
1802                return self
1803                    .pull_from_origin(image, auth, &cache_key, &digest_key)
1804                    .await;
1805            }
1806        }
1807
1808        // 2 & 3. Local blob/manifest CACHE and the shared S3 tier, ordered by
1809        //    policy. Skipped entirely under RemoteOnly.
1810        if use_local {
1811            if matches!(source, SourcePolicy::S3First) {
1812                if let Some(hit) = self
1813                    .try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
1814                    .await
1815                {
1816                    return Ok(hit);
1817                }
1818                if let Some(hit) = self
1819                    .try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
1820                    .await
1821                {
1822                    return Ok(hit);
1823                }
1824            } else {
1825                if let Some(hit) = self
1826                    .try_cached_manifest(image, auth, &cache_key, &digest_key, policy)
1827                    .await
1828                {
1829                    return Ok(hit);
1830                }
1831                if use_s3 {
1832                    if let Some(hit) = self
1833                        .try_s3_manifest(image, auth, &cache_key, &digest_key, policy)
1834                        .await
1835                    {
1836                        return Ok(hit);
1837                    }
1838                }
1839            }
1840        }
1841
1842        // 4 & 5. Origin (the ref's own registry / configured default registry).
1843        //    Skipped under LocalOnly — a local miss there is a clean error.
1844        if !use_origin {
1845            return Err(RegistryError::NotFound {
1846                registry: "local".to_string(),
1847                image: format!(
1848                    "{image} (source_policy=local_only: not present in any local source \
1849                     and remote resolution is disabled for this image)"
1850                ),
1851            });
1852        }
1853        self.pull_from_origin(image, auth, &cache_key, &digest_key)
1854            .await
1855    }
1856
1857    /// Steps 4 & 5 of the chain: pull the manifest from the ref's OWN registry
1858    /// (URL), or — for a bare/unqualified name found nowhere locally — from the
1859    /// configured last-resort default registry. `ZLayer` NEVER silently invents
1860    /// docker.io: a bare name with no default registry configured is an
1861    /// actionable error. A successful pull is propagated DOWN the chain (local
1862    /// cache + S3). On remote failure, the local registry is the last resort.
1863    async fn pull_from_origin(
1864        &self,
1865        image: &str,
1866        auth: &RegistryAuth,
1867        cache_key: &str,
1868        digest_key: &str,
1869    ) -> Result<(OciImageManifest, String)> {
1870        let pull_ref: Reference = if zlayer_types::image_str_is_unqualified(image) {
1871            let Some(default) = self.default_registry.as_deref() else {
1872                // Bare/unqualified name, found nowhere local, and NO default
1873                // registry configured. This is a config dead-end, not a true
1874                // "not found" — emit one CLEAR, actionable log naming the
1875                // missing knob so the operator fixes the config rather than
1876                // hunting a cryptic NotFound. ZLayer never silently invents
1877                // docker.io for a bare name.
1878                tracing::error!(
1879                    image = %image,
1880                    missing_config = "ZLAYER_DEFAULT_REGISTRY",
1881                    "cannot resolve unqualified image: no default registry is configured. Set \
1882                     ZLAYER_DEFAULT_REGISTRY (or run `zlayer login --default <host>`) to pick the \
1883                     registry bare names resolve against, push a fully-qualified ref (e.g. \
1884                     registry.example.com/{image}), or `zlayer build` it locally"
1885                );
1886                return Err(RegistryError::NotFound {
1887                    registry: "local".to_string(),
1888                    image: format!(
1889                        "{image} (unqualified image not found locally and no default registry is \
1890                         configured: set ZLAYER_DEFAULT_REGISTRY or run `zlayer login --default \
1891                         <host>` to choose the registry bare names resolve against, use a full \
1892                         registry URL such as registry.example.com/{image} for a remote pull, or \
1893                         run `zlayer build` to produce it locally — ZLayer never silently pulls \
1894                         bare names from a public registry)"
1895                    ),
1896                });
1897            };
1898            let qualified = format!("{}/{}", default.trim_end_matches('/'), image);
1899            tracing::info!(
1900                image = %image,
1901                default_registry = %default,
1902                qualified = %qualified,
1903                "bare name resolved nowhere; using configured last-resort default registry"
1904            );
1905            qualified.parse().map_err(|_| RegistryError::NotFound {
1906                registry: default.to_string(),
1907                image: qualified.clone(),
1908            })?
1909        } else {
1910            image.parse().map_err(|_| RegistryError::NotFound {
1911                registry: "unknown".to_string(),
1912                image: image.to_string(),
1913            })?
1914        };
1915
1916        tracing::info!(image = %image, reference = %pull_ref, "pulling manifest from registry");
1917
1918        self.note_network_call();
1919        match self.client.pull_image_manifest(&pull_ref, auth).await {
1920            Ok((manifest, digest)) => {
1921                tracing::debug!(
1922                    image = %image,
1923                    digest = %digest,
1924                    layers = manifest.layers.len(),
1925                    "manifest pulled successfully"
1926                );
1927
1928                // Propagate DOWN the chain: both the local cache AND the shared
1929                // S3 tier get the fresh body so later resolves (here or on other
1930                // nodes) stay consistent.
1931                self.propagate_manifest_down(image, cache_key, digest_key, &manifest, &digest)
1932                    .await;
1933
1934                Ok((manifest, digest))
1935            }
1936            Err(remote_err) => {
1937                // Remote failed — try local registry as last resort.
1938                #[cfg(feature = "local")]
1939                if let Some((manifest, digest)) = self.try_local_registry(image).await {
1940                    tracing::warn!(
1941                        image = %image,
1942                        error = %remote_err,
1943                        "remote pull failed, falling back to local registry"
1944                    );
1945                    return Ok((manifest, digest));
1946                }
1947
1948                tracing::error!(error = %remote_err, image = %image, "failed to pull manifest");
1949                Err(RegistryError::Oci(remote_err))
1950            }
1951        }
1952    }
1953
1954    /// Record the user's ORIGINAL (as-typed) `image` ref in the local cache so
1955    /// `list_images` can surface it instead of the canonical key. Best-effort.
1956    /// One place writes this sidecar (called from both warm + propagate).
1957    async fn record_original_ref(&self, image: &str) {
1958        let _ = self
1959            .cache
1960            .put(&manifest_orig_cache_key(image), image.as_bytes())
1961            .await;
1962    }
1963
1964    /// Write a manifest body + digest into the LOCAL cache only (warming it from
1965    /// a higher-authority tier) and record the original ref. Best-effort —
1966    /// failures are ignored; the already-resolved manifest is still returned.
1967    async fn warm_local_cache(
1968        &self,
1969        image: &str,
1970        cache_key: &str,
1971        digest_key: &str,
1972        manifest: &OciImageManifest,
1973        digest: &str,
1974    ) {
1975        if let Ok(bytes) = serde_json::to_vec(manifest) {
1976            let _ = self.cache.put(cache_key, &bytes).await;
1977            let _ = self.cache.put(digest_key, digest.as_bytes()).await;
1978        }
1979        self.record_original_ref(image).await;
1980    }
1981
1982    /// Propagate a remote-origin manifest DOWN the chain: into the local cache
1983    /// AND the shared S3 tier (when configured), and record the original ref.
1984    /// Best-effort; an S3 write failure is logged and never fails the resolve.
1985    async fn propagate_manifest_down(
1986        &self,
1987        image: &str,
1988        cache_key: &str,
1989        digest_key: &str,
1990        manifest: &OciImageManifest,
1991        digest: &str,
1992    ) {
1993        let Ok(bytes) = serde_json::to_vec(manifest) else {
1994            return;
1995        };
1996        // Detect a moved mutable tag: if a *different* manifest digest was
1997        // cached for this ref, the superseded manifest's layers may now be
1998        // unreferenced and should be reclaimed once the new manifest is stored.
1999        let prev_digest = self
2000            .cache
2001            .get(digest_key)
2002            .await
2003            .ok()
2004            .flatten()
2005            .and_then(|b| String::from_utf8(b).ok());
2006        let tag_moved = matches!(prev_digest, Some(prev) if prev != digest);
2007
2008        let _ = self.cache.put(cache_key, &bytes).await;
2009        let _ = self.cache.put(digest_key, digest.as_bytes()).await;
2010        self.record_original_ref(image).await;
2011        if let Some(s3) = &self.s3_cache {
2012            if let Err(e) = s3.put(cache_key, &bytes).await {
2013                tracing::debug!(error = %e, "failed to propagate manifest body to S3 tier");
2014            }
2015            if let Err(e) = s3.put(digest_key, digest.as_bytes()).await {
2016                tracing::debug!(error = %e, "failed to propagate manifest digest to S3 tier");
2017            }
2018        }
2019
2020        // The new manifest is now stored, so reachability GC keeps its layers
2021        // (and every other cached image's). Reclaim only blobs that no surviving
2022        // manifest references — content-addressed, so layers still shared with
2023        // another image are preserved. Best-effort; never fails the resolve.
2024        if tag_moved {
2025            match crate::prune::prune_dangling_blobs(self.cache.as_ref().as_ref()).await {
2026                Ok((deleted, reclaimed)) if !deleted.is_empty() => {
2027                    tracing::info!(
2028                        image = %image,
2029                        superseded = deleted.len(),
2030                        reclaimed_bytes = reclaimed,
2031                        "reclaimed layers from a superseded manifest after tag update"
2032                    );
2033                }
2034                Ok(_) => {}
2035                Err(e) => {
2036                    tracing::debug!(image = %image, error = %e, "post-tag-update blob prune failed");
2037                }
2038            }
2039        }
2040    }
2041
2042    /// Probe the shared S3 tier for a cached manifest, mirroring
2043    /// [`Self::try_cached_manifest`]'s revalidation policy. A hit is written
2044    /// through to the LOCAL cache (warming it) before returning. Returns `None`
2045    /// when no S3 tier is configured, it misses, or its copy is stale vs origin.
2046    async fn try_s3_manifest(
2047        &self,
2048        image: &str,
2049        auth: &RegistryAuth,
2050        cache_key: &str,
2051        digest_key: &str,
2052        policy: PullPolicy,
2053    ) -> Option<(OciImageManifest, String)> {
2054        // No-S3 / unreachable-S3 / timeout all collapse to `None` (a miss) via
2055        // `s3_tier_get`, so a dead S3 tier can never propagate an error up the
2056        // resolution chain or hang it — the chain continues to origin/local.
2057        self.s3_cache.as_ref()?;
2058        let data = self.s3_tier_get(cache_key).await?;
2059        let manifest = parse_image_manifest_only(&data)?;
2060        let cached_digest = self
2061            .s3_tier_get(digest_key)
2062            .await
2063            .and_then(|b| String::from_utf8(b).ok());
2064
2065        // IfNotPresent/Never or pinned ref: serve without revalidation.
2066        if matches!(policy, PullPolicy::IfNotPresent | PullPolicy::Never) || !is_mutable_tag(image)
2067        {
2068            let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
2069            self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
2070                .await;
2071            tracing::debug!(image = %image, "manifest S3 tier hit");
2072            return Some((manifest, digest));
2073        }
2074
2075        // Mutable + Newer: revalidate against the origin registry.
2076        match self.remote_manifest_digest(image, auth).await {
2077            Ok(Some(remote_digest)) if cached_digest.as_deref() == Some(remote_digest.as_str()) => {
2078                self.warm_local_cache(image, cache_key, digest_key, &manifest, &remote_digest)
2079                    .await;
2080                tracing::debug!(image = %image, "manifest S3 tier hit (revalidated)");
2081                Some((manifest, remote_digest))
2082            }
2083            Ok(Some(_)) => {
2084                tracing::info!(image = %image, "S3 manifest stale vs origin, refetching");
2085                None
2086            }
2087            Ok(None) | Err(_) => {
2088                let digest = cached_digest.unwrap_or_else(|| crate::cache::compute_digest(&data));
2089                self.warm_local_cache(image, cache_key, digest_key, &manifest, &digest)
2090                    .await;
2091                tracing::warn!(image = %image, "S3 manifest revalidation unavailable, serving S3 copy");
2092                Some((manifest, digest))
2093            }
2094        }
2095    }
2096
2097    /// Resolve a manifest STRICTLY from local stores — the blob cache and (with
2098    /// the `local` feature) the local registry — with NO network call.
2099    ///
2100    /// Returns `Ok(Some(..))` on a local hit, `Ok(None)` when the image is not
2101    /// present locally. Unlike [`pull_manifest_inner`], a local miss never falls
2102    /// through to a remote pull, so a caller can probe several caches in turn
2103    /// without each miss triggering (and rate-limiting) a Docker Hub round-trip.
2104    ///
2105    /// This is the no-network half of the macOS image-OS-resolution fix: the
2106    /// composite runtime probes the VZ-Linux cache and then the primary Sandbox
2107    /// cache, and only hits the network as a deliberate final fallback.
2108    async fn resolve_manifest_local_only(&self, image: &str) -> Option<(OciImageManifest, String)> {
2109        let cache_key = manifest_cache_key(image);
2110        let digest_key = manifest_digest_cache_key(image);
2111
2112        // 1. Blob-cache content read FIRST — this is the authoritative source and
2113        //    must win before anything else. The pull writes the *resolved* (per-
2114        //    arch) manifest body under `manifest_cache_key(image)` (e.g.
2115        //    `manifest:docker.io/library/alpine:latest`), and the canonical key
2116        //    normalization (see `canonical_manifest_ref`) makes a BARE
2117        //    `alpine:latest` inspect collide with that qualified writer key.
2118        //
2119        //    Under `IfNotPresent`, `try_cached_manifest` returns the cached body
2120        //    with NO digest revalidation and NO network call (the network-only
2121        //    `Newer`/`Always` + mutable-tag branch is unreachable here). We must
2122        //    NOT route through the `manifest:digest-<ref>` sidecar to drive a
2123        //    by-digest fetch: that sidecar holds the multi-arch INDEX digest,
2124        //    which is never stored as content and is irrelevant to reading the
2125        //    already-resolved manifest. The blob-cache content read below is the
2126        //    one and only manifest source in the local-only path.
2127        if let Some(hit) = self
2128            .try_cached_manifest(
2129                image,
2130                &RegistryAuth::Anonymous,
2131                &cache_key,
2132                &digest_key,
2133                PullPolicy::IfNotPresent,
2134            )
2135            .await
2136        {
2137            return Some(hit);
2138        }
2139
2140        // 2. ONLY THEN consult the local registry, and treat every outcome as a
2141        //    pure hit-or-miss — `try_local_registry` returns `Option`, so a
2142        //    bare-name miss (and its "not found in registry local" log) is a
2143        //    `None` we fall through on, NEVER a propagated error that could
2144        //    short-circuit the caller before the blob-cache content was tried.
2145        //    On a hit, populate the blob cache so the next inspect is a direct
2146        //    content hit. This probe is local-disk only — no network.
2147        #[cfg(feature = "local")]
2148        if let Some((manifest, digest)) = self.try_local_registry(image).await {
2149            if let Ok(bytes) = serde_json::to_vec(&manifest) {
2150                let _ = self.cache.put(&cache_key, &bytes).await;
2151                let _ = self.cache.put(&digest_key, digest.as_bytes()).await;
2152            }
2153            return Some((manifest, digest));
2154        }
2155
2156        // 3. Genuine local miss. Return `None` (→ `Ok(None)` at the callers) so
2157        //    the composite runtime probes the next cache. NEVER fall through to
2158        //    a network fetch from a `*_local_only` / `*_in_cache_only` path.
2159        None
2160    }
2161
2162    /// Resolve `image`'s OCI `os` field STRICTLY from local stores, with no
2163    /// network call. Returns `Ok(None)` when the image (its manifest/config) is
2164    /// not present locally — the caller should then probe the next cache or, as
2165    /// a last resort, the network.
2166    ///
2167    /// # Errors
2168    /// Returns an error only when a locally-present config blob cannot be read
2169    /// or parsed — never for a plain local miss (that is `Ok(None)`).
2170    pub async fn image_os_in_cache_only(&self, image: &str) -> Result<Option<zlayer_spec::OsKind>> {
2171        let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2172            return Ok(None);
2173        };
2174
2175        let config_digest = &manifest.config.digest;
2176        // The config blob is content-addressed by digest; a local-only blob
2177        // read never hits the network. If it is somehow absent, treat it as a
2178        // local miss (Ok(None)) so the caller falls through rather than failing.
2179        let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
2180            return Ok(None);
2181        };
2182
2183        let config_root: OciImageConfigRoot =
2184            serde_json::from_slice(&config_blob).map_err(|e| {
2185                tracing::error!(
2186                    error = %e,
2187                    image = %image,
2188                    config_digest = %config_digest,
2189                    "failed to parse cached image config JSON for OS inspection"
2190                );
2191                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2192                    "failed to parse image config for {image}: {e}"
2193                )))
2194            })?;
2195
2196        Ok(config_root
2197            .os
2198            .as_deref()
2199            .and_then(zlayer_spec::OsKind::from_oci_str))
2200    }
2201
2202    /// Stamp a locally-built image's platform (`os` + architecture) into the
2203    /// blob cache so the no-network dispatch inspection can resolve it.
2204    ///
2205    /// This is the writer counterpart to [`Self::image_os_in_cache_only`]. A
2206    /// native build (e.g. the macOS Seatbelt builder) never goes through a
2207    /// registry, so nothing writes the manifest + config blob that the
2208    /// local-only OS read consumes. Without it a freshly built Mac-native bundle
2209    /// carries no `os` hint and the composite mis-routes it to the Linux VM. We
2210    /// write a MINIMAL OCI manifest (under [`manifest_cache_key`]) pointing at a
2211    /// config blob whose only meaningful fields are `os` and `architecture` —
2212    /// the same keyspace and shape a real pull leaves behind — plus the digest
2213    /// and original-ref sidecars. Idempotent: re-stamping overwrites the keys.
2214    ///
2215    /// # Errors
2216    /// Returns an error if the manifest or config blob cannot be serialized, or
2217    /// if a cache write fails.
2218    pub async fn cache_local_image_platform(
2219        &self,
2220        image: &str,
2221        os: &str,
2222        architecture: &str,
2223    ) -> Result<()> {
2224        // Minimal image config: only the platform fields the dispatch read
2225        // cares about, plus an empty runtime config. There is no layer to point
2226        // at (the rootfs lives on disk as a plain directory, not as cached
2227        // blobs), so we deliberately omit rootfs/diff_ids — this blob exists
2228        // purely to advertise the OS for routing.
2229        let config_json = serde_json::json!({
2230            "architecture": architecture,
2231            "os": os,
2232            "config": {},
2233        });
2234        let config_bytes = serde_json::to_vec(&config_json).map_err(|e| {
2235            RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2236                "failed to serialize local image config for {image}: {e}"
2237            )))
2238        })?;
2239        let config_digest = crate::cache::compute_digest(&config_bytes);
2240        self.cache.put(&config_digest, &config_bytes).await?;
2241
2242        // The manifest the local-only resolver reads back. It only needs to
2243        // reference the config blob by digest; no layers are cached for a native
2244        // build.
2245        let manifest = OciImageManifest {
2246            schema_version: 2,
2247            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
2248            artifact_type: None,
2249            config: oci_client::manifest::OciDescriptor {
2250                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
2251                digest: config_digest.clone(),
2252                size: i64::try_from(config_bytes.len()).unwrap_or(0),
2253                urls: None,
2254                annotations: None,
2255            },
2256            layers: vec![],
2257            annotations: None,
2258            subject: None,
2259        };
2260        let manifest_bytes = serde_json::to_vec(&manifest).map_err(|e| {
2261            RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2262                "failed to serialize local image manifest for {image}: {e}"
2263            )))
2264        })?;
2265        let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
2266
2267        // Write under the EXACT keys the reader uses (see `manifest_cache_key`):
2268        // manifest body, digest sidecar, and the original-ref sidecar so a
2269        // cache-driven `list_images` surfaces the canonical tag.
2270        self.cache
2271            .put(&manifest_cache_key(image), &manifest_bytes)
2272            .await?;
2273        self.cache
2274            .put(
2275                &manifest_digest_cache_key(image),
2276                manifest_digest.as_bytes(),
2277            )
2278            .await?;
2279        self.record_original_ref(image).await;
2280        Ok(())
2281    }
2282
2283    /// Resolve `image`'s `com.zlayer.runtime` manifest annotation STRICTLY from
2284    /// local stores, with no network call. `Ok(None)` on a local miss (or when
2285    /// the annotation is absent).
2286    ///
2287    /// # Errors
2288    /// Currently infallible in practice; the `Result` mirrors
2289    /// [`ImagePuller::image_os_in_cache_only`] for a uniform caller contract.
2290    pub async fn image_runtime_marker_in_cache_only(&self, image: &str) -> Result<Option<String>> {
2291        let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2292            return Ok(None);
2293        };
2294        Ok(manifest
2295            .annotations
2296            .as_ref()
2297            .and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
2298    }
2299
2300    /// Resolve `image`'s [`crate::ZLAYER_ISOLATION_ANNOTATION`]
2301    /// (`com.zlayer.isolation`) image-declared isolation default STRICTLY from
2302    /// local stores, with no network call. `Ok(None)` on a local miss (or when
2303    /// the label is absent).
2304    ///
2305    /// Unlike [`Self::image_runtime_marker_in_cache_only`] (a *manifest*
2306    /// annotation), the isolation default is an image **config label**, so this
2307    /// reads the cached CONFIG blob's `config.Labels` — mirroring
2308    /// [`Self::image_os_in_cache_only`], which reads the same blob's `os` field.
2309    ///
2310    /// # Errors
2311    /// Returns an error only when a locally-present config blob cannot be
2312    /// parsed — never for a plain local miss (that is `Ok(None)`).
2313    pub async fn image_isolation_marker_in_cache_only(
2314        &self,
2315        image: &str,
2316    ) -> Result<Option<String>> {
2317        let Some((manifest, _digest)) = self.resolve_manifest_local_only(image).await else {
2318            return Ok(None);
2319        };
2320
2321        let config_digest = &manifest.config.digest;
2322        // Content-addressed config blob: a local-only read never hits the
2323        // network. A missing blob is treated as a local miss so the caller
2324        // probes the next cache rather than failing.
2325        let Some(config_blob) = self.cache.get(config_digest).await.ok().flatten() else {
2326            return Ok(None);
2327        };
2328
2329        let config_root: OciImageConfigRoot =
2330            serde_json::from_slice(&config_blob).map_err(|e| {
2331                tracing::error!(
2332                    error = %e,
2333                    image = %image,
2334                    config_digest = %config_digest,
2335                    "failed to parse cached image config JSON for isolation inspection"
2336                );
2337                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2338                    "failed to parse image config for {image}: {e}"
2339                )))
2340            })?;
2341
2342        Ok(config_root
2343            .config
2344            .and_then(|c| c.labels)
2345            .and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
2346    }
2347
2348    /// Pull an image manifest, honoring the requested [`PullPolicy`].
2349    ///
2350    /// `PullPolicy::Always` invalidates any cached manifest entry before the
2351    /// fetch, guaranteeing a fresh round-trip to the registry.
2352    /// `PullPolicy::Newer` preserves the legacy revalidate-mutable-tag
2353    /// behavior. `PullPolicy::IfNotPresent` and `PullPolicy::Never` trust the
2354    /// blob cache / local registry and skip the remote HEAD revalidation that
2355    /// would otherwise fail for locally-built images sitting behind a 401.
2356    ///
2357    /// # Errors
2358    ///
2359    /// Returns an error if the manifest cannot be pulled or the image
2360    /// reference is invalid.
2361    pub async fn pull_manifest_with_policy(
2362        &self,
2363        image: &str,
2364        auth: &RegistryAuth,
2365        policy: PullPolicy,
2366    ) -> Result<(OciImageManifest, String)> {
2367        let force_refresh = matches!(policy, PullPolicy::Always);
2368        if force_refresh {
2369            let cache_key = manifest_cache_key(image);
2370            let digest_key = manifest_digest_cache_key(image);
2371            if let Err(e) = self.cache.delete(&cache_key).await {
2372                tracing::warn!(
2373                    image = %image,
2374                    error = %e,
2375                    "failed to invalidate manifest cache for force refresh"
2376                );
2377            }
2378            if let Err(e) = self.cache.delete(&digest_key).await {
2379                tracing::warn!(
2380                    image = %image,
2381                    error = %e,
2382                    "failed to invalidate manifest digest cache for force refresh"
2383                );
2384            }
2385        }
2386        self.pull_manifest_inner(image, auth, policy).await
2387    }
2388
2389    /// Pull and parse the image configuration from the registry.
2390    ///
2391    /// This fetches the manifest, extracts the config blob digest, pulls the
2392    /// config blob, and parses it to extract container runtime defaults like
2393    /// `Entrypoint`, `Cmd`, `WorkingDir`, `Env`, and `User`.
2394    ///
2395    /// # Arguments
2396    ///
2397    /// * `image` - Image reference (e.g., "docker.io/library/nginx:latest")
2398    /// * `auth` - Registry authentication credentials
2399    ///
2400    /// # Returns
2401    ///
2402    /// Returns the parsed `ImageConfig` containing the container runtime defaults.
2403    /// If the image config blob has no `config` section, returns a default (empty)
2404    /// `ImageConfig`.
2405    ///
2406    /// # Errors
2407    ///
2408    /// Returns an error if the manifest or config blob cannot be fetched, or if
2409    /// the config blob cannot be parsed as valid JSON.
2410    pub async fn pull_image_config(&self, image: &str, auth: &RegistryAuth) -> Result<ImageConfig> {
2411        self.pull_image_config_inner(image, auth, PullPolicy::Newer)
2412            .await
2413    }
2414
2415    /// Internal config pull driven by an explicit [`PullPolicy`].
2416    async fn pull_image_config_inner(
2417        &self,
2418        image: &str,
2419        auth: &RegistryAuth,
2420        policy: PullPolicy,
2421    ) -> Result<ImageConfig> {
2422        let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2423
2424        let config_digest = &manifest.config.digest;
2425
2426        tracing::debug!(
2427            image = %image,
2428            config_digest = %config_digest,
2429            config_media_type = %manifest.config.media_type,
2430            "fetching image config blob"
2431        );
2432
2433        let config_blob = self.pull_blob(image, config_digest, auth).await?;
2434
2435        let config_root: OciImageConfigRoot =
2436            serde_json::from_slice(&config_blob).map_err(|e| {
2437                tracing::error!(
2438                    error = %e,
2439                    image = %image,
2440                    config_digest = %config_digest,
2441                    "failed to parse image config JSON"
2442                );
2443                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2444                    "failed to parse image config for {image}: {e}"
2445                )))
2446            })?;
2447
2448        let config = config_root.config.unwrap_or_default();
2449
2450        tracing::info!(
2451            image = %image,
2452            has_entrypoint = config.entrypoint.is_some(),
2453            has_cmd = config.cmd.is_some(),
2454            has_working_dir = config.working_dir.is_some(),
2455            has_user = config.user.is_some(),
2456            env_count = config.env.as_ref().map_or(0, std::vec::Vec::len),
2457            "image config parsed successfully"
2458        );
2459
2460        Ok(config)
2461    }
2462
2463    /// Pull and parse the image configuration, honoring the requested
2464    /// [`PullPolicy`].
2465    ///
2466    /// `PullPolicy::Always` invalidates the cached manifest entry before
2467    /// fetching. The config blob itself is content-addressed by digest, so it
2468    /// does not need explicit invalidation — once the refreshed manifest
2469    /// points at a new config digest, the existing blob-cache lookup will
2470    /// naturally miss and refetch. `PullPolicy::IfNotPresent` and
2471    /// `PullPolicy::Never` skip remote revalidation entirely when a manifest
2472    /// is already cached.
2473    ///
2474    /// # Errors
2475    ///
2476    /// Returns an error if the manifest or config blob cannot be fetched, or
2477    /// if the config blob cannot be parsed as valid JSON.
2478    pub async fn pull_image_config_with_policy(
2479        &self,
2480        image: &str,
2481        auth: &RegistryAuth,
2482        policy: PullPolicy,
2483    ) -> Result<ImageConfig> {
2484        let force_refresh = matches!(policy, PullPolicy::Always);
2485        if force_refresh {
2486            let cache_key = manifest_cache_key(image);
2487            let digest_key = manifest_digest_cache_key(image);
2488            if let Err(e) = self.cache.delete(&cache_key).await {
2489                tracing::warn!(
2490                    image = %image,
2491                    error = %e,
2492                    "failed to invalidate manifest cache for force refresh"
2493                );
2494            }
2495            if let Err(e) = self.cache.delete(&digest_key).await {
2496                tracing::warn!(
2497                    image = %image,
2498                    error = %e,
2499                    "failed to invalidate manifest digest cache for force refresh"
2500                );
2501            }
2502        }
2503        // Single-flight the config fetch: a CI burst of N creates of the same
2504        // image each calls this after the (already-deduped) layer pull, and each
2505        // would otherwise fetch the small config blob over the wire until one
2506        // populates the cache. The config is a pure owned value with no per-call
2507        // staging state, so — unlike the layer pull — the parsed result is
2508        // shared by-clone among all followers; there is nothing caller-specific
2509        // to keep separate. `Always` already cleared the manifest cache above,
2510        // so the leader re-fetches; followers ride the same fresh result.
2511        let key = self.pull_singleflight_key(image, policy);
2512        let (slot, is_leader) = {
2513            let mut map = config_singleflight().lock().await;
2514            if let Some(existing) = map.get(&key).and_then(std::sync::Weak::upgrade) {
2515                (existing, false)
2516            } else {
2517                let fresh: Arc<ConfigSlot> = Arc::new(tokio::sync::OnceCell::new());
2518                map.insert(key.clone(), Arc::downgrade(&fresh));
2519                (fresh, true)
2520            }
2521        };
2522
2523        let outcome = slot
2524            .get_or_init(|| async {
2525                self.pull_image_config_inner(image, auth, policy)
2526                    .await
2527                    .map_err(|e| e.to_string())
2528            })
2529            .await
2530            .clone();
2531
2532        if is_leader {
2533            // Drop the entry once resolved so a later fetch re-runs (mutable-tag
2534            // revalidation, or a config evicted from the cache).
2535            config_singleflight().lock().await.remove(&key);
2536        }
2537
2538        outcome.map_err(|msg| {
2539            RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2540                "image config fetch failed for {image}: {msg}"
2541            )))
2542        })
2543    }
2544
2545    /// Fetch the operating system targeted by `image` from its OCI config blob.
2546    ///
2547    /// Reads the top-level `os` field (OCI-canonical lowercase, e.g.
2548    /// `"linux"` / `"windows"` / `"darwin"`) from the image config and
2549    /// converts it via [`zlayer_spec::OsKind::from_oci_str`]. Multi-platform
2550    /// indexes are resolved by the puller's configured `platform_resolver`
2551    /// (set at construction time), so the answer reflects the manifest that
2552    /// would actually be pulled for this host.
2553    ///
2554    /// Returns:
2555    /// * `Ok(Some(os))` when the config blob carries a recognized OS.
2556    /// * `Ok(None)` when the `os` field is absent or holds an unknown value —
2557    ///   the caller should treat this as "fall through to a platform-agnostic
2558    ///   default" rather than an error.
2559    ///
2560    /// # Errors
2561    ///
2562    /// Returns an error if the manifest or config blob cannot be fetched, or
2563    /// if the config blob cannot be parsed as valid JSON.
2564    pub async fn image_os(
2565        &self,
2566        image: &str,
2567        auth: &RegistryAuth,
2568    ) -> Result<Option<zlayer_spec::OsKind>> {
2569        self.image_os_with_policy(image, auth, PullPolicy::Newer)
2570            .await
2571    }
2572
2573    /// Like [`ImagePuller::image_os`] but honoring an explicit [`PullPolicy`].
2574    ///
2575    /// The composite runtime's OS dispatch path drives this with
2576    /// [`PullPolicy::IfNotPresent`] so that a locally-cached image (its config
2577    /// blob already in the persistent blob cache / local registry) is inspected
2578    /// WITHOUT any network round-trip. This is what keeps a Linux image routing
2579    /// to the VZ-Linux runtime under a Docker Hub rate-limit: the OS comes from
2580    /// the local store the pull already wrote, never a re-inspection over the
2581    /// wire. `IfNotPresent`/`Never` cause [`pull_manifest_inner`] to trust the
2582    /// cache without the mutable-tag HEAD revalidation that `Newer` would do.
2583    ///
2584    /// # Errors
2585    ///
2586    /// Returns an error if the manifest or config blob cannot be fetched, or
2587    /// if the config blob cannot be parsed as valid JSON.
2588    pub async fn image_os_with_policy(
2589        &self,
2590        image: &str,
2591        auth: &RegistryAuth,
2592        policy: PullPolicy,
2593    ) -> Result<Option<zlayer_spec::OsKind>> {
2594        let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2595
2596        let config_digest = &manifest.config.digest;
2597        let config_blob = self.pull_blob(image, config_digest, auth).await?;
2598
2599        let config_root: OciImageConfigRoot =
2600            serde_json::from_slice(&config_blob).map_err(|e| {
2601                tracing::error!(
2602                    error = %e,
2603                    image = %image,
2604                    config_digest = %config_digest,
2605                    "failed to parse image config JSON for OS inspection"
2606                );
2607                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2608                    "failed to parse image config for {image}: {e}"
2609                )))
2610            })?;
2611
2612        Ok(config_root
2613            .os
2614            .as_deref()
2615            .and_then(zlayer_spec::OsKind::from_oci_str))
2616    }
2617
2618    /// Read the [`crate::ZLAYER_RUNTIME_ANNOTATION`] manifest annotation, used by
2619    /// the agent's composite runtime to auto-detect runtime-specific bundles
2620    /// (e.g. a macOS VZ base bundle published by `zlayer vz build-base`, which
2621    /// stamps `com.zlayer.runtime=vz`). Returns `Ok(None)` for ordinary images.
2622    ///
2623    /// # Errors
2624    /// Returns an error if the manifest cannot be fetched or parsed.
2625    pub async fn image_runtime_marker(
2626        &self,
2627        image: &str,
2628        auth: &RegistryAuth,
2629    ) -> Result<Option<String>> {
2630        self.image_runtime_marker_with_policy(image, auth, PullPolicy::Newer)
2631            .await
2632    }
2633
2634    /// Like [`ImagePuller::image_runtime_marker`] but honoring an explicit
2635    /// [`PullPolicy`]. The composite runtime drives this with
2636    /// [`PullPolicy::IfNotPresent`] so the `com.zlayer.runtime` marker resolves
2637    /// from the already-pulled local manifest without a network re-fetch.
2638    ///
2639    /// # Errors
2640    /// Returns an error if the manifest cannot be fetched or parsed.
2641    pub async fn image_runtime_marker_with_policy(
2642        &self,
2643        image: &str,
2644        auth: &RegistryAuth,
2645        policy: PullPolicy,
2646    ) -> Result<Option<String>> {
2647        let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2648        Ok(manifest
2649            .annotations
2650            .as_ref()
2651            .and_then(|a| a.get(crate::ZLAYER_RUNTIME_ANNOTATION).cloned()))
2652    }
2653
2654    /// Read the [`crate::ZLAYER_ISOLATION_ANNOTATION`] image-declared isolation
2655    /// default (`com.zlayer.isolation`) from `image`'s OCI config blob, honoring
2656    /// an explicit [`PullPolicy`]. Mirrors [`Self::image_os_with_policy`]: the
2657    /// composite runtime drives this with [`PullPolicy::IfNotPresent`] so the
2658    /// label resolves from the already-pulled local config blob without a
2659    /// network re-fetch. Returns `Ok(None)` for images that declare no default.
2660    ///
2661    /// # Errors
2662    /// Returns an error if the manifest or config blob cannot be fetched, or if
2663    /// the config blob cannot be parsed.
2664    pub async fn image_isolation_marker_with_policy(
2665        &self,
2666        image: &str,
2667        auth: &RegistryAuth,
2668        policy: PullPolicy,
2669    ) -> Result<Option<String>> {
2670        let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2671
2672        let config_digest = &manifest.config.digest;
2673        let config_blob = self.pull_blob(image, config_digest, auth).await?;
2674
2675        let config_root: OciImageConfigRoot =
2676            serde_json::from_slice(&config_blob).map_err(|e| {
2677                tracing::error!(
2678                    error = %e,
2679                    image = %image,
2680                    config_digest = %config_digest,
2681                    "failed to parse image config JSON for isolation inspection"
2682                );
2683                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2684                    "failed to parse image config for {image}: {e}"
2685                )))
2686            })?;
2687
2688        Ok(config_root
2689            .config
2690            .and_then(|c| c.labels)
2691            .and_then(|l| l.get(crate::ZLAYER_ISOLATION_ANNOTATION).cloned()))
2692    }
2693
2694    /// Fetch the `os.version` string carried by `image`'s OCI config blob.
2695    ///
2696    /// For Windows images this corresponds to the host build identifier
2697    /// (e.g. `"10.0.20348.2031"`) recorded by the image builder, and is the
2698    /// value the HCS runtime needs to auto-resolve process vs. Hyper-V
2699    /// isolation against the running host's build. Most Linux images do not
2700    /// record this field.
2701    ///
2702    /// Returns:
2703    /// * `Ok(Some(version))` when the config blob carries an `os.version`.
2704    /// * `Ok(None)` when the field is absent — callers should treat this as
2705    ///   "no builder-asserted version, fall through to a runtime default"
2706    ///   rather than an error.
2707    ///
2708    /// # Errors
2709    ///
2710    /// Returns an error if the manifest or config blob cannot be fetched, or
2711    /// if the config blob cannot be parsed as valid JSON.
2712    pub async fn image_os_version(
2713        &self,
2714        image: &str,
2715        auth: &RegistryAuth,
2716    ) -> Result<Option<String>> {
2717        let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2718
2719        let config_digest = &manifest.config.digest;
2720        let config_blob = self.pull_blob(image, config_digest, auth).await?;
2721
2722        let config_root: OciImageConfigRoot =
2723            serde_json::from_slice(&config_blob).map_err(|e| {
2724                tracing::error!(
2725                    error = %e,
2726                    image = %image,
2727                    config_digest = %config_digest,
2728                    "failed to parse image config JSON for os.version inspection"
2729                );
2730                RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
2731                    "failed to parse image config for {image}: {e}"
2732                )))
2733            })?;
2734
2735        Ok(config_root.os_version)
2736    }
2737
2738    /// Detect the artifact type of an image from its manifest
2739    ///
2740    /// This method pulls the manifest and determines whether the image is a
2741    /// traditional container image or a WASM artifact.
2742    ///
2743    /// # Arguments
2744    ///
2745    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
2746    /// * `auth` - Registry authentication credentials
2747    ///
2748    /// # Returns
2749    ///
2750    /// Returns the detected `ArtifactType` along with the manifest and digest.
2751    ///
2752    /// # Errors
2753    ///
2754    /// Returns an error if the manifest cannot be pulled.
2755    pub async fn detect_artifact_type(
2756        &self,
2757        image: &str,
2758        auth: &RegistryAuth,
2759    ) -> Result<(ArtifactType, OciImageManifest, String)> {
2760        let (manifest, digest) = self.pull_manifest(image, auth).await?;
2761        let artifact_type = detect_artifact_type(&manifest);
2762
2763        tracing::info!(
2764            image = %image,
2765            artifact_type = %artifact_type,
2766            "detected artifact type"
2767        );
2768
2769        Ok((artifact_type, manifest, digest))
2770    }
2771
2772    /// Extract WASM artifact information from an image
2773    ///
2774    /// This method pulls the manifest and extracts detailed information about
2775    /// a WASM artifact, including WASI version, layer digest, and module name.
2776    ///
2777    /// # Arguments
2778    ///
2779    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
2780    /// * `auth` - Registry authentication credentials
2781    ///
2782    /// # Returns
2783    ///
2784    /// Returns `Some(WasmArtifactInfo)` if this is a WASM artifact, `None` otherwise.
2785    ///
2786    /// # Errors
2787    ///
2788    /// Returns an error if the manifest cannot be pulled.
2789    pub async fn get_wasm_info(
2790        &self,
2791        image: &str,
2792        auth: &RegistryAuth,
2793    ) -> Result<Option<WasmArtifactInfo>> {
2794        let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2795        Ok(extract_wasm_info(&manifest))
2796    }
2797
2798    /// Pull a WASM binary from an image
2799    ///
2800    /// This method pulls the manifest, verifies it's a WASM artifact, and
2801    /// returns the raw WASM binary bytes.
2802    ///
2803    /// # Arguments
2804    ///
2805    /// * `image` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
2806    /// * `auth` - Registry authentication credentials
2807    ///
2808    /// # Returns
2809    ///
2810    /// Returns the WASM binary bytes if this is a WASM artifact.
2811    ///
2812    /// # Errors
2813    ///
2814    /// Returns an error if this is not a WASM artifact or if the WASM layer
2815    /// cannot be found.
2816    pub async fn pull_wasm(
2817        &self,
2818        image: &str,
2819        auth: &RegistryAuth,
2820    ) -> Result<(Vec<u8>, WasmArtifactInfo)> {
2821        let (manifest, _digest) = self.pull_manifest(image, auth).await?;
2822
2823        let wasm_info = extract_wasm_info(&manifest).ok_or_else(|| RegistryError::NotFound {
2824            registry: "unknown".to_string(),
2825            image: format!("{image} (not a WASM artifact)"),
2826        })?;
2827
2828        let wasm_digest =
2829            wasm_info
2830                .wasm_layer_digest
2831                .as_ref()
2832                .ok_or_else(|| RegistryError::NotFound {
2833                    registry: "unknown".to_string(),
2834                    image: format!("{image} (no WASM layer found)"),
2835                })?;
2836
2837        tracing::info!(
2838            image = %image,
2839            wasi_version = %wasm_info.wasi_version,
2840            wasm_digest = %wasm_digest,
2841            "pulling WASM binary"
2842        );
2843
2844        let wasm_bytes = self.pull_blob(image, wasm_digest, auth).await?;
2845
2846        tracing::info!(
2847            image = %image,
2848            wasm_size = wasm_bytes.len(),
2849            "WASM binary pulled successfully"
2850        );
2851
2852        Ok((wasm_bytes, wasm_info))
2853    }
2854
2855    /// Pull a complete image (manifest + all layers)
2856    ///
2857    /// Returns a vector of (`layer_data`, `media_type`) tuples in order (base layer first).
2858    ///
2859    /// # Errors
2860    ///
2861    /// Returns an error if the manifest or any layer cannot be pulled.
2862    pub async fn pull_image(
2863        &self,
2864        image: &str,
2865        auth: &RegistryAuth,
2866    ) -> Result<Vec<(Vec<u8>, String)>> {
2867        self.pull_image_inner(image, auth, PullPolicy::Newer).await
2868    }
2869
2870    /// Internal image pull driven by an explicit [`PullPolicy`].
2871    async fn pull_image_inner(
2872        &self,
2873        image: &str,
2874        auth: &RegistryAuth,
2875        policy: PullPolicy,
2876    ) -> Result<Vec<(Vec<u8>, String)>> {
2877        // Pull manifest first
2878        let (manifest, _digest) = self.pull_manifest_inner(image, auth, policy).await?;
2879
2880        tracing::info!(
2881            image = %image,
2882            layer_count = manifest.layers.len(),
2883            "pulling image layers"
2884        );
2885
2886        // Pull layers concurrently (bounded). `buffered` preserves submission
2887        // order, so the returned Vec stays in layer order. Network concurrency
2888        // is additionally capped by the shared `concurrency_limit` semaphore
2889        // acquired inside `pull_blob_with_urls`.
2890        // Snapshot per-layer inputs into owned values first (see the streamed
2891        // path for why a borrowed-argument future trips HRTB under `#[instrument]`).
2892        let layer_inputs: Vec<(usize, String, String, Vec<String>, i64)> = manifest
2893            .layers
2894            .iter()
2895            .enumerate()
2896            .map(|(i, l)| {
2897                (
2898                    i,
2899                    l.digest.clone(),
2900                    l.media_type.clone(),
2901                    l.urls.clone().unwrap_or_default(),
2902                    l.size,
2903                )
2904            })
2905            .collect();
2906        let layers: Vec<(Vec<u8>, String)> =
2907            futures_util::stream::iter(layer_inputs.into_iter().map(
2908                |(i, digest, media_type, urls, size)| async move {
2909                    tracing::debug!(
2910                        layer = i,
2911                        digest = %digest,
2912                        media_type = %media_type,
2913                        size,
2914                        "pulling layer"
2915                    );
2916
2917                    let data = self
2918                        .pull_blob_with_urls(image, &digest, auth, &urls, Some(size))
2919                        .await?;
2920
2921                    // Validate layer data is not empty
2922                    if data.is_empty() {
2923                        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
2924                            format!("layer {i} ({digest}) is empty after pull"),
2925                        )));
2926                    }
2927
2928                    Ok::<(Vec<u8>, String), RegistryError>((data, media_type))
2929                },
2930            ))
2931            .buffered(LAYER_PULL_CONCURRENCY)
2932            .try_collect()
2933            .await?;
2934
2935        tracing::info!(
2936            image = %image,
2937            layers_pulled = layers.len(),
2938            "image pull complete"
2939        );
2940
2941        Ok(layers)
2942    }
2943
2944    /// Pull a complete image, honoring the requested [`PullPolicy`].
2945    ///
2946    /// `PullPolicy::Always` invalidates the cached manifest entry before
2947    /// fetching. Layer blobs are content-addressed by digest, so they do not
2948    /// need explicit invalidation — once the refreshed manifest points at new
2949    /// layer digests, the existing blob-cache lookups will naturally miss and
2950    /// refetch the new layers. Shared layer blobs remain valid cache hits.
2951    /// `PullPolicy::IfNotPresent` and `PullPolicy::Never` trust the cache /
2952    /// local registry without revalidating mutable tags against the remote.
2953    ///
2954    /// # Errors
2955    ///
2956    /// Returns an error if the manifest or any layer cannot be pulled.
2957    pub async fn pull_image_with_policy(
2958        &self,
2959        image: &str,
2960        auth: &RegistryAuth,
2961        policy: PullPolicy,
2962    ) -> Result<Vec<(Vec<u8>, String)>> {
2963        let force_refresh = matches!(policy, PullPolicy::Always);
2964        if force_refresh {
2965            let cache_key = manifest_cache_key(image);
2966            let digest_key = manifest_digest_cache_key(image);
2967            if let Err(e) = self.cache.delete(&cache_key).await {
2968                tracing::warn!(
2969                    image = %image,
2970                    error = %e,
2971                    "failed to invalidate manifest cache for force refresh"
2972                );
2973            }
2974            if let Err(e) = self.cache.delete(&digest_key).await {
2975                tracing::warn!(
2976                    image = %image,
2977                    error = %e,
2978                    "failed to invalidate manifest digest cache for force refresh"
2979                );
2980            }
2981        }
2982        self.pull_image_inner(image, auth, policy).await
2983    }
2984
2985    /// Push a blob to a remote registry
2986    ///
2987    /// Uploads a blob (layer or config) to the specified registry. The blob is
2988    /// identified by its digest and will be stored at the repository specified
2989    /// in the reference.
2990    ///
2991    /// # Arguments
2992    ///
2993    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
2994    /// * `digest` - Content digest of the blob (e.g., "sha256:abc123...")
2995    /// * `data` - Raw blob data to upload
2996    /// * `_media_type` - MIME type of the blob content (reserved for future use)
2997    /// * `auth` - Registry authentication credentials
2998    ///
2999    /// # Errors
3000    ///
3001    /// Returns an error if:
3002    /// - The reference is invalid
3003    /// - Authentication fails
3004    /// - The blob upload fails
3005    #[instrument(
3006        name = "push_blob",
3007        skip(self, data, auth, _media_type),
3008        fields(
3009            reference = %reference,
3010            digest = %digest,
3011            size = data.len(),
3012        )
3013    )]
3014    pub async fn push_blob(
3015        &self,
3016        reference: &str,
3017        digest: &str,
3018        data: &[u8],
3019        _media_type: &str,
3020        auth: &RegistryAuth,
3021    ) -> std::result::Result<(), PushError> {
3022        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3023            reference: reference.to_string(),
3024        })?;
3025
3026        tracing::debug!(
3027            reference = %reference,
3028            digest = %digest,
3029            size = data.len(),
3030            "pushing blob to registry"
3031        );
3032
3033        // Authenticate for push operation
3034        self.client
3035            .auth(&image_ref, auth, RegistryOperation::Push)
3036            .await
3037            .map_err(|e| PushError::AuthenticationFailed {
3038                registry: image_ref.resolve_registry().to_string(),
3039                reason: e.to_string(),
3040            })?;
3041
3042        // Push the blob
3043        self.client
3044            .push_blob(&image_ref, data, digest)
3045            .await
3046            .map_err(|e| PushError::BlobUploadFailed {
3047                digest: digest.to_string(),
3048                reason: e.to_string(),
3049            })?;
3050
3051        tracing::info!(
3052            reference = %reference,
3053            digest = %digest,
3054            size = data.len(),
3055            "blob pushed successfully"
3056        );
3057
3058        Ok(())
3059    }
3060
3061    /// Push a manifest to a remote registry
3062    ///
3063    /// Uploads an OCI image manifest to the specified registry. The manifest
3064    /// should reference blobs that have already been uploaded.
3065    ///
3066    /// # Arguments
3067    ///
3068    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
3069    /// * `manifest` - OCI image manifest to upload
3070    /// * `auth` - Registry authentication credentials
3071    ///
3072    /// # Returns
3073    ///
3074    /// Returns the manifest digest on success.
3075    ///
3076    /// # Errors
3077    ///
3078    /// Returns an error if:
3079    /// - The reference is invalid
3080    /// - Authentication fails
3081    /// - The manifest upload fails
3082    #[instrument(
3083        name = "push_manifest_to_registry",
3084        skip(self, manifest, auth),
3085        fields(
3086            reference = %reference,
3087            layers = manifest.layers.len(),
3088        )
3089    )]
3090    pub async fn push_manifest_to_registry(
3091        &self,
3092        reference: &str,
3093        manifest: &OciImageManifest,
3094        auth: &RegistryAuth,
3095    ) -> std::result::Result<String, PushError> {
3096        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3097            reference: reference.to_string(),
3098        })?;
3099
3100        tracing::debug!(
3101            reference = %reference,
3102            layers = manifest.layers.len(),
3103            config_digest = %manifest.config.digest,
3104            "pushing manifest to registry"
3105        );
3106
3107        // Authenticate for push operation
3108        self.client
3109            .auth(&image_ref, auth, RegistryOperation::Push)
3110            .await
3111            .map_err(|e| PushError::AuthenticationFailed {
3112                registry: image_ref.resolve_registry().to_string(),
3113                reason: e.to_string(),
3114            })?;
3115
3116        // Push the manifest
3117        let manifest_url = self
3118            .client
3119            .push_manifest(&image_ref, &OciManifest::Image(manifest.clone()))
3120            .await
3121            .map_err(|e| PushError::ManifestUploadFailed {
3122                reason: e.to_string(),
3123            })?;
3124
3125        // Extract digest from the manifest URL or compute it
3126        // The manifest URL typically contains the digest after the @ symbol
3127        let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3128            manifest_url[digest_start + 1..].to_string()
3129        } else {
3130            // Compute digest from manifest JSON
3131            let manifest_json =
3132                serde_json::to_vec(manifest).map_err(|e| PushError::ManifestUploadFailed {
3133                    reason: format!("failed to serialize manifest: {e}"),
3134                })?;
3135            crate::cache::compute_digest(&manifest_json)
3136        };
3137
3138        tracing::info!(
3139            reference = %reference,
3140            digest = %digest,
3141            manifest_url = %manifest_url,
3142            "manifest pushed successfully"
3143        );
3144
3145        Ok(digest)
3146    }
3147
3148    /// Push an OCI image index (manifest list) to a remote registry.
3149    ///
3150    /// Used for multi-platform images where each platform has its own manifest
3151    /// and the index ties them together.
3152    ///
3153    /// # Errors
3154    ///
3155    /// Returns an error if the reference is invalid, authentication fails, or
3156    /// the index upload fails.
3157    #[instrument(
3158        name = "push_image_index_to_registry",
3159        skip(self, index, auth),
3160        fields(
3161            reference = %reference,
3162            manifests = index.manifests.len(),
3163        )
3164    )]
3165    pub async fn push_image_index_to_registry(
3166        &self,
3167        reference: &str,
3168        index: &OciImageIndex,
3169        auth: &RegistryAuth,
3170    ) -> std::result::Result<String, PushError> {
3171        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3172            reference: reference.to_string(),
3173        })?;
3174
3175        tracing::debug!(
3176            reference = %reference,
3177            manifests = index.manifests.len(),
3178            "pushing image index to registry"
3179        );
3180
3181        // Authenticate for push operation
3182        self.client
3183            .auth(&image_ref, auth, RegistryOperation::Push)
3184            .await
3185            .map_err(|e| PushError::AuthenticationFailed {
3186                registry: image_ref.resolve_registry().to_string(),
3187                reason: e.to_string(),
3188            })?;
3189
3190        // Push the image index
3191        let manifest_url = self
3192            .client
3193            .push_manifest(&image_ref, &OciManifest::ImageIndex(index.clone()))
3194            .await
3195            .map_err(|e| PushError::ManifestUploadFailed {
3196                reason: e.to_string(),
3197            })?;
3198
3199        let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3200            manifest_url[digest_start + 1..].to_string()
3201        } else {
3202            let index_json =
3203                serde_json::to_vec(index).map_err(|e| PushError::ManifestUploadFailed {
3204                    reason: format!("failed to serialize image index: {e}"),
3205                })?;
3206            crate::cache::compute_digest(&index_json)
3207        };
3208
3209        tracing::info!(
3210            reference = %reference,
3211            digest = %digest,
3212            "image index pushed successfully"
3213        );
3214
3215        Ok(digest)
3216    }
3217
3218    /// Push a pre-serialised manifest blob verbatim to a remote registry.
3219    ///
3220    /// Unlike [`Self::push_manifest_to_registry`], which round-trips through
3221    /// `OciImageManifest` and so re-serialises the JSON (potentially losing
3222    /// byte-level fidelity with the locally-computed digest), this PUTs the
3223    /// exact bytes the caller already computed a sha256 over. This matters
3224    /// for Windows WCOW manifests where the layer descriptors carry foreign
3225    /// `urls[]` arrays that must round-trip unmodified so Windows daemons
3226    /// recognise the layers as foreign and skip download.
3227    ///
3228    /// The `content_type` is sent verbatim as the `Content-Type` header; for
3229    /// a Docker manifest pass `"application/vnd.docker.distribution.manifest.v2+json"`,
3230    /// for an OCI image manifest pass `"application/vnd.oci.image.manifest.v1+json"`.
3231    ///
3232    /// # Errors
3233    ///
3234    /// - [`PushError::InvalidReference`] if `reference` is not a parseable image ref.
3235    /// - [`PushError::AuthenticationFailed`] on auth failure for the target registry.
3236    /// - [`PushError::ManifestUploadFailed`] if the underlying PUT fails or the
3237    ///   provided `content_type` is not a valid HTTP header value.
3238    #[instrument(
3239        name = "push_manifest_blob",
3240        skip(self, manifest_bytes, auth),
3241        fields(
3242            reference = %reference,
3243            content_type = %content_type,
3244            size = manifest_bytes.len(),
3245        )
3246    )]
3247    pub async fn push_manifest_blob(
3248        &self,
3249        reference: &str,
3250        manifest_bytes: Vec<u8>,
3251        content_type: &str,
3252        auth: &RegistryAuth,
3253    ) -> std::result::Result<String, PushError> {
3254        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3255            reference: reference.to_string(),
3256        })?;
3257
3258        let header_value =
3259            content_type
3260                .parse()
3261                .map_err(|e: reqwest::header::InvalidHeaderValue| {
3262                    PushError::ManifestUploadFailed {
3263                        reason: format!("invalid Content-Type {content_type:?}: {e}"),
3264                    }
3265                })?;
3266
3267        // Authenticate for push operation
3268        self.client
3269            .auth(&image_ref, auth, RegistryOperation::Push)
3270            .await
3271            .map_err(|e| PushError::AuthenticationFailed {
3272                registry: image_ref.resolve_registry().to_string(),
3273                reason: e.to_string(),
3274            })?;
3275
3276        let manifest_url = self
3277            .client
3278            .push_manifest_raw(&image_ref, manifest_bytes.clone(), header_value)
3279            .await
3280            .map_err(|e| PushError::ManifestUploadFailed {
3281                reason: e.to_string(),
3282            })?;
3283
3284        let digest = if let Some(digest_start) = manifest_url.rfind('@') {
3285            manifest_url[digest_start + 1..].to_string()
3286        } else {
3287            crate::cache::compute_digest(&manifest_bytes)
3288        };
3289
3290        tracing::info!(
3291            reference = %reference,
3292            digest = %digest,
3293            "manifest blob pushed successfully"
3294        );
3295
3296        Ok(digest)
3297    }
3298
3299    /// Push a WASM artifact to a remote registry
3300    ///
3301    /// This method pushes a complete WASM artifact including the config blob,
3302    /// WASM binary layer, and manifest. It uses the result from `export_wasm_as_oci`
3303    /// to obtain the properly formatted blobs.
3304    ///
3305    /// # Arguments
3306    ///
3307    /// * `reference` - Image reference (e.g., "ghcr.io/myorg/mymodule:v1.0")
3308    /// * `export_result` - Result from `export_wasm_as_oci` containing all blobs
3309    /// * `auth` - Registry authentication credentials
3310    ///
3311    /// # Returns
3312    ///
3313    /// Returns a `PushResult` containing the manifest digest and list of pushed blobs.
3314    ///
3315    /// # Errors
3316    ///
3317    /// Returns an error if:
3318    /// - The reference is invalid
3319    /// - Authentication fails
3320    /// - Any blob or manifest upload fails
3321    ///
3322    /// # Example
3323    ///
3324    /// ```rust,no_run
3325    /// use zlayer_registry::{ImagePuller, BlobCache};
3326    /// use zlayer_registry::wasm_export::{WasmExportConfig, export_wasm_as_oci};
3327    /// use oci_client::secrets::RegistryAuth;
3328    /// use std::path::PathBuf;
3329    ///
3330    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
3331    /// let puller = ImagePuller::new(BlobCache::new()?);
3332    ///
3333    /// let export_config = WasmExportConfig {
3334    ///     wasm_path: PathBuf::from("./my_module.wasm"),
3335    ///     module_name: "my-module".to_string(),
3336    ///     wasi_version: None,
3337    ///     annotations: Default::default(),
3338    /// };
3339    ///
3340    /// let export_result = export_wasm_as_oci(&export_config).await?;
3341    ///
3342    /// let auth = RegistryAuth::Basic("user".to_string(), "token".to_string());
3343    /// let push_result = puller.push_wasm(
3344    ///     "ghcr.io/myorg/my-module:v1.0",
3345    ///     &export_result,
3346    ///     &auth,
3347    /// ).await?;
3348    ///
3349    /// println!("Pushed manifest: {}", push_result.manifest_digest);
3350    /// # Ok(())
3351    /// # }
3352    /// ```
3353    #[cfg(feature = "local")]
3354    #[allow(clippy::too_many_lines)]
3355    #[instrument(
3356        name = "push_wasm",
3357        skip(self, export_result, auth),
3358        fields(
3359            reference = %reference,
3360            wasm_size = export_result.wasm_size,
3361            wasi_version = %export_result.wasi_version,
3362        )
3363    )]
3364    pub async fn push_wasm(
3365        &self,
3366        reference: &str,
3367        export_result: &WasmExportResult,
3368        auth: &RegistryAuth,
3369    ) -> std::result::Result<PushResult, PushError> {
3370        use crate::wasm::{WASM_CONFIG_MEDIA_TYPE_V0, WASM_LAYER_MEDIA_TYPE_GENERIC};
3371
3372        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3373            reference: reference.to_string(),
3374        })?;
3375
3376        tracing::info!(
3377            reference = %reference,
3378            wasm_size = export_result.wasm_size,
3379            wasi_version = %export_result.wasi_version,
3380            artifact_type = %export_result.artifact_type,
3381            "pushing WASM artifact to registry"
3382        );
3383
3384        // Authenticate for push operation
3385        self.client
3386            .auth(&image_ref, auth, RegistryOperation::Push)
3387            .await
3388            .map_err(|e| PushError::AuthenticationFailed {
3389                registry: image_ref.resolve_registry().to_string(),
3390                reason: e.to_string(),
3391            })?;
3392
3393        let mut blobs_pushed = Vec::new();
3394
3395        // Push config blob
3396        tracing::debug!(
3397            digest = %export_result.config_digest,
3398            size = export_result.config_size,
3399            "pushing config blob"
3400        );
3401        self.client
3402            .push_blob(
3403                &image_ref,
3404                &export_result.config_blob,
3405                &export_result.config_digest,
3406            )
3407            .await
3408            .map_err(|e| PushError::BlobUploadFailed {
3409                digest: export_result.config_digest.clone(),
3410                reason: e.to_string(),
3411            })?;
3412        blobs_pushed.push(export_result.config_digest.clone());
3413
3414        // Push WASM binary blob
3415        tracing::debug!(
3416            digest = %export_result.wasm_layer_digest,
3417            size = export_result.wasm_size,
3418            "pushing WASM layer blob"
3419        );
3420        self.client
3421            .push_blob(
3422                &image_ref,
3423                &export_result.wasm_binary,
3424                &export_result.wasm_layer_digest,
3425            )
3426            .await
3427            .map_err(|e| PushError::BlobUploadFailed {
3428                digest: export_result.wasm_layer_digest.clone(),
3429                reason: e.to_string(),
3430            })?;
3431        blobs_pushed.push(export_result.wasm_layer_digest.clone());
3432
3433        // Build the manifest from the export result
3434        #[allow(clippy::cast_possible_wrap)]
3435        let manifest = OciImageManifest {
3436            schema_version: 2,
3437            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
3438            artifact_type: Some(export_result.artifact_type.clone()),
3439            config: oci_client::manifest::OciDescriptor {
3440                media_type: WASM_CONFIG_MEDIA_TYPE_V0.to_string(),
3441                digest: export_result.config_digest.clone(),
3442                size: export_result.config_size as i64,
3443                urls: None,
3444                annotations: None,
3445            },
3446            layers: vec![oci_client::manifest::OciDescriptor {
3447                media_type: WASM_LAYER_MEDIA_TYPE_GENERIC.to_string(),
3448                digest: export_result.wasm_layer_digest.clone(),
3449                size: export_result.wasm_size as i64,
3450                urls: None,
3451                annotations: None,
3452            }],
3453            annotations: None,
3454            subject: None,
3455        };
3456
3457        // Push manifest
3458        tracing::debug!(
3459            config_digest = %export_result.config_digest,
3460            wasm_digest = %export_result.wasm_layer_digest,
3461            "pushing manifest"
3462        );
3463        let manifest_url = self
3464            .client
3465            .push_manifest(&image_ref, &OciManifest::Image(manifest))
3466            .await
3467            .map_err(|e| PushError::ManifestUploadFailed {
3468                reason: e.to_string(),
3469            })?;
3470
3471        // Extract digest from manifest URL or use the precomputed one
3472        let manifest_digest = if let Some(digest_start) = manifest_url.rfind('@') {
3473            manifest_url[digest_start + 1..].to_string()
3474        } else {
3475            export_result.manifest_digest.clone()
3476        };
3477
3478        tracing::info!(
3479            reference = %reference,
3480            manifest_digest = %manifest_digest,
3481            blobs_pushed = blobs_pushed.len(),
3482            "WASM artifact pushed successfully"
3483        );
3484
3485        Ok(PushResult {
3486            manifest_digest,
3487            blobs_pushed,
3488            reference: reference.to_string(),
3489        })
3490    }
3491
3492    /// Push a generic OCI artifact: a config blob plus an ordered set of
3493    /// [`ArtifactLayer`]s, with arbitrary manifest-level annotations.
3494    ///
3495    /// This is the registry-agnostic primitive behind `zlayer vz build-base`,
3496    /// which publishes a macOS VZ base bundle (`disk.img`, `hardware-model.bin`,
3497    /// `aux.img`) packed by [`crate::pack::pack_files_tar_zstd`] as a single
3498    /// `tar+zstd` layer. The manifest annotations carry the routing marker
3499    /// (`com.zlayer.runtime=vz`) the agent's composite runtime reads to prefer
3500    /// the VZ runtime for that image.
3501    ///
3502    /// Blob digests are computed here over the exact bytes provided. `oci-client`
3503    /// 0.15 has no streaming blob upload, so each blob is held in memory during
3504    /// its (chunked-over-the-wire) push; size the host accordingly for
3505    /// multi-gigabyte disk layers.
3506    ///
3507    /// # Errors
3508    /// Returns [`PushError`] on an invalid reference, auth failure, or a blob /
3509    /// manifest upload failure.
3510    #[cfg(feature = "local")]
3511    #[allow(clippy::too_many_arguments)]
3512    #[instrument(name = "push_artifact", skip(self, config_blob, layers, annotations, auth), fields(reference = %reference, artifact_type = %artifact_type, layers = layers.len()))]
3513    pub async fn push_artifact(
3514        &self,
3515        reference: &str,
3516        artifact_type: &str,
3517        config_media_type: &str,
3518        config_blob: &[u8],
3519        layers: &[ArtifactLayer],
3520        annotations: std::collections::BTreeMap<String, String>,
3521        auth: &RegistryAuth,
3522    ) -> std::result::Result<PushResult, PushError> {
3523        let image_ref: Reference = reference.parse().map_err(|_| PushError::InvalidReference {
3524            reference: reference.to_string(),
3525        })?;
3526
3527        self.client
3528            .auth(&image_ref, auth, RegistryOperation::Push)
3529            .await
3530            .map_err(|e| PushError::AuthenticationFailed {
3531                registry: image_ref.resolve_registry().to_string(),
3532                reason: e.to_string(),
3533            })?;
3534
3535        let mut blobs_pushed = Vec::new();
3536
3537        // --- config blob ---
3538        let config_digest = oci_sha256_digest(config_blob);
3539        self.client
3540            .push_blob(&image_ref, config_blob, &config_digest)
3541            .await
3542            .map_err(|e| PushError::BlobUploadFailed {
3543                digest: config_digest.clone(),
3544                reason: e.to_string(),
3545            })?;
3546        blobs_pushed.push(config_digest.clone());
3547
3548        // --- layer blobs ---
3549        let mut layer_descriptors = Vec::with_capacity(layers.len());
3550        for layer in layers {
3551            let digest = oci_sha256_digest(&layer.data);
3552            tracing::debug!(
3553                digest = %digest,
3554                size = layer.data.len(),
3555                media_type = %layer.media_type,
3556                "pushing artifact layer blob"
3557            );
3558            self.client
3559                .push_blob(&image_ref, &layer.data, &digest)
3560                .await
3561                .map_err(|e| PushError::BlobUploadFailed {
3562                    digest: digest.clone(),
3563                    reason: e.to_string(),
3564                })?;
3565            blobs_pushed.push(digest.clone());
3566
3567            let layer_annotations = layer.title.as_ref().map(|title| {
3568                let mut m = std::collections::BTreeMap::new();
3569                m.insert("org.opencontainers.image.title".to_string(), title.clone());
3570                m
3571            });
3572            #[allow(clippy::cast_possible_wrap)]
3573            layer_descriptors.push(oci_client::manifest::OciDescriptor {
3574                media_type: layer.media_type.clone(),
3575                digest,
3576                size: layer.data.len() as i64,
3577                urls: None,
3578                annotations: layer_annotations,
3579            });
3580        }
3581
3582        let manifest_annotations = if annotations.is_empty() {
3583            None
3584        } else {
3585            Some(annotations)
3586        };
3587
3588        #[allow(clippy::cast_possible_wrap)]
3589        let manifest = OciImageManifest {
3590            schema_version: 2,
3591            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
3592            artifact_type: Some(artifact_type.to_string()),
3593            config: oci_client::manifest::OciDescriptor {
3594                media_type: config_media_type.to_string(),
3595                digest: config_digest.clone(),
3596                size: config_blob.len() as i64,
3597                urls: None,
3598                annotations: None,
3599            },
3600            layers: layer_descriptors,
3601            annotations: manifest_annotations,
3602            subject: None,
3603        };
3604
3605        let manifest_url = self
3606            .client
3607            .push_manifest(&image_ref, &OciManifest::Image(manifest))
3608            .await
3609            .map_err(|e| PushError::ManifestUploadFailed {
3610                reason: e.to_string(),
3611            })?;
3612
3613        let manifest_digest = manifest_url
3614            .rfind('@')
3615            .map(|i| manifest_url[i + 1..].to_string())
3616            .unwrap_or(manifest_url);
3617
3618        tracing::info!(
3619            reference = %reference,
3620            manifest_digest = %manifest_digest,
3621            blobs_pushed = blobs_pushed.len(),
3622            "OCI artifact pushed successfully"
3623        );
3624
3625        Ok(PushResult {
3626            manifest_digest,
3627            blobs_pushed,
3628            reference: reference.to_string(),
3629        })
3630    }
3631}
3632
3633/// Image reference information
3634#[derive(Debug, Clone, PartialEq, Eq)]
3635pub struct Image {
3636    /// Registry host (e.g., "docker.io", "ghcr.io")
3637    pub registry: String,
3638    /// Repository name (e.g., "library/nginx")
3639    pub repository: String,
3640    /// Tag (e.g., "latest", "v1.0.0")
3641    pub tag: String,
3642}
3643
3644impl std::fmt::Display for Image {
3645    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3646        write!(f, "{}/{}:{}", self.registry, self.repository, self.tag)
3647    }
3648}
3649
3650/// Maximum number of `urls[]` entries consulted when a foreign layer 404s on
3651/// the primary registry. Descriptors rarely carry more than one or two URLs;
3652/// the cap is a defence against circular / abusive redirect lists.
3653const MAX_FOREIGN_LAYER_REDIRECTS: usize = 5;
3654
3655/// Return `true` when an `OciDistributionError` reports that the blob does not
3656/// exist on the primary registry — i.e. the conditions under which we should
3657/// fall back to the descriptor's `urls[]` list.
3658fn is_blob_not_found(err: &oci_client::errors::OciDistributionError) -> bool {
3659    use oci_client::errors::{OciDistributionError, OciErrorCode};
3660    match err {
3661        OciDistributionError::ImageManifestNotFoundError(_) => true,
3662        OciDistributionError::ServerError { code, .. } => *code == 404,
3663        OciDistributionError::RegistryError { envelope, .. } => envelope.errors.iter().any(|e| {
3664            matches!(
3665                e.code,
3666                OciErrorCode::BlobUnknown
3667                    | OciErrorCode::ManifestBlobUnknown
3668                    | OciErrorCode::ManifestUnknown
3669                    | OciErrorCode::NotFound
3670                    | OciErrorCode::NameUnknown
3671            )
3672        }),
3673        OciDistributionError::RequestError(req_err) => {
3674            req_err.status() == Some(reqwest::StatusCode::NOT_FOUND)
3675        }
3676        _ => false,
3677    }
3678}
3679
3680/// Fetch raw bytes from an HTTP(S) URL with optional HTTP Basic authentication.
3681///
3682/// This is the low-level primitive used by all other `fetch_*_from_url` helpers
3683/// in this module — `fetch_blob_from_url` (with digest/size verification),
3684/// `fetch_archive_from_url` (non-empty archive assertion), and any future
3685/// content-type-specific fetcher. It performs no validation on the response
3686/// body beyond HTTP status; callers are responsible for any content-specific
3687/// checks. `context` is a short human-readable label used to prefix error
3688/// messages (e.g. `"foreign-layer redirect"`, `"archive fetch"`).
3689///
3690/// The caller is responsible for supplying an HTTPS URL when credentials are
3691/// involved — TLS is never bypassed.
3692///
3693/// # Errors
3694///
3695/// Returns [`RegistryError::Cache`] on HTTP client construction failure,
3696/// network error, non-2xx status code, or I/O error while reading the
3697/// response body. The URL and `context` are included in the error for
3698/// diagnostics.
3699pub async fn fetch_from_url(
3700    url: &str,
3701    auth: Option<(&str, &str)>,
3702    context: &str,
3703) -> Result<Vec<u8>> {
3704    let client = reqwest::Client::builder().build().map_err(|e| {
3705        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3706            "failed to build HTTP client for {context} {url}: {e}"
3707        )))
3708    })?;
3709
3710    let mut req = client.get(url);
3711    if let Some((user, pw)) = auth {
3712        req = req.basic_auth(user, Some(pw));
3713    }
3714
3715    let response = req.send().await.map_err(|e| {
3716        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3717            "{context} GET {url} failed: {e}"
3718        )))
3719    })?;
3720
3721    if !response.status().is_success() {
3722        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3723            format!("{context} {url} returned HTTP {}", response.status()),
3724        )));
3725    }
3726
3727    let bytes = response.bytes().await.map_err(|e| {
3728        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3729            "failed to read {context} body from {url}: {e}"
3730        )))
3731    })?;
3732
3733    Ok(bytes.to_vec())
3734}
3735
3736/// Fetch a foreign layer blob from an out-of-registry URL (e.g. MCR) and
3737/// verify that its SHA-256 digest matches `expected_digest`. Size is verified
3738/// against `expected_size` when the value is `Some(n)` and `n >= 0`.
3739async fn fetch_blob_from_url(
3740    url: &str,
3741    expected_digest: &str,
3742    expected_size: Option<i64>,
3743) -> Result<Vec<u8>> {
3744    use sha2::{Digest, Sha256};
3745
3746    let bytes = fetch_from_url(url, None, "foreign-layer redirect").await?;
3747
3748    if bytes.is_empty() {
3749        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3750            format!("foreign-layer redirect {url} returned empty body"),
3751        )));
3752    }
3753
3754    if let Some(expected) = expected_size {
3755        if let Ok(expected_u) = u64::try_from(expected) {
3756            if bytes.len() as u64 != expected_u {
3757                return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3758                    format!(
3759                        "foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
3760                        bytes.len()
3761                    ),
3762                )));
3763            }
3764        }
3765    }
3766
3767    let mut hasher = Sha256::new();
3768    hasher.update(&bytes);
3769    let actual = hex::encode(hasher.finalize());
3770    let expected = expected_digest
3771        .strip_prefix("sha256:")
3772        .unwrap_or(expected_digest);
3773    if !actual.eq_ignore_ascii_case(expected) {
3774        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3775            format!(
3776                "foreign-layer redirect {url}: digest mismatch (expected {expected_digest}, got sha256:{actual})"
3777            ),
3778        )));
3779    }
3780
3781    Ok(bytes)
3782}
3783
3784/// Monotonic counter making `.part` temp-file names unique across concurrent
3785/// streaming pulls into the same staging directory.
3786static BLOB_PART_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3787
3788/// Staging filename for a blob `digest` (colons/slashes sanitized to one path
3789/// component). Digests are unique, so layers never collide within a stage dir.
3790fn blob_staging_filename(digest: &str) -> String {
3791    digest.replace([':', '/'], "_")
3792}
3793
3794/// Materialize `src` at `dest`, preferring a hardlink (same filesystem, O(1))
3795/// and falling back to a streamed copy across devices.
3796async fn link_or_copy(src: &std::path::Path, dest: &std::path::Path) -> Result<()> {
3797    let _ = tokio::fs::remove_file(dest).await;
3798    if tokio::fs::hard_link(src, dest).await.is_ok() {
3799        return Ok(());
3800    }
3801    tokio::fs::copy(src, dest)
3802        .await
3803        .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3804    Ok(())
3805}
3806
3807/// A `tokio::io::AsyncWrite` that tees everything written into a file while
3808/// updating a running SHA-256 — giving streaming download + inline digest
3809/// verification in a single pass (oci-client does no digest check itself).
3810///
3811/// All fields are `Unpin`, so the pin projection is a plain `get_mut()`.
3812struct HashingFileWriter {
3813    file: tokio::fs::File,
3814    hasher: sha2::Sha256,
3815    written: u64,
3816}
3817
3818impl HashingFileWriter {
3819    fn new(file: tokio::fs::File) -> Self {
3820        use sha2::Digest;
3821        Self {
3822            file,
3823            hasher: sha2::Sha256::new(),
3824            written: 0,
3825        }
3826    }
3827
3828    /// Flush + fsync the file, returning the finalized `sha256:<hex>` digest and
3829    /// the total byte count written.
3830    async fn finalize(mut self) -> Result<(String, u64)> {
3831        use sha2::Digest;
3832        use tokio::io::AsyncWriteExt as _;
3833        self.file
3834            .flush()
3835            .await
3836            .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3837        self.file
3838            .sync_all()
3839            .await
3840            .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3841        let digest = format!("sha256:{}", hex::encode(self.hasher.finalize()));
3842        Ok((digest, self.written))
3843    }
3844}
3845
3846impl tokio::io::AsyncWrite for HashingFileWriter {
3847    fn poll_write(
3848        self: std::pin::Pin<&mut Self>,
3849        cx: &mut std::task::Context<'_>,
3850        buf: &[u8],
3851    ) -> std::task::Poll<std::io::Result<usize>> {
3852        use sha2::Digest;
3853        let me = self.get_mut();
3854        match std::pin::Pin::new(&mut me.file).poll_write(cx, buf) {
3855            std::task::Poll::Ready(Ok(n)) => {
3856                me.hasher.update(&buf[..n]);
3857                me.written += n as u64;
3858                std::task::Poll::Ready(Ok(n))
3859            }
3860            other => other,
3861        }
3862    }
3863
3864    fn poll_flush(
3865        self: std::pin::Pin<&mut Self>,
3866        cx: &mut std::task::Context<'_>,
3867    ) -> std::task::Poll<std::io::Result<()>> {
3868        let me = self.get_mut();
3869        std::pin::Pin::new(&mut me.file).poll_flush(cx)
3870    }
3871
3872    fn poll_shutdown(
3873        self: std::pin::Pin<&mut Self>,
3874        cx: &mut std::task::Context<'_>,
3875    ) -> std::task::Poll<std::io::Result<()>> {
3876        let me = self.get_mut();
3877        std::pin::Pin::new(&mut me.file).poll_shutdown(cx)
3878    }
3879}
3880
3881/// Stream a foreign-layer blob from `url` directly into `writer` (chunk by
3882/// chunk, never buffering the whole blob), verifying the size against
3883/// `expected_size` after the body completes. The digest is verified by the
3884/// caller from the writer's finalized hash.
3885async fn fetch_blob_from_url_to_writer(
3886    url: &str,
3887    expected_size: Option<i64>,
3888    writer: &mut HashingFileWriter,
3889) -> Result<()> {
3890    use tokio::io::AsyncWriteExt as _;
3891
3892    let client = reqwest::Client::builder().build().map_err(|e| {
3893        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3894            "failed to build HTTP client for foreign-layer redirect {url}: {e}"
3895        )))
3896    })?;
3897
3898    let mut response = client.get(url).send().await.map_err(|e| {
3899        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3900            "foreign-layer redirect GET {url} failed: {e}"
3901        )))
3902    })?;
3903
3904    if !response.status().is_success() {
3905        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3906            format!(
3907                "foreign-layer redirect {url} returned HTTP {}",
3908                response.status()
3909            ),
3910        )));
3911    }
3912
3913    while let Some(chunk) = response.chunk().await.map_err(|e| {
3914        RegistryError::Cache(crate::error::CacheError::Corrupted(format!(
3915            "failed to read foreign-layer body from {url}: {e}"
3916        )))
3917    })? {
3918        writer
3919            .write_all(&chunk)
3920            .await
3921            .map_err(|e| RegistryError::Cache(crate::error::CacheError::Io(e)))?;
3922    }
3923
3924    if let Some(expected) = expected_size {
3925        if let Ok(expected_u) = u64::try_from(expected) {
3926            if writer.written != expected_u {
3927                return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3928                    format!(
3929                        "foreign-layer redirect {url}: size mismatch (expected {expected}, got {})",
3930                        writer.written
3931                    ),
3932                )));
3933            }
3934        }
3935    }
3936
3937    Ok(())
3938}
3939
3940/// Fetch an OCI tar archive (or tar.gz) from a remote HTTP(S) URL with optional
3941/// HTTP Basic authentication.
3942///
3943/// Unlike [`fetch_blob_from_url`], there is no digest verification — OCI
3944/// archives are not content-addressable blobs by URL. Validation happens
3945/// inside the importer via the embedded `oci-layout` + manifest digests.
3946/// Only asserts the response body is non-empty so callers get a clean error
3947/// message on accidental 200-with-empty-body responses from misconfigured
3948/// object stores.
3949///
3950/// Suitable for authenticating against Forgejo / Gitea generic-package APIs,
3951/// Nexus raw repositories, and similar file-blob endpoints.
3952///
3953/// # Errors
3954///
3955/// Returns [`RegistryError::Cache`] on any HTTP/network error (propagated
3956/// from [`fetch_from_url`]) or when the response body is empty.
3957pub async fn fetch_archive_from_url(url: &str, auth: Option<(&str, &str)>) -> Result<Vec<u8>> {
3958    let bytes = fetch_from_url(url, auth, "archive fetch").await?;
3959
3960    if bytes.is_empty() {
3961        return Err(RegistryError::Cache(crate::error::CacheError::Corrupted(
3962            format!("archive fetch {url} returned empty body"),
3963        )));
3964    }
3965
3966    Ok(bytes)
3967}
3968
3969/// Convert a [`zlayer_spec::RegistryAuth`] into the [`RegistryAuth`] shape
3970/// that the OCI client speaks. Anonymous is returned when `auth` is `None`.
3971///
3972/// Basic and Token map onto the same `(username, password)` shape today —
3973/// the client's bearer-token path is a parsing detail handled by
3974/// `oci-client` itself. The explicit match keeps us honest when a future
3975/// [`zlayer_spec::RegistryAuthType`] variant lands with different semantics.
3976#[must_use]
3977pub fn spec_auth_to_oci(auth: Option<&zlayer_spec::RegistryAuth>) -> RegistryAuth {
3978    let Some(a) = auth else {
3979        return RegistryAuth::Anonymous;
3980    };
3981    match a.auth_type {
3982        zlayer_spec::RegistryAuthType::Basic | zlayer_spec::RegistryAuthType::Token => {
3983            RegistryAuth::Basic(a.username.clone(), a.password.clone())
3984        }
3985    }
3986}
3987
3988/// Build an [`ImagePuller`] for one-shot OS / runtime-marker inspection,
3989/// reusing an existing blob cache (and, when compiled with the `local`
3990/// feature, an optional [`LocalRegistry`]) so the lookup sees the SAME store
3991/// the daemon's pull already wrote its manifest and config blob to.
3992///
3993/// `cache` should be the persistent blob cache the runtime pulled into (e.g.
3994/// the VZ-Linux runtime's `{data_dir}/vz/linux/images/blobs.redb`). When that
3995/// store holds the image, [`ImagePuller::image_os_with_policy`] driven with
3996/// [`PullPolicy::IfNotPresent`] resolves the OS with no network call.
3997// Only the `local`-gated `fetch_*_in_cache*` helpers construct an inspection
3998// puller (they are the entry points that take an explicit on-disk store plus
3999// an optional local registry), so this helper is itself `local`-gated. Without
4000// the feature there are no callers, and a non-`local` variant would be dead.
4001#[cfg(feature = "local")]
4002fn inspection_puller(
4003    cache: Arc<Box<dyn BlobCacheBackend>>,
4004    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4005) -> ImagePuller {
4006    let puller = ImagePuller::with_cache(cache);
4007    match local_registry {
4008        Some(reg) => puller.with_local_registry(reg),
4009        None => puller,
4010    }
4011}
4012
4013/// Fetch the OCI operating system of `image` LOCAL-FIRST, without pulling any
4014/// layers and without a network round-trip when the image is already cached.
4015///
4016/// Constructs an ephemeral [`ImagePuller`] backed by an in-memory
4017/// [`BlobCache`] and calls [`ImagePuller::image_os_with_policy`] with
4018/// [`PullPolicy::IfNotPresent`]. Intended for callers that need a one-shot OS
4019/// inspection and don't otherwise own a long-lived puller.
4020///
4021/// NOTE: because this overload uses a *fresh empty* in-memory cache, the
4022/// image will not be found locally and a network fetch is required. Callers
4023/// that own the daemon's persistent store (e.g. the agent's
4024/// `CompositeRuntime`) should prefer [`fetch_image_os_in_cache`] so the OS is
4025/// resolved from the already-pulled config blob even under a registry
4026/// rate-limit. This bare wrapper is kept for callers without a store.
4027///
4028/// Auth is the same [`zlayer_spec::RegistryAuth`] carried on the
4029/// [`Runtime::pull_image_with_policy`](crate) trait; `None` maps to
4030/// anonymous. The manifest is resolved for the process's runtime platform
4031/// (with the historical macOS `darwin → linux` fallback) — matching the
4032/// behavior of [`ImagePuller::new`].
4033///
4034/// # Errors
4035///
4036/// Returns an error if the in-memory cache cannot be initialized, or if the
4037/// manifest or config blob cannot be fetched or parsed. Callers in the hot
4038/// path (e.g. `CompositeRuntime::pull_image_with_policy`) should treat any
4039/// error as non-fatal: the safe fall-through is "dispatch to the primary
4040/// runtime" rather than failing the pull.
4041pub async fn fetch_image_os(
4042    image: &str,
4043    auth: Option<&zlayer_spec::RegistryAuth>,
4044) -> Result<Option<zlayer_spec::OsKind>> {
4045    let cache = crate::cache::BlobCache::new()?;
4046    let puller = ImagePuller::new(cache);
4047
4048    let oci_auth = spec_auth_to_oci(auth);
4049    puller
4050        .image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4051        .await
4052}
4053
4054/// Resolve the OCI operating system of `image` from an EXISTING local store
4055/// (the daemon's persistent blob cache plus an optional [`LocalRegistry`])
4056/// without a network call when the image is present.
4057///
4058/// This is the fix for the macOS image-OS-resolution bug: the composite
4059/// runtime's pull writes the manifest and config blob into a persistent blob
4060/// cache, then needs to inspect `config.os` to route the workload. Passing
4061/// that same `cache` (and `local_registry`) here lets
4062/// [`ImagePuller::image_os_with_policy`] satisfy the lookup from the cached
4063/// config blob under [`PullPolicy::IfNotPresent`] — so a locally-cached Linux
4064/// image is detected as Linux and routed to VZ-Linux even when Docker Hub is
4065/// returning `429 Too Many Requests`. Only a genuinely-absent image falls
4066/// back to the network.
4067///
4068/// # Errors
4069///
4070/// Returns an error if the manifest or config blob cannot be resolved from the
4071/// local store AND a fallback network fetch also fails, or if the config blob
4072/// cannot be parsed. Hot-path callers should treat any error as non-fatal.
4073#[cfg(feature = "local")]
4074pub async fn fetch_image_os_in_cache(
4075    image: &str,
4076    auth: Option<&zlayer_spec::RegistryAuth>,
4077    cache: Arc<Box<dyn BlobCacheBackend>>,
4078    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4079) -> Result<Option<zlayer_spec::OsKind>> {
4080    let puller = inspection_puller(cache, local_registry);
4081    let oci_auth = spec_auth_to_oci(auth);
4082    puller
4083        .image_os_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4084        .await
4085}
4086
4087/// Convenience wrapper around [`ImagePuller::image_runtime_marker_with_policy`]
4088/// using a fresh default [`BlobCache`] and [`PullPolicy::IfNotPresent`].
4089/// Returns the `com.zlayer.runtime` manifest annotation (e.g. `"vz"`) if
4090/// present, else `Ok(None)`.
4091///
4092/// Prefer [`fetch_image_runtime_marker_in_cache`] when the daemon's persistent
4093/// store is available, so the marker resolves with no network round-trip.
4094///
4095/// # Errors
4096/// Returns an error if a blob cache cannot be created, or the manifest cannot
4097/// be fetched/parsed.
4098pub async fn fetch_image_runtime_marker(
4099    image: &str,
4100    auth: Option<&zlayer_spec::RegistryAuth>,
4101) -> Result<Option<String>> {
4102    let cache = crate::cache::BlobCache::new()?;
4103    let puller = ImagePuller::new(cache);
4104
4105    let oci_auth = spec_auth_to_oci(auth);
4106    puller
4107        .image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4108        .await
4109}
4110
4111/// Resolve the `com.zlayer.runtime` marker of `image` from an EXISTING local
4112/// store (persistent blob cache + optional [`LocalRegistry`]) without a
4113/// network call when the image is present. The marker counterpart to
4114/// [`fetch_image_os_in_cache`].
4115///
4116/// # Errors
4117/// Returns an error if the manifest cannot be resolved locally and a fallback
4118/// network fetch also fails, or the manifest cannot be parsed.
4119#[cfg(feature = "local")]
4120pub async fn fetch_image_runtime_marker_in_cache(
4121    image: &str,
4122    auth: Option<&zlayer_spec::RegistryAuth>,
4123    cache: Arc<Box<dyn BlobCacheBackend>>,
4124    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4125) -> Result<Option<String>> {
4126    let puller = inspection_puller(cache, local_registry);
4127    let oci_auth = spec_auth_to_oci(auth);
4128    puller
4129        .image_runtime_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4130        .await
4131}
4132
4133/// Resolve `image`'s OCI operating system from an EXISTING local store with NO
4134/// network fallback — `Ok(None)` signals a clean local miss.
4135///
4136/// This differs from [`fetch_image_os_in_cache`], which falls through to the
4137/// network when the image is absent. Use this when probing SEVERAL caches in
4138/// turn (e.g. the composite runtime's VZ-Linux cache then the primary Sandbox
4139/// cache): each miss must NOT trigger a Docker Hub round-trip, or the rate-limit
4140/// the whole feature exists to avoid would fire on the first empty cache.
4141///
4142/// # Errors
4143/// Returns an error only when a locally-present config blob cannot be parsed.
4144#[cfg(feature = "local")]
4145pub async fn fetch_image_os_in_cache_only(
4146    image: &str,
4147    cache: Arc<Box<dyn BlobCacheBackend>>,
4148    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4149) -> Result<Option<zlayer_spec::OsKind>> {
4150    let puller = inspection_puller(cache, local_registry);
4151    puller.image_os_in_cache_only(image).await
4152}
4153
4154/// Resolve `image`'s `com.zlayer.runtime` marker from an EXISTING local store
4155/// with NO network fallback. The marker counterpart to
4156/// [`fetch_image_os_in_cache_only`].
4157///
4158/// # Errors
4159/// Mirrors [`fetch_image_os_in_cache_only`]; infallible in practice.
4160#[cfg(feature = "local")]
4161pub async fn fetch_image_runtime_marker_in_cache_only(
4162    image: &str,
4163    cache: Arc<Box<dyn BlobCacheBackend>>,
4164    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4165) -> Result<Option<String>> {
4166    let puller = inspection_puller(cache, local_registry);
4167    puller.image_runtime_marker_in_cache_only(image).await
4168}
4169
4170/// Convenience wrapper around
4171/// [`ImagePuller::image_isolation_marker_with_policy`] using a fresh default
4172/// [`BlobCache`] and [`PullPolicy::IfNotPresent`]. Returns the
4173/// `com.zlayer.isolation` image-declared isolation default (e.g. `"sandbox"` /
4174/// `"vz-linux"`) if present, else `Ok(None)`.
4175///
4176/// Prefer [`fetch_image_isolation_marker_in_cache_only`] when the daemon's
4177/// persistent store is available, so the default resolves with no network
4178/// round-trip. The isolation counterpart to [`fetch_image_runtime_marker`].
4179///
4180/// # Errors
4181/// Returns an error if a blob cache cannot be created, or the manifest/config
4182/// cannot be fetched/parsed.
4183pub async fn fetch_image_isolation_marker(
4184    image: &str,
4185    auth: Option<&zlayer_spec::RegistryAuth>,
4186) -> Result<Option<String>> {
4187    let cache = crate::cache::BlobCache::new()?;
4188    let puller = ImagePuller::new(cache);
4189
4190    let oci_auth = spec_auth_to_oci(auth);
4191    puller
4192        .image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4193        .await
4194}
4195
4196/// Resolve `image`'s `com.zlayer.isolation` default from an EXISTING local store
4197/// (persistent blob cache + optional [`LocalRegistry`]), falling through to the
4198/// network only when the image is absent. The isolation counterpart to
4199/// [`fetch_image_runtime_marker_in_cache`].
4200///
4201/// # Errors
4202/// Returns an error if the manifest/config cannot be resolved locally and a
4203/// fallback network fetch also fails, or the config blob cannot be parsed.
4204#[cfg(feature = "local")]
4205pub async fn fetch_image_isolation_marker_in_cache(
4206    image: &str,
4207    auth: Option<&zlayer_spec::RegistryAuth>,
4208    cache: Arc<Box<dyn BlobCacheBackend>>,
4209    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4210) -> Result<Option<String>> {
4211    let puller = inspection_puller(cache, local_registry);
4212    let oci_auth = spec_auth_to_oci(auth);
4213    puller
4214        .image_isolation_marker_with_policy(image, &oci_auth, PullPolicy::IfNotPresent)
4215        .await
4216}
4217
4218/// Resolve `image`'s `com.zlayer.isolation` default from an EXISTING local store
4219/// with NO network fallback. The isolation counterpart to
4220/// [`fetch_image_runtime_marker_in_cache_only`].
4221///
4222/// # Errors
4223/// Mirrors [`fetch_image_runtime_marker_in_cache_only`]; infallible in practice.
4224#[cfg(feature = "local")]
4225pub async fn fetch_image_isolation_marker_in_cache_only(
4226    image: &str,
4227    cache: Arc<Box<dyn BlobCacheBackend>>,
4228    local_registry: Option<std::sync::Arc<crate::local_registry::LocalRegistry>>,
4229) -> Result<Option<String>> {
4230    let puller = inspection_puller(cache, local_registry);
4231    puller.image_isolation_marker_in_cache_only(image).await
4232}
4233
4234#[cfg(test)]
4235mod tests {
4236    use super::*;
4237
4238    // =========================================================================
4239    // Image Display Tests
4240    // =========================================================================
4241
4242    #[test]
4243    fn test_image_display() {
4244        let image = Image {
4245            registry: "docker.io".to_string(),
4246            repository: "library/nginx".to_string(),
4247            tag: "latest".to_string(),
4248        };
4249        assert_eq!(image.to_string(), "docker.io/library/nginx:latest");
4250    }
4251
4252    #[test]
4253    fn test_image_display_ghcr() {
4254        let image = Image {
4255            registry: "ghcr.io".to_string(),
4256            repository: "myorg/myrepo".to_string(),
4257            tag: "v1.2.3".to_string(),
4258        };
4259        assert_eq!(image.to_string(), "ghcr.io/myorg/myrepo:v1.2.3");
4260    }
4261
4262    #[test]
4263    fn test_image_display_with_nested_repo() {
4264        let image = Image {
4265            registry: "gcr.io".to_string(),
4266            repository: "project/subdir/image".to_string(),
4267            tag: "sha-abc123".to_string(),
4268        };
4269        assert_eq!(image.to_string(), "gcr.io/project/subdir/image:sha-abc123");
4270    }
4271
4272    #[test]
4273    fn test_image_clone() {
4274        let image = Image {
4275            registry: "docker.io".to_string(),
4276            repository: "library/nginx".to_string(),
4277            tag: "latest".to_string(),
4278        };
4279        let cloned = image.clone();
4280        assert_eq!(image, cloned);
4281        assert_eq!(cloned.registry, "docker.io");
4282        assert_eq!(cloned.repository, "library/nginx");
4283        assert_eq!(cloned.tag, "latest");
4284    }
4285
4286    #[test]
4287    fn test_image_equality() {
4288        let image1 = Image {
4289            registry: "docker.io".to_string(),
4290            repository: "library/nginx".to_string(),
4291            tag: "latest".to_string(),
4292        };
4293        let image2 = Image {
4294            registry: "docker.io".to_string(),
4295            repository: "library/nginx".to_string(),
4296            tag: "latest".to_string(),
4297        };
4298        let image3 = Image {
4299            registry: "ghcr.io".to_string(),
4300            repository: "library/nginx".to_string(),
4301            tag: "latest".to_string(),
4302        };
4303
4304        assert_eq!(image1, image2);
4305        assert_ne!(image1, image3);
4306    }
4307
4308    #[test]
4309    fn test_image_debug() {
4310        let image = Image {
4311            registry: "docker.io".to_string(),
4312            repository: "test".to_string(),
4313            tag: "v1".to_string(),
4314        };
4315        let debug_str = format!("{image:?}");
4316        assert!(debug_str.contains("Image"));
4317        assert!(debug_str.contains("docker.io"));
4318        assert!(debug_str.contains("test"));
4319        assert!(debug_str.contains("v1"));
4320    }
4321
4322    // =========================================================================
4323    // PushError Display Tests
4324    // =========================================================================
4325
4326    #[test]
4327    fn test_push_error_display_authentication_failed() {
4328        let err = PushError::AuthenticationFailed {
4329            registry: "ghcr.io".to_string(),
4330            reason: "invalid token".to_string(),
4331        };
4332        assert_eq!(
4333            err.to_string(),
4334            "authentication failed for registry ghcr.io: invalid token"
4335        );
4336    }
4337
4338    #[test]
4339    fn test_push_error_display_authentication_failed_empty_reason() {
4340        let err = PushError::AuthenticationFailed {
4341            registry: "docker.io".to_string(),
4342            reason: String::new(),
4343        };
4344        assert_eq!(
4345            err.to_string(),
4346            "authentication failed for registry docker.io: "
4347        );
4348    }
4349
4350    #[test]
4351    fn test_push_error_display_authentication_failed_long_reason() {
4352        let long_reason = "a]".repeat(100);
4353        let err = PushError::AuthenticationFailed {
4354            registry: "ghcr.io".to_string(),
4355            reason: long_reason.clone(),
4356        };
4357        assert!(err.to_string().contains(&long_reason));
4358    }
4359
4360    #[test]
4361    fn test_push_error_display_blob_upload_failed() {
4362        let err = PushError::BlobUploadFailed {
4363            digest: "sha256:abc123".to_string(),
4364            reason: "connection reset".to_string(),
4365        };
4366        assert_eq!(
4367            err.to_string(),
4368            "failed to upload blob sha256:abc123: connection reset"
4369        );
4370    }
4371
4372    #[test]
4373    fn test_push_error_display_blob_upload_failed_with_full_digest() {
4374        let digest =
4375            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".to_string();
4376        let err = PushError::BlobUploadFailed {
4377            digest: digest.clone(),
4378            reason: "timeout".to_string(),
4379        };
4380        assert!(err.to_string().contains(&digest));
4381        assert!(err.to_string().contains("timeout"));
4382    }
4383
4384    #[test]
4385    fn test_push_error_display_manifest_upload_failed() {
4386        let err = PushError::ManifestUploadFailed {
4387            reason: "invalid manifest".to_string(),
4388        };
4389        assert_eq!(
4390            err.to_string(),
4391            "failed to upload manifest: invalid manifest"
4392        );
4393    }
4394
4395    #[test]
4396    fn test_push_error_display_manifest_upload_failed_json_error() {
4397        let err = PushError::ManifestUploadFailed {
4398            reason: "invalid JSON: unexpected token at position 42".to_string(),
4399        };
4400        assert!(err.to_string().contains("invalid JSON"));
4401        assert!(err.to_string().contains("position 42"));
4402    }
4403
4404    #[test]
4405    fn test_push_error_display_network_error() {
4406        let err = PushError::NetworkError("timeout".to_string());
4407        assert_eq!(err.to_string(), "network error: timeout");
4408    }
4409
4410    #[test]
4411    fn test_push_error_display_network_error_connection_refused() {
4412        let err = PushError::NetworkError("connection refused: 127.0.0.1:5000".to_string());
4413        assert_eq!(
4414            err.to_string(),
4415            "network error: connection refused: 127.0.0.1:5000"
4416        );
4417    }
4418
4419    #[test]
4420    fn test_push_error_display_network_error_dns() {
4421        let err =
4422            PushError::NetworkError("DNS resolution failed for registry.example.com".to_string());
4423        assert!(err.to_string().contains("DNS resolution failed"));
4424    }
4425
4426    #[test]
4427    fn test_push_error_display_invalid_reference() {
4428        let err = PushError::InvalidReference {
4429            reference: "invalid::ref".to_string(),
4430        };
4431        assert_eq!(err.to_string(), "invalid image reference: invalid::ref");
4432    }
4433
4434    #[test]
4435    fn test_push_error_display_invalid_reference_empty() {
4436        let err = PushError::InvalidReference {
4437            reference: String::new(),
4438        };
4439        assert_eq!(err.to_string(), "invalid image reference: ");
4440    }
4441
4442    #[test]
4443    fn test_push_error_display_invalid_reference_special_chars() {
4444        let err = PushError::InvalidReference {
4445            reference: "ghcr.io/test/image:tag@sha256:abc".to_string(),
4446        };
4447        assert!(err
4448            .to_string()
4449            .contains("ghcr.io/test/image:tag@sha256:abc"));
4450    }
4451
4452    // =========================================================================
4453    // PushError Debug Tests
4454    // =========================================================================
4455
4456    #[test]
4457    fn test_push_error_debug_authentication_failed() {
4458        let err = PushError::AuthenticationFailed {
4459            registry: "ghcr.io".to_string(),
4460            reason: "invalid token".to_string(),
4461        };
4462        let debug_str = format!("{err:?}");
4463        assert!(debug_str.contains("AuthenticationFailed"));
4464        assert!(debug_str.contains("ghcr.io"));
4465        assert!(debug_str.contains("invalid token"));
4466    }
4467
4468    #[test]
4469    fn test_push_error_debug_blob_upload_failed() {
4470        let err = PushError::BlobUploadFailed {
4471            digest: "sha256:abc123".to_string(),
4472            reason: "network error".to_string(),
4473        };
4474        let debug_str = format!("{err:?}");
4475        assert!(debug_str.contains("BlobUploadFailed"));
4476        assert!(debug_str.contains("sha256:abc123"));
4477        assert!(debug_str.contains("network error"));
4478    }
4479
4480    #[test]
4481    fn test_push_error_debug_manifest_upload_failed() {
4482        let err = PushError::ManifestUploadFailed {
4483            reason: "schema validation failed".to_string(),
4484        };
4485        let debug_str = format!("{err:?}");
4486        assert!(debug_str.contains("ManifestUploadFailed"));
4487        assert!(debug_str.contains("schema validation failed"));
4488    }
4489
4490    #[test]
4491    fn test_push_error_debug_network_error() {
4492        let err = PushError::NetworkError("connection timed out".to_string());
4493        let debug_str = format!("{err:?}");
4494        assert!(debug_str.contains("NetworkError"));
4495        assert!(debug_str.contains("connection timed out"));
4496    }
4497
4498    #[test]
4499    fn test_push_error_debug_invalid_reference() {
4500        let err = PushError::InvalidReference {
4501            reference: "bad-ref".to_string(),
4502        };
4503        let debug_str = format!("{err:?}");
4504        assert!(debug_str.contains("InvalidReference"));
4505        assert!(debug_str.contains("bad-ref"));
4506    }
4507
4508    #[test]
4509    fn test_push_error_debug_oci_error() {
4510        // Create an OCI error using a valid variant (GenericError)
4511        let oci_err =
4512            oci_client::errors::OciDistributionError::GenericError(Some("test error".to_string()));
4513        let err = PushError::OciError(oci_err);
4514        let debug_str = format!("{err:?}");
4515        assert!(debug_str.contains("OciError"));
4516    }
4517
4518    // =========================================================================
4519    // PushError From OCI Error Tests
4520    // =========================================================================
4521
4522    #[test]
4523    fn test_push_error_from_oci_generic_error() {
4524        let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
4525            "generic error message".to_string(),
4526        ));
4527        let push_err: PushError = oci_err.into();
4528        match push_err {
4529            PushError::OciError(inner) => {
4530                assert!(inner.to_string().contains("generic error message"));
4531            }
4532            _ => panic!("Expected OciError variant"),
4533        }
4534    }
4535
4536    #[test]
4537    fn test_push_error_from_oci_config_conversion_error() {
4538        let oci_err = oci_client::errors::OciDistributionError::ConfigConversionError(
4539            "config conversion failed".to_string(),
4540        );
4541        let push_err: PushError = oci_err.into();
4542        match push_err {
4543            PushError::OciError(inner) => {
4544                assert!(inner.to_string().contains("config conversion"));
4545            }
4546            _ => panic!("Expected OciError variant"),
4547        }
4548    }
4549
4550    #[test]
4551    fn test_push_error_from_oci_manifest_parsing_error() {
4552        let oci_err = oci_client::errors::OciDistributionError::ManifestParsingError(
4553            "invalid manifest JSON".to_string(),
4554        );
4555        let push_err: PushError = oci_err.into();
4556        match push_err {
4557            PushError::OciError(inner) => {
4558                assert!(
4559                    inner.to_string().contains("manifest") || inner.to_string().contains("JSON")
4560                );
4561            }
4562            _ => panic!("Expected OciError variant"),
4563        }
4564    }
4565
4566    #[test]
4567    fn test_push_error_from_oci_image_manifest_not_found() {
4568        let oci_err = oci_client::errors::OciDistributionError::ImageManifestNotFoundError(
4569            "image:tag".to_string(),
4570        );
4571        let push_err: PushError = oci_err.into();
4572        match push_err {
4573            PushError::OciError(inner) => {
4574                assert!(inner.to_string().contains("image:tag"));
4575            }
4576            _ => panic!("Expected OciError variant"),
4577        }
4578    }
4579
4580    #[test]
4581    fn test_push_error_from_oci_url_parse_error() {
4582        let oci_err =
4583            oci_client::errors::OciDistributionError::UrlParseError("invalid URL".to_string());
4584        let push_err: PushError = oci_err.into();
4585        match push_err {
4586            PushError::OciError(inner) => {
4587                assert!(inner.to_string().contains("URL"));
4588            }
4589            _ => panic!("Expected OciError variant"),
4590        }
4591    }
4592
4593    #[test]
4594    fn test_push_error_from_oci_unsupported_schema_version() {
4595        let oci_err = oci_client::errors::OciDistributionError::UnsupportedSchemaVersionError(99);
4596        let push_err: PushError = oci_err.into();
4597        match push_err {
4598            PushError::OciError(inner) => {
4599                // The error should contain information about the version
4600                let _ = inner.to_string();
4601            }
4602            _ => panic!("Expected OciError variant"),
4603        }
4604    }
4605
4606    #[test]
4607    fn test_push_error_from_oci_unsupported_media_type() {
4608        let oci_err = oci_client::errors::OciDistributionError::UnsupportedMediaTypeError(
4609            "application/unknown".to_string(),
4610        );
4611        let push_err: PushError = oci_err.into();
4612        match push_err {
4613            PushError::OciError(inner) => {
4614                assert!(inner.to_string().contains("application/unknown"));
4615            }
4616            _ => panic!("Expected OciError variant"),
4617        }
4618    }
4619
4620    #[test]
4621    fn test_push_error_oci_error_display() {
4622        let oci_err = oci_client::errors::OciDistributionError::GenericError(Some(
4623            "version mismatch".to_string(),
4624        ));
4625        let push_err = PushError::OciError(oci_err);
4626        assert!(push_err.to_string().contains("OCI distribution error"));
4627    }
4628
4629    #[test]
4630    fn test_push_error_from_oci_spec_violation() {
4631        let oci_err = oci_client::errors::OciDistributionError::SpecViolationError(
4632            "OCI spec violation".to_string(),
4633        );
4634        let push_err: PushError = oci_err.into();
4635        match push_err {
4636            PushError::OciError(inner) => {
4637                assert!(
4638                    inner.to_string().contains("spec") || inner.to_string().contains("violation")
4639                );
4640            }
4641            _ => panic!("Expected OciError variant"),
4642        }
4643    }
4644
4645    #[test]
4646    fn test_push_error_from_oci_versioned_parsing_error() {
4647        let oci_err = oci_client::errors::OciDistributionError::VersionedParsingError(
4648            "failed to parse versioned content".to_string(),
4649        );
4650        let push_err: PushError = oci_err.into();
4651        match push_err {
4652            PushError::OciError(inner) => {
4653                let _ = inner.to_string();
4654            }
4655            _ => panic!("Expected OciError variant"),
4656        }
4657    }
4658
4659    #[test]
4660    fn test_push_error_from_oci_registry_token_decode() {
4661        let oci_err = oci_client::errors::OciDistributionError::RegistryTokenDecodeError(
4662            "invalid token format".to_string(),
4663        );
4664        let push_err: PushError = oci_err.into();
4665        match push_err {
4666            PushError::OciError(inner) => {
4667                assert!(inner.to_string().contains("token"));
4668            }
4669            _ => panic!("Expected OciError variant"),
4670        }
4671    }
4672
4673    #[test]
4674    fn test_push_error_from_oci_incompatible_layer_media_type() {
4675        let oci_err = oci_client::errors::OciDistributionError::IncompatibleLayerMediaTypeError(
4676            "application/vnd.incompatible".to_string(),
4677        );
4678        let push_err: PushError = oci_err.into();
4679        match push_err {
4680            PushError::OciError(inner) => {
4681                assert!(
4682                    inner.to_string().contains("incompatible")
4683                        || inner.to_string().contains("layer")
4684                );
4685            }
4686            _ => panic!("Expected OciError variant"),
4687        }
4688    }
4689
4690    // =========================================================================
4691    // PushResult Tests
4692    // =========================================================================
4693
4694    #[test]
4695    fn test_push_result_creation_all_fields() {
4696        let result = PushResult {
4697            manifest_digest: "sha256:abc123".to_string(),
4698            blobs_pushed: vec!["sha256:def456".to_string(), "sha256:ghi789".to_string()],
4699            reference: "ghcr.io/test/image:v1.0".to_string(),
4700        };
4701        assert_eq!(result.manifest_digest, "sha256:abc123");
4702        assert_eq!(result.blobs_pushed.len(), 2);
4703        assert_eq!(result.blobs_pushed[0], "sha256:def456");
4704        assert_eq!(result.blobs_pushed[1], "sha256:ghi789");
4705        assert_eq!(result.reference, "ghcr.io/test/image:v1.0");
4706    }
4707
4708    #[test]
4709    fn test_push_result_creation_empty_blobs() {
4710        let result = PushResult {
4711            manifest_digest: "sha256:empty".to_string(),
4712            blobs_pushed: vec![],
4713            reference: "docker.io/test:latest".to_string(),
4714        };
4715        assert!(result.blobs_pushed.is_empty());
4716        assert_eq!(result.manifest_digest, "sha256:empty");
4717    }
4718
4719    #[test]
4720    fn test_push_result_creation_single_blob() {
4721        let result = PushResult {
4722            manifest_digest: "sha256:single".to_string(),
4723            blobs_pushed: vec!["sha256:only_one".to_string()],
4724            reference: "registry.example.com/repo:tag".to_string(),
4725        };
4726        assert_eq!(result.blobs_pushed.len(), 1);
4727    }
4728
4729    #[test]
4730    fn test_push_result_creation_many_blobs() {
4731        let blobs: Vec<String> = (0..100).map(|i| format!("sha256:blob{i:03}")).collect();
4732        let result = PushResult {
4733            manifest_digest: "sha256:many".to_string(),
4734            blobs_pushed: blobs,
4735            reference: "test/image:v1".to_string(),
4736        };
4737        assert_eq!(result.blobs_pushed.len(), 100);
4738        assert_eq!(result.blobs_pushed[0], "sha256:blob000");
4739        assert_eq!(result.blobs_pushed[99], "sha256:blob099");
4740    }
4741
4742    #[test]
4743    fn test_push_result_clone() {
4744        let result = PushResult {
4745            manifest_digest: "sha256:abc".to_string(),
4746            blobs_pushed: vec!["sha256:def".to_string()],
4747            reference: "test:v1".to_string(),
4748        };
4749        let cloned = result.clone();
4750        assert_eq!(result.manifest_digest, cloned.manifest_digest);
4751        assert_eq!(result.blobs_pushed, cloned.blobs_pushed);
4752        assert_eq!(result.reference, cloned.reference);
4753    }
4754
4755    #[test]
4756    fn test_push_result_clone_independence() {
4757        let result = PushResult {
4758            manifest_digest: "sha256:original".to_string(),
4759            blobs_pushed: vec!["sha256:blob1".to_string()],
4760            reference: "original:v1".to_string(),
4761        };
4762        let mut cloned = result.clone();
4763        cloned.manifest_digest = "sha256:modified".to_string();
4764        cloned.blobs_pushed.push("sha256:blob2".to_string());
4765
4766        // Original should be unchanged
4767        assert_eq!(result.manifest_digest, "sha256:original");
4768        assert_eq!(result.blobs_pushed.len(), 1);
4769
4770        // Cloned should have changes
4771        assert_eq!(cloned.manifest_digest, "sha256:modified");
4772        assert_eq!(cloned.blobs_pushed.len(), 2);
4773    }
4774
4775    #[test]
4776    fn test_push_result_debug() {
4777        let result = PushResult {
4778            manifest_digest: "sha256:test".to_string(),
4779            blobs_pushed: vec!["sha256:blob1".to_string(), "sha256:blob2".to_string()],
4780            reference: "ghcr.io/org/repo:tag".to_string(),
4781        };
4782        let debug_str = format!("{result:?}");
4783        assert!(debug_str.contains("PushResult"));
4784        assert!(debug_str.contains("sha256:test"));
4785        assert!(debug_str.contains("sha256:blob1"));
4786        assert!(debug_str.contains("sha256:blob2"));
4787        assert!(debug_str.contains("ghcr.io/org/repo:tag"));
4788    }
4789
4790    #[test]
4791    fn test_push_result_with_full_sha256_digest() {
4792        let full_digest = "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
4793        let result = PushResult {
4794            manifest_digest: full_digest.to_string(),
4795            blobs_pushed: vec![full_digest.to_string()],
4796            reference: "test:latest".to_string(),
4797        };
4798        assert_eq!(result.manifest_digest.len(), 71); // "sha256:" + 64 hex chars
4799    }
4800
4801    // =========================================================================
4802    // Reference Parsing Tests (for push methods)
4803    // =========================================================================
4804
4805    #[test]
4806    fn test_valid_reference_parsing_docker_hub() {
4807        let reference = "docker.io/library/nginx:latest";
4808        let parsed: Result<Reference, _> = reference.parse();
4809        assert!(parsed.is_ok());
4810    }
4811
4812    #[test]
4813    fn test_valid_reference_parsing_ghcr() {
4814        let reference = "ghcr.io/myorg/myrepo:v1.0.0";
4815        let parsed: Result<Reference, _> = reference.parse();
4816        assert!(parsed.is_ok());
4817    }
4818
4819    #[test]
4820    fn test_valid_reference_parsing_with_digest() {
4821        let reference = "ghcr.io/test/image@sha256:abc123def456789012345678901234567890123456789012345678901234";
4822        let parsed: Result<Reference, _> = reference.parse();
4823        // Note: The oci_client may or may not accept this format
4824        // This test documents the current behavior
4825        let _ = parsed;
4826    }
4827
4828    #[test]
4829    fn test_valid_reference_parsing_nested_repo() {
4830        let reference = "gcr.io/project-id/subdir/image:tag";
4831        let parsed: Result<Reference, _> = reference.parse();
4832        assert!(parsed.is_ok());
4833    }
4834
4835    #[test]
4836    fn test_invalid_reference_empty() {
4837        let reference = "";
4838        let parsed: Result<Reference, _> = reference.parse();
4839        assert!(parsed.is_err());
4840    }
4841
4842    #[test]
4843    fn test_invalid_reference_double_colon() {
4844        let reference = "invalid::reference";
4845        let parsed: Result<Reference, _> = reference.parse();
4846        assert!(parsed.is_err());
4847    }
4848
4849    // =========================================================================
4850    // PushError Construction Helper Tests
4851    // =========================================================================
4852
4853    #[test]
4854    fn test_push_error_authentication_failed_construction() {
4855        let err = PushError::AuthenticationFailed {
4856            registry: "test.registry.io".to_string(),
4857            reason: "credentials expired".to_string(),
4858        };
4859        // Verify the error contains the expected information
4860        let display = err.to_string();
4861        assert!(display.contains("test.registry.io"));
4862        assert!(display.contains("credentials expired"));
4863    }
4864
4865    #[test]
4866    fn test_push_error_blob_upload_failed_construction() {
4867        let digest = "sha256:1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef";
4868        let err = PushError::BlobUploadFailed {
4869            digest: digest.to_string(),
4870            reason: "server returned 500".to_string(),
4871        };
4872        let display = err.to_string();
4873        assert!(display.contains(digest));
4874        assert!(display.contains("server returned 500"));
4875    }
4876
4877    #[test]
4878    fn test_push_error_manifest_upload_failed_construction() {
4879        let err = PushError::ManifestUploadFailed {
4880            reason: "manifest already exists with different content".to_string(),
4881        };
4882        let display = err.to_string();
4883        assert!(display.contains("manifest already exists"));
4884    }
4885
4886    #[test]
4887    fn test_push_error_network_error_construction() {
4888        let err = PushError::NetworkError("TLS handshake failed".to_string());
4889        let display = err.to_string();
4890        assert!(display.contains("TLS handshake failed"));
4891    }
4892
4893    #[test]
4894    fn test_push_error_invalid_reference_construction() {
4895        let err = PushError::InvalidReference {
4896            reference: "not/a/valid/reference!!!".to_string(),
4897        };
4898        let display = err.to_string();
4899        assert!(display.contains("not/a/valid/reference!!!"));
4900    }
4901
4902    // =========================================================================
4903    // Error Variant Discrimination Tests
4904    // =========================================================================
4905
4906    #[test]
4907    fn test_push_error_is_authentication_failed() {
4908        let err = PushError::AuthenticationFailed {
4909            registry: "test".to_string(),
4910            reason: "test".to_string(),
4911        };
4912        assert!(matches!(err, PushError::AuthenticationFailed { .. }));
4913        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4914        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4915        assert!(!matches!(err, PushError::NetworkError(_)));
4916        assert!(!matches!(err, PushError::InvalidReference { .. }));
4917        assert!(!matches!(err, PushError::OciError(_)));
4918    }
4919
4920    #[test]
4921    fn test_push_error_is_blob_upload_failed() {
4922        let err = PushError::BlobUploadFailed {
4923            digest: "test".to_string(),
4924            reason: "test".to_string(),
4925        };
4926        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4927        assert!(matches!(err, PushError::BlobUploadFailed { .. }));
4928        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4929        assert!(!matches!(err, PushError::NetworkError(_)));
4930        assert!(!matches!(err, PushError::InvalidReference { .. }));
4931        assert!(!matches!(err, PushError::OciError(_)));
4932    }
4933
4934    #[test]
4935    fn test_push_error_is_manifest_upload_failed() {
4936        let err = PushError::ManifestUploadFailed {
4937            reason: "test".to_string(),
4938        };
4939        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4940        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4941        assert!(matches!(err, PushError::ManifestUploadFailed { .. }));
4942        assert!(!matches!(err, PushError::NetworkError(_)));
4943        assert!(!matches!(err, PushError::InvalidReference { .. }));
4944        assert!(!matches!(err, PushError::OciError(_)));
4945    }
4946
4947    #[test]
4948    fn test_push_error_is_network_error() {
4949        let err = PushError::NetworkError("test".to_string());
4950        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4951        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4952        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4953        assert!(matches!(err, PushError::NetworkError(_)));
4954        assert!(!matches!(err, PushError::InvalidReference { .. }));
4955        assert!(!matches!(err, PushError::OciError(_)));
4956    }
4957
4958    #[test]
4959    fn test_push_error_is_invalid_reference() {
4960        let err = PushError::InvalidReference {
4961            reference: "test".to_string(),
4962        };
4963        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4964        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4965        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4966        assert!(!matches!(err, PushError::NetworkError(_)));
4967        assert!(matches!(err, PushError::InvalidReference { .. }));
4968        assert!(!matches!(err, PushError::OciError(_)));
4969    }
4970
4971    #[test]
4972    fn test_push_error_is_oci_error() {
4973        let oci_err =
4974            oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
4975        let err = PushError::OciError(oci_err);
4976        assert!(!matches!(err, PushError::AuthenticationFailed { .. }));
4977        assert!(!matches!(err, PushError::BlobUploadFailed { .. }));
4978        assert!(!matches!(err, PushError::ManifestUploadFailed { .. }));
4979        assert!(!matches!(err, PushError::NetworkError(_)));
4980        assert!(!matches!(err, PushError::InvalidReference { .. }));
4981        assert!(matches!(err, PushError::OciError(_)));
4982    }
4983
4984    // =========================================================================
4985    // Error std::error::Error Trait Tests
4986    // =========================================================================
4987
4988    #[test]
4989    fn test_push_error_implements_error_trait() {
4990        let err = PushError::NetworkError("test".to_string());
4991        // Verify it implements std::error::Error by using the Error trait
4992        let _: &dyn std::error::Error = &err;
4993    }
4994
4995    #[test]
4996    fn test_push_error_source_for_oci_error() {
4997        use std::error::Error;
4998        let oci_err =
4999            oci_client::errors::OciDistributionError::GenericError(Some("test".to_string()));
5000        let err = PushError::OciError(oci_err);
5001        // OciError variant should have a source
5002        let source = err.source();
5003        assert!(source.is_some());
5004    }
5005
5006    #[test]
5007    fn test_push_error_source_for_other_variants() {
5008        use std::error::Error;
5009
5010        let err1 = PushError::AuthenticationFailed {
5011            registry: "test".to_string(),
5012            reason: "test".to_string(),
5013        };
5014        assert!(err1.source().is_none());
5015
5016        let err2 = PushError::BlobUploadFailed {
5017            digest: "test".to_string(),
5018            reason: "test".to_string(),
5019        };
5020        assert!(err2.source().is_none());
5021
5022        let err3 = PushError::ManifestUploadFailed {
5023            reason: "test".to_string(),
5024        };
5025        assert!(err3.source().is_none());
5026
5027        let err4 = PushError::NetworkError("test".to_string());
5028        assert!(err4.source().is_none());
5029
5030        let err5 = PushError::InvalidReference {
5031            reference: "test".to_string(),
5032        };
5033        assert!(err5.source().is_none());
5034    }
5035
5036    // =========================================================================
5037    // ImagePuller Creation Tests (without network)
5038    // =========================================================================
5039
5040    #[test]
5041    fn test_image_puller_creation_with_blob_cache() {
5042        let cache = crate::cache::BlobCache::new().unwrap();
5043        let puller = ImagePuller::new(cache);
5044        // Just verify it was created successfully
5045        let _ = puller;
5046    }
5047
5048    #[test]
5049    fn test_image_puller_with_concurrency_limit() {
5050        let cache = crate::cache::BlobCache::new().unwrap();
5051        let puller = ImagePuller::new(cache).with_concurrency_limit(5);
5052        let _ = puller;
5053    }
5054
5055    #[test]
5056    fn test_image_puller_with_concurrency_limit_one() {
5057        let cache = crate::cache::BlobCache::new().unwrap();
5058        let puller = ImagePuller::new(cache).with_concurrency_limit(1);
5059        let _ = puller;
5060    }
5061
5062    #[test]
5063    fn test_image_puller_with_shared_cache() {
5064        let cache = crate::cache::BlobCache::new().unwrap();
5065        let shared: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(cache));
5066        let puller = ImagePuller::with_cache(shared);
5067        let _ = puller;
5068    }
5069
5070    // =========================================================================
5071    // Push Method Reference Validation Tests (async)
5072    // =========================================================================
5073
5074    #[tokio::test]
5075    async fn test_push_blob_invalid_reference_returns_error() {
5076        let cache = crate::cache::BlobCache::new().unwrap();
5077        let puller = ImagePuller::new(cache);
5078
5079        let result = puller
5080            .push_blob(
5081                "invalid::reference",
5082                "sha256:test",
5083                b"test data",
5084                "application/octet-stream",
5085                &RegistryAuth::Anonymous,
5086            )
5087            .await;
5088
5089        assert!(result.is_err());
5090        match result {
5091            Err(PushError::InvalidReference { reference }) => {
5092                assert_eq!(reference, "invalid::reference");
5093            }
5094            other => panic!("Expected InvalidReference error, got {other:?}"),
5095        }
5096    }
5097
5098    #[tokio::test]
5099    async fn test_push_blob_empty_reference_returns_error() {
5100        let cache = crate::cache::BlobCache::new().unwrap();
5101        let puller = ImagePuller::new(cache);
5102
5103        let result = puller
5104            .push_blob(
5105                "",
5106                "sha256:test",
5107                b"test data",
5108                "application/octet-stream",
5109                &RegistryAuth::Anonymous,
5110            )
5111            .await;
5112
5113        assert!(result.is_err());
5114        match result {
5115            Err(PushError::InvalidReference { reference }) => {
5116                assert!(reference.is_empty());
5117            }
5118            other => panic!("Expected InvalidReference error, got {other:?}"),
5119        }
5120    }
5121
5122    #[tokio::test]
5123    async fn test_push_manifest_invalid_reference_returns_error() {
5124        let cache = crate::cache::BlobCache::new().unwrap();
5125        let puller = ImagePuller::new(cache);
5126
5127        let manifest = oci_client::manifest::OciImageManifest::default();
5128
5129        let result = puller
5130            .push_manifest_to_registry("invalid::reference", &manifest, &RegistryAuth::Anonymous)
5131            .await;
5132
5133        assert!(result.is_err());
5134        match result {
5135            Err(PushError::InvalidReference { reference }) => {
5136                assert_eq!(reference, "invalid::reference");
5137            }
5138            other => panic!("Expected InvalidReference error, got {other:?}"),
5139        }
5140    }
5141
5142    #[tokio::test]
5143    async fn test_push_manifest_empty_reference_returns_error() {
5144        let cache = crate::cache::BlobCache::new().unwrap();
5145        let puller = ImagePuller::new(cache);
5146
5147        let manifest = oci_client::manifest::OciImageManifest::default();
5148
5149        let result = puller
5150            .push_manifest_to_registry("", &manifest, &RegistryAuth::Anonymous)
5151            .await;
5152
5153        assert!(result.is_err());
5154        match result {
5155            Err(PushError::InvalidReference { reference }) => {
5156                assert!(reference.is_empty());
5157            }
5158            other => panic!("Expected InvalidReference error, got {other:?}"),
5159        }
5160    }
5161
5162    // =========================================================================
5163    // Push WASM Reference Validation Tests (async, feature-gated)
5164    // =========================================================================
5165
5166    #[cfg(feature = "local")]
5167    #[tokio::test]
5168    async fn test_push_wasm_invalid_reference_returns_error() {
5169        use crate::wasm::WasiVersion;
5170        use crate::wasm_export::WasmExportResult;
5171
5172        let cache = crate::cache::BlobCache::new().unwrap();
5173        let puller = ImagePuller::new(cache);
5174
5175        let export_result = WasmExportResult {
5176            manifest_digest: "sha256:test".to_string(),
5177            manifest_size: 100,
5178            wasm_layer_digest: "sha256:wasm".to_string(),
5179            wasm_size: 1000,
5180            config_digest: "sha256:config".to_string(),
5181            config_size: 2,
5182            wasi_version: WasiVersion::Preview1,
5183            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5184            manifest_json: b"{}".to_vec(),
5185            config_blob: b"{}".to_vec(),
5186            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00],
5187        };
5188
5189        let result = puller
5190            .push_wasm(
5191                "invalid::reference",
5192                &export_result,
5193                &RegistryAuth::Anonymous,
5194            )
5195            .await;
5196
5197        assert!(result.is_err());
5198        match result {
5199            Err(PushError::InvalidReference { reference }) => {
5200                assert_eq!(reference, "invalid::reference");
5201            }
5202            other => panic!("Expected InvalidReference error, got {other:?}"),
5203        }
5204    }
5205
5206    #[cfg(feature = "local")]
5207    #[tokio::test]
5208    async fn test_push_wasm_empty_reference_returns_error() {
5209        use crate::wasm::WasiVersion;
5210        use crate::wasm_export::WasmExportResult;
5211
5212        let cache = crate::cache::BlobCache::new().unwrap();
5213        let puller = ImagePuller::new(cache);
5214
5215        let export_result = WasmExportResult {
5216            manifest_digest: "sha256:test".to_string(),
5217            manifest_size: 100,
5218            wasm_layer_digest: "sha256:wasm".to_string(),
5219            wasm_size: 1000,
5220            config_digest: "sha256:config".to_string(),
5221            config_size: 2,
5222            wasi_version: WasiVersion::Preview2,
5223            artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
5224            manifest_json: b"{}".to_vec(),
5225            config_blob: b"{}".to_vec(),
5226            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d, 0x0d, 0x00, 0x01, 0x00],
5227        };
5228
5229        let result = puller
5230            .push_wasm("", &export_result, &RegistryAuth::Anonymous)
5231            .await;
5232
5233        assert!(result.is_err());
5234        match result {
5235            Err(PushError::InvalidReference { reference }) => {
5236                assert!(reference.is_empty());
5237            }
5238            other => panic!("Expected InvalidReference error, got {other:?}"),
5239        }
5240    }
5241
5242    // =========================================================================
5243    // WasmExportResult Field Verification Tests (feature-gated)
5244    // =========================================================================
5245
5246    #[cfg(feature = "local")]
5247    #[test]
5248    fn test_wasm_export_result_debug_formatting() {
5249        use crate::wasm::WasiVersion;
5250        use crate::wasm_export::WasmExportResult;
5251
5252        let result = WasmExportResult {
5253            manifest_digest: "sha256:manifest".to_string(),
5254            manifest_size: 500,
5255            wasm_layer_digest: "sha256:layer".to_string(),
5256            wasm_size: 10000,
5257            config_digest: "sha256:cfg".to_string(),
5258            config_size: 2,
5259            wasi_version: WasiVersion::Preview2,
5260            artifact_type: "application/vnd.wasm.component.v1+wasm".to_string(),
5261            manifest_json: vec![],
5262            config_blob: vec![],
5263            wasm_binary: vec![],
5264        };
5265
5266        let debug_str = format!("{result:?}");
5267        assert!(debug_str.contains("WasmExportResult"));
5268        assert!(debug_str.contains("sha256:manifest"));
5269        assert!(debug_str.contains("sha256:layer"));
5270        assert!(debug_str.contains("Preview2"));
5271    }
5272
5273    #[cfg(feature = "local")]
5274    #[test]
5275    fn test_wasm_export_result_clone_independence() {
5276        use crate::wasm::WasiVersion;
5277        use crate::wasm_export::WasmExportResult;
5278
5279        let result = WasmExportResult {
5280            manifest_digest: "sha256:original".to_string(),
5281            manifest_size: 100,
5282            wasm_layer_digest: "sha256:wasm".to_string(),
5283            wasm_size: 1000,
5284            config_digest: "sha256:config".to_string(),
5285            config_size: 2,
5286            wasi_version: WasiVersion::Preview1,
5287            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5288            manifest_json: b"{}".to_vec(),
5289            config_blob: b"{}".to_vec(),
5290            wasm_binary: vec![0x00, 0x61, 0x73, 0x6d],
5291        };
5292
5293        let mut cloned = result.clone();
5294        cloned.manifest_digest = "sha256:modified".to_string();
5295
5296        // Original should be unchanged
5297        assert_eq!(result.manifest_digest, "sha256:original");
5298        assert_eq!(cloned.manifest_digest, "sha256:modified");
5299    }
5300
5301    #[cfg(feature = "local")]
5302    #[test]
5303    fn test_wasm_export_result_all_fields_populated() {
5304        use crate::wasm::WasiVersion;
5305        use crate::wasm_export::WasmExportResult;
5306
5307        let wasm_binary = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
5308        let config_blob = b"{}".to_vec();
5309        let manifest_json = b"{\"schemaVersion\": 2}".to_vec();
5310
5311        let result = WasmExportResult {
5312            manifest_digest: "sha256:abc".to_string(),
5313            manifest_size: manifest_json.len() as u64,
5314            wasm_layer_digest: "sha256:def".to_string(),
5315            wasm_size: wasm_binary.len() as u64,
5316            config_digest: "sha256:ghi".to_string(),
5317            config_size: config_blob.len() as u64,
5318            wasi_version: WasiVersion::Preview1,
5319            artifact_type: "application/vnd.wasm.module.v1+wasm".to_string(),
5320            manifest_json: manifest_json.clone(),
5321            config_blob: config_blob.clone(),
5322            wasm_binary: wasm_binary.clone(),
5323        };
5324
5325        // Verify all fields
5326        assert!(result.manifest_digest.starts_with("sha256:"));
5327        assert_eq!(result.manifest_size, manifest_json.len() as u64);
5328        assert!(result.wasm_layer_digest.starts_with("sha256:"));
5329        assert_eq!(result.wasm_size, wasm_binary.len() as u64);
5330        assert!(result.config_digest.starts_with("sha256:"));
5331        assert_eq!(result.config_size, config_blob.len() as u64);
5332        assert_eq!(result.wasi_version, WasiVersion::Preview1);
5333        assert!(result.artifact_type.contains("wasm"));
5334        assert!(!result.manifest_json.is_empty());
5335        assert!(!result.config_blob.is_empty());
5336        assert!(!result.wasm_binary.is_empty());
5337    }
5338
5339    // =========================================================================
5340    // Integration Tests for Push Flow (Documenting Expected Behavior)
5341    // =========================================================================
5342    // Note: These tests document the expected behavior of push operations.
5343    // Full integration tests would require a mock registry server.
5344
5345    #[test]
5346    fn test_push_flow_documentation_blob_before_manifest() {
5347        // This test documents that blobs must be pushed before the manifest.
5348        // The manifest references blobs by digest, so blobs must exist first.
5349        //
5350        // Expected flow:
5351        // 1. Push config blob -> get config digest
5352        // 2. Push layer blob(s) -> get layer digest(s)
5353        // 3. Build manifest referencing the digests
5354        // 4. Push manifest
5355        //
5356        // This is enforced by the push_wasm method which pushes blobs first.
5357    }
5358
5359    #[test]
5360    fn test_push_flow_documentation_authentication_order() {
5361        // This test documents that authentication happens before each push operation.
5362        // The client authenticates separately for blob and manifest pushes.
5363        //
5364        // Expected flow for push_blob:
5365        // 1. Parse reference
5366        // 2. Authenticate for push operation
5367        // 3. Push blob data
5368        //
5369        // Expected flow for push_manifest:
5370        // 1. Parse reference
5371        // 2. Authenticate for push operation
5372        // 3. Push manifest
5373    }
5374
5375    #[test]
5376    fn test_push_result_blobs_pushed_order() {
5377        // This test documents that blobs_pushed should contain digests
5378        // in the order they were pushed (config first, then layers).
5379        //
5380        // For WASM artifacts:
5381        // - blobs_pushed[0] = config digest (empty JSON)
5382        // - blobs_pushed[1] = wasm layer digest
5383        let result = PushResult {
5384            manifest_digest: "sha256:manifest".to_string(),
5385            blobs_pushed: vec!["sha256:config".to_string(), "sha256:wasm_layer".to_string()],
5386            reference: "test:v1".to_string(),
5387        };
5388
5389        assert_eq!(result.blobs_pushed.len(), 2);
5390        // Config is pushed first
5391        assert!(result.blobs_pushed[0].contains("config"));
5392        // Layer is pushed second
5393        assert!(result.blobs_pushed[1].contains("layer"));
5394    }
5395
5396    // =========================================================================
5397    // is_mutable_tag Tests
5398    // =========================================================================
5399
5400    #[test]
5401    fn is_mutable_tag_recognises_no_tag() {
5402        assert!(is_mutable_tag("nginx"));
5403        assert!(is_mutable_tag("zachhandley/zlayer-manager"));
5404        assert!(is_mutable_tag("registry.example.com:5000/img"));
5405    }
5406
5407    #[test]
5408    fn is_mutable_tag_recognises_empty_tag() {
5409        assert!(is_mutable_tag("nginx:"));
5410    }
5411
5412    #[test]
5413    fn is_mutable_tag_recognises_known_mutable_tags() {
5414        assert!(is_mutable_tag("nginx:latest"));
5415        assert!(is_mutable_tag("nginx:dev"));
5416        assert!(is_mutable_tag("nginx:edge"));
5417        assert!(is_mutable_tag("nginx:main"));
5418        assert!(is_mutable_tag("nginx:master"));
5419        assert!(is_mutable_tag("zachhandley/zlayer-manager:latest"));
5420        assert!(is_mutable_tag("registry.example.com:5000/img:latest"));
5421    }
5422
5423    #[test]
5424    fn is_mutable_tag_rejects_pinned_tags() {
5425        assert!(!is_mutable_tag("nginx:1.25"));
5426        assert!(!is_mutable_tag("nginx:1.25.3"));
5427        assert!(!is_mutable_tag("zachhandley/zlayer-manager:v0.10.70"));
5428        assert!(!is_mutable_tag("registry.example.com:5000/img:v1"));
5429    }
5430
5431    #[test]
5432    fn is_mutable_tag_rejects_digest_refs() {
5433        assert!(!is_mutable_tag(
5434            "img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5435        ));
5436        assert!(!is_mutable_tag(
5437            "nginx:latest@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5438        ));
5439        assert!(!is_mutable_tag(
5440            "registry.example.com:5000/img@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
5441        ));
5442    }
5443
5444    // =========================================================================
5445    // Foreign-layer redirect fallback tests (MCR urls[])
5446    // =========================================================================
5447
5448    #[test]
5449    fn is_blob_not_found_detects_404_server_error() {
5450        use oci_client::errors::OciDistributionError;
5451        let err = OciDistributionError::ServerError {
5452            code: 404,
5453            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5454            message: "not found".to_string(),
5455        };
5456        assert!(is_blob_not_found(&err));
5457    }
5458
5459    #[test]
5460    fn is_blob_not_found_detects_manifest_not_found() {
5461        use oci_client::errors::OciDistributionError;
5462        let err = OciDistributionError::ImageManifestNotFoundError("foo".to_string());
5463        assert!(is_blob_not_found(&err));
5464    }
5465
5466    #[test]
5467    fn is_blob_not_found_detects_blob_unknown_registry_error() {
5468        use oci_client::errors::{OciDistributionError, OciEnvelope, OciError, OciErrorCode};
5469        let envelope = OciEnvelope {
5470            errors: vec![OciError {
5471                code: OciErrorCode::BlobUnknown,
5472                message: "blob gone".to_string(),
5473                detail: serde_json::Value::Null,
5474            }],
5475        };
5476        let err = OciDistributionError::RegistryError {
5477            envelope,
5478            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5479        };
5480        assert!(is_blob_not_found(&err));
5481    }
5482
5483    #[test]
5484    fn is_blob_not_found_rejects_non_404_server_error() {
5485        use oci_client::errors::OciDistributionError;
5486        let err = OciDistributionError::ServerError {
5487            code: 500,
5488            url: "https://example.com/v2/foo/blobs/sha256:abc".to_string(),
5489            message: "boom".to_string(),
5490        };
5491        assert!(!is_blob_not_found(&err));
5492    }
5493
5494    #[test]
5495    fn is_blob_not_found_rejects_auth_failure() {
5496        use oci_client::errors::OciDistributionError;
5497        let err = OciDistributionError::AuthenticationFailure("bad creds".to_string());
5498        assert!(!is_blob_not_found(&err));
5499    }
5500
5501    #[test]
5502    fn max_foreign_layer_redirects_is_capped() {
5503        // Guard against silently lifting the redirect cap — the pull path uses
5504        // .take(MAX_FOREIGN_LAYER_REDIRECTS) to avoid redirect spam.
5505        assert_eq!(MAX_FOREIGN_LAYER_REDIRECTS, 5);
5506    }
5507
5508    #[tokio::test]
5509    async fn fetch_blob_from_url_rejects_invalid_url() {
5510        let result = fetch_blob_from_url(
5511            "not-a-url",
5512            "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
5513            None,
5514        )
5515        .await;
5516        assert!(result.is_err());
5517    }
5518
5519    #[tokio::test]
5520    async fn fetch_archive_from_url_rejects_invalid_url() {
5521        let result = fetch_archive_from_url("not-a-url", None).await;
5522        assert!(result.is_err());
5523    }
5524
5525    #[tokio::test]
5526    async fn fetch_archive_from_url_rejects_unreachable_host() {
5527        // 127.0.0.1:1 is not bound; connect refused happens synchronously.
5528        let result = fetch_archive_from_url("http://127.0.0.1:1/archive.tar", None).await;
5529        assert!(result.is_err());
5530    }
5531
5532    #[tokio::test]
5533    async fn fetch_archive_from_url_accepts_basic_auth_without_panic() {
5534        // Auth should be forwarded to the reqwest builder; errors still surface
5535        // cleanly when the host is unreachable. Regression guard for the
5536        // `.basic_auth(user, Some(pw))` call path.
5537        let result =
5538            fetch_archive_from_url("http://127.0.0.1:1/archive.tar", Some(("user", "password")))
5539                .await;
5540        assert!(result.is_err());
5541    }
5542
5543    #[tokio::test]
5544    async fn fetch_from_url_surfaces_context_in_error() {
5545        let result = fetch_from_url("http://127.0.0.1:1/thing", None, "test-context").await;
5546        let Err(err) = result else {
5547            panic!("expected connect-refused error");
5548        };
5549        let msg = err.to_string();
5550        assert!(
5551            msg.contains("test-context"),
5552            "error should include context label, got: {msg}"
5553        );
5554    }
5555
5556    #[tokio::test]
5557    async fn fetch_blob_from_url_rejects_unreachable_host() {
5558        // 127.0.0.1:1 is not bound; connect refused happens synchronously.
5559        let result = fetch_blob_from_url(
5560            "http://127.0.0.1:1/foo",
5561            "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
5562            None,
5563        )
5564        .await;
5565        assert!(result.is_err());
5566    }
5567
5568    // =========================================================================
5569    // OCI image-index following on stored manifest reads
5570    // =========================================================================
5571
5572    #[test]
5573    fn parse_image_manifest_only_rejects_index() {
5574        // An index body (no `config`, has `manifests`) must NOT parse as an image
5575        // manifest — this is the `missing field config` crash the fix removes.
5576        let index_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}"#;
5577        assert!(parse_image_manifest_only(index_json).is_none());
5578    }
5579
5580    #[test]
5581    fn parse_image_manifest_only_accepts_image_manifest() {
5582        let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
5583        assert!(parse_image_manifest_only(image_json).is_some());
5584    }
5585
5586    #[cfg(feature = "local")]
5587    #[tokio::test]
5588    async fn resolve_stored_manifest_follows_local_index() {
5589        let tmp = tempfile::TempDir::new().unwrap();
5590        let registry = std::sync::Arc::new(
5591            crate::local_registry::LocalRegistry::new(tmp.path().to_path_buf())
5592                .await
5593                .unwrap(),
5594        );
5595
5596        // Store a concrete platform image manifest; capture its content digest.
5597        let image_json = br#"{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{"mediaType":"application/vnd.oci.image.config.v1+json","digest":"sha256:cfg","size":1},"layers":[]}"#;
5598        let sub_digest = registry
5599            .put_manifest("test/img", "sha256:ignored", image_json)
5600            .await
5601            .unwrap();
5602
5603        // Build an index referencing it for THIS host platform, then hand the raw
5604        // index bytes to the resolver exactly as `try_local_registry` would.
5605        let index = OciImageIndex {
5606            schema_version: 2,
5607            media_type: Some("application/vnd.oci.image.index.v1+json".to_string()),
5608            manifests: vec![mk_entry(go_os_name(), go_arch_name(), None, &sub_digest)],
5609            artifact_type: None,
5610            annotations: None,
5611        };
5612        let index_bytes = serde_json::to_vec(&index).unwrap();
5613
5614        let cache: Arc<Box<dyn BlobCacheBackend>> =
5615            Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
5616        let puller = ImagePuller::with_cache(cache).with_local_registry(registry.clone());
5617
5618        // The index resolves to the host-platform sub-manifest (by digest).
5619        let (_manifest, digest) = puller
5620            .resolve_stored_manifest(&registry, "test/img", &index_bytes)
5621            .await
5622            .expect("index should resolve to the host-platform manifest");
5623        assert_eq!(digest, sub_digest);
5624
5625        // A plain image manifest passes through unchanged.
5626        let (_m2, d2) = puller
5627            .resolve_stored_manifest(&registry, "test/img", image_json)
5628            .await
5629            .expect("plain image manifest should resolve as-is");
5630        assert_eq!(d2, sub_digest);
5631    }
5632
5633    // =========================================================================
5634    // build_platform_resolver tests — Windows os.version handling
5635    // =========================================================================
5636
5637    /// Helper: build a minimal `ImageIndexEntry` with `os` / `arch` / optional
5638    /// `os.version` — all we need for resolver tests.
5639    fn mk_entry(os: &str, arch: &str, os_version: Option<&str>, digest: &str) -> ImageIndexEntry {
5640        ImageIndexEntry {
5641            media_type: "application/vnd.oci.image.manifest.v1+json".to_string(),
5642            digest: digest.to_string(),
5643            size: 0,
5644            platform: Some(oci_client::manifest::Platform {
5645                architecture: arch.to_string(),
5646                os: os.to_string(),
5647                os_version: os_version.map(str::to_string),
5648                os_features: None,
5649                variant: None,
5650                features: None,
5651            }),
5652            annotations: None,
5653        }
5654    }
5655
5656    #[test]
5657    fn platform_resolver_windows_os_version_prefers_prefix_match() {
5658        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5659        // Two windows/amd64 entries differing only by os.version. Target
5660        // matches the 26100 family (Server 2025 / Win11 24H2).
5661        let manifests = vec![
5662            mk_entry(
5663                "windows",
5664                "amd64",
5665                Some("10.0.20348.2113"),
5666                "sha256:server2022",
5667            ),
5668            mk_entry(
5669                "windows",
5670                "amd64",
5671                Some("10.0.26100.1742"),
5672                "sha256:server2025",
5673            ),
5674        ];
5675        let target =
5676            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
5677        let resolver = build_platform_resolver(Some(target));
5678        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
5679    }
5680
5681    #[test]
5682    fn platform_resolver_windows_os_version_exact_match() {
5683        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5684        let manifests = vec![
5685            mk_entry(
5686                "windows",
5687                "amd64",
5688                Some("10.0.20348.2113"),
5689                "sha256:server2022",
5690            ),
5691            mk_entry(
5692                "windows",
5693                "amd64",
5694                Some("10.0.26100.1742"),
5695                "sha256:server2025",
5696            ),
5697        ];
5698        let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64)
5699            .with_os_version("10.0.26100.1742");
5700        let resolver = build_platform_resolver(Some(target));
5701        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:server2025"));
5702    }
5703
5704    #[test]
5705    fn platform_resolver_windows_no_os_version_falls_back_to_first_match() {
5706        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5707        // When the caller doesn't pin os_version the resolver's behavior is
5708        // unchanged from Phase A: it picks the first os+arch match.
5709        let manifests = vec![
5710            mk_entry("windows", "amd64", Some("10.0.20348.2113"), "sha256:first"),
5711            mk_entry("windows", "amd64", Some("10.0.26100.1742"), "sha256:second"),
5712        ];
5713        let target = TargetPlatform::new(OsKind::Windows, ArchKind::Amd64);
5714        let resolver = build_platform_resolver(Some(target));
5715        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:first"));
5716    }
5717
5718    #[test]
5719    fn platform_resolver_windows_os_version_falls_back_when_no_version_match() {
5720        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5721        // Target wants 26100 but the index only has 20348. Fall back to the
5722        // any-windows/amd64 entry rather than returning None — otherwise a
5723        // bootstrap image that ships a single old-build manifest is
5724        // unpullable on a new host.
5725        let manifests = vec![mk_entry(
5726            "windows",
5727            "amd64",
5728            Some("10.0.20348.2113"),
5729            "sha256:only",
5730        )];
5731        let target =
5732            TargetPlatform::new(OsKind::Windows, ArchKind::Amd64).with_os_version("10.0.26100");
5733        let resolver = build_platform_resolver(Some(target));
5734        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:only"));
5735    }
5736
5737    #[test]
5738    fn platform_resolver_non_windows_ignores_os_version() {
5739        use zlayer_spec::{ArchKind, OsKind, TargetPlatform};
5740        // os_version is a Windows-only concept; setting it on a Linux target
5741        // must NOT accidentally filter out a valid linux/amd64 manifest.
5742        let manifests = vec![mk_entry("linux", "amd64", None, "sha256:linux")];
5743        let target =
5744            TargetPlatform::new(OsKind::Linux, ArchKind::Amd64).with_os_version("ignored.on.linux");
5745        let resolver = build_platform_resolver(Some(target));
5746        assert_eq!(resolver(&manifests).as_deref(), Some("sha256:linux"));
5747    }
5748
5749    #[test]
5750    fn manifest_cache_key_is_stable() {
5751        // The key stem is the CANONICAL reference, so a bare Docker Hub name is
5752        // normalized to its `docker.io/library/...` form (this is the macOS
5753        // image-OS-resolution fix: the qualified pull and the bare inspect must
5754        // land on the SAME key).
5755        assert_eq!(
5756            manifest_cache_key("alpine:latest"),
5757            "manifest:docker.io/library/alpine:latest"
5758        );
5759        // An already-qualified ref is unchanged.
5760        assert_eq!(
5761            manifest_cache_key("docker.io/library/alpine:latest"),
5762            "manifest:docker.io/library/alpine:latest"
5763        );
5764        // A non-parseable input falls back to the raw string (deterministic).
5765        assert_eq!(manifest_cache_key(""), "manifest:");
5766    }
5767
5768    #[test]
5769    fn manifest_cache_key_normalizes_bare_and_qualified_to_same_key() {
5770        // This is bug #1 from the live evidence: the VZ-Linux pull wrote the
5771        // manifest under the QUALIFIED ref while the composite's inspect queried
5772        // the BARE ref. Both must hash to one key.
5773        assert_eq!(
5774            manifest_cache_key("alpine:latest"),
5775            manifest_cache_key("docker.io/library/alpine:latest"),
5776        );
5777        assert_eq!(
5778            manifest_digest_cache_key("alpine:latest"),
5779            manifest_digest_cache_key("docker.io/library/alpine:latest"),
5780        );
5781    }
5782
5783    #[test]
5784    fn manifest_digest_cache_key_is_stable() {
5785        assert_eq!(
5786            manifest_digest_cache_key("alpine:latest"),
5787            "manifest:digest-docker.io/library/alpine:latest"
5788        );
5789    }
5790
5791    #[test]
5792    fn manifest_and_digest_keys_never_collide() {
5793        // The digest variant always has `:digest-` after the leading
5794        // `manifest`, so for any pair of non-empty image references the two
5795        // keys are distinct. Spot-check a handful of inputs.
5796        for image in [
5797            "alpine",
5798            "alpine:latest",
5799            "library/redis:7",
5800            "ghcr.io/x/y:tag",
5801        ] {
5802            let body = manifest_cache_key(image);
5803            let digest = manifest_digest_cache_key(image);
5804            assert_ne!(body, digest, "cache-key collision for {image}");
5805            assert!(body.starts_with("manifest:"), "manifest key shape: {body}");
5806            assert!(
5807                digest.starts_with("manifest:digest-"),
5808                "digest key shape: {digest}"
5809            );
5810        }
5811    }
5812
5813    // =========================================================================
5814    // Local-first image-OS / runtime-marker inspection (the macOS rate-limit
5815    // routing fix). These resolve OS / marker from a pre-seeded blob cache with
5816    // NO network access, exercising the real `pull_manifest_inner` →
5817    // `try_cached_manifest` → `pull_blob` (cache-hit) path under
5818    // `PullPolicy::IfNotPresent`.
5819    // =========================================================================
5820
5821    /// Seed `cache` with a manifest + config blob for `image` whose config
5822    /// declares `os = <os>` and the given optional `com.zlayer.runtime` marker.
5823    /// Returns the in-memory cache wrapped for `ImagePuller::with_cache`.
5824    fn seed_cache_with_os(
5825        image: &str,
5826        os: &str,
5827        runtime_marker: Option<&str>,
5828    ) -> Arc<Box<dyn BlobCacheBackend>> {
5829        let cache = crate::cache::BlobCache::new().unwrap();
5830
5831        // Config blob carrying the OS field.
5832        let config_json = serde_json::json!({
5833            "architecture": "arm64",
5834            "os": os,
5835            "config": {},
5836        });
5837        let config_bytes = serde_json::to_vec(&config_json).unwrap();
5838        let config_digest = crate::cache::compute_digest(&config_bytes);
5839        cache.put(&config_digest, &config_bytes).unwrap();
5840
5841        let annotations = runtime_marker.map(|m| {
5842            let mut a = std::collections::BTreeMap::new();
5843            a.insert(crate::ZLAYER_RUNTIME_ANNOTATION.to_string(), m.to_string());
5844            a
5845        });
5846
5847        let manifest = OciImageManifest {
5848            schema_version: 2,
5849            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
5850            artifact_type: None,
5851            config: oci_client::manifest::OciDescriptor {
5852                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
5853                digest: config_digest.clone(),
5854                size: i64::try_from(config_bytes.len()).unwrap(),
5855                urls: None,
5856                annotations: None,
5857            },
5858            layers: vec![],
5859            annotations,
5860            subject: None,
5861        };
5862        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
5863        let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
5864
5865        // Store under the exact keys the puller reads.
5866        cache
5867            .put(&manifest_cache_key(image), &manifest_bytes)
5868            .unwrap();
5869        cache
5870            .put(
5871                &manifest_digest_cache_key(image),
5872                manifest_digest.as_bytes(),
5873            )
5874            .unwrap();
5875
5876        Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
5877    }
5878
5879    // =========================================================================
5880    // Single-flight image-pull dedup (the CI-burst win).
5881    //
5882    // Under a burst of N concurrent CreateContainer of the SAME image, only ONE
5883    // pull's expensive work (manifest fetch + blob download into the cache)
5884    // should run; the rest await it. These tests prove that with a COUNTING
5885    // cache that (a) injects a delay on the watched key to widen the dedup
5886    // window and (b) records the high-water mark of CONCURRENT reads of that
5887    // key. Without single-flight, N concurrent callers would all be inside that
5888    // read at once (max concurrency == N). With single-flight, the leader holds
5889    // the slot while followers block BEFORE the read, so the leader's expensive
5890    // work is the only one in-flight (max concurrency == 1). Followers then
5891    // re-materialize from the now-warm cache — into their OWN staging dir.
5892    // =========================================================================
5893
5894    /// A `BlobCacheBackend` that wraps a real [`crate::cache::BlobCache`] and,
5895    /// for one watched key, (1) sleeps briefly on every `get` to widen the
5896    /// concurrency window and (2) tracks the maximum number of `get`s in-flight
5897    /// against that key simultaneously. The high-water mark is the single-flight
5898    /// discriminator: 1 with dedup, N without.
5899    struct CountingCache {
5900        inner: crate::cache::BlobCache,
5901        watch_key: String,
5902        in_flight: std::sync::atomic::AtomicUsize,
5903        max_in_flight: std::sync::atomic::AtomicUsize,
5904        delay: std::time::Duration,
5905    }
5906
5907    impl CountingCache {
5908        fn new(inner: crate::cache::BlobCache, watch_key: String) -> Arc<Self> {
5909            Arc::new(Self {
5910                inner,
5911                watch_key,
5912                in_flight: std::sync::atomic::AtomicUsize::new(0),
5913                max_in_flight: std::sync::atomic::AtomicUsize::new(0),
5914                delay: std::time::Duration::from_millis(50),
5915            })
5916        }
5917
5918        fn max_concurrent(&self) -> usize {
5919            self.max_in_flight.load(std::sync::atomic::Ordering::SeqCst)
5920        }
5921    }
5922
5923    #[async_trait::async_trait]
5924    impl BlobCacheBackend for CountingCache {
5925        async fn get(
5926            &self,
5927            digest: &str,
5928        ) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
5929            if digest == self.watch_key {
5930                let now = self
5931                    .in_flight
5932                    .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
5933                    + 1;
5934                self.max_in_flight
5935                    .fetch_max(now, std::sync::atomic::Ordering::SeqCst);
5936                tokio::time::sleep(self.delay).await;
5937                let out = self.inner.get(digest);
5938                self.in_flight
5939                    .fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
5940                out
5941            } else {
5942                self.inner.get(digest)
5943            }
5944        }
5945
5946        async fn put(
5947            &self,
5948            digest: &str,
5949            data: &[u8],
5950        ) -> std::result::Result<(), crate::error::CacheError> {
5951            self.inner.put(digest, data)
5952        }
5953
5954        async fn contains(
5955            &self,
5956            digest: &str,
5957        ) -> std::result::Result<bool, crate::error::CacheError> {
5958            self.inner.contains(digest)
5959        }
5960
5961        async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
5962            self.inner.delete(digest)
5963        }
5964    }
5965
5966    /// Build a `CountingCache` seeded with a zero-layer manifest + config for
5967    /// `image`, watching the manifest body key. A zero-layer manifest keeps the
5968    /// pull fully offline (no blobs to download) while still routing through the
5969    /// real `pull_manifest_inner` → `try_cached_manifest` (cache `get`) path
5970    /// that the single-flight gates.
5971    fn counting_cache_for(image: &str) -> Arc<CountingCache> {
5972        let inner = crate::cache::BlobCache::new().unwrap();
5973
5974        let config_json =
5975            serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
5976        let config_bytes = serde_json::to_vec(&config_json).unwrap();
5977        let config_digest = crate::cache::compute_digest(&config_bytes);
5978        inner.put(&config_digest, &config_bytes).unwrap();
5979
5980        let manifest = OciImageManifest {
5981            schema_version: 2,
5982            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
5983            artifact_type: None,
5984            config: oci_client::manifest::OciDescriptor {
5985                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
5986                digest: config_digest.clone(),
5987                size: i64::try_from(config_bytes.len()).unwrap(),
5988                urls: None,
5989                annotations: None,
5990            },
5991            layers: vec![],
5992            annotations: None,
5993            subject: None,
5994        };
5995        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
5996        let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
5997        inner
5998            .put(&manifest_cache_key(image), &manifest_bytes)
5999            .unwrap();
6000        inner
6001            .put(
6002                &manifest_digest_cache_key(image),
6003                manifest_digest.as_bytes(),
6004            )
6005            .unwrap();
6006
6007        CountingCache::new(inner, manifest_cache_key(image))
6008    }
6009
6010    #[tokio::test]
6011    async fn pull_image_to_files_single_flights_concurrent_pulls_of_same_ref() {
6012        // N concurrent pulls of the SAME ref: the leader's expensive work runs
6013        // alone (max concurrent manifest reads == 1), and EVERY caller gets a
6014        // correct result materialized into its OWN staging dir. Use a PINNED ref
6015        // so `try_cached_manifest` trusts the cache without a network HEAD.
6016        let image = "registry.example.com/team/executor@sha256:\
6017                     1111111111111111111111111111111111111111111111111111111111111111";
6018        let counting = counting_cache_for(image);
6019        let cache: Arc<Box<dyn BlobCacheBackend>> =
6020            Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
6021        let puller = Arc::new(ImagePuller::with_cache(cache));
6022
6023        let tmp = tempfile::tempdir().unwrap();
6024        let n = 10usize;
6025        let mut set = tokio::task::JoinSet::new();
6026        for i in 0..n {
6027            let puller = puller.clone();
6028            let image = image.to_string();
6029            let stage = tmp.path().join(format!("stage-{i}"));
6030            set.spawn(async move {
6031                puller
6032                    .pull_image_to_files_with_policy(
6033                        &image,
6034                        &RegistryAuth::Anonymous,
6035                        &stage,
6036                        PullPolicy::IfNotPresent,
6037                    )
6038                    .await
6039            });
6040        }
6041
6042        let mut ok = 0usize;
6043        while let Some(joined) = set.join_next().await {
6044            let layers = joined
6045                .expect("task must not panic")
6046                .expect("pull must succeed");
6047            assert!(
6048                layers.is_empty(),
6049                "zero-layer manifest yields zero layer files"
6050            );
6051            ok += 1;
6052        }
6053        assert_eq!(ok, n, "every concurrent caller must complete");
6054
6055        assert_eq!(
6056            counting.max_concurrent(),
6057            1,
6058            "single-flight must collapse the {n} concurrent pulls onto ONE in-flight \
6059             manifest fetch (the leader); followers block until it completes",
6060        );
6061    }
6062
6063    #[tokio::test]
6064    async fn pull_image_config_single_flights_concurrent_fetches_of_same_ref() {
6065        // The config-fetch sibling: N concurrent config fetches of the same ref
6066        // collapse onto one `pull_image_config_inner`, observed as max ONE
6067        // in-flight read of the CONFIG blob.
6068        let image = "registry.example.com/team/cfg@sha256:\
6069                     2222222222222222222222222222222222222222222222222222222222222222";
6070        // Watch the config-blob key instead of the manifest key.
6071        let inner = crate::cache::BlobCache::new().unwrap();
6072        let config_json =
6073            serde_json::json!({ "architecture": "arm64", "os": "linux", "config": {} });
6074        let config_bytes = serde_json::to_vec(&config_json).unwrap();
6075        let config_digest = crate::cache::compute_digest(&config_bytes);
6076        inner.put(&config_digest, &config_bytes).unwrap();
6077        let manifest = OciImageManifest {
6078            schema_version: 2,
6079            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
6080            artifact_type: None,
6081            config: oci_client::manifest::OciDescriptor {
6082                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
6083                digest: config_digest.clone(),
6084                size: i64::try_from(config_bytes.len()).unwrap(),
6085                urls: None,
6086                annotations: None,
6087            },
6088            layers: vec![],
6089            annotations: None,
6090            subject: None,
6091        };
6092        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
6093        let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
6094        inner
6095            .put(&manifest_cache_key(image), &manifest_bytes)
6096            .unwrap();
6097        inner
6098            .put(
6099                &manifest_digest_cache_key(image),
6100                manifest_digest.as_bytes(),
6101            )
6102            .unwrap();
6103        let counting = CountingCache::new(inner, config_digest.clone());
6104        let cache: Arc<Box<dyn BlobCacheBackend>> =
6105            Arc::new(Box::new(CountingCacheHandle(counting.clone())) as Box<dyn BlobCacheBackend>);
6106        let puller = Arc::new(ImagePuller::with_cache(cache));
6107
6108        let n = 10usize;
6109        let mut set = tokio::task::JoinSet::new();
6110        for _ in 0..n {
6111            let puller = puller.clone();
6112            let image = image.to_string();
6113            set.spawn(async move {
6114                puller
6115                    .pull_image_config_with_policy(
6116                        &image,
6117                        &RegistryAuth::Anonymous,
6118                        PullPolicy::IfNotPresent,
6119                    )
6120                    .await
6121            });
6122        }
6123        let mut ok = 0usize;
6124        while let Some(joined) = set.join_next().await {
6125            joined
6126                .expect("task must not panic")
6127                .expect("config fetch must succeed");
6128            ok += 1;
6129        }
6130        assert_eq!(ok, n);
6131        assert_eq!(
6132            counting.max_concurrent(),
6133            1,
6134            "single-flight must collapse the {n} concurrent config fetches onto ONE \
6135             in-flight config-blob read",
6136        );
6137    }
6138
6139    #[tokio::test]
6140    async fn pull_image_to_files_does_not_false_share_across_refs() {
6141        // Two DIFFERENT refs sharing the same process must NOT dedup against each
6142        // other: each is its own leader and runs its own expensive work. We give
6143        // them SEPARATE caches (distinct cache identity) AND distinct refs, then
6144        // assert both ran (max-concurrent == 1 each is trivially their own
6145        // leader) and produced correct results — i.e. no cross-key blocking.
6146        let image_a = "registry.example.com/team/a@sha256:\
6147                       3333333333333333333333333333333333333333333333333333333333333333";
6148        let image_b = "registry.example.com/team/b@sha256:\
6149                       4444444444444444444444444444444444444444444444444444444444444444";
6150        let counting_a = counting_cache_for(image_a);
6151        let counting_b = counting_cache_for(image_b);
6152        let puller_a = Arc::new(ImagePuller::with_cache(Arc::new(
6153            Box::new(CountingCacheHandle(counting_a.clone())) as Box<dyn BlobCacheBackend>,
6154        )));
6155        let puller_b = Arc::new(ImagePuller::with_cache(Arc::new(
6156            Box::new(CountingCacheHandle(counting_b.clone())) as Box<dyn BlobCacheBackend>,
6157        )));
6158
6159        let tmp = tempfile::tempdir().unwrap();
6160        let stage_a = tmp.path().join("a");
6161        let stage_b = tmp.path().join("b");
6162        let (ra, rb) = tokio::join!(
6163            puller_a.pull_image_to_files_with_policy(
6164                image_a,
6165                &RegistryAuth::Anonymous,
6166                &stage_a,
6167                PullPolicy::IfNotPresent,
6168            ),
6169            puller_b.pull_image_to_files_with_policy(
6170                image_b,
6171                &RegistryAuth::Anonymous,
6172                &stage_b,
6173                PullPolicy::IfNotPresent,
6174            ),
6175        );
6176        assert!(ra.expect("ref A pull must succeed").is_empty());
6177        assert!(rb.expect("ref B pull must succeed").is_empty());
6178        // Each ref is its own leader — neither was starved or blocked by the
6179        // other (a false-sharing bug would deadlock or serialize incorrectly,
6180        // but both completing proves the keys are independent).
6181        assert_eq!(counting_a.max_concurrent(), 1);
6182        assert_eq!(counting_b.max_concurrent(), 1);
6183    }
6184
6185    /// Newtype so `Arc<CountingCache>` can be boxed as `Box<dyn
6186    /// BlobCacheBackend>` (the trait is implemented on `CountingCache`, and a
6187    /// blanket forward keeps the `Arc` identity stable for the single-flight
6188    /// key, which is derived from `Arc::as_ptr(&self.cache)`).
6189    struct CountingCacheHandle(Arc<CountingCache>);
6190
6191    #[async_trait::async_trait]
6192    impl BlobCacheBackend for CountingCacheHandle {
6193        async fn get(
6194            &self,
6195            digest: &str,
6196        ) -> std::result::Result<Option<Vec<u8>>, crate::error::CacheError> {
6197            self.0.get(digest).await
6198        }
6199        async fn put(
6200            &self,
6201            digest: &str,
6202            data: &[u8],
6203        ) -> std::result::Result<(), crate::error::CacheError> {
6204            self.0.put(digest, data).await
6205        }
6206        async fn contains(
6207            &self,
6208            digest: &str,
6209        ) -> std::result::Result<bool, crate::error::CacheError> {
6210            self.0.contains(digest).await
6211        }
6212        async fn delete(&self, digest: &str) -> std::result::Result<(), crate::error::CacheError> {
6213            self.0.delete(digest).await
6214        }
6215    }
6216
6217    #[tokio::test]
6218    async fn image_os_with_policy_resolves_linux_from_local_cache_no_network() {
6219        // A locally-cached Linux image must resolve to `OsKind::Linux` purely
6220        // from the seeded cache — no network. We use a MUTABLE tag (`:latest`)
6221        // on purpose: under `IfNotPresent` the cache is authoritative and NO
6222        // remote HEAD revalidation is performed, which is exactly the behaviour
6223        // that survives a Docker Hub 429.
6224        let image = "docker.io/library/alpine:latest";
6225        let cache = seed_cache_with_os(image, "linux", None);
6226        let puller = ImagePuller::with_cache(cache);
6227
6228        let os = puller
6229            .image_os_with_policy(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
6230            .await
6231            .expect("local-first OS inspection must not error");
6232        assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6233    }
6234
6235    #[cfg(feature = "local")]
6236    #[tokio::test]
6237    async fn fetch_image_os_in_cache_resolves_linux_no_network() {
6238        // Drive the public `fetch_image_os_in_cache` entry point (the one the
6239        // composite uses) against a seeded cache and confirm it returns
6240        // `Linux` with no network call.
6241        let image = "docker.io/library/alpine:latest";
6242        let cache = seed_cache_with_os(image, "linux", None);
6243
6244        let os = fetch_image_os_in_cache(image, None, cache, None)
6245            .await
6246            .expect("local-first OS inspection must not error");
6247        assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6248    }
6249
6250    #[cfg(feature = "local")]
6251    #[tokio::test]
6252    async fn fetch_image_runtime_marker_in_cache_resolves_marker_no_network() {
6253        let image = "ghcr.io/example/vz-base:1.0";
6254        let cache = seed_cache_with_os(image, "linux", Some("vz"));
6255
6256        let marker = fetch_image_runtime_marker_in_cache(image, None, cache, None)
6257            .await
6258            .expect("local-first marker inspection must not error");
6259        assert_eq!(marker.as_deref(), Some("vz"));
6260    }
6261
6262    // -- Live-bug reproductions ------------------------------------------------
6263
6264    #[tokio::test]
6265    async fn bare_ref_resolves_from_cache_seeded_under_qualified_ref() {
6266        // LIVE BUG #1: the VZ-Linux pull wrote the manifest under the QUALIFIED
6267        // `docker.io/library/alpine:latest`, but the composite's inspect was
6268        // invoked with the BARE `alpine:latest`. With the canonical key
6269        // normalization, the bare-ref inspect now hits the qualified-seeded
6270        // cache — with NO network call.
6271        let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6272        let puller = ImagePuller::with_cache(cache);
6273
6274        let os = puller
6275            .image_os_in_cache_only("alpine:latest")
6276            .await
6277            .expect("bare-ref local inspection must not error");
6278        assert_eq!(
6279            os,
6280            Some(zlayer_spec::OsKind::Linux),
6281            "bare `alpine:latest` must resolve from a cache seeded under the qualified ref",
6282        );
6283    }
6284
6285    #[cfg(feature = "local")]
6286    #[tokio::test]
6287    async fn fetch_image_os_in_cache_only_bare_ref_no_network() {
6288        // Same bug, driven through the public entry point the composite uses.
6289        let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6290        let os = fetch_image_os_in_cache_only("alpine:latest", cache, None)
6291            .await
6292            .expect("local-only inspection must not error");
6293        assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6294    }
6295
6296    #[tokio::test]
6297    async fn image_os_in_cache_only_no_network_when_manifest_and_config_present() {
6298        // LIVE BUG #2: resolution must succeed with NO network when the
6299        // manifest + config are present under `IfNotPresent`. `image_os_in_cache_only`
6300        // never touches the network, so a green assertion here proves the
6301        // short-circuit. We use a MUTABLE tag on purpose — the cache must be
6302        // authoritative without a remote HEAD revalidation (the path that
6303        // survives a Docker Hub 429).
6304        let image = "docker.io/library/alpine:latest";
6305        let cache = seed_cache_with_os(image, "linux", None);
6306        let puller = ImagePuller::with_cache(cache);
6307
6308        let os = puller
6309            .image_os_in_cache_only(image)
6310            .await
6311            .expect("cached manifest+config must resolve OS with no network");
6312        assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6313    }
6314
6315    #[tokio::test]
6316    async fn cache_local_image_platform_round_trips_darwin() {
6317        // The macOS Seatbelt builder calls `cache_local_image_platform` instead
6318        // of pulling, so a freshly built native image carries no manifest/config
6319        // until this writer runs. Proving the write→read round trip here locks
6320        // in the dispatch fix: after the stamp, `image_os_in_cache_only` resolves
6321        // `darwin` (→ OsKind::Macos) with no network, so the composite routes a
6322        // local build to the Sandbox runtime instead of the Linux VM.
6323        let image = "ghcr.io/owner/seatbelt-app:latest";
6324        let cache: Arc<Box<dyn BlobCacheBackend>> =
6325            Arc::new(Box::new(crate::cache::BlobCache::new().unwrap()));
6326        let puller = ImagePuller::with_cache(cache);
6327
6328        // Nothing cached yet → genuine local miss.
6329        assert_eq!(
6330            puller.image_os_in_cache_only(image).await.unwrap(),
6331            None,
6332            "no stamp yet must be a clean local miss"
6333        );
6334
6335        puller
6336            .cache_local_image_platform(image, "darwin", "arm64")
6337            .await
6338            .expect("stamping a local image's platform must succeed");
6339
6340        let os = puller
6341            .image_os_in_cache_only(image)
6342            .await
6343            .expect("stamped manifest+config must resolve OS with no network");
6344        assert_eq!(os, Some(zlayer_spec::OsKind::Macos));
6345    }
6346
6347    #[tokio::test]
6348    async fn image_os_in_cache_only_returns_none_on_clean_local_miss() {
6349        // A genuinely-absent image must be a clean `Ok(None)` (so the composite
6350        // can probe the NEXT cache), NOT a network fetch or an error. The cache
6351        // is empty, so there is nothing to hit the network with anyway.
6352        let cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
6353            crate::cache::BlobCache::new().unwrap(),
6354        )
6355            as Box<dyn BlobCacheBackend>);
6356        let puller = ImagePuller::with_cache(cache);
6357
6358        let os = puller
6359            .image_os_in_cache_only("docker.io/library/absent:latest")
6360            .await
6361            .expect("a local miss must be Ok(None), never an error");
6362        assert_eq!(os, None);
6363        // Even on a clean MISS the local-only path must stay offline.
6364        assert_eq!(
6365            puller.network_call_count(),
6366            0,
6367            "image_os_in_cache_only must never issue a network call, even on a local miss",
6368        );
6369    }
6370
6371    #[tokio::test]
6372    async fn image_os_in_cache_only_bare_ref_issues_zero_network_calls() {
6373        // The load-bearing regression assertion: the BARE `alpine:latest`
6374        // inspect, served from a cache seeded under the QUALIFIED writer key,
6375        // must resolve to `Linux` while the network-call spy stays at zero.
6376        // This is the exact macOS path that previously re-inspected Docker Hub
6377        // and 429'd, misrouting a cached Linux image to a sandbox (exit 127).
6378        let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", None);
6379        let puller = ImagePuller::with_cache(cache);
6380
6381        let os = puller
6382            .image_os_in_cache_only("alpine:latest")
6383            .await
6384            .expect("bare-ref local inspection must not error");
6385
6386        assert_eq!(os, Some(zlayer_spec::OsKind::Linux));
6387        assert_eq!(
6388            puller.network_call_count(),
6389            0,
6390            "a cached image's OS must resolve with ZERO network calls (no Docker Hub re-inspect)",
6391        );
6392    }
6393
6394    #[tokio::test]
6395    async fn image_runtime_marker_in_cache_only_bare_ref_zero_network() {
6396        // Mirror of the OS path for the `com.zlayer.runtime` annotation: bare
6397        // ref, qualified-seeded cache, marker resolved, network spy at zero.
6398        let cache = seed_cache_with_os("docker.io/library/alpine:latest", "linux", Some("vz"));
6399        let puller = ImagePuller::with_cache(cache);
6400
6401        let marker = puller
6402            .image_runtime_marker_in_cache_only("alpine:latest")
6403            .await
6404            .expect("bare-ref marker inspection must not error");
6405
6406        assert_eq!(marker.as_deref(), Some("vz"));
6407        assert_eq!(
6408            puller.network_call_count(),
6409            0,
6410            "runtime-marker inspection must resolve from cache with ZERO network calls",
6411        );
6412    }
6413
6414    /// Seed `cache` with a manifest + config blob for `image` whose config
6415    /// carries the `com.zlayer.isolation` LABEL (the image-declared isolation
6416    /// default the `ZImage` builder stamps into `config.Labels`).
6417    fn seed_cache_with_isolation(image: &str, isolation: &str) -> Arc<Box<dyn BlobCacheBackend>> {
6418        let cache = crate::cache::BlobCache::new().unwrap();
6419
6420        // Config blob carrying the isolation default under config.Labels —
6421        // the same place the builder writes it and that rides through push/pull.
6422        let config_json = serde_json::json!({
6423            "architecture": "arm64",
6424            "os": "linux",
6425            "config": { "Labels": { crate::ZLAYER_ISOLATION_ANNOTATION: isolation } },
6426        });
6427        let config_bytes = serde_json::to_vec(&config_json).unwrap();
6428        let config_digest = crate::cache::compute_digest(&config_bytes);
6429        cache.put(&config_digest, &config_bytes).unwrap();
6430
6431        let manifest = OciImageManifest {
6432            schema_version: 2,
6433            media_type: Some("application/vnd.oci.image.manifest.v1+json".to_string()),
6434            artifact_type: None,
6435            config: oci_client::manifest::OciDescriptor {
6436                media_type: "application/vnd.oci.image.config.v1+json".to_string(),
6437                digest: config_digest.clone(),
6438                size: i64::try_from(config_bytes.len()).unwrap(),
6439                urls: None,
6440                annotations: None,
6441            },
6442            layers: vec![],
6443            annotations: None,
6444            subject: None,
6445        };
6446        let manifest_bytes = serde_json::to_vec(&manifest).unwrap();
6447        let manifest_digest = crate::cache::compute_digest(&manifest_bytes);
6448
6449        cache
6450            .put(&manifest_cache_key(image), &manifest_bytes)
6451            .unwrap();
6452        cache
6453            .put(
6454                &manifest_digest_cache_key(image),
6455                manifest_digest.as_bytes(),
6456            )
6457            .unwrap();
6458
6459        Arc::new(Box::new(cache) as Box<dyn BlobCacheBackend>)
6460    }
6461
6462    #[tokio::test]
6463    async fn image_isolation_marker_in_cache_only_reads_config_label_zero_network() {
6464        // The isolation default rides inside the config blob's Labels (not a
6465        // manifest annotation), so the reader resolves it from the local config
6466        // blob with NO network — the create-side dispatch can then honor it.
6467        let image = "docker.io/library/alpine:latest";
6468        let cache = seed_cache_with_isolation(image, "vz-linux");
6469        let puller = ImagePuller::with_cache(cache);
6470
6471        let iso = puller
6472            .image_isolation_marker_in_cache_only("alpine:latest")
6473            .await
6474            .expect("isolation-label inspection must not error");
6475
6476        assert_eq!(iso.as_deref(), Some("vz-linux"));
6477        assert_eq!(
6478            puller.network_call_count(),
6479            0,
6480            "isolation inspection must resolve from cache with ZERO network calls",
6481        );
6482    }
6483
6484    #[tokio::test]
6485    async fn image_isolation_marker_in_cache_only_none_when_label_absent() {
6486        // An image with no isolation label is a clean Ok(None) (dispatch falls
6487        // through to the lower-precedence rules), never an error.
6488        let image = "docker.io/library/alpine:latest";
6489        let cache = seed_cache_with_os(image, "linux", None);
6490        let puller = ImagePuller::with_cache(cache);
6491
6492        let iso = puller
6493            .image_isolation_marker_in_cache_only(image)
6494            .await
6495            .expect("missing isolation label must be Ok(None), never an error");
6496        assert_eq!(iso, None);
6497    }
6498
6499    #[tokio::test]
6500    async fn manifest_cache_key_collides_bare_qualified_and_literal() {
6501        // Bug #1, asserted end-to-end: the bare ref, the qualified ref, and the
6502        // exact on-disk writer key must all be ONE key. Reader (bare inspect)
6503        // and writer (qualified pull) collide → the cache hit lands.
6504        assert_eq!(
6505            manifest_cache_key("alpine:latest"),
6506            "manifest:docker.io/library/alpine:latest",
6507        );
6508        assert_eq!(
6509            manifest_cache_key("docker.io/library/alpine:latest"),
6510            "manifest:docker.io/library/alpine:latest",
6511        );
6512        assert_eq!(
6513            manifest_cache_key("alpine:latest"),
6514            manifest_cache_key("docker.io/library/alpine:latest"),
6515        );
6516    }
6517
6518    // -- Unreachable S3 tier is never a hard dependency ------------------------
6519
6520    /// A `BlobCacheBackend` whose every read/write FAILS, standing in for a
6521    /// configured-but-unreachable shared S3 tier (e.g. `ZLayer`'s own in-cluster
6522    /// `ZataStorage` reached as a `*.service.local` name that is down or not yet
6523    /// up while the daemon is booting). It must never turn into a hard
6524    /// resolution failure: reads must degrade to a cache MISS.
6525    struct BrokenS3;
6526
6527    use crate::error::CacheError;
6528
6529    #[async_trait::async_trait]
6530    impl BlobCacheBackend for BrokenS3 {
6531        async fn get(&self, _digest: &str) -> std::result::Result<Option<Vec<u8>>, CacheError> {
6532            Err(CacheError::Database(
6533                "simulated S3 endpoint unreachable".to_string(),
6534            ))
6535        }
6536        async fn put(&self, _digest: &str, _data: &[u8]) -> std::result::Result<(), CacheError> {
6537            Err(CacheError::Database(
6538                "simulated S3 endpoint unreachable".to_string(),
6539            ))
6540        }
6541        async fn contains(&self, _digest: &str) -> std::result::Result<bool, CacheError> {
6542            Err(CacheError::Database(
6543                "simulated S3 endpoint unreachable".to_string(),
6544            ))
6545        }
6546    }
6547
6548    fn broken_s3() -> Arc<Box<dyn BlobCacheBackend>> {
6549        Arc::new(Box::new(BrokenS3) as Box<dyn BlobCacheBackend>)
6550    }
6551
6552    #[tokio::test]
6553    async fn s3_tier_get_treats_error_as_miss() {
6554        // The single fail-soft chokepoint: an erroring S3 tier returns None
6555        // (a miss), never propagating the underlying CacheError.
6556        let puller = ImagePuller::with_cache(seed_cache_with_os(
6557            "docker.io/library/alpine:latest",
6558            "linux",
6559            None,
6560        ))
6561        .with_s3_cache(broken_s3());
6562
6563        assert!(
6564            puller.s3_tier_get("any-key").await.is_none(),
6565            "an erroring S3 tier must degrade to a cache MISS, not surface the error",
6566        );
6567    }
6568
6569    #[tokio::test]
6570    async fn unreachable_s3_does_not_break_local_cache_hit() {
6571        // REGRESSION: a fully-qualified image whose manifest is already in the
6572        // LOCAL cache must still resolve when an UNREACHABLE S3 tier is
6573        // configured. The S3 read errors, is swallowed as a miss, and the chain
6574        // continues — here landing on the local cache. S3 being down must never
6575        // turn a perfectly resolvable image into a hard failure.
6576        let image = "ghcr.io/example/app:1.2.3";
6577        let puller = ImagePuller::with_cache(seed_cache_with_os(image, "linux", None))
6578            .with_s3_cache(broken_s3());
6579
6580        let (_manifest, _digest) = puller
6581            .pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::IfNotPresent)
6582            .await
6583            .expect("a local cache hit must survive an unreachable S3 tier");
6584    }
6585
6586    #[tokio::test]
6587    async fn unreachable_s3_falls_through_to_origin_not_a_hard_s3_error() {
6588        // REGRESSION (core of this hardening): a fully-qualified image NOT
6589        // present locally, with an UNREACHABLE S3 tier configured, must fall
6590        // THROUGH S3 (treated as a miss) and reach the ORIGIN path. With no
6591        // network in the test env the origin attempt fails — but the failure
6592        // must be an origin-class error (NotFound / OCI transport), proving the
6593        // S3 tier degraded to a miss rather than aborting resolution with its
6594        // own error. An empty cache + broken S3 + bad origin host exercises the
6595        // whole chain.
6596        let image = "registry.invalid.example.test/example/app:1.0.0";
6597        let empty_cache: Arc<Box<dyn BlobCacheBackend>> = Arc::new(Box::new(
6598            crate::cache::BlobCache::new().unwrap(),
6599        )
6600            as Box<dyn BlobCacheBackend>);
6601        let puller = ImagePuller::with_cache(empty_cache).with_s3_cache(broken_s3());
6602
6603        let err = puller
6604            .pull_manifest_inner(image, &RegistryAuth::Anonymous, PullPolicy::Newer)
6605            .await
6606            .expect_err("an unreachable origin should error (no network in test env)");
6607
6608        // The error must come from the ORIGIN attempt, never be a propagated
6609        // S3 CacheError — i.e. S3 being down is a miss, not a pull failure.
6610        match err {
6611            RegistryError::NotFound { .. } | RegistryError::Oci(_) => {}
6612            other => panic!("expected an origin-class error after S3 fell through, got: {other:?}"),
6613        }
6614    }
6615}