arcbox-computer-runtime 0.10.3

Sandbox orchestration over nested microVMs behind the arcbox-vm-driver port: boot, exec, files, checkpoints, warm pools. The in-sandbox init is arcbox-vm-agent; the wire vocabulary is arcbox-vm-proto.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! Build bootable ext4 rootfs images for sandboxes.
//!
//! Two builders live here, both backed by the pure-Rust `oci2rootfs` /
//! `arcbox-ext4` stack (no external binary, no mount, no root required for
//! the ext4 write itself):
//!
//! - [`RootfsBuilder::convert_layer_to_rootfs`] — convert a staged OCI image
//!   layout (or a Docker overlay2 layer directory) to ext4, then inject
//!   `/sbin/vm-agent` through a loop mount. Cached ext4 images are reused to
//!   avoid redundant conversions.
//! - [`RootfsBuilder::ensure_default_rootfs`] — build the default busybox +
//!   vm-agent image used when a create supplies no rootfs. Rebuilt when the
//!   source binaries are newer than the cached image.
//!
//! The rootfs convention the boot protocol relies on — the agent binary at
//! `/sbin/vm-agent`, `/etc/resolv.conf`
//! symlinked into the `/run` tmpfs — is enforced only by the guest failing to
//! boot, so it is implemented once, here, with the agent binary source and
//! the output location supplied by the composer through [`RootfsPaths`].
//! Converted images retain their own `/sbin/init`; select the agent with
//! `init=/sbin/vm-agent`. The default busybox image also links `/sbin/init`.

mod build;
mod inject;

pub use build::{ROOTFS_CAPACITY_GRANULARITY, RootfsSource, RootfsSpec};

use std::collections::BTreeSet;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use arcbox_ext4::constants::file_mode;
use arcbox_ext4::{FormatOptions, Formatter};
use arcbox_snapshot::snapshot_cow::BlockTools;
use tokio::process::Command;
use uuid::Uuid;

use crate::error::ComputerError;

/// Capacity of the default busybox rootfs image. The image file is written
/// sparsely; per-sandbox writes land in the dm-snapshot COW overlay, so this
/// bounds a sandbox's writable space, not host disk use.
const DEFAULT_ROOTFS_SIZE: u64 = 512 * 1024 * 1024;

/// Initial template capacity; the formatter can grow the image to fit its source.
/// Keep capacity out of the cache key because
/// template catalogs use the existing stem as their image digest input.
const TEMPLATE_ROOTFS_SIZE: u64 = 512 * 1024 * 1024;

/// Agent path in every built image. Use this path in the kernel's `init=` argument.
pub const VM_AGENT_PATH: &str = "/sbin/vm-agent";

/// Where the rootfs builder finds its inputs and keeps its outputs.
#[derive(Debug, Clone)]
pub struct RootfsPaths {
    /// The `vm-agent` binary injected into every image at `/sbin/vm-agent`.
    pub vm_agent: PathBuf,
    /// Directory the generated ext4 images (and their `.ext4.tmp` build
    /// files) live in.
    pub cache_dir: PathBuf,
    /// Static busybox that becomes the default rootfs's userland
    /// (`/bin/busybox` plus one applet symlink per `busybox --list` entry).
    pub busybox: PathBuf,
}

/// Builds sandbox rootfs images; see the module docs.
pub struct RootfsBuilder {
    paths: RootfsPaths,
    /// Loop-device attach/detach for the `vm-agent` injection mount.
    #[cfg_attr(
        not(target_os = "linux"),
        allow(
            dead_code,
            reason = "the injection loop mount is Linux-only; other platforms never attach"
        )
    )]
    block_tools: Arc<dyn BlockTools>,
}

