boxlite 0.10.1

Embeddable virtual machine runtime for secure, isolated code execution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
//! Guest rootfs types and metadata.

use std::fs;
use std::path::{Path, PathBuf};

use boxlite_shared::errors::{BoxliteError, BoxliteResult};

use crate::disk::{
    BaseDisk, BaseDiskKind, BaseDiskManager, Disk, DiskFormat, create_ext4_from_dir,
    inject_file_into_ext4,
};
use crate::images::{ImageDiskManager, ImageObject};
#[cfg(test)]
use crate::runtime::id::BaseDiskID;
use crate::runtime::id::BaseDiskIDMint;
use crate::vmm::guest_artifacts::GuestArtifacts;
use crate::vmm::guest_binary::GuestBinary;

/// A fully resolved and ready-to-use guest rootfs.
///
/// This struct represents the box's guest rootfs that runs boxlite-guest:
/// - Image pulled (if needed)
/// - Layers extracted/overlayed
/// - Guest binary injected and validated
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GuestRootfs {
    /// Path to the merged/final rootfs directory
    pub path: PathBuf,

    /// How this rootfs was prepared
    pub strategy: Strategy,

    /// Kernel images path (for Firecracker/microVM)
    pub kernel: Option<PathBuf>,

    /// Initrd path (optional)
    pub initrd: Option<PathBuf>,

    /// Environment variables from the init image config (e.g., PATH)
    #[serde(default)]
    pub env: Vec<(String, String)>,
}

/// Strategy used to prepare the rootfs.
///
/// This tracks how the rootfs was assembled, which is important for:
/// - Cleanup logic (overlayfs mounts need unmounting)
/// - Debugging (understand which strategy was used)
/// - Performance metrics (compare overlay vs extraction)
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub enum Strategy {
    /// Direct path provided by user (no processing needed)
    #[default]
    Direct,

    /// Layers extracted into a single directory
    ///
    /// Used on macOS (no overlayfs) and as fallback on Linux
    Extracted {
        /// Number of layers extracted
        layers: usize,
    },

    /// Linux overlayfs mount (requires cleanup on drop)
    ///
    /// This is the preferred strategy on Linux when CAP_SYS_ADMIN is available
    OverlayMount {
        /// Lower directories (read-only layers)
        lower: Vec<PathBuf>,
        /// Upper directory (writable layer)
        upper: PathBuf,
        /// Work directory (required by overlayfs)
        work: PathBuf,
    },

    /// Disk-based rootfs (ext4 disk image)
    ///
    /// The guest rootfs is stored in an ext4 disk image that the box boots from.
    /// This provides better performance than virtiofs for the guest rootfs.
    Disk {
        /// Path to the ext4 disk image
        disk_path: PathBuf,
        /// Device path in guest (e.g., "/dev/vdc").
        /// Set by build_disk_attachments when disks are configured.
        device_path: Option<String>,
    },
}

impl GuestRootfs {
    /// Create a new GuestRootfs, injecting the guest binary if needed.
    pub fn new(
        path: PathBuf,
        strategy: Strategy,
        kernel: Option<PathBuf>,
        initrd: Option<PathBuf>,
        env: Vec<(String, String)>,
    ) -> BoxliteResult<Self> {
        // Inject guest binary for directory-based strategies only.
        // For disk-based strategies, the guest binary was already included
        // during disk creation from the merged layers.
        match &strategy {
            Strategy::Disk { disk_path, .. } => {
                tracing::debug!(
                    "Skipping guest binary injection for disk-based rootfs: {}",
                    disk_path.display()
                );
            }
            _ => {
                crate::util::inject_guest_binary(&path)?;
            }
        }

        Ok(Self {
            path,
            strategy,
            kernel,
            initrd,
            env,
        })
    }

    /// Clean up this rootfs.
    ///
    /// Behavior depends on strategy:
    /// - `Direct`: No-op (user-provided path, don't delete)
    /// - `Extracted`: Remove the directory
    /// - `OverlayMount`: Unmount, then remove the directory
    ///
    /// Returns Ok(()) if cleanup succeeded or wasn't needed.
    pub fn cleanup(&self) -> BoxliteResult<()> {
        match &self.strategy {
            Strategy::Direct => {
                // User-provided path - don't clean up
                tracing::debug!(
                    "Skipping cleanup for direct rootfs: {}",
                    self.path.display()
                );
                Ok(())
            }
            Strategy::Extracted { layers } => {
                tracing::info!(
                    "Cleaning up extracted rootfs ({} layers): {}",
                    layers,
                    self.path.display()
                );
                // Remove parent directory (contains merged/)
                if let Some(parent) = self.path.parent() {
                    Self::remove_directory(parent)
                } else {
                    Self::remove_directory(&self.path)
                }
            }
            Strategy::OverlayMount { .. } => {
                tracing::info!("Cleaning up overlay mount: {}", self.path.display());

                #[cfg(target_os = "linux")]
                {
                    // Unmount overlay first
                    Self::unmount_overlay(&self.path)?;
                }

                // Remove parent directory (contains merged/, upper/, work/, patch/)
                if let Some(parent) = self.path.parent() {
                    Self::remove_directory(parent)
                } else {
                    Ok(())
                }
            }
            Strategy::Disk { disk_path, .. } => {
                // Disk-based rootfs: disk is managed by the cache, don't clean up
                tracing::debug!(
                    "Skipping cleanup for disk-based rootfs: {} (managed by cache)",
                    disk_path.display()
                );
                Ok(())
            }
        }
    }

