ktstr/cache/
metadata.rs

1//! Pure data types for the kernel image cache.
2//!
3//! Public shape of cache entries — [`KernelSource`] /
4//! [`KernelMetadata`] / [`CacheArtifacts`] / [`KconfigStatus`] /
5//! [`CacheEntry`] / [`ListedEntry`] — plus the internal
6//! [`classify_corrupt_reason`] dispatcher that routes
7//! `read_metadata`-emitted reason strings into stable `error_kind`
8//! snake_case identifiers surfaced by `kernel list --json`. No I/O,
9//! no syscalls — every entry point is a pure transformation over
10//! already-loaded data.
11
12use std::fmt;
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16
17use crate::vmm::initramfs::InitrdCompression;
18
19/// How a cached kernel's source was acquired, with per-variant
20/// payload (git details for `Git`, source-tree path and git hash for
21/// `Local`).
22///
23/// Serialized as `{"type": "tarball"}`, `{"type": "git", "git_hash": ..., "ref": ...}`,
24/// or `{"type": "local", "source_tree_path": ..., "git_hash": ...}`.
25/// Every per-variant payload field is emitted explicitly — `Option`
26/// fields serialize as `null` when `None` rather than being skipped,
27/// so JSON consumers see stable keys across every variant regardless
28/// of which optional payload values are set.
29///
30/// On deserialize, serde_json treats absent `Option` keys as `None`,
31/// so an old `metadata.json` that drops `git_hash`, `ref`, or
32/// `source_tree_path` still round-trips. Cache-integrity enforcement
33/// (truncated `metadata.json` surfacing as [`ListedEntry::Corrupt`]
34/// via [`crate::cache::CacheDir::list`]) rides on the required
35/// non-`Option` fields of [`KernelMetadata`], not on the optional
36/// payloads here.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "lowercase", tag = "type")]
39#[non_exhaustive]
40pub enum KernelSource {
41    /// Downloaded tarball from kernel.org (version / prefix / EOL
42    /// probe paths).
43    Tarball,
44    /// Shallow clone of a git URL at a caller-specified ref.
45    Git {
46        /// Git commit hash of the kernel source (short form).
47        git_hash: Option<String>,
48        /// Git ref used for checkout (branch, tag, or ref spec).
49        #[serde(rename = "ref")]
50        git_ref: Option<String>,
51    },
52    /// Build of a local on-disk kernel source tree.
53    Local {
54        /// Path to the source tree on disk. `None` when the tree has
55        /// been sanitized for remote cache transport or is otherwise
56        /// unavailable.
57        source_tree_path: Option<PathBuf>,
58        /// Git commit hash of the source tree at build time (short
59        /// form). `None` when the tree is not a git repository, the
60        /// hash could not be read, or the worktree is dirty — a
61        /// HEAD hash does not describe a tree with uncommitted
62        /// changes, so identifying it by that hash would mislead a
63        /// reproducer.
64        git_hash: Option<String>,
65    },
66    /// Prebuilt distro kernel downloaded from an official repo
67    /// (`--kernel fedora` / `ubuntu` / `amazonlinux`). Serialized as
68    /// `{"type": "distropackage", "distro": ..., "packages": [...]}`.
69    DistroPackage {
70        /// Short distro tag (e.g. `"fedora44"`, `"ubuntu24.04-hwe"`,
71        /// `"al2023"`) from the repo resolver.
72        distro: String,
73        /// The `name-version` of each package that was extracted
74        /// (kernel image/modules + debuginfo), for provenance.
75        packages: Vec<String>,
76    },
77    /// Prebuilt kernel unpacked from local `.rpm`/`.deb` files
78    /// (`--kernel ./pkg.rpm`). Serialized as
79    /// `{"type": "localpackage", "packages": [...]}`.
80    LocalPackage {
81        /// Basenames of the local package files that were extracted.
82        packages: Vec<String>,
83    },
84}
85
86impl fmt::Display for KernelSource {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        match self {
89            KernelSource::Tarball => f.write_str("tarball"),
90            KernelSource::Git { .. } => f.write_str("git"),
91            KernelSource::Local { .. } => f.write_str("local"),
92            KernelSource::DistroPackage { .. } => f.write_str("distro-package"),
93            KernelSource::LocalPackage { .. } => f.write_str("local-package"),
94        }
95    }
96}
97
98impl KernelSource {
99    /// Borrow the `git_hash` field on a [`KernelSource::Local`]
100    /// variant. Returns `None` for any other variant or when the
101    /// Local variant carries `git_hash: None` (dirty / non-git
102    /// tree at acquire time).
103    ///
104    /// Mainly used by [`crate::cli::kernel_build_pipeline`]'s
105    /// post-build dirty re-check, which compares the post-build
106    /// HEAD hash against the acquire-time hash to detect mid-build
107    /// commits or branch flips. Borrows rather than clones so the
108    /// caller does not pay an allocation when only comparing.
109    pub fn as_local_git_hash(&self) -> Option<&str> {
110        match self {
111            KernelSource::Local { git_hash, .. } => git_hash.as_deref(),
112            _ => None,
113        }
114    }
115
116    /// Construct [`KernelSource::Git`] with both `git_hash` and
117    /// `git_ref` populated. Use struct-literal syntax directly if
118    /// either field should be `None`.
119    pub fn git(git_hash: impl Into<String>, git_ref: impl Into<String>) -> Self {
120        KernelSource::Git {
121            git_hash: Some(git_hash.into()),
122            git_ref: Some(git_ref.into()),
123        }
124    }
125}
126
127/// Metadata stored alongside a cached kernel image.
128///
129/// Required fields (`source`, `arch`, `image_name`, `built_at`,
130/// `has_vmlinux`, `vmlinux_stripped`) must be present in
131/// `metadata.json` during deserialization; a truncated file that
132/// drops any of them surfaces the entry as [`ListedEntry::Corrupt`]
133/// via [`crate::cache::CacheDir::list`] rather than silently
134/// defaulting. Optional fields tolerate absent keys as `None`.
135#[derive(Debug, Clone, Serialize, Deserialize)]
136#[non_exhaustive]
137pub struct KernelMetadata {
138    /// Kernel version string (e.g. "6.14.2", "6.15-rc3").
139    /// `None` when no version could be established — a local or git
140    /// source whose `Makefile` is unreadable/unparsable, or an
141    /// acquisition path that records none.
142    pub version: Option<String>,
143    /// How the kernel source was acquired, with per-source payload.
144    pub source: KernelSource,
145    /// Target architecture (e.g. "x86_64", "aarch64").
146    pub arch: String,
147    /// Boot image filename (e.g. "bzImage", "Image").
148    pub image_name: String,
149    /// CRC32 of the final .config used for the build.
150    pub config_hash: Option<String>,
151    /// ISO 8601 timestamp of when the image was built.
152    pub built_at: String,
153    /// CRC32 of ktstr.kconfig at build time.
154    pub ktstr_kconfig_hash: Option<String>,
155    /// CRC32 of the user-supplied `--extra-kconfig` fragment (raw
156    /// bytes) at build time. `None` for builds without
157    /// `--extra-kconfig`.
158    pub extra_kconfig_hash: Option<String>,
159    /// Whether a vmlinux ELF was cached alongside the image.
160    /// Required in metadata.json.
161    pub(crate) has_vmlinux: bool,
162    /// Whether the cached vmlinux ELF came from a successful strip
163    /// pass (`true`) or the raw-fallback path (`false`).
164    pub(crate) vmlinux_stripped: bool,
165    /// Size in bytes of the SOURCE-TREE vmlinux at cache-store time.
166    pub source_vmlinux_size: Option<u64>,
167    /// Modification time (seconds since UNIX epoch) of the
168    /// SOURCE-TREE vmlinux at cache-store time.
169    pub source_vmlinux_mtime_secs: Option<i64>,
170}
171
172impl KernelMetadata {
173    /// Create a new KernelMetadata with required fields.
174    pub fn new(
175        source: KernelSource,
176        arch: impl Into<String>,
177        image_name: impl Into<String>,
178        built_at: impl Into<String>,
179    ) -> Self {
180        KernelMetadata {
181            version: None,
182            source,
183            arch: arch.into(),
184            image_name: image_name.into(),
185            config_hash: None,
186            built_at: built_at.into(),
187            ktstr_kconfig_hash: None,
188            extra_kconfig_hash: None,
189            has_vmlinux: false,
190            vmlinux_stripped: false,
191            source_vmlinux_size: None,
192            source_vmlinux_mtime_secs: None,
193        }
194    }
195
196    /// Set the source-tree vmlinux size and mtime captured at cache
197    /// store time.
198    pub fn with_source_vmlinux_stat(mut self, size: u64, mtime_secs: i64) -> Self {
199        self.source_vmlinux_size = Some(size);
200        self.source_vmlinux_mtime_secs = Some(mtime_secs);
201        self
202    }
203
204    /// Unset the source-tree vmlinux stat (both size and mtime back
205    /// to the `None` default).
206    pub fn clear_source_vmlinux_stat(mut self) -> Self {
207        self.source_vmlinux_size = None;
208        self.source_vmlinux_mtime_secs = None;
209        self
210    }
211
212    /// Set the kernel version.
213    pub fn with_version(mut self, version: impl Into<String>) -> Self {
214        self.version = Some(version.into());
215        self
216    }
217
218    /// Unset the kernel version (back to the `None` default).
219    pub fn clear_version(mut self) -> Self {
220        self.version = None;
221        self
222    }
223
224    /// Set the .config CRC32 hash.
225    pub fn with_config_hash(mut self, hash: impl Into<String>) -> Self {
226        self.config_hash = Some(hash.into());
227        self
228    }
229
230    /// Unset the .config CRC32 hash (back to the `None` default).
231    pub fn clear_config_hash(mut self) -> Self {
232        self.config_hash = None;
233        self
234    }
235
236    /// Set the ktstr.kconfig CRC32 hash.
237    pub fn with_ktstr_kconfig_hash(mut self, hash: impl Into<String>) -> Self {
238        self.ktstr_kconfig_hash = Some(hash.into());
239        self
240    }
241
242    /// Unset the ktstr.kconfig CRC32 hash (back to the `None` default).
243    pub fn clear_ktstr_kconfig_hash(mut self) -> Self {
244        self.ktstr_kconfig_hash = None;
245        self
246    }
247
248    /// Set the `--extra-kconfig` fragment CRC32 hash.
249    pub fn with_extra_kconfig_hash(mut self, hash: impl Into<String>) -> Self {
250        self.extra_kconfig_hash = Some(hash.into());
251        self
252    }
253
254    /// Unset the `--extra-kconfig` fragment CRC32 hash (back to the `None` default).
255    pub fn clear_extra_kconfig_hash(mut self) -> Self {
256        self.extra_kconfig_hash = None;
257        self
258    }
259
260    /// Whether a vmlinux ELF was cached alongside the image.
261    pub fn has_vmlinux(&self) -> bool {
262        self.has_vmlinux
263    }
264
265    /// Crate-only mutator for `has_vmlinux`.
266    pub(crate) fn set_has_vmlinux(&mut self, value: bool) {
267        self.has_vmlinux = value;
268    }
269
270    /// Whether the cached vmlinux came from a successful strip pass.
271    pub fn vmlinux_stripped(&self) -> bool {
272        self.vmlinux_stripped
273    }
274
275    /// Crate-only mutator for `vmlinux_stripped`.
276    pub(crate) fn set_vmlinux_stripped(&mut self, value: bool) {
277        self.vmlinux_stripped = value;
278    }
279}
280
281/// Bundle of cache artifacts for [`crate::cache::CacheDir::store`].
282///
283/// The vmlinux path points at the raw (unstripped) ELF. `store()`
284/// strips it internally via `crate::cache::strip_vmlinux_debug`
285/// and writes the result.
286#[derive(Debug, Clone)]
287#[non_exhaustive]
288pub struct CacheArtifacts<'a> {
289    /// Path to the kernel boot image (bzImage or Image).
290    pub image: &'a Path,
291    /// Optional path to the raw (unstripped) vmlinux ELF. `store()`
292    /// strips it internally before caching.
293    pub vmlinux: Option<&'a Path>,
294    /// Ordered, already-decompressed `.ko` boot modules to embed in
295    /// the cache entry under `modules/NNN-<name>` (dependency-first).
296    /// Consumed by prebuilt distro kernels whose virtio drivers are
297    /// modular; empty for built kernels (which need none). `store()`
298    /// preserves the slice order in the `NNN` index so the boot side
299    /// loads them in the same order.
300    pub modules: &'a [PathBuf],
301    /// Optional kernel `.config` to save alongside the image (as
302    /// `config`), for provenance and post-hoc inspection of a prebuilt
303    /// kernel's feature set.
304    pub config: Option<&'a Path>,
305}
306
307impl<'a> CacheArtifacts<'a> {
308    /// Create an artifact bundle with only the required image.
309    pub fn new(image: &'a Path) -> Self {
310        CacheArtifacts {
311            image,
312            vmlinux: None,
313            modules: &[],
314            config: None,
315        }
316    }
317
318    /// Attach the raw (unstripped) vmlinux ELF.
319    pub fn with_vmlinux(mut self, vmlinux: &'a Path) -> Self {
320        self.vmlinux = Some(vmlinux);
321        self
322    }
323
324    /// Attach the ordered boot-module set (already-decompressed `.ko`).
325    pub fn with_modules(mut self, modules: &'a [PathBuf]) -> Self {
326        self.modules = modules;
327        self
328    }
329
330    /// Attach the kernel `.config` to save into the entry.
331    pub fn with_config(mut self, config: &'a Path) -> Self {
332        self.config = Some(config);
333        self
334    }
335}
336
337/// Comparison between a cache entry's kconfig hash and a current
338/// reference hash. Returned by [`CacheEntry::kconfig_status`].
339#[derive(Debug, Clone, PartialEq, Eq)]
340#[non_exhaustive]
341pub enum KconfigStatus {
342    /// Entry was built with the current kconfig — nothing to do.
343    Matches,
344    /// Entry was built with a different kconfig.
345    Stale {
346        /// Hash recorded in the cache entry.
347        cached: String,
348        /// Hash the caller compared against.
349        current: String,
350    },
351    /// Entry has no kconfig hash recorded (pre-tracking cache
352    /// format). Treat as unknown; do not assume stale.
353    Untracked,
354}
355
356impl KconfigStatus {
357    /// `true` iff the entry is stale against the current kconfig.
358    pub fn is_stale(&self) -> bool {
359        matches!(self, Self::Stale { .. })
360    }
361
362    /// `true` iff the entry has no recorded kconfig hash.
363    pub fn is_untracked(&self) -> bool {
364        matches!(self, Self::Untracked)
365    }
366}
367
368impl fmt::Display for KconfigStatus {
369    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370        match self {
371            KconfigStatus::Matches => f.write_str("matches"),
372            KconfigStatus::Stale { .. } => f.write_str("stale"),
373            KconfigStatus::Untracked => f.write_str("untracked"),
374        }
375    }
376}
377
378/// A cached kernel entry returned by
379/// [`crate::cache::CacheDir::lookup`] and
380/// [`crate::cache::CacheDir::store`].
381#[derive(Debug)]
382#[non_exhaustive]
383pub struct CacheEntry {
384    /// Cache key (directory name).
385    pub key: String,
386    /// Path to the cache entry directory.
387    pub path: PathBuf,
388    /// Deserialized metadata. Always present on a [`CacheEntry`].
389    pub metadata: KernelMetadata,
390}
391
392impl CacheEntry {
393    /// Absolute path to the cached boot image.
394    pub fn image_path(&self) -> PathBuf {
395        self.path.join(&self.metadata.image_name)
396    }
397
398    /// Absolute path to the cached stripped vmlinux ELF, when one
399    /// was stored alongside the image.
400    pub fn vmlinux_path(&self) -> Option<PathBuf> {
401        self.metadata.has_vmlinux.then(|| self.path.join("vmlinux"))
402    }
403
404    /// Absolute path to the cached btrfs disk template
405    /// (`<entry>/disk-template.img`).
406    pub fn disk_template_path(&self) -> PathBuf {
407        self.path.join("disk-template.img")
408    }
409
410    /// Ordered boot modules embedded in this entry
411    /// (`<entry>/modules/NNN-*.ko`), dependency-first, or empty when
412    /// the entry carries none (every built kernel). Scans the
413    /// directory so the layout is the single source of truth.
414    pub fn boot_modules(&self) -> Vec<PathBuf> {
415        ordered_boot_modules_in(&self.path.join("modules"))
416    }
417
418    /// Compare this entry's kconfig hash against `current_hash`.
419    pub fn kconfig_status(&self, current_hash: &str) -> KconfigStatus {
420        match self.metadata.ktstr_kconfig_hash.as_deref() {
421            None => KconfigStatus::Untracked,
422            Some(h) if h == current_hash => KconfigStatus::Matches,
423            Some(h) => KconfigStatus::Stale {
424                cached: h.to_string(),
425                current: current_hash.to_string(),
426            },
427        }
428    }
429
430    /// Whether this cache entry was built with a user
431    /// `--extra-kconfig` fragment.
432    pub fn has_extra_kconfig(&self) -> bool {
433        self.metadata.extra_kconfig_hash.is_some()
434    }
435}
436
437/// Ordered boot modules under `modules_dir` (`NNN-*.ko`), sorted by
438/// file name so the zero-padded `NNN` index reproduces the load order
439/// `CacheDir::store` wrote. Non-directory / missing paths yield an
440/// empty vector. Pure over one `read_dir`.
441pub fn ordered_boot_modules_in(modules_dir: &Path) -> Vec<PathBuf> {
442    let Ok(rd) = std::fs::read_dir(modules_dir) else {
443        return Vec::new();
444    };
445    let mut entries: Vec<PathBuf> = rd
446        .flatten()
447        .filter(|e| e.file_type().map(|t| t.is_file()).unwrap_or(false))
448        .map(|e| e.path())
449        .collect();
450    entries.sort();
451    entries
452}
453
454/// Ordered boot modules for a cached kernel image, discovered from the
455/// `modules/` subdirectory that sits beside the image in its cache
456/// entry (`<entry>/bzImage` + `<entry>/modules/`). Empty for built
457/// kernels and build-tree images (no sibling `modules/`), so callers
458/// can pass the result to `KtstrVmBuilder::kernel_modules`
459/// unconditionally — an empty set is a no-op.
460pub fn boot_modules_for_image(image: &Path) -> Vec<PathBuf> {
461    match image.parent() {
462        Some(dir) => ordered_boot_modules_in(&dir.join("modules")),
463        None => Vec::new(),
464    }
465}
466
467/// Initrd compression the kernel behind `image` can unpack, discovered
468/// from the `config` file that sits beside the image in its cache entry
469/// (`<entry>/bzImage` + `<entry>/config`). No config (built kernels
470/// pin `CONFIG_RD_LZ4=y` via ktstr.kconfig; raw images carry no
471/// sidecar) defaults to LZ4 — today's behavior. With a config, the
472/// first of `RD_LZ4` / `RD_ZSTD` / `RD_GZIP` the kernel enables wins,
473/// falling back to uncompressed cpio (which needs no `CONFIG_RD_*`)
474/// when it enables none. Callers pass the result to
475/// `KtstrVmBuilder::initrd_compression` (crate-private) unconditionally.
476pub fn initrd_compression_for_image(image: &Path) -> InitrdCompression {
477    let Some(config) = image.parent().map(|d| d.join("config")) else {
478        return InitrdCompression::Lz4;
479    };
480    let Ok(text) = std::fs::read_to_string(&config) else {
481        return InitrdCompression::Lz4;
482    };
483    initrd_compression_for_config(&text)
484}
485
486/// Return the cached kernel config at the exact path libbpf probes in a guest.
487///
488/// Distro kernels commonly disable `CONFIG_IKCONFIG_PROC`, while BPF objects
489/// can still declare `CONFIG_*` kconfig externs. libbpf resolves those externs
490/// from `/boot/config-$(uname -r)` before trying `/proc/config.gz`. Cached
491/// package kernels already retain both the config and their exact release in
492/// `metadata.json`; expose that pair so every VM boot path can place the config
493/// in the immutable base initramfs.
494pub(crate) fn kernel_config_include_for_image(image: &Path) -> Option<(String, PathBuf)> {
495    let entry_dir = image.parent()?;
496    let metadata = super::housekeeping::read_metadata(entry_dir).ok()?;
497    if image.file_name()? != std::ffi::OsStr::new(&metadata.image_name) {
498        return None;
499    }
500    let release = metadata.version.as_deref()?;
501    let mut components = Path::new(release).components();
502    if release.is_empty()
503        || release.len() > 64
504        || !matches!(components.next(), Some(std::path::Component::Normal(_)))
505        || components.next().is_some()
506    {
507        return None;
508    }
509    let config = entry_dir.join("config");
510    std::fs::metadata(&config)
511        .ok()
512        .filter(|metadata| metadata.is_file())?;
513    Some((format!("boot/config-{release}"), config))
514}
515
516/// Pure core of [`initrd_compression_for_image`]: pick the best
517/// initrd compression from a kernel `.config`'s `CONFIG_RD_*` set.
518fn initrd_compression_for_config(text: &str) -> InitrdCompression {
519    // The RD_* decompressor options are bool symbols: `=y` or absent.
520    let enabled = |opt: &str| text.lines().any(|l| l.strip_prefix(opt) == Some("=y"));
521    if enabled("CONFIG_RD_LZ4") {
522        InitrdCompression::Lz4
523    } else if enabled("CONFIG_RD_ZSTD") {
524        InitrdCompression::Zstd
525    } else if enabled("CONFIG_RD_GZIP") {
526        InitrdCompression::Gzip
527    } else {
528        InitrdCompression::Uncompressed
529    }
530}
531
532/// Entry yielded by [`crate::cache::CacheDir::list`]. Distinguishes
533/// valid entries from corrupt ones.
534#[derive(Debug)]
535#[non_exhaustive]
536pub enum ListedEntry {
537    /// Valid cache entry with parsed metadata and an image file
538    /// present on disk at the metadata-declared path.
539    Valid(Box<CacheEntry>),
540    /// Entry directory exists but is unusable.
541    Corrupt {
542        /// Cache key (directory name).
543        key: String,
544        /// Path to the (corrupt) entry directory.
545        path: PathBuf,
546        /// Human-readable explanation of why the entry is classified
547        /// as corrupt.
548        reason: String,
549    },
550}
551
552impl ListedEntry {
553    /// Cache key (directory name) for either variant.
554    pub fn key(&self) -> &str {
555        match self {
556            ListedEntry::Valid(e) => &e.key,
557            ListedEntry::Corrupt { key, .. } => key,
558        }
559    }
560
561    /// Path to the entry directory for either variant.
562    pub fn path(&self) -> &Path {
563        match self {
564            ListedEntry::Valid(e) => &e.path,
565            ListedEntry::Corrupt { path, .. } => path,
566        }
567    }
568
569    /// Borrow the valid [`CacheEntry`] payload, or `None` for
570    /// [`ListedEntry::Corrupt`].
571    pub fn as_valid(&self) -> Option<&CacheEntry> {
572        match self {
573            ListedEntry::Valid(e) => Some(e.as_ref()),
574            ListedEntry::Corrupt { .. } => None,
575        }
576    }
577
578    /// Machine-readable classification of a corrupt entry's failure
579    /// mode. Returns `None` on a `Valid` entry.
580    pub fn error_kind(&self) -> Option<&'static str> {
581        match self {
582            ListedEntry::Valid(_) => None,
583            ListedEntry::Corrupt { reason, .. } => Some(classify_corrupt_reason(reason)),
584        }
585    }
586}
587
588/// Trailing literal of every "image_missing" reason string. Pinned
589/// here so [`format_image_missing_reason`] (the producer) and
590/// [`classify_corrupt_reason`] (the consumer) reference the same
591/// constant — the exact-suffix match in the classifier's
592/// `image_missing` arm cannot drift if a future edit changes the
593/// trailing wording without updating both sites.
594pub(crate) const IMAGE_MISSING_SUFFIX: &str = " missing from entry directory";
595
596/// Leading literal of every "image_missing" reason string. Pinned
597/// alongside [`IMAGE_MISSING_SUFFIX`] so both the producer and the
598/// classifier key on the same constants.
599pub(crate) const IMAGE_MISSING_PREFIX: &str = "image file ";
600
601/// Format the canonical "image_missing" reason string emitted by
602/// [`crate::cache::CacheDir::list`] when an entry's
603/// `metadata.json` is parseable but the boot image it names is
604/// absent from the entry directory.
605///
606/// Centralised here so the producer site (`cache_dir.rs`'s
607/// `list` corrupt-entry arm) and the classifier
608/// [`classify_corrupt_reason`] cannot drift out of lockstep —
609/// the result begins with [`IMAGE_MISSING_PREFIX`] and ends with
610/// [`IMAGE_MISSING_SUFFIX`], so the classifier's exact prefix +
611/// exact suffix predicate matches by construction without
612/// admitting unrelated reasons that merely happen to contain
613/// either literal.
614pub(crate) fn format_image_missing_reason(image_name: &str) -> String {
615    format!("{IMAGE_MISSING_PREFIX}{image_name}{IMAGE_MISSING_SUFFIX}")
616}
617
618/// Shared prefix → `error_kind` classifier.
619///
620/// Each `ListedEntry::Corrupt` carries a free-form `reason` string
621/// produced either by [`super::housekeeping::read_metadata`] (the
622/// six `metadata.json …` reasons) or by
623/// [`format_image_missing_reason`] at list-time (the `image_missing`
624/// reason, emitted from `cache_dir.rs`'s `list` corrupt arm when the
625/// image file is absent). This helper
626/// flattens those strings into a small, stable enum-of-strings the
627/// CLI surfaces in `cargo ktstr kernel list --json` as the
628/// `error_kind` field.
629///
630/// Reason-prefix → kind mapping (matched in this order):
631///
632/// | Reason (prefix or exact)                     | `error_kind`     |
633/// |----------------------------------------------|------------------|
634/// | `"metadata.json missing"` (exact)            | `"missing"`      |
635/// | `"metadata.json unreadable: …"`              | `"unreadable"`   |
636/// | `"metadata.json schema drift: …"`            | `"schema_drift"` |
637/// | `"metadata.json malformed: …"`               | `"malformed"`    |
638/// | `"metadata.json truncated: …"`               | `"truncated"`    |
639/// | `"metadata.json parse error: …"`             | `"parse_error"`  |
640/// | `"image file <name> missing from entry directory"` | `"image_missing"`|
641/// | (anything else)                              | `"unknown"`      |
642///
643/// The `image_missing` arm matches on the exact prefix
644/// [`IMAGE_MISSING_PREFIX`] AND the exact suffix
645/// [`IMAGE_MISSING_SUFFIX`] — both literals are produced verbatim
646/// by [`format_image_missing_reason`]. A loose `contains("missing")`
647/// would also match unrelated future reasons that happen to mention
648/// "missing" inside an `image file …` prefix (e.g. an "image file X
649/// missing checksum field" reason), so the dispatcher pins both ends
650/// of the canonical form.
651///
652/// [`super::housekeeping::read_metadata`] is the authoritative
653/// source of the six `metadata.json …` prefixes;
654/// [`format_image_missing_reason`] is the authoritative source of
655/// the `image_missing` prefix. If a new failure mode is
656/// added there, both this dispatcher and the
657/// `classify_corrupt_reason_covers_every_documented_prefix` test
658/// must be updated in lockstep so the JSON contract stays stable.
659pub(crate) fn classify_corrupt_reason(reason: &str) -> &'static str {
660    if reason == "metadata.json missing" {
661        "missing"
662    } else if reason.starts_with("metadata.json unreadable: ") {
663        "unreadable"
664    } else if reason.starts_with("metadata.json schema drift: ") {
665        "schema_drift"
666    } else if reason.starts_with("metadata.json malformed: ") {
667        "malformed"
668    } else if reason.starts_with("metadata.json truncated: ") {
669        "truncated"
670    } else if reason.starts_with("metadata.json parse error: ") {
671        // Forward-compat slot: no live producer in the current
672        // codebase. `read_metadata` uses `serde_json::from_str`
673        // which cannot return `Category::Io` (the arm is pinned
674        // `unreachable!` — see housekeeping.rs). The classifier
675        // arm is retained so a future producer that switches to
676        // `from_reader` (or any path that genuinely surfaces an
677        // I/O error during JSON decode) can emit the canonical
678        // prefix and have it route to the same stable
679        // `error_kind` value scripted consumers already dispatch
680        // on. Removing the arm now would force such a producer
681        // to either invent a new prefix (breaking the contract)
682        // or land in `unknown` (losing dispatch fidelity).
683        "parse_error"
684    } else if reason.starts_with(IMAGE_MISSING_PREFIX)
685        && reason.ends_with(IMAGE_MISSING_SUFFIX)
686        && reason.len() > IMAGE_MISSING_PREFIX.len() + IMAGE_MISSING_SUFFIX.len()
687    {
688        "image_missing"
689    } else {
690        "unknown"
691    }
692}
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697    use crate::cache::shared_test_helpers::{create_fake_image, test_metadata};
698    use crate::cache::{CacheArtifacts, CacheDir};
699    use std::fs;
700    use std::path::PathBuf;
701    use tempfile::TempDir;
702
703    // -- initrd compression discovery --
704
705    #[test]
706    fn cache_initrd_compression_prefers_lz4_then_zstd_then_gzip() {
707        // ktstr-built / Fedora shape: RD_LZ4 present wins outright.
708        let all = "CONFIG_RD_GZIP=y\nCONFIG_RD_LZ4=y\nCONFIG_RD_ZSTD=y\n";
709        assert_eq!(initrd_compression_for_config(all), InitrdCompression::Lz4);
710        // AL2023 shape: no RD_LZ4, RD_ZSTD present.
711        let al2023 = "CONFIG_RD_GZIP=y\n# CONFIG_RD_LZ4 is not set\nCONFIG_RD_ZSTD=y\n";
712        assert_eq!(
713            initrd_compression_for_config(al2023),
714            InitrdCompression::Zstd
715        );
716        let gzip_only = "CONFIG_RD_GZIP=y\n# CONFIG_RD_LZ4 is not set\n";
717        assert_eq!(
718            initrd_compression_for_config(gzip_only),
719            InitrdCompression::Gzip
720        );
721        // No decompressor at all: plain cpio still boots.
722        assert_eq!(
723            initrd_compression_for_config("CONFIG_FOO=y\n"),
724            InitrdCompression::Uncompressed
725        );
726        // A prefix-colliding symbol must not count as enabled.
727        assert_eq!(
728            initrd_compression_for_config("CONFIG_RD_LZ4_EXTRA=y\nCONFIG_RD_ZSTD=y\n"),
729            InitrdCompression::Zstd
730        );
731    }
732
733    #[test]
734    fn cache_initrd_compression_for_image_defaults_to_lz4() {
735        let tmp = TempDir::new().unwrap();
736        let image = tmp.path().join("bzImage");
737        fs::write(&image, b"fake").unwrap();
738        // No config sibling: LZ4 (built kernels / raw images).
739        assert_eq!(initrd_compression_for_image(&image), InitrdCompression::Lz4);
740        // With an AL2023-shaped config sibling: zstd.
741        fs::write(
742            tmp.path().join("config"),
743            "# CONFIG_RD_LZ4 is not set\nCONFIG_RD_ZSTD=y\n",
744        )
745        .unwrap();
746        assert_eq!(
747            initrd_compression_for_image(&image),
748            InitrdCompression::Zstd
749        );
750    }
751
752    #[test]
753    fn cached_kernel_config_uses_libbpf_guest_path() {
754        let tmp = TempDir::new().unwrap();
755        let image = tmp.path().join("bzImage");
756        let config = tmp.path().join("config");
757        fs::write(&image, b"fake image").unwrap();
758        fs::write(&config, b"CONFIG_PREEMPT_RCU=y\n").unwrap();
759        let metadata = test_metadata("7.0.0-14-generic");
760        fs::write(
761            tmp.path().join("metadata.json"),
762            serde_json::to_vec(&metadata).unwrap(),
763        )
764        .unwrap();
765
766        assert_eq!(
767            kernel_config_include_for_image(&image),
768            Some(("boot/config-7.0.0-14-generic".to_string(), config))
769        );
770    }
771
772    #[test]
773    fn cached_kernel_config_rejects_non_release_paths_and_mismatched_images() {
774        let tmp = TempDir::new().unwrap();
775        let image = tmp.path().join("bzImage");
776        fs::write(&image, b"fake image").unwrap();
777        fs::write(tmp.path().join("config"), b"CONFIG_PREEMPT_RCU=y\n").unwrap();
778
779        let invalid = test_metadata("../host-config");
780        fs::write(
781            tmp.path().join("metadata.json"),
782            serde_json::to_vec(&invalid).unwrap(),
783        )
784        .unwrap();
785        assert_eq!(kernel_config_include_for_image(&image), None);
786
787        let mut mismatch = test_metadata("7.0.0-test");
788        mismatch.image_name = "Image".to_string();
789        fs::write(
790            tmp.path().join("metadata.json"),
791            serde_json::to_vec(&mismatch).unwrap(),
792        )
793        .unwrap();
794        assert_eq!(kernel_config_include_for_image(&image), None);
795    }
796
797    // -- KernelMetadata serde --
798
799    #[test]
800    fn cache_metadata_serde_roundtrip() {
801        let meta = test_metadata("6.14.2");
802        let json = serde_json::to_string_pretty(&meta).unwrap();
803        let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
804        assert_eq!(parsed.version.as_deref(), Some("6.14.2"));
805        assert_eq!(parsed.source, KernelSource::Tarball);
806        assert_eq!(parsed.arch, "x86_64");
807        assert_eq!(parsed.image_name, "bzImage");
808        assert_eq!(parsed.config_hash.as_deref(), Some("abc123"));
809        assert_eq!(parsed.built_at, "2026-04-12T10:00:00Z");
810        assert_eq!(parsed.ktstr_kconfig_hash.as_deref(), Some("def456"));
811        assert!(!parsed.has_vmlinux);
812        assert!(!parsed.vmlinux_stripped);
813    }
814
815    #[test]
816    fn cache_metadata_serde_git_with_payload() {
817        let meta = KernelMetadata {
818            version: Some("6.15-rc3".to_string()),
819            source: KernelSource::git("a1b2c3d", "v6.15-rc3"),
820            arch: "aarch64".to_string(),
821            image_name: "Image".to_string(),
822            config_hash: None,
823            built_at: "2026-04-12T12:00:00Z".to_string(),
824            ktstr_kconfig_hash: None,
825            extra_kconfig_hash: None,
826            has_vmlinux: false,
827            vmlinux_stripped: false,
828            source_vmlinux_size: None,
829            source_vmlinux_mtime_secs: None,
830        };
831        let json = serde_json::to_string(&meta).unwrap();
832        let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
833        assert!(matches!(
834            parsed.source,
835            KernelSource::Git {
836                git_hash: Some(ref h),
837                git_ref: Some(ref r),
838            }
839            if h == "a1b2c3d" && r == "v6.15-rc3"
840        ));
841    }
842
843    /// Every `Option<…>` field on the `KernelMetadata` wrapper struct
844    /// (not on its `KernelSource` payload — that is covered by
845    /// `kernel_source_*` tests) serializes as an explicit `null` when
846    /// `None` and deserializes back as `None`. Pins the post-shim
847    /// wire shape: with `serde(default)` and `skip_serializing_if`
848    /// removed, `None` round-trips through a literal `null` token in
849    /// the JSON, never an absent key.
850    ///
851    /// Built via `KernelMetadata::new` with `KernelSource::Tarball` —
852    /// the constructor sets every `Option` field to `None`, so the
853    /// `is_none()` assertions confirm both that the constructor is
854    /// the canonical path to an all-`None` value and that the wire
855    /// shape preserves it across a round-trip.
856    #[test]
857    fn kernel_metadata_option_fields_serialize_as_explicit_null() {
858        let meta = KernelMetadata::new(
859            KernelSource::Tarball,
860            "x86_64",
861            "bzImage",
862            "2026-04-12T10:00:00Z",
863        );
864        let json = serde_json::to_string(&meta).unwrap();
865        for null_key in [
866            r#""version":null"#,
867            r#""config_hash":null"#,
868            r#""ktstr_kconfig_hash":null"#,
869            r#""extra_kconfig_hash":null"#,
870            r#""source_vmlinux_size":null"#,
871            r#""source_vmlinux_mtime_secs":null"#,
872        ] {
873            assert!(
874                json.contains(null_key),
875                "serialized JSON must contain explicit `{null_key}` \
876                 — None must round-trip as null, not as an absent \
877                 key. Got: {json}",
878            );
879        }
880        // Round-trip back: every Option must still be None.
881        let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
882        assert!(parsed.version.is_none(), "version must round-trip None");
883        assert!(
884            parsed.config_hash.is_none(),
885            "config_hash must round-trip None"
886        );
887        assert!(
888            parsed.ktstr_kconfig_hash.is_none(),
889            "ktstr_kconfig_hash must round-trip None"
890        );
891        assert!(
892            parsed.extra_kconfig_hash.is_none(),
893            "extra_kconfig_hash must round-trip None"
894        );
895        assert!(
896            parsed.source_vmlinux_size.is_none(),
897            "source_vmlinux_size must round-trip None"
898        );
899        assert!(
900            parsed.source_vmlinux_mtime_secs.is_none(),
901            "source_vmlinux_mtime_secs must round-trip None"
902        );
903    }
904
905    /// Every `Option<…>` wrapper field with a Some(...) value
906    /// round-trips byte-equal through serialize → deserialize.
907    /// Pins the populated branch of every Option, complementing the
908    /// all-None test.
909    ///
910    /// Built via `KernelMetadata::new` followed by every chainable
911    /// setter for the six `Option` fields (`with_version`,
912    /// `with_config_hash`, `with_ktstr_kconfig_hash`,
913    /// `with_extra_kconfig_hash`, `with_source_vmlinux_stat` covers
914    /// both `source_vmlinux_size` and `source_vmlinux_mtime_secs`),
915    /// so this test also pins that the builder API can produce a
916    /// fully-populated value without touching the struct directly.
917    #[test]
918    fn kernel_metadata_all_option_fields_populated_roundtrip() {
919        let meta = KernelMetadata::new(
920            KernelSource::Tarball,
921            "x86_64",
922            "bzImage",
923            "2026-04-12T10:00:00Z",
924        )
925        .with_version("6.14.2")
926        .with_config_hash("cfg-hash")
927        .with_ktstr_kconfig_hash("ktstr-hash")
928        .with_extra_kconfig_hash("extra-hash")
929        .with_source_vmlinux_stat(123_456_789, 1_700_000_000);
930        let json = serde_json::to_string(&meta).unwrap();
931        let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
932        assert_eq!(parsed.version.as_deref(), Some("6.14.2"));
933        assert_eq!(parsed.config_hash.as_deref(), Some("cfg-hash"));
934        assert_eq!(parsed.ktstr_kconfig_hash.as_deref(), Some("ktstr-hash"));
935        assert_eq!(parsed.extra_kconfig_hash.as_deref(), Some("extra-hash"));
936        assert_eq!(parsed.source_vmlinux_size, Some(123_456_789));
937        assert_eq!(parsed.source_vmlinux_mtime_secs, Some(1_700_000_000));
938    }
939
940    /// Pins the with_X → clear_X round-trip for every Option-bearing
941    /// setter group. Each pair must be symmetric: with_X populates,
942    /// clear_X resets to None. The pair-stat method
943    /// (`with_source_vmlinux_stat` / `clear_source_vmlinux_stat`)
944    /// covers two fields together — both must be Some after with_X
945    /// and both must be None after clear_X.
946    #[test]
947    fn kernel_metadata_clear_setters_round_trip() {
948        let populated = KernelMetadata::new(
949            KernelSource::Tarball,
950            "x86_64",
951            "bzImage",
952            "2026-04-12T10:00:00Z",
953        )
954        .with_version("6.14.2")
955        .with_config_hash("cfg-hash")
956        .with_ktstr_kconfig_hash("ktstr-hash")
957        .with_extra_kconfig_hash("extra-hash")
958        .with_source_vmlinux_stat(123_456_789, 1_700_000_000);
959        assert!(populated.version.is_some());
960        assert!(populated.config_hash.is_some());
961        assert!(populated.ktstr_kconfig_hash.is_some());
962        assert!(populated.extra_kconfig_hash.is_some());
963        assert!(populated.source_vmlinux_size.is_some());
964        assert!(populated.source_vmlinux_mtime_secs.is_some());
965
966        let cleared = populated
967            .clear_version()
968            .clear_config_hash()
969            .clear_ktstr_kconfig_hash()
970            .clear_extra_kconfig_hash()
971            .clear_source_vmlinux_stat();
972        assert!(cleared.version.is_none());
973        assert!(cleared.config_hash.is_none());
974        assert!(cleared.ktstr_kconfig_hash.is_none());
975        assert!(cleared.extra_kconfig_hash.is_none());
976        assert!(cleared.source_vmlinux_size.is_none());
977        assert!(cleared.source_vmlinux_mtime_secs.is_none());
978    }
979
980    #[test]
981    fn cache_metadata_serde_local_with_source_tree() {
982        let meta = KernelMetadata {
983            version: Some("6.14.0".to_string()),
984            source: KernelSource::Local {
985                source_tree_path: Some(PathBuf::from("/tmp/linux")),
986                git_hash: Some("deadbee".to_string()),
987            },
988            arch: "x86_64".to_string(),
989            image_name: "bzImage".to_string(),
990            config_hash: Some("fff000".to_string()),
991            built_at: "2026-04-12T14:00:00Z".to_string(),
992            ktstr_kconfig_hash: Some("aaa111".to_string()),
993            extra_kconfig_hash: None,
994            has_vmlinux: true,
995            vmlinux_stripped: true,
996            source_vmlinux_size: None,
997            source_vmlinux_mtime_secs: None,
998        };
999        let json = serde_json::to_string(&meta).unwrap();
1000        let parsed: KernelMetadata = serde_json::from_str(&json).unwrap();
1001        assert!(matches!(
1002            parsed.source,
1003            KernelSource::Local {
1004                source_tree_path: Some(ref p),
1005                git_hash: Some(ref h),
1006            }
1007            if p == &PathBuf::from("/tmp/linux") && h == "deadbee"
1008        ));
1009        assert!(parsed.has_vmlinux);
1010        assert!(parsed.vmlinux_stripped);
1011    }
1012
1013    /// git_hash on KernelSource::Local is a plain Option<String> with
1014    /// no serde attributes — the compat shims (serde(default) +
1015    /// skip_serializing_if) were removed for pre-1.0, so `None`
1016    /// serializes as an explicit `null` key and deserialization
1017    /// accepts `null` back as `None`. This test pins only the
1018    /// None → null → None round trip; the absent-key branch is
1019    /// exercised separately by
1020    /// [`kernel_source_absent_option_keys_deserialize_as_none`].
1021    #[test]
1022    fn kernel_source_local_git_hash_serde_round_trip_none() {
1023        let src = KernelSource::Local {
1024            source_tree_path: Some(PathBuf::from("/tmp/linux")),
1025            git_hash: None,
1026        };
1027        let json = serde_json::to_string(&src).unwrap();
1028        assert!(
1029            json.contains(r#""git_hash":null"#),
1030            "git_hash=None must round-trip as explicit null, got {json}"
1031        );
1032        let parsed: KernelSource = serde_json::from_str(&json).unwrap();
1033        assert!(matches!(parsed, KernelSource::Local { git_hash: None, .. }));
1034    }
1035
1036    /// Pins the post-shim wire format: `Option` payload fields inside
1037    /// every [`KernelSource`] variant serialize as explicit `null`
1038    /// rather than being omitted.
1039    #[test]
1040    fn kernel_source_option_fields_serialize_as_explicit_null() {
1041        let local = KernelSource::Local {
1042            source_tree_path: None,
1043            git_hash: None,
1044        };
1045        let local_json = serde_json::to_string(&local).unwrap();
1046        assert!(
1047            local_json.contains(r#""source_tree_path":null"#),
1048            "Local.source_tree_path=None must serialize as explicit null, got {local_json}"
1049        );
1050        assert!(
1051            local_json.contains(r#""git_hash":null"#),
1052            "Local.git_hash=None must serialize as explicit null, got {local_json}"
1053        );
1054
1055        let git = KernelSource::Git {
1056            git_hash: None,
1057            git_ref: None,
1058        };
1059        let git_json = serde_json::to_string(&git).unwrap();
1060        assert!(
1061            git_json.contains(r#""git_hash":null"#),
1062            "Git.git_hash=None must serialize as explicit null, got {git_json}"
1063        );
1064        assert!(
1065            git_json.contains(r#""ref":null"#),
1066            "Git.git_ref=None must serialize as explicit null under the `ref` key, got {git_json}"
1067        );
1068    }
1069
1070    /// Older `metadata.json` files written before `Option` fields
1071    /// were emitted as explicit `null` simply omit the keys.
1072    #[test]
1073    fn kernel_source_absent_option_keys_deserialize_as_none() {
1074        let git_bare: KernelSource = serde_json::from_str(r#"{"type":"git"}"#)
1075            .expect("Git with absent Option keys must deserialize");
1076        assert!(matches!(
1077            git_bare,
1078            KernelSource::Git {
1079                git_hash: None,
1080                git_ref: None,
1081            }
1082        ));
1083
1084        let git_hash_only: KernelSource =
1085            serde_json::from_str(r#"{"type":"git","git_hash":"abc"}"#)
1086                .expect("Git with only git_hash must deserialize");
1087        assert!(matches!(
1088            git_hash_only,
1089            KernelSource::Git {
1090                git_hash: Some(ref h),
1091                git_ref: None,
1092            } if h == "abc"
1093        ));
1094
1095        let git_ref_only: KernelSource = serde_json::from_str(r#"{"type":"git","ref":"main"}"#)
1096            .expect("Git with only ref must deserialize");
1097        assert!(matches!(
1098            git_ref_only,
1099            KernelSource::Git {
1100                git_hash: None,
1101                git_ref: Some(ref r),
1102            } if r == "main"
1103        ));
1104
1105        let local_bare: KernelSource = serde_json::from_str(r#"{"type":"local"}"#)
1106            .expect("Local with absent Option keys must deserialize");
1107        assert!(matches!(
1108            local_bare,
1109            KernelSource::Local {
1110                source_tree_path: None,
1111                git_hash: None,
1112            }
1113        ));
1114
1115        let local_path_only: KernelSource =
1116            serde_json::from_str(r#"{"type":"local","source_tree_path":"/tmp/linux"}"#)
1117                .expect("Local with only source_tree_path must deserialize");
1118        assert!(matches!(
1119            local_path_only,
1120            KernelSource::Local {
1121                source_tree_path: Some(ref p),
1122                git_hash: None,
1123            } if p.to_str() == Some("/tmp/linux")
1124        ));
1125
1126        let local_hash_only: KernelSource =
1127            serde_json::from_str(r#"{"type":"local","git_hash":"deadbeef"}"#)
1128                .expect("Local with only git_hash must deserialize");
1129        assert!(matches!(
1130            local_hash_only,
1131            KernelSource::Local {
1132                source_tree_path: None,
1133                git_hash: Some(ref h),
1134            } if h == "deadbeef"
1135        ));
1136    }
1137
1138    #[test]
1139    fn kernel_source_serde_tagged_representation() {
1140        let t = serde_json::to_string(&KernelSource::Tarball).unwrap();
1141        assert_eq!(t, r#"{"type":"tarball"}"#);
1142        let g = serde_json::to_string(&KernelSource::git("abc", "main")).unwrap();
1143        assert!(g.contains(r#""type":"git""#));
1144        assert!(g.contains(r#""git_hash":"abc""#));
1145        assert!(g.contains(r#""ref":"main""#));
1146        let l = serde_json::to_string(&KernelSource::Local {
1147            source_tree_path: Some(PathBuf::from("/tmp/linux")),
1148            git_hash: Some("a1b2c3d".to_string()),
1149        })
1150        .unwrap();
1151        assert!(l.contains(r#""type":"local""#));
1152        assert!(l.contains(r#""source_tree_path":"/tmp/linux""#));
1153        assert!(l.contains(r#""git_hash":"a1b2c3d""#));
1154    }
1155
1156    /// Table-drive every prefix → `error_kind` classifier mapping.
1157    #[test]
1158    fn classify_corrupt_reason_covers_every_documented_prefix() {
1159        let cases: &[(&str, &str)] = &[
1160            ("metadata.json missing", "missing"),
1161            (
1162                "metadata.json unreadable: Is a directory (os error 21)",
1163                "unreadable",
1164            ),
1165            (
1166                "metadata.json schema drift: missing field `source` at line 1 column 21",
1167                "schema_drift",
1168            ),
1169            (
1170                "metadata.json malformed: expected value at line 1 column 1",
1171                "malformed",
1172            ),
1173            (
1174                "metadata.json truncated: EOF while parsing a value at line 1 column 10",
1175                "truncated",
1176            ),
1177            (
1178                "metadata.json parse error: something unexpected",
1179                "parse_error",
1180            ),
1181            (
1182                "image file bzImage missing from entry directory",
1183                "image_missing",
1184            ),
1185            ("some future prefix nobody wrote yet", "unknown"),
1186        ];
1187        for (reason, expected) in cases {
1188            assert_eq!(
1189                classify_corrupt_reason(reason),
1190                *expected,
1191                "reason `{reason}` should classify as `{expected}`",
1192            );
1193        }
1194    }
1195
1196    /// The `image_missing` arm requires BOTH the canonical prefix
1197    /// AND the canonical trailing literal — strings that share only
1198    /// one half (or that would have matched the legacy loose
1199    /// `starts_with("image file ") && contains("missing")` predicate)
1200    /// must drop into `unknown`. Locks the tightening described on
1201    /// [`classify_corrupt_reason`].
1202    #[test]
1203    fn classify_corrupt_reason_image_missing_requires_exact_suffix() {
1204        // Loose predicate would match (prefix + the substring
1205        // "missing" in the wrong position). The tightened predicate
1206        // rejects it because the suffix isn't the canonical
1207        // ` missing from entry directory`.
1208        assert_eq!(
1209            classify_corrupt_reason("image file bzImage missing checksum field"),
1210            "unknown",
1211            "non-canonical 'image file … missing X' reason must NOT \
1212             classify as `image_missing` — only the exact \
1213             format_image_missing_reason() form is accepted",
1214        );
1215        // Suffix matches but prefix doesn't — must not classify.
1216        assert_eq!(
1217            classify_corrupt_reason("foo bzImage missing from entry directory"),
1218            "unknown",
1219            "suffix-only match without the canonical prefix must classify as unknown",
1220        );
1221        // Empty image name produces a degenerate prefix+suffix abut —
1222        // the length guard rejects it so a future bug that emits
1223        // `format_image_missing_reason("")` cannot silently classify.
1224        assert_eq!(
1225            classify_corrupt_reason("image file  missing from entry directory"),
1226            "unknown",
1227            "prefix+suffix with no image_name in between must classify as unknown",
1228        );
1229    }
1230
1231    /// Producer→consumer round trip: every reason produced by
1232    /// [`format_image_missing_reason`] must classify as
1233    /// `image_missing`, regardless of the image_name value
1234    /// (alphanumerics, dots, dashes, multi-word names).
1235    #[test]
1236    fn classify_corrupt_reason_accepts_every_format_image_missing_output() {
1237        for image_name in [
1238            "bzImage",
1239            "Image",
1240            "vmlinuz-6.14.2",
1241            "kernel.bin",
1242            "image_with_underscores",
1243            "name-with-many-dashes",
1244        ] {
1245            let reason = format_image_missing_reason(image_name);
1246            assert_eq!(
1247                classify_corrupt_reason(&reason),
1248                "image_missing",
1249                "every produced reason (image_name={image_name:?}) must \
1250                 classify as image_missing — got reason {reason:?}",
1251            );
1252        }
1253    }
1254
1255    /// `ListedEntry::error_kind()` returns `None` on a Valid entry
1256    /// and the classifier result on a Corrupt entry.
1257    #[test]
1258    fn listed_entry_error_kind_dispatches_on_variant() {
1259        let tmp = TempDir::new().unwrap();
1260        let cache = CacheDir::with_root(tmp.path().join("cache"));
1261        let src_dir = TempDir::new().unwrap();
1262        let image = create_fake_image(src_dir.path());
1263        let meta = test_metadata("6.14.2");
1264        cache
1265            .store("valid-ek", &CacheArtifacts::new(&image), &meta)
1266            .unwrap();
1267
1268        let bad_dir = tmp.path().join("cache").join("corrupt-ek");
1269        fs::create_dir_all(&bad_dir).unwrap();
1270
1271        let entries = cache.list().unwrap();
1272        assert_eq!(entries.len(), 2);
1273        let valid = entries
1274            .iter()
1275            .find(|e| e.key() == "valid-ek")
1276            .expect("valid entry must be listed");
1277        let corrupt = entries
1278            .iter()
1279            .find(|e| e.key() == "corrupt-ek")
1280            .expect("corrupt entry must be listed");
1281        assert_eq!(
1282            valid.error_kind(),
1283            None,
1284            "Valid entries must report no error_kind",
1285        );
1286        assert_eq!(
1287            corrupt.error_kind(),
1288            Some("missing"),
1289            "missing-metadata Corrupt entry must classify as `missing`",
1290        );
1291    }
1292
1293    // -- KconfigStatus Display impl --
1294    //
1295    // Pins the three Display strings that flow through `kernel list
1296    // --json` as the `kconfig_status` field. CI scripts consume these
1297    // exact strings, so any rewording is a downstream-visible
1298    // contract change.
1299
1300    #[test]
1301    fn kconfig_status_display_matches_renders_lowercase_word() {
1302        assert_eq!(KconfigStatus::Matches.to_string(), "matches");
1303    }
1304
1305    #[test]
1306    fn kconfig_status_display_stale_renders_lowercase_word_without_hashes() {
1307        let s = KconfigStatus::Stale {
1308            cached: "deadbeef".to_string(),
1309            current: "cafebabe".to_string(),
1310        }
1311        .to_string();
1312        assert_eq!(
1313            s, "stale",
1314            "Display elides the cached/current hashes; callers that need them must match on the variant directly"
1315        );
1316    }
1317
1318    #[test]
1319    fn kconfig_status_display_untracked_renders_lowercase_word() {
1320        assert_eq!(KconfigStatus::Untracked.to_string(), "untracked");
1321    }
1322
1323    // -- KconfigStatus predicates --
1324    //
1325    // `is_stale()` and `is_untracked()` collapse the variant pattern
1326    // match into a bool, which the kernel-build pipeline keys on for
1327    // its rebuild decision. The predicates are independent of the
1328    // Display impl tested above — the pipeline never round-trips
1329    // through Display, it dispatches on the bool. A regression that
1330    // flipped either predicate's polarity (e.g. `Stale` returning
1331    // false from `is_stale`) would invisibly change the rebuild
1332    // policy.
1333
1334    /// `Matches` is neither stale nor untracked.
1335    #[test]
1336    fn kconfig_status_matches_is_neither_stale_nor_untracked() {
1337        let s = KconfigStatus::Matches;
1338        assert!(!s.is_stale(), "Matches must not be stale");
1339        assert!(!s.is_untracked(), "Matches must not be untracked");
1340    }
1341
1342    /// `Stale` is stale and not untracked — the two predicates are
1343    /// mutually exclusive on this variant.
1344    #[test]
1345    fn kconfig_status_stale_is_stale_only() {
1346        let s = KconfigStatus::Stale {
1347            cached: "old".to_string(),
1348            current: "new".to_string(),
1349        };
1350        assert!(s.is_stale(), "Stale variant must report is_stale=true");
1351        assert!(
1352            !s.is_untracked(),
1353            "Stale must NOT report is_untracked — the two predicates \
1354             discriminate distinct variants",
1355        );
1356    }
1357
1358    /// `Untracked` is untracked and not stale — pre-tracking-format
1359    /// entries must NOT trigger a rebuild via the stale-check.
1360    #[test]
1361    fn kconfig_status_untracked_is_untracked_only() {
1362        let s = KconfigStatus::Untracked;
1363        assert!(
1364            s.is_untracked(),
1365            "Untracked variant must report is_untracked=true"
1366        );
1367        assert!(
1368            !s.is_stale(),
1369            "Untracked must NOT report is_stale — pre-tracking-format \
1370             entries are unknown, not stale; treating them as stale \
1371             would force a rebuild on every old cache hit",
1372        );
1373    }
1374
1375    // -- KernelSource::as_local_git_hash --
1376    //
1377    // The accessor exists for kernel_build_pipeline's post-build
1378    // dirty re-check (see cli/kernel_build/build.rs
1379    // compute_mid_wait_state / post_build_dirty_skip, where
1380    // as_local_git_hash is called): it
1381    // compares the post-build HEAD hash against the acquire-time
1382    // hash to detect mid-build commits. The accessor MUST return
1383    // the inner `git_hash` for `Local` variant only and `None` for
1384    // every other variant — a regression that returned `git_hash`
1385    // for `Git` (which has its own `git_hash` field at a different
1386    // role) would silently corrupt the dirty-check.
1387
1388    /// `Local` with `git_hash: Some(...)` returns the borrowed hash.
1389    /// Borrows rather than clones — a regression that owned the
1390    /// returned string would force the caller to allocate.
1391    #[test]
1392    fn as_local_git_hash_returns_local_hash() {
1393        let src = KernelSource::Local {
1394            source_tree_path: Some(PathBuf::from("/tmp/linux")),
1395            git_hash: Some("deadbee".to_string()),
1396        };
1397        assert_eq!(
1398            src.as_local_git_hash(),
1399            Some("deadbee"),
1400            "Local with git_hash=Some must surface the inner str",
1401        );
1402    }
1403
1404    /// `Local` with `git_hash: None` (dirty / non-git tree at acquire
1405    /// time) returns `None`. The caller distinguishes "we have a
1406    /// hash to compare" from "we have no anchor" — collapsing both
1407    /// into `Some("")` would mislead the dirty-check.
1408    #[test]
1409    fn as_local_git_hash_returns_none_when_local_has_no_hash() {
1410        let src = KernelSource::Local {
1411            source_tree_path: Some(PathBuf::from("/tmp/linux")),
1412            git_hash: None,
1413        };
1414        assert_eq!(
1415            src.as_local_git_hash(),
1416            None,
1417            "Local with git_hash=None must surface None — the dirty \
1418             check has no anchor on a non-git or dirty tree",
1419        );
1420    }
1421
1422    /// `Tarball` returns `None` — tarball builds have no git anchor
1423    /// and the accessor must NOT borrow from the wrong variant's
1424    /// payload (Tarball has no payload at all, so a regression
1425    /// reaching for one would produce a compile error rather than a
1426    /// silent bug — but pin the contract anyway).
1427    #[test]
1428    fn as_local_git_hash_returns_none_for_tarball() {
1429        let src = KernelSource::Tarball;
1430        assert_eq!(
1431            src.as_local_git_hash(),
1432            None,
1433            "Tarball variant has no git_hash and must surface None",
1434        );
1435    }
1436
1437    /// `Git` variant returns `None` even though it has its own
1438    /// `git_hash` field — the accessor is `as_local_git_hash`, not
1439    /// `as_git_hash`. Pins that the accessor does NOT cross-wire
1440    /// the Git variant's `git_hash` (which describes the cloned
1441    /// commit, a different role from the Local variant's
1442    /// `git_hash` which describes the acquire-time HEAD).
1443    #[test]
1444    fn as_local_git_hash_returns_none_for_git_even_with_hash_field() {
1445        let src = KernelSource::git("a1b2c3d", "main");
1446        assert_eq!(
1447            src.as_local_git_hash(),
1448            None,
1449            "Git variant has its own git_hash field but the \
1450             accessor is named as_LOCAL_git_hash — it MUST NOT \
1451             surface the Git variant's hash, since the Git hash \
1452             describes the cloned commit (acquire-time) and the \
1453             Local hash describes the operator's working tree HEAD \
1454             (a different role with different semantics)",
1455        );
1456    }
1457
1458    // -- format_image_missing_reason --
1459    //
1460    // The producer pairs with `classify_corrupt_reason`'s
1461    // `image_missing` arm via the [`IMAGE_MISSING_PREFIX`] /
1462    // [`IMAGE_MISSING_SUFFIX`] constants. Direct producer coverage
1463    // pins the canonical literal so a future edit to the format!
1464    // string can't drift the producer side without breaking the
1465    // round-trip test in `classify_corrupt_reason_accepts_every_format_image_missing_output`.
1466
1467    /// Producer composes prefix + image_name + suffix verbatim.
1468    #[test]
1469    fn format_image_missing_reason_uses_canonical_prefix_and_suffix() {
1470        let reason = format_image_missing_reason("bzImage");
1471        assert_eq!(
1472            reason, "image file bzImage missing from entry directory",
1473            "the produced reason MUST be the exact prefix + image_name + \
1474             suffix concatenation — any drift breaks the classifier's \
1475             exact-match predicate",
1476        );
1477        assert!(
1478            reason.starts_with(IMAGE_MISSING_PREFIX),
1479            "produced reason must start with IMAGE_MISSING_PREFIX",
1480        );
1481        assert!(
1482            reason.ends_with(IMAGE_MISSING_SUFFIX),
1483            "produced reason must end with IMAGE_MISSING_SUFFIX",
1484        );
1485    }
1486
1487    /// Empty image_name produces a degenerate prefix+suffix abut
1488    /// (the prefix's trailing space and the suffix's leading space
1489    /// become adjacent, giving `"file  missing"` with two consecutive
1490    /// spaces). The classifier's length-guard rejects the result.
1491    /// The producer itself does NOT validate (image_name is supposed
1492    /// to come from already-validated metadata.image_name), so the
1493    /// empty case still produces the verbatim concatenation — but the
1494    /// classifier MUST reject the result. Pins the contract that
1495    /// degenerate producer output is consumer-rejected, not silently
1496    /// classified as image_missing.
1497    #[test]
1498    fn format_image_missing_reason_with_empty_image_name() {
1499        let reason = format_image_missing_reason("");
1500        assert_eq!(
1501            reason, "image file  missing from entry directory",
1502            "empty image_name must produce a verbatim concatenation \
1503             (prefix trailing-space + suffix leading-space → two \
1504             consecutive spaces between `file` and `missing`); the \
1505             producer does not validate (validation is at \
1506             validate_filename time), so the degenerate concatenation \
1507             is the documented behaviour",
1508        );
1509        // The classifier MUST reject this degenerate form via its
1510        // length-guard arm so the empty case classifies as `unknown`
1511        // rather than `image_missing`.
1512        assert_eq!(
1513            classify_corrupt_reason(&reason),
1514            "unknown",
1515            "the classifier's length-guard MUST reject the \
1516             prefix+suffix-with-empty-image-name form — a regression \
1517             that loosened the guard would let a future bug emit \
1518             format_image_missing_reason(\"\") and silently classify \
1519             it as image_missing, hiding the real defect (empty \
1520             image_name in metadata)",
1521        );
1522    }
1523
1524    // -- CacheEntry::disk_template_path --
1525    //
1526    // The accessor names the canonical filename for the per-entry
1527    // btrfs disk template (`<entry>/disk-template.img`) that
1528    // `vmm/disk_template.rs` writes and reads. The contract is
1529    // path-only: no I/O, no validation. Pin the literal so a
1530    // future rename (`disk-template.img` → `disk.img`) is caught
1531    // by the test rather than only at runtime when the VMM tries
1532    // to read a path that no longer exists.
1533    #[test]
1534    fn cache_entry_disk_template_path_joins_canonical_filename() {
1535        let tmp = TempDir::new().unwrap();
1536        let cache = CacheDir::with_root(tmp.path().join("cache"));
1537        let src_dir = TempDir::new().unwrap();
1538        let image = create_fake_image(src_dir.path());
1539        let entry = cache
1540            .store(
1541                "disk-tmpl-key",
1542                &CacheArtifacts::new(&image),
1543                &test_metadata("6.14.2"),
1544            )
1545            .unwrap();
1546        assert_eq!(
1547            entry.disk_template_path(),
1548            entry.path.join("disk-template.img"),
1549            "disk_template_path() MUST resolve to <entry>/disk-template.img — \
1550             the literal `disk-template.img` is the canonical filename the \
1551             VMM disk_template module writes/reads",
1552        );
1553        // The accessor is path-only; the file does NOT have to
1554        // exist for the path to be returned. Pin that the file
1555        // is absent immediately after store() (since store() does
1556        // not create the disk template — that's a separate
1557        // pipeline step in vmm/disk_template.rs).
1558        assert!(
1559            !entry.disk_template_path().exists(),
1560            "disk_template_path() must be path-only — store() does not \
1561             create the file; absence is the expected post-store state",
1562        );
1563    }
1564
1565    // -- CacheEntry::has_extra_kconfig --
1566    //
1567    // Predicate that wraps `metadata.extra_kconfig_hash.is_some()`.
1568    // Pin both branches so a regression that flipped the polarity
1569    // (returning `is_none()`) would surface here rather than only
1570    // in downstream consumers that select rebuild policies on the
1571    // bool.
1572
1573    /// `extra_kconfig_hash: Some(...)` → predicate returns true.
1574    #[test]
1575    fn cache_entry_has_extra_kconfig_true_when_hash_present() {
1576        let tmp = TempDir::new().unwrap();
1577        let cache = CacheDir::with_root(tmp.path().join("cache"));
1578        let src_dir = TempDir::new().unwrap();
1579        let image = create_fake_image(src_dir.path());
1580        let meta = test_metadata("6.14.2").with_extra_kconfig_hash("user-fragment-hash");
1581        let entry = cache
1582            .store("with-extra", &CacheArtifacts::new(&image), &meta)
1583            .unwrap();
1584        assert!(
1585            entry.has_extra_kconfig(),
1586            "extra_kconfig_hash=Some MUST report has_extra_kconfig()=true — \
1587             a regression that flipped polarity would invert the \
1588             rebuild-on-fragment-change policy",
1589        );
1590    }
1591
1592    /// `extra_kconfig_hash: None` → predicate returns false.
1593    #[test]
1594    fn cache_entry_has_extra_kconfig_false_when_hash_absent() {
1595        let tmp = TempDir::new().unwrap();
1596        let cache = CacheDir::with_root(tmp.path().join("cache"));
1597        let src_dir = TempDir::new().unwrap();
1598        let image = create_fake_image(src_dir.path());
1599        // test_metadata sets extra_kconfig_hash=None by default.
1600        let meta = test_metadata("6.14.2");
1601        assert!(
1602            meta.extra_kconfig_hash.is_none(),
1603            "test_metadata default must keep extra_kconfig_hash=None \
1604             so this test exercises the false branch",
1605        );
1606        let entry = cache
1607            .store("no-extra", &CacheArtifacts::new(&image), &meta)
1608            .unwrap();
1609        assert!(
1610            !entry.has_extra_kconfig(),
1611            "extra_kconfig_hash=None MUST report has_extra_kconfig()=false",
1612        );
1613    }
1614
1615    // -- ListedEntry::path accessor --
1616    //
1617    // The accessor abstracts over the variant — Valid carries the
1618    // path inside its boxed CacheEntry, Corrupt carries it as a
1619    // direct field. Existing list() tests reach into the variant
1620    // and read the field, so the accessor itself is uncovered.
1621    // Pin both branches.
1622
1623    /// `Valid` variant: path() returns the inner CacheEntry's path.
1624    #[test]
1625    fn listed_entry_path_accessor_returns_valid_entry_path() {
1626        let tmp = TempDir::new().unwrap();
1627        let cache = CacheDir::with_root(tmp.path().join("cache"));
1628        let src_dir = TempDir::new().unwrap();
1629        let image = create_fake_image(src_dir.path());
1630        let entry = cache
1631            .store(
1632                "valid-path-test",
1633                &CacheArtifacts::new(&image),
1634                &test_metadata("6.14.2"),
1635            )
1636            .unwrap();
1637        let expected_path = entry.path.clone();
1638        let entries = cache.list().unwrap();
1639        let listed = entries
1640            .iter()
1641            .find(|e| e.key() == "valid-path-test")
1642            .expect("the just-stored entry must be in the list");
1643        assert!(
1644            matches!(listed, ListedEntry::Valid(_)),
1645            "precondition: stored entry must surface as Valid",
1646        );
1647        assert_eq!(
1648            listed.path(),
1649            expected_path,
1650            "ListedEntry::path() on Valid must return the inner \
1651             CacheEntry's path — accessor MUST forward, not synthesize",
1652        );
1653    }
1654
1655    /// `Corrupt` variant: path() returns the per-variant path field.
1656    #[test]
1657    fn listed_entry_path_accessor_returns_corrupt_entry_path() {
1658        let tmp = TempDir::new().unwrap();
1659        let cache = CacheDir::with_root(tmp.path().join("cache"));
1660        // Create a corrupt-shaped entry (directory exists but no
1661        // metadata.json), so list() classifies it as Corrupt.
1662        let entry_dir = tmp.path().join("cache").join("corrupt-path-test");
1663        std::fs::create_dir_all(&entry_dir).unwrap();
1664        let entries = cache.list().unwrap();
1665        let listed = entries
1666            .iter()
1667            .find(|e| e.key() == "corrupt-path-test")
1668            .expect("corrupt-shaped entry must be in the list");
1669        assert!(
1670            matches!(listed, ListedEntry::Corrupt { .. }),
1671            "precondition: missing-metadata entry must surface as Corrupt",
1672        );
1673        assert_eq!(
1674            listed.path(),
1675            entry_dir,
1676            "ListedEntry::path() on Corrupt must return the variant's \
1677             `path` field — accessor MUST forward, not synthesize",
1678        );
1679    }
1680}