/// Serializes default-rootfs builds so concurrent creates don't each rebuild
/// the 512 MiB image. Process-wide, not per builder: two builders over the
/// same paths (the service's and a startup sweep's) must not race each other
/// either. The atomic rename already prevents corruption; this only avoids
/// the redundant work.
fn build_lock() -> &'static tokio::sync::Mutex<()> {
    static LOCK: std::sync::OnceLock<tokio::sync::Mutex<()>> = std::sync::OnceLock::new();
    LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

impl RootfsBuilder {
    /// A builder over `paths`, mounting through `block_tools`.
    pub fn new(paths: RootfsPaths, block_tools: Arc<dyn BlockTools>) -> Self {
        Self { paths, block_tools }
    }

    /// The paths this builder was composed with.
    pub fn paths(&self) -> &RootfsPaths {
        &self.paths
    }
}

fn rootfs_err(error: anyhow::Error) -> ComputerError {
    ComputerError::Rootfs(format!("{error:#}"))
}

/// Check if a file has a valid ext4 superblock magic (0x53EF at offset 0x438).
pub fn has_ext4_magic(path: &Path) -> bool {
    use std::io::{Seek, SeekFrom};
    let Ok(mut file) = std::fs::File::open(path) else {
        return false;
    };
    let mut magic = [0u8; 2];
    file.seek(SeekFrom::Start(0x438)).is_ok()
        && file.read_exact(&mut magic).is_ok()
        && magic == [0x53, 0xEF]
}

/// Marker file that identifies an OCI image layout directory.
const OCI_LAYOUT_MARKER: &str = "oci-layout";

/// True when `dir` is an OCI image layout rather than an overlay2 layer.
///
/// Dispatching on the marker keeps the choice explicit: a `docker save`
/// layout also carries a legacy `manifest.json`, so leaning on the
/// `oci2rootfs` autodetect heuristics would be guesswork.
fn is_oci_layout(dir: &Path) -> bool {
    dir.join(OCI_LAYOUT_MARKER).is_file()
}

impl RootfsBuilder {
    /// Convert an image source directory to a bootable ext4 rootfs.
    ///
    /// `layer_path` is a directory: either an OCI image layout staged by the
    /// host CLI (the `--from-image` / `--from-dockerfile` path) or a Docker
    /// overlay2 chain-id directory (e.g. `/var/lib/docker/overlay2/<chain-id>`).
    ///
    /// `pinned` are images that must survive the superseded-image sweep
    /// because a durable record, snapshot, or template still needs them
    /// (`ComputerManager::pinned_rootfs_paths`).
    ///
    /// Returns the path to the generated (or cached) ext4 image.
    pub async fn convert_layer_to_rootfs(
        &self,
        layer_path: &str,
        pinned: &BTreeSet<PathBuf>,
    ) -> crate::error::Result<String> {
        self.convert_layer(layer_path, pinned)
            .await
            .map_err(rootfs_err)
    }

    async fn convert_layer(&self, layer_path: &str, pinned: &BTreeSet<PathBuf>) -> Result<String> {
        if !Path::new(layer_path).exists() {
            bail!("layer path not found: {layer_path}");
        }

        // The cached image has two ingredients, so the key names both: the layer
        // (whose directory name carries the image digest for either source kind,
        // making the path a stable identifier) and the `vm-agent` binary injected
        // below. Keying on the layer alone meant a newer agent never reached an
        // already-converted image — the sandbox kept booting the old init with no
        // sign anything was stale.
        let layer_key = path_hash(layer_path);
        let agent_key = self.vm_agent_key().await?;
        let cache_dir = &self.paths.cache_dir;
        let ext4_path = cache_dir
            .join(format!("rootfs-{layer_key}-{agent_key}.ext4"))
            .to_string_lossy()
            .into_owned();

        // Check cache.
        if Path::new(&ext4_path).exists() && has_ext4_magic(Path::new(&ext4_path)) {
            tracing::info!(path = %ext4_path, "using cached rootfs");
            return Ok(ext4_path);
        }

        tracing::info!(layer = %layer_path, ext4 = %ext4_path, "converting image layer to ext4");
        self.write_and_publish(
            RootfsSource::Directory(PathBuf::from(layer_path)),
            Path::new(&ext4_path),
            TEMPLATE_ROOTFS_SIZE,
        )
        .await?;

        sweep_superseded(cache_dir, &layer_key, &agent_key, pinned).await;

        tracing::info!(path = %ext4_path, "rootfs ready");
        Ok(ext4_path)
    }