    /// Unmount overlayfs (Linux only)
    #[cfg(target_os = "linux")]
    fn unmount_overlay(merged_dir: &Path) -> BoxliteResult<()> {
        if !merged_dir.exists() {
            return Ok(());
        }

        match std::process::Command::new("umount")
            .arg(merged_dir)
            .status()
        {
            Ok(status) if status.success() => {
                tracing::debug!("Unmounted overlay: {}", merged_dir.display());
                Ok(())
            }
            Ok(status) => {
                tracing::warn!(
                    "Failed to unmount overlay {}: exit status {}",
                    merged_dir.display(),
                    status
                );
                Err(BoxliteError::Storage(format!(
                    "umount failed with status {}",
                    status
                )))
            }
            Err(e) => {
                tracing::warn!(
                    "Failed to execute umount for {}: {}",
                    merged_dir.display(),
                    e
                );
                Err(BoxliteError::Storage(format!(
                    "umount execution failed: {}",
                    e
                )))
            }
        }
    }

    /// Remove directory recursively
    fn remove_directory(path: &Path) -> BoxliteResult<()> {
        if let Err(e) = std::fs::remove_dir_all(path) {
            tracing::warn!(
                "Failed to cleanup rootfs directory {}: {}",
                path.display(),
                e
            );
            Err(BoxliteError::Storage(format!("cleanup failed: {}", e)))
        } else {
            tracing::info!("Cleaned up rootfs directory: {}", path.display());
            Ok(())
        }
    }
}

/// Manages versioned guest rootfs disks.
///
/// A guest rootfs = pure image disk + injected `boxlite-guest` binary.
/// Version key = `{image_digest_short}-{guest_hash_short}`.
///
/// Old versions are kept alive as long as existing box qcow2 overlays
/// reference them. GC removes unreferenced entries on startup.
///
/// Follows the staged install pattern: copy to temp → inject → atomic rename.
///
/// # Concurrency
///
/// Thread-safety is provided by the caller:
/// - Multi-process: `RuntimeLock` ensures single-process access per BOXLITE_HOME
/// - In-process: `OnceCell<GuestRootfs>` serializes all calls to `get_or_create()`
/// - GC runs at startup (in `recover_boxes()`) before any box creation
///
/// No internal locking is needed.
///
/// Cache location: `~/.boxlite/bases/`
///
/// Rootfs entries use `BaseDiskID` filenames (e.g., `bases/a7Kx9mPq.ext4`) and are
/// tracked in the `base_disk` table with `kind = 'rootfs'` and
/// `source_box_id = "__global__"`. The `name` field stores the version key
/// for content-addressable lookup.
pub struct GuestRootfsManager {
    base_disk_mgr: BaseDiskManager,
    temp_dir: PathBuf,
}

/// Sentinel source_box_id for global rootfs cache entries.
const GLOBAL_SOURCE: &str = "__global__";

impl GuestRootfsManager {
    pub fn new(base_disk_mgr: BaseDiskManager, temp_dir: PathBuf) -> Self {
        Self {
            base_disk_mgr,
            temp_dir,
        }
    }

    /// Get or create a versioned guest rootfs.
    ///
    /// Stage 1 (via `ImageDiskManager`): ensure pure image ext4 exists.
    /// Stage 2: copy image disk → inject guest binary via debugfs → cache.
    ///
    /// Returns a `GuestRootfs` with `Strategy::Disk` pointing at the cached ext4.
    pub async fn get_or_create(
        &self,
        image: &ImageObject,
        image_disk_mgr: &ImageDiskManager,
        env: Vec<(String, String)>,
    ) -> BoxliteResult<GuestRootfs> {
        let total_start = std::time::Instant::now();

        // Stage 1: ensure pure image disk exists
        let stage1_start = std::time::Instant::now();
        let image_disk = image_disk_mgr.get_or_create(image).await?;
        tracing::info!(
            elapsed_ms = stage1_start.elapsed().as_millis() as u64,
            "get_or_create: stage1 image_disk done"
        );

        // Stage 2: versioned guest rootfs
        let digest = image.compute_image_digest();
        let guest = GuestBinary::get()?;
        let version_key = Self::version_key(&digest, guest.id());

        if let Some(disk) = self.find(&version_key) {
            tracing::info!(
                version_key = %version_key,
                commit = boxlite_shared::GIT_COMMIT.unwrap_or("unknown"),
                total_ms = total_start.elapsed().as_millis() as u64,
                "get_or_create: CACHE HIT"
            );
            return Self::disk_to_guest_rootfs(disk, env);
        }

        tracing::info!(
            version_key = %version_key,
            "get_or_create: CACHE MISS — building guest rootfs"
        );
        let disk = self.build_and_install(&image_disk, &version_key).await?;

        tracing::info!(
            total_ms = total_start.elapsed().as_millis() as u64,
            cache_hit = false,
            "get_or_create: completed"
        );

        Self::disk_to_guest_rootfs(disk, env)
    }

