a3s-box-runtime 3.2.2

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

#[cfg(target_os = "macos")]
mod apfs;
mod baseline;
mod builder;
#[cfg(unix)]
mod ext4;
#[cfg(any(target_os = "macos", all(unix, test)))]
mod ext4_artifact;
#[cfg(any(target_os = "macos", all(unix, test)))]
mod ext4_cache;
#[cfg(target_os = "macos")]
mod guest_native_ext4;
#[cfg(target_os = "macos")]
mod guest_native_migration;
mod layout;
#[cfg(any(target_os = "macos", all(unix, test)))]
mod oci_ext4;
pub(crate) mod overlay;
mod provider;
mod staging_path;

pub use baseline::{
    create_diff_baseline_if_absent, guest_diff_baseline_required, publish_guest_diff_baseline,
    walk_rootfs, RootfsFileInfo, DIFF_BASELINE_FILE,
};
pub use builder::RootfsBuilder;
#[cfg(unix)]
pub use ext4::{
    publish_ext4_artifact, Ext4Artifact, Ext4ArtifactManifest, Ext4ArtifactOptions,
    EXT4_ARTIFACT_SCHEMA, EXT4_BUILDER_ID,
};
#[cfg(target_os = "macos")]
pub(crate) use ext4_cache::{Ext4ArtifactCache, Ext4CacheIdentity};
#[cfg(target_os = "macos")]
pub use guest_native_ext4::GuestNativeExt4Provider;
pub use layout::{GuestLayout, GUEST_WORKDIR};
pub use provider::{
    default_provider, default_provider_for_box, CopyProvider, OverlayProvider, ResumedRootfs,
    RootfsArtifactCacheOptions, RootfsFinalizeOptions, RootfsOciPrepareOptions, RootfsProvider,
    RootfsResumeOptions,
};
pub(crate) use provider::{default_provider_for_boot, default_provider_for_box_boot};
pub(crate) use staging_path::{
    ensure_directory_transport_is_lossless, host_staging_path, logical_path_for_staged_child,
    staging_path_map,
};

use std::io::Read;
use std::path::{Path, PathBuf};

use a3s_box_core::error::{BoxError, Result};
use a3s_box_core::guest_exec::{
    GuestTerminalStatus, GUEST_TERMINAL_STATUS_FILE_NAME, MAX_GUEST_TERMINAL_STATUS_BYTES,
};

enum TerminalStatusRead {
    Absent,
    PendingOrInvalid,
    Complete(GuestTerminalStatus),
}

fn read_guest_terminal_status(box_dir: &Path) -> TerminalStatusRead {
    let path = box_dir
        .join("runtime-control")
        .join(GUEST_TERMINAL_STATUS_FILE_NAME);
    let metadata = match std::fs::symlink_metadata(&path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return TerminalStatusRead::Absent;
        }
        Err(_) => return TerminalStatusRead::PendingOrInvalid,
    };
    if !metadata.is_file()
        || metadata.file_type().is_symlink()
        || metadata.len() > MAX_GUEST_TERMINAL_STATUS_BYTES as u64
    {
        return TerminalStatusRead::PendingOrInvalid;
    }

    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW);
    }
    let Ok(file) = options.open(&path) else {
        return TerminalStatusRead::PendingOrInvalid;
    };
    let mut bytes = Vec::with_capacity(metadata.len() as usize);
    if file
        .take(MAX_GUEST_TERMINAL_STATUS_BYTES as u64 + 1)
        .read_to_end(&mut bytes)
        .is_err()
        || bytes.is_empty()
        || bytes.len() > MAX_GUEST_TERMINAL_STATUS_BYTES
    {
        return TerminalStatusRead::PendingOrInvalid;
    }
    let Ok(status) = serde_json::from_slice::<GuestTerminalStatus>(&bytes) else {
        return TerminalStatusRead::PendingOrInvalid;
    };
    if status.validate().is_err() {
        return TerminalStatusRead::PendingOrInvalid;
    }
    TerminalStatusRead::Complete(status)
}