    /// Content key for the `vm-agent` binary that gets injected into every
    /// image.
    ///
    /// Content rather than mtime: this binary is copied into place by
    /// installers and by hand during development, so an older build can
    /// easily carry a newer timestamp — which an mtime check would read as
    /// fresh and then bake in.
    async fn vm_agent_key(&self) -> Result<String> {
        use std::hash::Hasher;
        let bytes = tokio::fs::read(&self.paths.vm_agent)
            .await
            .with_context(|| format!("failed to read {}", self.paths.vm_agent.display()))?;
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        hasher.write(&bytes);
        Ok(format!("{:016x}", hasher.finish()))
    }
}

/// Delete images for `layer_key` built against a different `vm-agent`.
///
/// Retain images pinned by snapshots, templates, or durable sandbox records.
/// These references require the original path and bytes across restarts.
/// Rebuilding with a different agent cannot reproduce checkpoint provenance.
/// An unpinned open image survives unlink until its last file reference closes.
async fn sweep_superseded(
    cache_dir: &Path,
    layer_key: &str,
    agent_key: &str,
    pinned: &BTreeSet<PathBuf>,
) {
    let Ok(mut entries) = tokio::fs::read_dir(cache_dir).await else {
        return;
    };
    let mut removed = 0usize;
    while let Ok(Some(entry)) = entries.next_entry().await {
        let name = entry.file_name().to_string_lossy().into_owned();
        if !is_superseded_image(&name, layer_key, agent_key) {
            continue;
        }
        let path = entry.path();
        if pinned.contains(&path) {
            tracing::debug!(path = %path.display(), "keeping superseded rootfs: pinned");
            continue;
        }
        if tokio::fs::remove_file(&path).await.is_ok() {
            removed += 1;
        }
    }
    if removed > 0 {
        tracing::info!(removed, layer = %layer_key, "removed superseded rootfs images");
    }
}

/// True when `name` is a cached image for `layer_key` built against some other
/// `vm-agent` than `agent_key`.
fn is_superseded_image(name: &str, layer_key: &str, agent_key: &str) -> bool {
    let Some(keys) = name
        .strip_prefix("rootfs-")
        .and_then(|rest| rest.strip_suffix(".ext4"))
    else {
        return false;
    };
    let Some((layer, agent)) = keys.split_once('-') else {
        // Pre-`agent_key` naming (`rootfs-<layer>.ext4`): its injected agent is
        // unknown, so treat it as superseded rather than keep it forever.
        return keys == layer_key;
    };
    layer == layer_key && agent != agent_key
}

impl RootfsBuilder {
    /// Remove leftover `*.ext4.tmp` build artifacts from the rootfs cache dir.
    ///
    /// A rootfs build that crashed or panicked leaves a `.default-<uuid>.ext4.tmp`
    /// or `.rootfs-<id>.ext4.tmp` (each up to the image size) with no owner;
    /// sweep them at startup so repeated failures don't accrue disk usage.
    pub async fn sweep_stale_tmp(&self) {
        let Ok(mut entries) = tokio::fs::read_dir(&self.paths.cache_dir).await else {
            return;
        };
        let mut removed = 0usize;
        while let Ok(Some(entry)) = entries.next_entry().await {
            if entry.file_name().to_string_lossy().ends_with(".ext4.tmp")
                && tokio::fs::remove_file(entry.path()).await.is_ok()
            {
                removed += 1;
            }
        }
        if removed > 0 {
            tracing::info!(removed, "swept stale rootfs build artifacts");
        }
    }