    /// Get or create the minimal guest rootfs from the standalone artifacts.
    ///
    /// The minimal rootfs is just `boxlite-guest` plus the static
    /// `mke2fs`/`resize2fs`; it is built straight into an ext4 (no OCI image,
    /// nothing injected afterward) and cached content-addressed in `bases/`
    /// under the combined artifact hash, tracked and GC'd like the Debian rootfs.
    pub async fn get_or_create_minimal(
        &self,
        artifacts: &GuestArtifacts,
    ) -> BoxliteResult<GuestRootfs> {
        let key = Self::minimal_version_key(artifacts);

        if let Some(disk) = self.find(&key) {
            tracing::debug!(version_key = %key, "get_or_create_minimal: cache hit");
            return Self::disk_to_guest_rootfs(disk, Vec::new());
        }

        tracing::info!(version_key = %key, "get_or_create_minimal: cache miss — building");
        let disk = self.build_minimal_and_install(artifacts, &key).await?;
        Self::disk_to_guest_rootfs(disk, Vec::new())
    }

    /// Stage the artifacts into a tree, build an ext4, and install it through
    /// the shared cache (`install`), so the minimal rootfs is tracked and GC'd
    /// like the Debian rootfs.
    async fn build_minimal_and_install(
        &self,
        artifacts: &GuestArtifacts,
        key: &str,
    ) -> BoxliteResult<Disk> {
        let temp = tempfile::tempdir_in(&self.temp_dir).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to create minimal rootfs temp dir in {}: {}",
                self.temp_dir.display(),
                e
            ))
        })?;

        let tree_root = temp.path().join("rootfs");
        stage_tree(&tree_root, artifacts)?;
        let staged_path = temp.path().join("minimal-rootfs.ext4");

        // mke2fs runs as a subprocess plus disk I/O; keep it off the async path.
        let tree_for_build = tree_root.clone();
        let staged_for_build = staged_path.clone();
        let disk = tokio::task::spawn_blocking(move || {
            create_ext4_from_dir(&tree_for_build, &staged_for_build, 0)
        })
        .await
        .map_err(|e| BoxliteError::Storage(format!("minimal rootfs build task failed: {e}")))??;

        self.install(key, disk)
    }

    /// Convert a persistent `Disk` into a `GuestRootfs` with `Strategy::Disk`.
    ///
    /// Leaks the disk (prevents drop cleanup) since ownership transfers to
    /// the `OnceCell<GuestRootfs>` in the runtime.
    fn disk_to_guest_rootfs(disk: Disk, env: Vec<(String, String)>) -> BoxliteResult<GuestRootfs> {
        let disk_path = disk.path().to_path_buf();
        let _ = disk.leak();
        GuestRootfs::new(
            disk_path.clone(),
            Strategy::Disk {
                disk_path,
                device_path: None,
            },
            None,
            None,
            env,
        )
    }

    /// Look up a cached guest rootfs by version key (DB-backed).
    fn find(&self, version_key: &str) -> Option<Disk> {
        let record = self
            .base_disk_mgr
            .store()
            .find_by_name(GLOBAL_SOURCE, version_key)
            .ok()
            .flatten()?;
        let path = PathBuf::from(record.base_path());
        if path.exists() {
            Some(Disk::new(path, DiskFormat::Ext4, true))
        } else {
            tracing::warn!(
                version_key = %version_key,
                base_path = %record.base_path(),
                "DB record exists but file missing, removing stale record"
            );
            let _ = self.base_disk_mgr.store().delete(record.id());
            None
        }
    }

    /// Build guest rootfs from image disk and atomically install.
    ///
    /// Injects the same [`GuestBinary`] the caller keyed `version_key` on, so
    /// what is cached always matches what the key names.
    async fn build_and_install(&self, image_disk: &Disk, version_key: &str) -> BoxliteResult<Disk> {
        let build_start = std::time::Instant::now();

        // Stage: copy image disk to temp, inject guest binary there
        let temp = tempfile::tempdir_in(&self.temp_dir).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to create temp directory in {}: {}",
                self.temp_dir.display(),
                e
            ))
        })?;
        let staged_path = temp.path().join("guest-rootfs.ext4");

        let copy_start = std::time::Instant::now();
        let copy_bytes = fs::copy(image_disk.path(), &staged_path).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to copy image disk {} to staged path {}: {}",
                image_disk.path().display(),
                staged_path.display(),
                e
            ))
        })?;
        tracing::info!(
            elapsed_ms = copy_start.elapsed().as_millis() as u64,
            size_mb = copy_bytes / (1024 * 1024),
            "build_and_install: copy image disk done"
        );

        // Inject the guest binary the version key was derived from. Resolution
        // and validation already happened in `GuestBinary::get`, so there is no
        // second lookup that could pick a different file.
        let inject_start = std::time::Instant::now();
        let guest = GuestBinary::get()?;

        inject_file_into_ext4(&staged_path, guest.path(), "boxlite/bin/boxlite-guest")?;
        tracing::info!(
            elapsed_ms = inject_start.elapsed().as_millis() as u64,
            "build_and_install: inject guest binary done"
        );

        let staged_disk = Disk::new(staged_path, DiskFormat::Ext4, false);
        let result = self.install(version_key, staged_disk);

        tracing::info!(
            version_key = %version_key,
            commit = boxlite_shared::GIT_COMMIT.unwrap_or("unknown"),
            guest_id = %guest.id(),
            total_ms = build_start.elapsed().as_millis() as u64,
            "build_and_install: completed"
        );

        result
    }

    /// Atomically install a staged guest rootfs to the bases directory.
    ///
    /// Generates a `BaseDiskID` filename and inserts a DB record for tracking.
    fn install(&self, version_key: &str, staged_disk: Disk) -> BoxliteResult<Disk> {
        // Defensive: another process may have installed while we were building.
        if let Some(disk) = self.find(version_key) {
            tracing::debug!(version_key = %version_key, "Guest rootfs already installed (race)");
            return Ok(disk);
        }

        let bases_dir = self.base_disk_mgr.bases_dir();
        fs::create_dir_all(bases_dir).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to create bases directory {}: {}",
                bases_dir.display(),
                e
            ))
        })?;

        let layer_id = BaseDiskIDMint::mint();
        let target = bases_dir.join(format!("{}.ext4", layer_id));
        let source = staged_disk.path().to_path_buf();

        // Atomic rename (same filesystem guaranteed by startup validation)
        fs::rename(&source, &target).map_err(|e| {
            BoxliteError::Storage(format!(
                "Failed to install guest rootfs from {} to {}: {}",
                source.display(),
                target.display(),
                e
            ))
        })?;

        let _ = staged_disk.leak();

        // File size for the record.
        let size_bytes = fs::metadata(&target).map(|m| m.len()).unwrap_or(0);

        let disk = BaseDisk {
            id: layer_id.clone(),
            source_box_id: GLOBAL_SOURCE.to_string(),
            name: Some(version_key.to_string()),
            kind: BaseDiskKind::Rootfs,
            disk_info: crate::disk::DiskInfo {
                base_path: target.to_string_lossy().to_string(),
                container_disk_bytes: 0,
                size_bytes,
            },
            created_at: chrono::Utc::now().timestamp(),
        };

        if let Err(e) = self.base_disk_mgr.store().insert(&disk) {
            // UNIQUE constraint violation means another process inserted first.
            // Clean up our file and return the existing entry.
            tracing::warn!(
                version_key = %version_key,
                error = %e,
                "DB insert failed (possible race), checking for existing entry"
            );
            let _ = fs::remove_file(&target);
            if let Some(disk) = self.find(version_key) {
                return Ok(disk);
            }
            return Err(e);
        }

        tracing::info!(
            layer_id = %layer_id,
            version_key = %version_key,
            path = %target.display(),
            "Installed guest rootfs to cache"
        );
        Ok(Disk::new(target, DiskFormat::Ext4, true))
    }

    /// Garbage-collect stale guest rootfs entries.
    ///
    /// Keeps the current minimal rootfs (keyed by the combined artifact id) and
    /// any base an existing box overlay still backs onto. Deletes everything else
    /// — including OCI Debian rootfs bases, which the boot path no longer produces.
    ///
    /// Returns the number of entries removed.
    pub fn gc(&self, boxes_dir: &Path) -> BoxliteResult<usize> {
        let gc_start = std::time::Instant::now();

        // Propagate resolution failure: a transient error must not turn the
        // current key into `None`, which would make gc_inner delete every cached
        // rootfs as non-current.
        let current_minimal_key = GuestArtifacts::get()?.id().to_string();

        let result = self.gc_inner(boxes_dir, Some(&current_minimal_key));

        tracing::info!(
            elapsed_ms = gc_start.elapsed().as_millis() as u64,
            "GC completed"
        );

        result
    }

    /// Inner GC logic, separated for testability.
    ///
    /// Queries the DB for all rootfs entries, then determines which to keep:
    /// - The current minimal rootfs entry (name == `current_minimal_key`)
    /// - Entries whose base_path any box overlay backs onto (see
    ///   [`BaseDiskManager::referenced_backing_paths`], which covers both
    ///   `disk.qcow2` and `disks/guest-rootfs.qcow2`)
    fn gc_inner(
        &self,
        boxes_dir: &Path,
        current_minimal_key: Option<&str>,
    ) -> BoxliteResult<usize> {
        let records = self
            .base_disk_mgr
            .store()
            .list_by_box(GLOBAL_SOURCE, Some(BaseDiskKind::Rootfs))?;

        if records.is_empty() {
            return Ok(0);
        }

        // Collect all referenced backing file paths from box qcow2 overlays.
        let referenced = self.base_disk_mgr.referenced_backing_paths(boxes_dir);

        tracing::info!(
            referenced_count = referenced.len(),
            total_records = records.len(),
            "gc_inner: scanned boxes for references"
        );

        let mut removed = 0;
        let mut preserved_current = 0;
        let mut preserved_referenced = 0;

        for record in &records {
            let base_path = PathBuf::from(record.base_path());
            let version_key = record.name().unwrap_or("");

            // Keep entries referenced by existing boxes
            if referenced.contains(&base_path) {
                preserved_referenced += 1;
                continue;
            }

            // Keep the current minimal rootfs entry
            if current_minimal_key == Some(version_key) {
                preserved_current += 1;
                tracing::debug!(
                    version_key = %version_key,
                    "GC: keeping current minimal rootfs"
                );
                continue;
            }

            // Delete stale entries (old guest version, no box references)
            tracing::info!(
                id = %record.id(),
                version_key = %version_key,
                path = %record.base_path(),
                "GC: removing stale guest rootfs"
            );
            if let Err(e) = fs::remove_file(&base_path)
                && base_path.exists()
            {
                tracing::warn!("GC: failed to remove {}: {}", base_path.display(), e);
            }
            if let Err(e) = self.base_disk_mgr.store().delete(record.id()) {
                tracing::warn!("GC: failed to delete DB record {}: {}", record.id(), e);
            } else {
                removed += 1;
            }
        }

        tracing::info!(
            total_entries = records.len(),
            preserved_current,
            preserved_referenced,
            removed,
            "gc_inner: summary"
        );

        Ok(removed)
    }

    /// Compute the version key from image digest and guest binary id.
    fn version_key(digest: &str, guest_hash: &str) -> String {
        let d = digest.strip_prefix("sha256:").unwrap_or(digest);
        let d = &d[..12.min(d.len())];
        let g = &guest_hash[..12.min(guest_hash.len())];
        format!("{}-{}", d, g)
    }

    /// Version key for the minimal rootfs: the combined artifact content id.
    fn minimal_version_key(artifacts: &GuestArtifacts) -> String {
        artifacts.id().to_string()
    }
}