/// Return whether the current guest generation completed a clean block-root
/// handoff after publishing its terminal workload status.
pub(crate) fn guest_rootfs_handoff_complete(box_dir: &Path) -> bool {
    matches!(
        read_guest_terminal_status(box_dir),
        TerminalStatusRead::Complete(GuestTerminalStatus {
            rootfs_quiesced: true,
            ..
        })
    )
}

/// Read the exit code persisted by guest-init.
///
/// New MicroVMs publish through the private terminal-control sidecar. Legacy
/// providers expose `/.a3s_exit_code` at the overlay upper directory, copied
/// rootfs, or case-sensitive APFS data directory.
pub fn read_persisted_exit_code(box_dir: &Path) -> Option<i32> {
    resolve_workload_exit_code(box_dir, None)
}

/// Resolve a workload exit code without treating a clean provider shutdown as
/// proof that the guest workload succeeded.
///
/// Once the private terminal channel is staged, an empty or invalid status
/// means the guest never published a result. A nonzero provider status remains
/// useful crash evidence, but a provider zero is not substituted for missing
/// guest state.
pub fn resolve_workload_exit_code(box_dir: &Path, provider_exit_code: Option<i32>) -> Option<i32> {
    match read_guest_terminal_status(box_dir) {
        TerminalStatusRead::Complete(status) => return Some(status.exit_code),
        // A staged-but-empty terminal file belongs to the current generation.
        // Never fall back to a stale rootfs marker or a successful shim status.
        TerminalStatusRead::PendingOrInvalid => {
            return provider_exit_code.filter(|exit_code| *exit_code != 0);
        }
        TerminalStatusRead::Absent => {}
    }

    let candidates = [
        box_dir
            .join("upper")
            .join(a3s_box_core::rootfs_metadata::EXIT_CODE_PATH.trim_start_matches('/')),
        box_dir
            .join("rootfs")
            .join(".a3s-rootfs")
            .join(a3s_box_core::rootfs_metadata::EXIT_CODE_PATH.trim_start_matches('/')),
        box_dir
            .join("rootfs")
            .join(a3s_box_core::rootfs_metadata::EXIT_CODE_PATH.trim_start_matches('/')),
    ];

    candidates
        .into_iter()
        .find_map(|path| {
            std::fs::read_to_string(path)
                .ok()
                .and_then(|contents| contents.trim().parse::<i32>().ok())
        })
        .or(provider_exit_code)
}

/// A temporarily attached persistent rootfs.
///
/// Dropping this guard detaches only mounts created by
/// [`attach_persistent_rootfs`]. An already mounted rootfs is left untouched.
pub struct AttachedRootfs {
    path: std::path::PathBuf,
    detach_on_drop: bool,
}

/// Return whether a box has a retained guest-native raw rootfs generation.
///
/// Any directory entry at the versioned artifact path counts. Validation is
/// performed by the provider before boot; detection must still fail closed for
/// malformed generations instead of falling back to a host directory.
pub fn guest_native_ext4_generation_exists(box_dir: &Path) -> Result<bool> {
    let path = box_dir.join("rootfs-ext4-v1");
    match std::fs::symlink_metadata(&path) {
        Ok(_) => Ok(true),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(BoxError::BuildError(format!(
            "Failed to inspect guest-native rootfs generation {}: {error}",
            path.display()
        ))),
    }
}