    /// Ensure the default busybox + vm-agent rootfs exists at `path` and is
    /// newer than its source binaries. Returns without touching the image
    /// when it is already up to date.
    pub async fn ensure_default_rootfs(&self, path: &str) -> crate::error::Result<()> {
        self.ensure_default(path).await.map_err(rootfs_err)
    }

    async fn ensure_default(&self, path: &str) -> Result<()> {
        let image = Path::new(path);
        if self.is_default_rootfs_fresh(image) {
            return Ok(());
        }

        // Single-flight: a concurrent create for the same default image waits here,
        // then the re-check lets it reuse the just-built image instead of
        // redundantly rebuilding 512 MiB.
        let _build = build_lock().lock().await;
        if self.is_default_rootfs_fresh(image) {
            return Ok(());
        }

        if !self.paths.vm_agent.exists() {
            bail!(
                "vm-agent not found at {}; it is staged by the host daemon next to arcbox-agent",
                self.paths.vm_agent.display()
            );
        }

        let applets = self.busybox_applets().await?;

        let parent = image
            .parent()
            .with_context(|| format!("default rootfs path has no parent: {path}"))?;
        tokio::fs::create_dir_all(parent)
            .await
            .context("failed to create default rootfs dir")?;

        let tmp = parent.join(format!(".default-{}.ext4.tmp", Uuid::new_v4()));
        let spec = DefaultRootfsSpec {
            busybox: self.paths.busybox.clone(),
            vm_agent: self.paths.vm_agent.clone(),
            applets,
            size: DEFAULT_ROOTFS_SIZE,
        };

        tracing::info!(path, "building default sandbox rootfs");
        {
            let tmp = tmp.clone();
            tokio::task::spawn_blocking(move || build_default_rootfs(&spec, &tmp))
                .await
                .context("default rootfs build task panicked")??;
        }

        tokio::fs::rename(&tmp, image)
            .await
            .context("failed to move default rootfs into place")?;
        tracing::info!(path, "default sandbox rootfs ready");
        Ok(())
    }

    /// True when the default rootfs image can be used as-is (no rebuild
    /// needed).
    ///
    /// A valid ext4 image is fresh unless a build source (busybox or
    /// vm-agent) is **present and newer** than it. A *missing* source is not
    /// staleness: we cannot rebuild from an absent binary, so an existing
    /// valid image — e.g. a caller-supplied default rootfs, or the production
    /// image on a host without the dev build sources — is kept rather than
    /// clobbered.
    fn is_default_rootfs_fresh(&self, image: &Path) -> bool {
        is_fresh_against(image, &[&self.paths.busybox, &self.paths.vm_agent])
    }

    /// List busybox applets via `busybox --list`.
    async fn busybox_applets(&self) -> Result<Vec<String>> {
        let output = Command::new(&self.paths.busybox)
            .arg("--list")
            .output()
            .await
            .with_context(|| format!("failed to run {} --list", self.paths.busybox.display()))?;
        if !output.status.success() {
            bail!("busybox --list failed with {}", output.status);
        }
        Ok(String::from_utf8_lossy(&output.stdout)
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .map(str::to_owned)
            .collect())
    }
}

/// [`RootfsBuilder::is_default_rootfs_fresh`] over explicit sources.
fn is_fresh_against(image: &Path, sources: &[&Path]) -> bool {
    if !has_ext4_magic(image) {
        return false;
    }
    let Ok(image_mtime) = image.metadata().and_then(|m| m.modified()) else {
        return false;
    };
    for source in sources {
        // Only a source that exists AND is newer forces a rebuild.
        if let Ok(mtime) = std::fs::metadata(source).and_then(|m| m.modified())
            && mtime > image_mtime
        {
            return false;
        }
    }
    true
}