/// Stage the minimal rootfs tree: `boxlite/bin/{boxlite-guest, mke2fs, resize2fs, mkfs.ext4}`.
fn stage_tree(rootfs: &Path, artifacts: &GuestArtifacts) -> BoxliteResult<()> {
    let bin = rootfs.join("boxlite").join("bin");
    std::fs::create_dir_all(&bin).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to create minimal rootfs tree {}: {}",
            bin.display(),
            e
        ))
    })?;

    copy_artifact(artifacts.guest_path(), &bin.join("boxlite-guest"))?;
    copy_artifact(artifacts.mke2fs().path(), &bin.join("mke2fs"))?;
    copy_artifact(artifacts.resize2fs().path(), &bin.join("resize2fs"))?;
    // The guest invokes `mkfs.ext4` (`src/guest/src/storage/block_device.rs`);
    // mke2fs dispatches on argv[0], so a byte-identical copy is the alias.
    copy_artifact(artifacts.mke2fs().path(), &bin.join("mkfs.ext4"))?;

    // The rootfs is attached read-only, so every directory that is created at
    // boot must already exist:
    // - `/tmp`, `/var/tmp`, `/run` — tmpfs mount points the guest mounts itself.
    // - `/dev`, `/proc`, `/sys` — mount points libkrun's init.krun mkdirs before
    //   mounting devtmpfs/proc/sysfs (init.c mount_filesystems).
    for dir in ["tmp", "var/tmp", "run", "dev", "proc", "sys"] {
        std::fs::create_dir_all(rootfs.join(dir)).map_err(|e| {
            BoxliteError::Storage(format!("Failed to create mount point {dir}: {e}"))
        })?;
    }

    Ok(())
}