/// Return the logical disk capacity owned by a retained guest-native rootfs.
///
/// CLI state predates block-root capacities and therefore cannot be the source
/// of truth for a restored raw snapshot. Reconstructing a boot must use the
/// validated artifact's own immutable geometry instead of silently applying a
/// process default that may disagree with it.
pub fn guest_native_ext4_disk_mib(box_dir: &Path) -> Result<Option<u32>> {
    if !guest_native_ext4_generation_exists(box_dir)? {
        return Ok(None);
    }
    #[cfg(target_os = "macos")]
    {
        let directory = GuestNativeExt4Provider::artifact_directory(box_dir);
        let (artifact, _) = ext4_artifact::open_ext4_artifact_for_resume(&directory)?;
        const MIB: u64 = 1024 * 1024;
        if artifact.manifest.capacity_bytes % MIB != 0 {
            return Err(BoxError::StateError(format!(
                "Guest-native rootfs capacity is not MiB-aligned at {}",
                artifact.disk.display()
            )));
        }
        let disk_mib = u32::try_from(artifact.manifest.capacity_bytes / MIB).map_err(|_| {
            BoxError::StateError(format!(
                "Guest-native rootfs capacity exceeds the Box configuration range at {}",
                artifact.disk.display()
            ))
        })?;
        Ok(Some(disk_mib))
    }
    #[cfg(not(target_os = "macos"))]
    {
        Err(BoxError::StateError(format!(
            "Guest-native rootfs state is unsupported on this host: {}",
            box_dir.join("rootfs-ext4-v1").display()
        )))
    }
}

/// Open a clean guest-native generation for an immutable filesystem snapshot.
///
/// A snapshot is observational state: it must never replay a guest journal or
/// capture a disk whose final writes are still ambiguous. Normal writable boot
/// owns recovery; callers can retry after one successful start and clean stop.
#[cfg(target_os = "macos")]
pub(crate) fn open_clean_guest_native_ext4_artifact(
    artifact_directory: &Path,
) -> Result<Ext4Artifact> {
    let (artifact, validation) = ext4_artifact::open_ext4_artifact_for_resume(artifact_directory)?;
    if validation == ext4::Ext4ResumeValidation::JournalRecoveryRequired {
        return Err(BoxError::StateError(format!(
            "Guest-native rootfs at {} needs ext4 journal recovery; start the box and stop it cleanly before creating or restoring a filesystem snapshot",
            artifact.disk.display()
        )));
    }
    Ok(artifact)
}

/// Clone one clean raw-ext4 generation into a private atomically published
/// artifact directory. The source is never attached or opened writable.
#[cfg(target_os = "macos")]
pub(crate) fn clone_clean_guest_native_ext4_artifact(
    artifact_directory: &Path,
    destination: &Path,
) -> Result<Ext4Artifact> {
    let source = open_clean_guest_native_ext4_artifact(artifact_directory)?;
    let cloned = ext4_cache::clone_artifact(&source, destination)?;
    let validated = match open_clean_guest_native_ext4_artifact(destination) {
        Ok(validated) => validated,
        Err(error) => {
            let _ = std::fs::remove_dir_all(destination);
            return Err(error);
        }
    };
    if cloned != validated || source.manifest != validated.manifest {
        let _ = std::fs::remove_dir_all(destination);
        return Err(BoxError::StateError(format!(
            "Cloned guest-native rootfs identity changed at {}",
            destination.display()
        )));
    }
    Ok(validated)
}

#[cfg(target_os = "macos")]
pub(crate) fn guest_native_ext4_sparse_digest(artifact: &Ext4Artifact) -> Result<String> {
    ext4_cache::sparse_sha256(&artifact.disk, artifact.manifest.capacity_bytes)
}

#[cfg(target_os = "macos")]
pub(crate) fn guest_native_ext4_allocated_bytes(artifact_directory: &Path) -> Result<u64> {
    ext4_cache::allocated_bytes(artifact_directory)
}

/// Resolve a clean guest-native generation for the trusted read-only
/// maintenance VM.
///
/// A crashed filesystem is intentionally rejected here. The observation path
/// attaches its disk read-only and mounts ext4 with `noload`, so journal replay
/// belongs to a normal writable boot followed by a verified clean stop.
#[cfg(target_os = "macos")]
pub(crate) fn guest_native_ext4_maintenance_disk(box_dir: &Path) -> Result<PathBuf> {
    let directory = GuestNativeExt4Provider::artifact_directory(box_dir);
    let (artifact, validation) = ext4_artifact::open_ext4_artifact_for_resume(&directory)?;
    if validation == ext4::Ext4ResumeValidation::JournalRecoveryRequired {
        return Err(BoxError::StateError(format!(
            "Guest-native rootfs at {} needs ext4 journal recovery; start the box and stop it cleanly before offline diff, export, or commit",
            artifact.disk.display()
        )));
    }
    Ok(artifact.disk)
}