/// Inputs for [`build_default_rootfs`].
struct DefaultRootfsSpec {
    /// Static busybox binary copied to `/bin/busybox`.
    busybox: std::path::PathBuf,
    /// vm-agent binary copied to `/sbin/vm-agent` (the sandbox init).
    vm_agent: std::path::PathBuf,
    /// Applet names to symlink into `/bin` (from `busybox --list`).
    applets: Vec<String>,
    /// ext4 image capacity in bytes.
    size: u64,
}

/// Write a minimal bootable rootfs: busybox + applet symlinks + vm-agent as
/// `/sbin/vm-agent` (and `/sbin/init`), plus the standard directory skeleton.
fn build_default_rootfs(spec: &DefaultRootfsSpec, out: &Path) -> Result<()> {
    const DIR: u16 = file_mode::S_IFDIR | 0o755;
    const EXE: u16 = file_mode::S_IFREG | 0o755;
    const LNK: u16 = file_mode::S_IFLNK | 0o777;

    let mut fmt = Formatter::with_options(out, FormatOptions::new(spec.size).label("arcbox-sbx"))
        .context("failed to create ext4 formatter")?;

    for dir in [
        "/bin", "/sbin", "/dev", "/proc", "/sys", "/run", "/etc", "/root", "/var",
    ] {
        fmt.create(dir, DIR, None, None, None, None, None, None)
            .with_context(|| format!("mkdir {dir}"))?;
    }
    // World-writable sticky /tmp.
    fmt.create(
        "/tmp",
        file_mode::S_IFDIR | file_mode::S_ISVTX | 0o777,
        None,
        None,
        None,
        None,
        None,
        None,
    )
    .context("mkdir /tmp")?;

    let mut busybox = std::fs::File::open(&spec.busybox)
        .with_context(|| format!("failed to open {}", spec.busybox.display()))?;
    fmt.create(
        "/bin/busybox",
        EXE,
        None,
        None,
        Some(&mut busybox),
        None,
        None,
        None,
    )
    .context("write /bin/busybox")?;

    for applet in &spec.applets {
        if applet == "busybox" || applet.contains('/') {
            continue;
        }
        let path = format!("/bin/{applet}");
        fmt.create(&path, LNK, Some("busybox"), None, None, None, None, None)
            .with_context(|| format!("symlink {path}"))?;
    }

    let mut vm_agent = std::fs::File::open(&spec.vm_agent)
        .with_context(|| format!("failed to open {}", spec.vm_agent.display()))?;
    fmt.create(
        VM_AGENT_PATH,
        EXE,
        None,
        None,
        Some(&mut vm_agent),
        None,
        None,
        None,
    )
    .context("write /sbin/vm-agent")?;
    // Fallback for boot args that omit init=: PID 1 is still vm-agent.
    fmt.create(
        "/sbin/init",
        LNK,
        Some("vm-agent"),
        None,
        None,
        None,
        None,
        None,
    )
    .context("symlink /sbin/init")?;

    let passwd = "root:x:0:0:root:/root:/bin/sh\n";
    fmt.create(
        "/etc/passwd",
        file_mode::S_IFREG | 0o644,
        None,
        None,
        Some(&mut passwd.as_bytes()),
        None,
        None,
        None,
    )
    .context("write /etc/passwd")?;
    let group = "root:x:0:\n";
    fmt.create(
        "/etc/group",
        file_mode::S_IFREG | 0o644,
        None,
        None,
        Some(&mut group.as_bytes()),
        None,
        None,
        None,
    )
    .context("write /etc/group")?;

    // resolv.conf lives on tmpfs (/run, mounted by vm-agent): DNS writes on
    // the post-restore reconfig path must not touch the block device — the
    // clone's first ext4 write pays a synchronous dm-snapshot CoW exception
    // through the nested I/O stack, measured at ~30 ms (CORE-75).
    fmt.create(
        "/etc/resolv.conf",
        LNK,
        Some("../run/resolv.conf"),
        None,
        None,
        None,
        None,
        None,
    )
    .context("symlink /etc/resolv.conf")?;

    fmt.close().context("failed to finalize ext4 image")?;
    Ok(())
}