/// Copy a host artifact into the tree with mode 0755, matching the build contract.
fn copy_artifact(src: &Path, dst: &Path) -> BoxliteResult<()> {
    std::fs::copy(src, dst).map_err(|e| {
        BoxliteError::Storage(format!(
            "Failed to copy {} -> {}: {}",
            src.display(),
            dst.display(),
            e
        ))
    })?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(dst, std::fs::Permissions::from_mode(0o755)).map_err(|e| {
            BoxliteError::Storage(format!("Failed to chmod 0755 {}: {}", dst.display(), e))
        })?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Database;
    use crate::db::base_disk::BaseDiskStore;

    fn id(s: &str) -> BaseDiskID {
        BaseDiskID::parse(s).expect("test ID must be valid Base62 length-8")
    }

    fn test_store() -> BaseDiskStore {
        let dir = tempfile::TempDir::new().unwrap();
        let db_path = dir.keep().join("test.db");
        let db = Database::open(&db_path).unwrap();
        BaseDiskStore::new(db)
    }

    fn make_mgr(bases_dir: PathBuf, temp_dir: PathBuf) -> GuestRootfsManager {
        let base_disk_mgr = BaseDiskManager::new(bases_dir, test_store());
        GuestRootfsManager::new(base_disk_mgr, temp_dir)
    }

    /// Insert a rootfs record directly for test setup.
    fn insert_rootfs_record(store: &BaseDiskStore, rootfs_id: &str, version_key: &str, path: &str) {
        store
            .insert(&BaseDisk {
                id: id(rootfs_id),
                source_box_id: GLOBAL_SOURCE.to_string(),
                name: Some(version_key.to_string()),
                kind: BaseDiskKind::Rootfs,
                disk_info: crate::disk::DiskInfo {
                    base_path: path.to_string(),
                    container_disk_bytes: 0,
                    size_bytes: 100,
                },
                created_at: chrono::Utc::now().timestamp(),
            })
            .unwrap();
    }

    #[test]
    fn test_version_key_strips_sha256_prefix() {
        let key = GuestRootfsManager::version_key(
            "sha256:abcdef123456789012345678",
            "fedcba987654321012345678",
        );
        assert_eq!(key, "abcdef123456-fedcba987654");
    }

    #[test]
    fn test_version_key_no_prefix() {
        let key = GuestRootfsManager::version_key("abcdef123456789012", "111222333444555666");
        assert_eq!(key, "abcdef123456-111222333444");
    }

    #[test]
    fn test_version_key_short_inputs() {
        let key = GuestRootfsManager::version_key("abc", "def");
        assert_eq!(key, "abc-def");
    }

    /// Rebuilding the guest must move the cache key, so an existing entry is not
    /// reused for a different binary.
    ///
    /// Same verification caveat as `guest_binary::id_tracks_the_bytes_on_disk`:
    /// this composes `GuestBinary::resolve_at`, which the fix introduces, so a
    /// full production revert stops it compiling instead of failing it. It was
    /// checked by mutation (digest the path, not the bytes) and by a booted VM.
    #[test]
    fn version_key_follows_the_guest_binary_on_disk() {
        let dir = tempfile::TempDir::new().unwrap();
        let digest = "sha256:18264223e3ecaaaabbbbccccdddd";

        // One path, rewritten — what `make guest` does. Distinct paths would let
        // an implementation that keyed on the path alone pass this test.
        let write_guest = |filler: u8| {
            let path = dir.path().join("boxlite-guest");
            let mut elf = vec![0u8; 128];
            elf[..4].copy_from_slice(&[0x7f, b'E', b'L', b'F']);
            elf[4] = 2;
            let machine: u16 = if std::env::consts::ARCH == "x86_64" {
                0x3E
            } else {
                0xB7
            };
            elf[18..20].copy_from_slice(&machine.to_le_bytes());
            elf[64..].fill(filler);
            std::fs::write(&path, elf).unwrap();
            path
        };

        let before = GuestBinary::resolve_at(write_guest(0xAA)).unwrap();
        let after = GuestBinary::resolve_at(write_guest(0xBB)).unwrap();

        let key_before = GuestRootfsManager::version_key(digest, before.id());
        let key_after = GuestRootfsManager::version_key(digest, after.id());

        assert_ne!(
            key_before, key_after,
            "a rebuilt guest must not reuse the previous rootfs cache entry"
        );
        // Same image, so only the guest half may move — otherwise every image
        // would rebuild whenever the guest changed.
        assert_eq!(
            key_before[..12],
            key_after[..12],
            "image half must be stable"
        );
        assert!(key_after.ends_with(after.id()), "GC matches on this suffix");
    }

    #[test]
    fn test_find_returns_none_for_missing() {
        let dir = tempfile::TempDir::new().unwrap();
        let mgr = make_mgr(dir.path().to_path_buf(), dir.path().to_path_buf());

        assert!(mgr.find("nonexistent-key").is_none());
    }

    #[test]
    fn test_find_returns_disk_for_existing_db_record() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().to_path_buf();
        let store = test_store();

        // Create a fake cached file with BaseDiskID name
        let cached = bases_dir.join("aB3xQ9mP.ext4");
        std::fs::write(&cached, "fake disk").unwrap();

        // Insert DB record mapping version_key → file path
        insert_rootfs_record(&store, "aB3xQ9mP", "test-version", cached.to_str().unwrap());

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        let disk = mgr.find("test-version");
        assert!(disk.is_some());
        let disk = disk.unwrap();
        assert_eq!(disk.path(), cached);
        assert_eq!(disk.format(), DiskFormat::Ext4);
        let _ = disk.leak();
    }

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

        // Insert DB record but DON'T create the file
        insert_rootfs_record(
            &store,
            "aB3xQ9mP",
            "ghost-key",
            dir.path().join("ghost.ext4").to_str().unwrap(),
        );

        let base_disk_mgr = BaseDiskManager::new(dir.path().to_path_buf(), store.clone());
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());
        assert!(mgr.find("ghost-key").is_none());

        // Stale DB record should have been deleted
        assert!(
            store
                .find_by_name(GLOBAL_SOURCE, "ghost-key")
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn test_install_creates_bases_dir_and_moves_file() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        let store = test_store();
        let base_disk_mgr = BaseDiskManager::new(bases_dir.clone(), store.clone());
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        // Create staged file
        let staged_path = dir.path().join("staged.ext4");
        std::fs::write(&staged_path, "staged disk content").unwrap();
        let staged_disk = Disk::new(staged_path, DiskFormat::Ext4, false);

        let result = mgr.install("ver-key", staged_disk).unwrap();

        // File should be in bases/ with .ext4 extension (BaseDiskID name)
        assert!(result.path().starts_with(&bases_dir));
        assert_eq!(result.path().extension().unwrap(), "ext4");
        assert!(result.path().exists());
        let stem = result.path().file_stem().unwrap().to_string_lossy();
        assert!(
            BaseDiskID::parse(&stem).is_some(),
            "rootfs filename should be valid BaseDiskID"
        );

        // DB record should exist
        let record = store.find_by_name(GLOBAL_SOURCE, "ver-key").unwrap();
        assert!(record.is_some());
        let record = record.unwrap();
        assert_eq!(record.kind(), BaseDiskKind::Rootfs);
        assert_eq!(record.base_path(), result.path().to_string_lossy());

        let _ = result.leak();
    }

    #[test]
    fn test_install_race_safe_returns_existing() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        std::fs::create_dir_all(&bases_dir).unwrap();
        let store = test_store();

        // Pre-install via DB (simulating another process)
        let existing = bases_dir.join("first123.ext4");
        std::fs::write(&existing, "first install").unwrap();
        insert_rootfs_record(&store, "first123", "raced-key", existing.to_str().unwrap());

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        // Try to install again with same version_key
        let staged_path = dir.path().join("staged.ext4");
        std::fs::write(&staged_path, "second install").unwrap();
        let staged_disk = Disk::new(staged_path, DiskFormat::Ext4, false);

        let result = mgr.install("raced-key", staged_disk).unwrap();
        assert_eq!(result.path(), existing);

        // Original content preserved (first install wins)
        assert_eq!(
            std::fs::read_to_string(result.path()).unwrap(),
            "first install"
        );
        let _ = result.leak();
    }

    #[test]
    fn test_gc_removes_stale_entries() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        let boxes_dir = dir.path().join("boxes");
        std::fs::create_dir_all(&bases_dir).unwrap();
        std::fs::create_dir_all(&boxes_dir).unwrap();

        let store = test_store();

        // Create entries with old guest hash via DB + filesystem
        let file1 = bases_dir.join("aaa11111.ext4");
        let file2 = bases_dir.join("bbb22222.ext4");
        std::fs::write(&file1, "old1").unwrap();
        std::fs::write(&file2, "old2").unwrap();
        insert_rootfs_record(
            &store,
            "aaa11111",
            "img123-oldguest1",
            file1.to_str().unwrap(),
        );
        insert_rootfs_record(
            &store,
            "bbb22222",
            "img456-oldguest2",
            file2.to_str().unwrap(),
        );

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        // No boxes reference anything and neither matches the current minimal
        // key → both removed.
        let removed = mgr.gc_inner(&boxes_dir, None).unwrap();
        assert_eq!(removed, 2);
        assert!(!file1.exists());
        assert!(!file2.exists());
    }

    #[test]
    fn test_gc_preserves_current_minimal_entry() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        let boxes_dir = dir.path().join("boxes");
        std::fs::create_dir_all(&bases_dir).unwrap();
        std::fs::create_dir_all(&boxes_dir).unwrap();

        let store = test_store();

        // Current minimal rootfs entry (name == current_minimal_key)
        let current_file = bases_dir.join("ccc33333.ext4");
        std::fs::write(&current_file, "current minimal").unwrap();
        insert_rootfs_record(
            &store,
            "ccc33333",
            "minimal-current",
            current_file.to_str().unwrap(),
        );

        // Stale entry (a different rootfs key)
        let stale_file = bases_dir.join("ddd44444.ext4");
        std::fs::write(&stale_file, "stale").unwrap();
        insert_rootfs_record(
            &store,
            "ddd44444",
            "minimal-old",
            stale_file.to_str().unwrap(),
        );

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        let removed = mgr.gc_inner(&boxes_dir, Some("minimal-current")).unwrap();
        assert_eq!(removed, 1);
        assert!(
            current_file.exists(),
            "Current minimal entry should be kept"
        );
        assert!(!stale_file.exists(), "Stale entry should be removed");
    }

    #[test]
    fn test_gc_preserves_referenced_entries() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        let boxes_dir = dir.path().join("boxes");
        std::fs::create_dir_all(&bases_dir).unwrap();

        let store = test_store();

        // Old-version entry referenced by a box (should survive)
        let referenced_file = bases_dir.join("eee55555.ext4");
        std::fs::write(&referenced_file, "keep me").unwrap();
        insert_rootfs_record(
            &store,
            "eee55555",
            "img123-oldguest",
            referenced_file.to_str().unwrap(),
        );

        // Old-version entry not referenced (should be deleted)
        let unreferenced_file = bases_dir.join("fff66666.ext4");
        std::fs::write(&unreferenced_file, "delete me").unwrap();
        insert_rootfs_record(
            &store,
            "fff66666",
            "img456-oldguest",
            unreferenced_file.to_str().unwrap(),
        );

        // Create a box with a qcow2 that references one of them.
        // Note: correct path is boxes/{box_id}/disks/guest-rootfs.qcow2
        let box_disks = boxes_dir.join("box-1").join("disks");
        std::fs::create_dir_all(&box_disks).unwrap();
        let qcow2_path = box_disks.join("guest-rootfs.qcow2");

        // Write a minimal qcow2 header with backing file pointing to referenced_file
        let backing_str = referenced_file.to_str().unwrap();
        let backing_bytes = backing_str.as_bytes();
        let mut buf = vec![0u8; 1024];
        buf[0..4].copy_from_slice(&0x514649fbu32.to_be_bytes()); // Magic
        buf[4..8].copy_from_slice(&3u32.to_be_bytes()); // Version
        buf[8..16].copy_from_slice(&512u64.to_be_bytes()); // Backing offset
        buf[16..20].copy_from_slice(&(backing_bytes.len() as u32).to_be_bytes());
        buf[512..512 + backing_bytes.len()].copy_from_slice(backing_bytes);
        std::fs::write(&qcow2_path, &buf).unwrap();

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        let removed = mgr.gc_inner(&boxes_dir, None).unwrap();
        assert_eq!(removed, 1);
        assert!(referenced_file.exists(), "Referenced entry should be kept");
        assert!(
            !unreferenced_file.exists(),
            "Unreferenced stale entry should be removed"
        );
    }

    #[test]
    fn test_gc_no_records() {
        let dir = tempfile::TempDir::new().unwrap();
        let mgr = make_mgr(dir.path().join("bases"), dir.path().to_path_buf());

        let removed = mgr.gc_inner(dir.path(), None).unwrap();
        assert_eq!(removed, 0);
    }

    #[test]
    fn test_gc_no_boxes_dir() {
        let dir = tempfile::TempDir::new().unwrap();
        let bases_dir = dir.path().join("bases");
        std::fs::create_dir_all(&bases_dir).unwrap();

        let store = test_store();

        // Stale entry (doesn't match the current minimal key)
        let stale = bases_dir.join("ggg77777.ext4");
        std::fs::write(&stale, "orphan").unwrap();
        insert_rootfs_record(&store, "ggg77777", "img-oldguest", stale.to_str().unwrap());

        let base_disk_mgr = BaseDiskManager::new(bases_dir, store);
        let mgr = GuestRootfsManager::new(base_disk_mgr, dir.path().to_path_buf());

        let removed = mgr
            .gc_inner(&dir.path().join("nonexistent-boxes"), None)
            .unwrap();
        assert_eq!(removed, 1);
    }

    /// Smallest byte sequence `GuestBinary::resolve_at` accepts for this host.
    fn fake_guest(filler: u8) -> Vec<u8> {
        let mut elf = vec![0u8; 128];
        elf[..4].copy_from_slice(&[0x7f, b'E', b'L', b'F']);
        elf[4] = 2; // 64-bit
        let machine: u16 = match std::env::consts::ARCH {
            "x86_64" => 0x3E,
            _ => 0xB7,
        };
        elf[18..20].copy_from_slice(&machine.to_le_bytes());
        elf[64..].fill(filler);
        elf
    }

    fn fake_artifacts(dir: &tempfile::TempDir) -> GuestArtifacts {
        let guest_path = dir.path().join("boxlite-guest");
        std::fs::write(&guest_path, fake_guest(0xAA)).unwrap();
        let guest = GuestBinary::resolve_at(guest_path).unwrap();

        let mke2fs = dir.path().join("guest-mke2fs");
        let resize2fs = dir.path().join("guest-resize2fs");
        std::fs::write(&mke2fs, fake_guest(0x11)).unwrap();
        std::fs::write(&resize2fs, fake_guest(0x22)).unwrap();

        GuestArtifacts::resolve_at(&guest, mke2fs, resize2fs).unwrap()
    }

    #[test]
    fn stage_tree_copies_artifacts_and_mkfs_ext4_alias() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let artifacts = fake_artifacts(&dir);

        let tree = dir.path().join("rootfs");
        stage_tree(&tree, &artifacts).unwrap();

        let bin = tree.join("boxlite").join("bin");
        for name in ["boxlite-guest", "mke2fs", "resize2fs", "mkfs.ext4"] {
            let path = bin.join(name);
            assert!(path.is_file(), "{name} must be staged");
            assert_eq!(
                std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
                0o755,
                "{name} must be mode 0755"
            );
        }

        assert_eq!(
            std::fs::read(bin.join("mkfs.ext4")).unwrap(),
            std::fs::read(bin.join("mke2fs")).unwrap(),
            "mkfs.ext4 must be a byte-copy of mke2fs"
        );

        // The rootfs is attached read-only, so every mount point the guest
        // creates at boot must already exist in the staged tree.
        for dir in ["tmp", "var/tmp", "run", "dev", "proc", "sys"] {
            assert!(tree.join(dir).is_dir(), "{dir} mount point must be staged");
        }
    }

    /// The full build must land the artifacts inside a real ext4 image, tracked
    /// in the bases/ cache. Skipped without the host e2fsprogs binaries.
    #[tokio::test]
    async fn get_or_create_minimal_builds_ext4_with_artifacts() {
        use crate::util::find_binary;

        if find_binary("mke2fs").is_err() || find_binary("debugfs").is_err() {
            eprintln!("skipping: mke2fs/debugfs not found (run `make runtime:debug`)");
            return;
        }

        let dir = tempfile::tempdir().unwrap();
        let artifacts = fake_artifacts(&dir);
        let temp_dir = dir.path().join("tmp");
        std::fs::create_dir_all(&temp_dir).unwrap();
        let mgr = make_mgr(dir.path().join("bases"), temp_dir);

        let rootfs = mgr.get_or_create_minimal(&artifacts).await.unwrap();
        let Strategy::Disk { disk_path, .. } = rootfs.strategy else {
            panic!("minimal rootfs must be disk-based");
        };
        assert!(disk_path.is_file());

        let debugfs = find_binary("debugfs").unwrap();
        let ls = std::process::Command::new(&debugfs)
            .args(["-R", "ls /boxlite/bin"])
            .arg(&disk_path)
            .output()
            .expect("run debugfs ls");
        assert!(
            ls.status.success(),
            "debugfs ls failed: {}",
            String::from_utf8_lossy(&ls.stderr)
        );
        let listing = String::from_utf8_lossy(&ls.stdout);
        for name in ["boxlite-guest", "mke2fs", "resize2fs", "mkfs.ext4"] {
            assert!(
                listing.contains(name),
                "image /boxlite/bin must contain {name}:\n{listing}"
            );
        }

        // Second call is a cache hit — same path, no rebuild.
        let rootfs2 = mgr.get_or_create_minimal(&artifacts).await.unwrap();
        let Strategy::Disk {
            disk_path: disk_path2,
            ..
        } = rootfs2.strategy
        else {
            panic!("minimal rootfs must be disk-based");
        };
        assert_eq!(disk_path, disk_path2);
    }
}