impl AttachedRootfs {
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for AttachedRootfs {
    fn drop(&mut self) {
        if self.detach_on_drop {
            unmount_box_rootfs(&self.path);
        }
    }
}

/// Attach an existing platform-backed persistent rootfs for offline access.
///
/// Returns `None` when the box has no platform-specific backing image. This
/// never creates a new image, so callers cannot accidentally commit an empty
/// filesystem when a backing image is missing.
pub fn attach_persistent_rootfs(
    box_dir: &Path,
) -> a3s_box_core::error::Result<Option<AttachedRootfs>> {
    if guest_native_ext4_generation_exists(box_dir)? {
        return Err(BoxError::StateError(
            "Guest-native rootfs generations have no host directory attachment; use the trusted maintenance archive path for stopped access"
                .to_string(),
        ));
    }

    #[cfg(target_os = "macos")]
    {
        let image = box_dir.join("rootfs-apfs-v2.sparseimage");
        if !image.is_file() {
            return Ok(None);
        }
        let rootfs = box_dir.join("rootfs");
        let was_mounted = is_mountpoint(&rootfs);
        let path = provider::CaseSensitiveApfsProvider.prepare_empty(box_dir)?;
        Ok(Some(AttachedRootfs {
            path,
            detach_on_drop: !was_mounted,
        }))
    }

    #[cfg(not(target_os = "macos"))]
    {
        let _ = box_dir;
        Ok(None)
    }
}

/// Invalidate the last clean-shutdown metadata generation before launching a
/// box, retaining it at the one-shot replay path used by guest-init.
///
/// Overlay providers can expose the same entry through `merged` and `upper`.
/// Staging is idempotent when the canonical marker is already absent: an
/// existing replay marker is retained so a boot that failed before guest replay
/// can be retried safely.
pub fn stage_box_terminal_rootfs_metadata(box_dir: &Path) -> a3s_box_core::error::Result<()> {
    if guest_native_ext4_generation_exists(box_dir)? {
        // The raw disk is not host-mounted. Guest-init invalidates and consumes
        // the prior terminal generation before it starts any workload process.
        return Ok(());
    }
    let attached = attach_persistent_rootfs(box_dir)?;
    let mut roots = Vec::<PathBuf>::new();
    if let Some(rootfs) = attached.as_ref() {
        roots.push(rootfs.path().to_path_buf());
    }
    roots.extend([
        box_dir.join("rootfs"),
        box_dir.join("upper"),
        box_dir.join("merged"),
    ]);
    roots.sort();
    roots.dedup();

    let mut existing_roots = Vec::new();
    for root in roots {
        match std::fs::symlink_metadata(&root) {
            Ok(_) => existing_roots.push(root),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
    }
    stage_metadata_roots(&existing_roots)?;
    Ok(())
}

fn stage_metadata_roots(roots: &[PathBuf]) -> std::io::Result<()> {
    for root in roots {
        a3s_box_core::rootfs_metadata::stage_terminal_rootfs_metadata_for_boot(root)?;
    }
    Ok(())
}

/// Unmount a box's overlayfs `merged` view — best-effort and idempotent.
///
/// Box teardown must release this mount BEFORE removing the box dir, or
/// `remove_dir_all` deletes *into* the live mount and fails with "Stale file
/// handle", leaking the mount. A restart re-mounts without unmounting first, so
/// the overlay can be stacked (mounted 2–3×); unmount in a bounded loop until
/// `merged` is no longer a mountpoint. No-op if it was never mounted.
pub fn unmount_box_overlay(merged: &Path) {
    for _ in 0..8 {
        if !is_mountpoint(merged) {
            break;
        }
        if overlay::overlay_unmount(merged).is_err() {
            break;
        }
    }
}

/// Fully unmount a box overlay before its writable layer is reused.
///
/// Unlike [`unmount_box_overlay`], this path never falls back to lazy detach:
/// callers must not start another overlay writer until every stacked mount has
/// been synchronously released.
pub(crate) fn unmount_box_overlay_for_reuse(merged: &Path) -> a3s_box_core::error::Result<()> {
    for _ in 0..8 {
        if !is_mountpoint(merged) {
            return Ok(());
        }
        overlay::overlay_unmount_for_reuse(merged)?;
    }

    if is_mountpoint(merged) {
        return Err(a3s_box_core::error::BoxError::BuildError(format!(
            "Overlay at {} remained mounted after synchronous cleanup",
            merged.display()
        )));
    }
    Ok(())
}

/// True if `path` is a mountpoint (its device id differs from its parent's).
#[cfg(unix)]
pub(crate) fn is_mountpoint(path: &Path) -> bool {
    use std::os::unix::fs::MetadataExt;
    match (std::fs::metadata(path), std::fs::metadata(path.join(".."))) {
        (Ok(here), Ok(parent)) => here.dev() != parent.dev(),
        _ => false,
    }
}

#[cfg(not(unix))]
pub(crate) fn is_mountpoint(_path: &Path) -> bool {
    false
}

/// Unmount a platform-specific writable rootfs mount.
pub fn unmount_box_rootfs(rootfs: &Path) {
    #[cfg(target_os = "macos")]
    {
        // The case-sensitive provider returns `<mount>/.a3s-rootfs`, keeping
        // APFS-created volume metadata outside the Linux tree. Accept either
        // that data path or the mountpoint itself at cleanup call sites.
        let mountpoint = if rootfs.file_name().is_some_and(|name| name == ".a3s-rootfs") {
            rootfs.parent().unwrap_or(rootfs)
        } else {
            rootfs
        };
        if !is_mountpoint(mountpoint) {
            return;
        }
        match std::process::Command::new("hdiutil")
            .arg("detach")
            .arg("-quiet")
            .arg(mountpoint)
            .status()
        {
            Ok(status) if status.success() => {}
            Ok(status) => tracing::warn!(
                path = %mountpoint.display(),
                ?status,
                "Failed to detach case-sensitive rootfs image"
            ),
            Err(error) => tracing::warn!(
                path = %mountpoint.display(),
                %error,
                "Failed to run hdiutil detach"
            ),
        }
    }

    #[cfg(not(target_os = "macos"))]
    let _ = rootfs;
}

/// Synchronously detach a macOS staging filesystem before a block artifact is
/// handed to the guest. Unlike teardown cleanup, ownership handoff is not
/// best-effort: a remaining host mount violates the guest-native invariant and
/// aborts the boot.
#[cfg(target_os = "macos")]
pub(crate) fn unmount_box_rootfs_for_handoff(rootfs: &Path) -> a3s_box_core::error::Result<()> {
    let mountpoint = if rootfs.file_name().is_some_and(|name| name == ".a3s-rootfs") {
        rootfs.parent().unwrap_or(rootfs)
    } else {
        rootfs
    };
    if !is_mountpoint(mountpoint) {
        return Err(a3s_box_core::error::BoxError::BuildError(format!(
            "Expected a mounted rootfs staging filesystem at {}",
            mountpoint.display()
        )));
    }
    let status = std::process::Command::new("hdiutil")
        .arg("detach")
        .arg("-quiet")
        .arg(mountpoint)
        .status()
        .map_err(|error| {
            a3s_box_core::error::BoxError::BuildError(format!(
                "Failed to run hdiutil detach for {}: {error}",
                mountpoint.display()
            ))
        })?;
    if !status.success() || is_mountpoint(mountpoint) {
        return Err(a3s_box_core::error::BoxError::BuildError(format!(
            "Rootfs staging filesystem remained attached at {} after handoff",
            mountpoint.display()
        )));
    }
    Ok(())
}

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

    #[test]
    fn persisted_exit_code_supports_each_rootfs_provider_layout() {
        for (relative, expected) in [
            ("upper/.a3s_exit_code", 17),
            ("rootfs/.a3s_exit_code", 23),
            ("rootfs/.a3s-rootfs/.a3s_exit_code", 29),
        ] {
            let temp = tempfile::tempdir().unwrap();
            let path = temp.path().join(relative);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, format!("{expected}\n")).unwrap();

            assert_eq!(read_persisted_exit_code(temp.path()), Some(expected));
        }
    }