/// Derive a stable cache key from the layer path.
fn path_hash(path: &str) -> String {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    path.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

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

    pub(super) fn isolated_log_test(name: &str) -> bool {
        const CHILD_TEST: &str = "ARCBOX_ROOTFS_LOG_TEST";
        if std::env::var(CHILD_TEST).as_deref() == Ok(name) {
            return true;
        }
        // Callsite interest is process-global; another test can register the
        // cleanup event before the scoped subscriber observes that event.
        let output = std::process::Command::new(std::env::current_exe().unwrap())
            .args(["--exact", name, "--nocapture"])
            .env(CHILD_TEST, name)
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            output.status.success() && stdout.contains("1 passed; 0 failed; 0 ignored"),
            "isolated log test {name} failed:\n{stdout}\n{}",
            String::from_utf8_lossy(&output.stderr)
        );
        false
    }

    #[test]
    fn test_has_ext4_magic_nonexistent() {
        assert!(!has_ext4_magic(Path::new("/nonexistent")));
    }

    #[test]
    fn is_superseded_image_matches_only_the_same_layer_with_another_agent() {
        // Same layer, older agent build: must go, or the sandbox keeps booting
        // the stale init.
        assert!(is_superseded_image("rootfs-aaaa-0000.ext4", "aaaa", "1111"));
        // The image we just published.
        assert!(!is_superseded_image(
            "rootfs-aaaa-1111.ext4",
            "aaaa",
            "1111"
        ));
        // A different layer is a different image, not a superseded one.
        assert!(!is_superseded_image(
            "rootfs-bbbb-0000.ext4",
            "aaaa",
            "1111"
        ));
        // Legacy name from before the agent key existed: same layer, unknown
        // agent, so treat as superseded; other layers stay.
        assert!(is_superseded_image("rootfs-aaaa.ext4", "aaaa", "1111"));
        assert!(!is_superseded_image("rootfs-bbbb.ext4", "aaaa", "1111"));
        // Anything that is not a published image is left alone, including the
        // in-progress temp files sweep_stale_tmp owns.
        assert!(!is_superseded_image(
            ".rootfs-aaaa-1111.ext4.tmp",
            "aaaa",
            "1111"
        ));
        assert!(!is_superseded_image("default.ext4", "aaaa", "1111"));
        assert!(!is_superseded_image(
            "rootfs-aaaa-1111.ext4.bak",
            "aaaa",
            "1111"
        ));
    }

    #[test]
    fn is_oci_layout_detects_the_layout_marker() {
        let dir = tempfile::TempDir::new().unwrap();

        // An overlay2 chain-id directory has no marker.
        std::fs::create_dir(dir.path().join("diff")).unwrap();
        assert!(!is_oci_layout(dir.path()));

        // A `docker save` export does, alongside a legacy manifest.json.
        std::fs::write(dir.path().join("manifest.json"), "[]").unwrap();
        std::fs::write(
            dir.path().join(OCI_LAYOUT_MARKER),
            r#"{"imageLayoutVersion":"1.0.0"}"#,
        )
        .unwrap();
        assert!(is_oci_layout(dir.path()));
    }

    #[tokio::test]
    async fn sweep_superseded_keeps_images_a_snapshot_still_needs() {
        let dir = tempfile::tempdir().unwrap();
        let image = |name: &str| dir.path().join(name);
        for name in [
            "rootfs-aaaa-0000.ext4",
            "rootfs-aaaa.ext4",
            "rootfs-aaaa-1111.ext4",
            "rootfs-bbbb-0000.ext4",
        ] {
            std::fs::write(image(name), b"x").unwrap();
        }
        let pinned = BTreeSet::from([image("rootfs-aaaa.ext4")]);

        sweep_superseded(dir.path(), "aaaa", "1111", &pinned).await;

        // Superseded and unreferenced: gone.
        assert!(!image("rootfs-aaaa-0000.ext4").exists());
        // Superseded but a snapshot records it as its dm-snapshot origin, and a
        // re-conversion would not reproduce those bytes.
        assert!(image("rootfs-aaaa.ext4").exists());
        // Current image and other layers are untouched.
        assert!(image("rootfs-aaaa-1111.ext4").exists());
        assert!(image("rootfs-bbbb-0000.ext4").exists());
    }

    #[test]
    fn test_path_hash_deterministic() {
        let a = path_hash("/var/lib/docker/overlay2/abc123");
        let b = path_hash("/var/lib/docker/overlay2/abc123");
        assert_eq!(a, b);
        assert_eq!(a.len(), 16);
    }

    #[test]
    fn test_path_hash_different() {
        let a = path_hash("/var/lib/docker/overlay2/abc123");
        let b = path_hash("/var/lib/docker/overlay2/def456");
        assert_ne!(a, b);
    }

    #[test]
    fn default_rootfs_builds_and_contains_init_chain() {
        let dir = tempfile::tempdir().unwrap();
        let busybox = dir.path().join("busybox");
        let vm_agent = dir.path().join("vm-agent");
        std::fs::write(&busybox, b"#!busybox-stub").unwrap();
        std::fs::write(&vm_agent, b"#!vm-agent-stub").unwrap();

        let out = dir.path().join("rootfs.ext4");
        let spec = DefaultRootfsSpec {
            busybox,
            vm_agent,
            applets: vec!["sh".into(), "ls".into(), "busybox".into()],
            size: 8 * 1024 * 1024,
        };
        build_default_rootfs(&spec, &out).unwrap();

        assert!(has_ext4_magic(&out));

        let reader = arcbox_ext4::Reader::new(&out).unwrap();
        for path in [
            "/bin/busybox",
            "/sbin/vm-agent",
            "/sbin/init",
            "/bin/sh",
            "/etc/passwd",
        ] {
            assert!(
                reader.tree().lookup(Path::new(path)).is_some(),
                "missing {path}"
            );
        }
        assert!(
            reader
                .tree()
                .lookup(Path::new("/bin/nonexistent"))
                .is_none()
        );
    }

    #[test]
    fn existing_image_is_fresh_when_build_sources_are_absent() {
        // A valid ext4 default rootfs must be reused as-is when the dev build
        // sources (/bin/busybox, /arcbox/bin/vm-agent) don't exist — the case
        // of a caller-supplied default rootfs on a host without the build
        // toolchain. Regression for the sandbox_service_manager integration
        // test, which passes an empty request rootfs backed by a real image.
        let dir = tempfile::tempdir().unwrap();
        let image = dir.path().join("rootfs.ext4");
        let spec = DefaultRootfsSpec {
            busybox: dir.path().join("busybox"),
            vm_agent: dir.path().join("vm-agent"),
            applets: vec!["sh".into()],
            size: 8 * 1024 * 1024,
        };
        std::fs::write(&spec.busybox, b"stub").unwrap();
        std::fs::write(&spec.vm_agent, b"stub").unwrap();
        build_default_rootfs(&spec, &image).unwrap();
        assert!(has_ext4_magic(&image));

        // Sources that do not exist exercise the missing-source branch
        // directly.
        let absent = dir.path().join("absent");
        assert!(
            is_fresh_against(&image, &[&absent, &absent]),
            "a valid image with absent build sources must be reused, not rebuilt"
        );
        assert!(!is_fresh_against(
            &dir.path().join("missing.ext4"),
            &[&absent]
        ));
        // A source that exists and is newer than the image forces a rebuild.
        std::thread::sleep(std::time::Duration::from_millis(20));
        let newer = dir.path().join("newer-agent");
        std::fs::write(&newer, b"stub").unwrap();
        assert!(!is_fresh_against(&image, &[&newer]));
    }
}