    #[test]
    fn persisted_exit_code_ignores_missing_or_invalid_files() {
        let temp = tempfile::tempdir().unwrap();
        assert_eq!(read_persisted_exit_code(temp.path()), None);

        let path = temp.path().join("rootfs/.a3s_exit_code");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, "not-an-exit-code").unwrap();
        assert_eq!(read_persisted_exit_code(temp.path()), None);
    }

    #[test]
    fn terminal_status_is_preferred_over_legacy_rootfs_marker() {
        let temp = tempfile::tempdir().unwrap();
        let terminal = temp
            .path()
            .join("runtime-control")
            .join(GUEST_TERMINAL_STATUS_FILE_NAME);
        std::fs::create_dir_all(terminal.parent().unwrap()).unwrap();
        std::fs::write(
            &terminal,
            serde_json::to_vec(&GuestTerminalStatus::new(31)).unwrap(),
        )
        .unwrap();
        let legacy = temp.path().join("rootfs/.a3s_exit_code");
        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        std::fs::write(legacy, "7").unwrap();

        assert_eq!(read_persisted_exit_code(temp.path()), Some(31));
    }

    #[test]
    fn rootfs_handoff_requires_an_explicit_guest_quiescence_ack() {
        let temp = tempfile::tempdir().unwrap();
        let terminal = temp
            .path()
            .join("runtime-control")
            .join(GUEST_TERMINAL_STATUS_FILE_NAME);
        std::fs::create_dir_all(terminal.parent().unwrap()).unwrap();

        std::fs::write(
            &terminal,
            serde_json::to_vec(&GuestTerminalStatus::new(0)).unwrap(),
        )
        .unwrap();
        assert!(!guest_rootfs_handoff_complete(temp.path()));

        std::fs::write(
            &terminal,
            serde_json::to_vec(&GuestTerminalStatus::new(0).with_rootfs_quiesced()).unwrap(),
        )
        .unwrap();
        assert!(guest_rootfs_handoff_complete(temp.path()));
    }

    #[test]
    fn pending_terminal_status_blocks_stale_rootfs_fallback() {
        let temp = tempfile::tempdir().unwrap();
        let terminal = temp
            .path()
            .join("runtime-control")
            .join(GUEST_TERMINAL_STATUS_FILE_NAME);
        std::fs::create_dir_all(terminal.parent().unwrap()).unwrap();
        std::fs::write(terminal, []).unwrap();
        let legacy = temp.path().join("rootfs/.a3s_exit_code");
        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        std::fs::write(legacy, "0").unwrap();

        assert_eq!(read_persisted_exit_code(temp.path()), None);
        assert_eq!(resolve_workload_exit_code(temp.path(), Some(0)), None);
        assert_eq!(resolve_workload_exit_code(temp.path(), Some(9)), Some(9));
    }

    #[test]
    fn missing_path_is_not_mountpoint() {
        let temp = tempfile::tempdir().unwrap();
        let missing = temp.path().join("missing");

        assert!(!is_mountpoint(&missing));
    }

    #[test]
    fn unmount_overlay_noops_for_non_mountpoint() {
        let temp = tempfile::tempdir().unwrap();
        let merged = temp.path().join("merged");
        std::fs::create_dir(&merged).unwrap();

        unmount_box_overlay(&merged);

        assert!(merged.exists());
    }

    #[test]
    fn staging_is_idempotent_until_guest_replay_succeeds() {
        let root = tempfile::tempdir().unwrap();
        let terminal = root
            .path()
            .join(a3s_box_core::rootfs_metadata::ROOTFS_METADATA_PATH.trim_start_matches('/'));
        let previous = root.path().join(
            a3s_box_core::rootfs_metadata::PREVIOUS_ROOTFS_METADATA_PATH.trim_start_matches('/'),
        );
        std::fs::write(&terminal, b"clean generation").unwrap();

        stage_metadata_roots(&[root.path().to_path_buf()]).unwrap();
        stage_metadata_roots(&[root.path().to_path_buf()]).unwrap();

        assert!(!terminal.exists());
        assert_eq!(std::fs::read(previous).unwrap(), b"clean generation");
    }

    #[test]
    fn staging_one_candidate_never_discards_an_alias_replay() {
        let directory = tempfile::tempdir().unwrap();
        let merged = directory.path().join("merged");
        let upper = directory.path().join("upper");
        std::fs::create_dir_all(&merged).unwrap();
        std::fs::create_dir_all(&upper).unwrap();
        let terminal_name =
            a3s_box_core::rootfs_metadata::ROOTFS_METADATA_PATH.trim_start_matches('/');
        let previous_name =
            a3s_box_core::rootfs_metadata::PREVIOUS_ROOTFS_METADATA_PATH.trim_start_matches('/');
        std::fs::write(merged.join(terminal_name), b"clean generation").unwrap();
        // Models the view through `upper` immediately after the same overlay
        // entry was renamed through `merged`.
        std::fs::write(upper.join(previous_name), b"clean generation").unwrap();

        stage_metadata_roots(&[merged.clone(), upper.clone()]).unwrap();

        assert!(merged.join(previous_name).is_file());
        assert!(upper.join(previous_name).is_file());
    }

    #[test]
    fn staging_box_roots_clears_every_previous_exit_status() {
        let directory = tempfile::tempdir().unwrap();
        let box_dir = directory.path().join("box");
        for provider_root in ["rootfs", "upper", "merged"] {
            let root = box_dir.join(provider_root);
            std::fs::create_dir_all(&root).unwrap();
            std::fs::write(
                root.join(a3s_box_core::rootfs_metadata::EXIT_CODE_PATH.trim_start_matches('/')),
                b"17\n",
            )
            .unwrap();
        }

        stage_box_terminal_rootfs_metadata(&box_dir).unwrap();

        assert_eq!(read_persisted_exit_code(&box_dir), None);
        for provider_root in ["rootfs", "upper", "merged"] {
            assert!(!box_dir
                .join(provider_root)
                .join(a3s_box_core::rootfs_metadata::EXIT_CODE_PATH.trim_start_matches('/'))
                .exists());
        }
    }

    #[test]
    fn raw_generation_keeps_terminal_fencing_inside_guest() {
        let directory = tempfile::tempdir().unwrap();
        let box_dir = directory.path().join("box");
        let artifact = box_dir.join("rootfs-ext4-v1");
        let rootfs = box_dir.join("rootfs");
        std::fs::create_dir_all(&artifact).unwrap();
        std::fs::create_dir_all(&rootfs).unwrap();
        let terminal = rootfs
            .join(a3s_box_core::rootfs_metadata::ROOTFS_METADATA_PATH.trim_start_matches('/'));
        std::fs::write(&terminal, b"guest-owned").unwrap();

        assert!(guest_native_ext4_generation_exists(&box_dir).unwrap());
        stage_box_terminal_rootfs_metadata(&box_dir).unwrap();
        assert_eq!(std::fs::read(&terminal).unwrap(), b"guest-owned");
        assert!(attach_persistent_rootfs(&box_dir).is_err());
    }
}