From e69bfb9aefe747cdf297de7d02d5ec9d8ef94aac Mon Sep 17 00:00:00 2001 From: Phoebus Date: Fri, 25 Sep 2026 18:26:08 -0700 Subject: [PATCH] refactor(executor): box ExecError command details, clear Clippy -D warnings gate Box the CommandFailure payload so ExecError shrinks 128 -> 96 bytes and Result passes result_large_err without per-site boxing. Preserve the display text, redacted stdout/stderr capture, and the stderr tail used for update failures; update the constructor and every match site. Add regression tests for the error text, captured output, and the 96-byte size bound. Resolve the remaining Clippy warnings without blanket allows: a type alias for the snap-entry tuple in actions.rs, a CommandRecord params struct for Logger::command in log.rs, and DiskPhase variant renames in gui_bridge.rs. cargo clippy --workspace --all-targets -- -D warnings is clean; cargo test --workspace passes (692 tests). --- .../crates/phoebus-executor/src/actions.rs | 7 +- .../crates/phoebus-executor/src/error.rs | 96 +++++++++++++++++-- .../crates/phoebus-executor/src/exec.rs | 20 ++-- .../crates/phoebus-executor/src/lib.rs | 4 +- .../crates/phoebus-executor/src/log.rs | 55 ++++++----- .../crates/phoebus-executor/src/update.rs | 6 +- .../phoebus-installer/src/gui_bridge.rs | 22 ++--- 7 files changed, 148 insertions(+), 62 deletions(-) diff --git a/installer-rs/crates/phoebus-executor/src/actions.rs b/installer-rs/crates/phoebus-executor/src/actions.rs index 64251a5..728c9e3 100644 --- a/installer-rs/crates/phoebus-executor/src/actions.rs +++ b/installer-rs/crates/phoebus-executor/src/actions.rs @@ -459,9 +459,10 @@ pub(crate) fn flatpak_update_transactions( /// revision is the immutable identity and the tracking channel is the scope. pub(crate) fn parse_snap_transactions(refresh: &str, installed: &str) -> Vec { use std::collections::BTreeMap; + /// Installed snap entry: (version, revision, tracking, notes). + type InstalledSnapEntry = (Option, Option, Option, String); // name -> (version, revision, tracking, notes) - let mut current: BTreeMap, Option, Option, String)> = - BTreeMap::new(); + let mut current: BTreeMap = BTreeMap::new(); for line in installed.lines().skip(1) { let cols: Vec<&str> = line.split_whitespace().collect(); if cols.len() < 4 || cols[0].is_empty() { @@ -1742,7 +1743,7 @@ Total: 1 package (1 new), Size of downloads: 512 KiB Path::new(&exec.root), ) .unwrap_err(); - assert!(matches!(err, ExecError::Command { .. }), "got {err}"); + assert!(matches!(err, ExecError::Command(_)), "got {err}"); // The mutation must not run, and no snapshot may be recorded as // committed when creation failed. assert!(!runner.programs().iter().any(|p| p == "emerge")); diff --git a/installer-rs/crates/phoebus-executor/src/error.rs b/installer-rs/crates/phoebus-executor/src/error.rs index bc90b4f..4b7e936 100644 --- a/installer-rs/crates/phoebus-executor/src/error.rs +++ b/installer-rs/crates/phoebus-executor/src/error.rs @@ -7,17 +7,33 @@ use phoebus_core::CoreError; pub type Result = std::result::Result; +/// Heap-allocated command failure details. Kept on the heap so `ExecError` +/// stays small enough for `Result` to pass `result_large_err` +/// (128-byte threshold) without boxing at every call site. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CommandFailure { + pub stage: String, + pub operation: String, + pub program: String, + pub status: i32, + pub stdout: String, + pub stderr: String, +} + +impl std::fmt::Display for CommandFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "[{}] {} failed (exit {}): {}", + self.stage, self.operation, self.status, self.program + ) + } +} + #[derive(Debug, thiserror::Error)] pub enum ExecError { - #[error("[{stage}] {operation} failed (exit {status}): {program}")] - Command { - stage: String, - operation: String, - program: String, - status: i32, - stdout: String, - stderr: String, - }, + #[error("{0}")] + Command(Box), #[error("[{stage}] {operation}: {message}")] Operation { @@ -51,6 +67,17 @@ pub enum ExecError { } impl ExecError { + pub fn command(details: CommandFailure) -> Self { + ExecError::Command(Box::new(details)) + } + + pub fn command_details(&self) -> Option<&CommandFailure> { + match self { + ExecError::Command(details) => Some(details), + _ => None, + } + } + pub fn io(path: impl Into, source: std::io::Error) -> Self { ExecError::Io { path: path.into(), @@ -66,3 +93,54 @@ impl ExecError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_failure() -> CommandFailure { + CommandFailure { + stage: "storage_prepare".into(), + operation: "create GPT".into(), + program: "sgdisk".into(), + status: 2, + stdout: "partial output".into(), + stderr: "line1\nline2\nline3\nline4\nline5\nline6".into(), + } + } + + #[test] + fn command_error_text_preserves_stage_operation_status_and_program() { + let err = ExecError::command(sample_failure()); + assert_eq!( + err.to_string(), + "[storage_prepare] create GPT failed (exit 2): sgdisk" + ); + } + + #[test] + fn command_error_preserves_captured_stdout_and_stderr() { + let err = ExecError::command(sample_failure()); + let details = err.command_details().expect("command details"); + assert_eq!(details.stdout, "partial output"); + assert_eq!(details.stderr, "line1\nline2\nline3\nline4\nline5\nline6"); + assert_eq!(details.status, 2); + } + + #[test] + fn command_error_stays_small_enough_for_result_large_err() { + // Clippy's `result_large_err` fires at 128 bytes. The boxed details + // must keep the whole enum comfortably below that. + assert!( + std::mem::size_of::() <= 96, + "ExecError is {} bytes", + std::mem::size_of::() + ); + } + + #[test] + fn non_command_errors_have_no_command_details() { + let err = ExecError::operation("stage", "op", "message"); + assert!(err.command_details().is_none()); + } +} diff --git a/installer-rs/crates/phoebus-executor/src/exec.rs b/installer-rs/crates/phoebus-executor/src/exec.rs index 2ffc447..598d33b 100644 --- a/installer-rs/crates/phoebus-executor/src/exec.rs +++ b/installer-rs/crates/phoebus-executor/src/exec.rs @@ -61,15 +61,15 @@ impl Exec { stdin_hidden, ); let output = self.runner.execute(&spec)?; - self.logger.command( - &spec.stage, - &spec.operation, - &spec.program, - &spec.args, - output.status, - output.duration, + self.logger.command(crate::log::CommandRecord { + stage: &spec.stage, + operation: &spec.operation, + program: &spec.program, + args: &spec.args, + status: output.status, + duration: output.duration, stdin_hidden, - ); + }); if !self.runner.is_streaming() { if !output.stdout.is_empty() { self.logger.output(&output.stdout); @@ -79,14 +79,14 @@ impl Exec { } } if !output.success { - return Err(ExecError::Command { + return Err(ExecError::command(crate::error::CommandFailure { stage: spec.stage.clone(), operation: spec.operation.clone(), program: spec.program.clone(), status: output.status, stdout: self.redactor().redact(&output.stdout_lossy()), stderr: self.redactor().redact(&output.stderr_lossy()), - }); + })); } Ok(output) } diff --git a/installer-rs/crates/phoebus-executor/src/lib.rs b/installer-rs/crates/phoebus-executor/src/lib.rs index 90baaa2..83ae297 100644 --- a/installer-rs/crates/phoebus-executor/src/lib.rs +++ b/installer-rs/crates/phoebus-executor/src/lib.rs @@ -46,6 +46,6 @@ pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAut pub use command::{ CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner, }; -pub use error::{ExecError, Result}; +pub use error::{CommandFailure, ExecError, Result}; pub use exec::Exec; -pub use log::Logger; +pub use log::{CommandRecord, Logger}; diff --git a/installer-rs/crates/phoebus-executor/src/log.rs b/installer-rs/crates/phoebus-executor/src/log.rs index 594ea8c..cc111ed 100644 --- a/installer-rs/crates/phoebus-executor/src/log.rs +++ b/installer-rs/crates/phoebus-executor/src/log.rs @@ -35,6 +35,18 @@ use std::sync::Arc; pub type LogListener = Arc; +/// Parameters for [`Logger::command`], grouped so the call stays within the +/// argument-count lint while keeping every field explicit at the call site. +pub struct CommandRecord<'a> { + pub stage: &'a str, + pub operation: &'a str, + pub program: &'a str, + pub args: &'a [String], + pub status: i32, + pub duration: Duration, + pub stdin_hidden: bool, +} + struct LoggerInner { path: PathBuf, file: Mutex>, @@ -152,27 +164,22 @@ impl Logger { } /// Log a command with its exit status and duration (all redacted). - pub fn command( - &self, - stage: &str, - operation: &str, - program: &str, - args: &[String], - status: i32, - duration: Duration, - stdin_hidden: bool, - ) { - let mut line = format!("[{stage}] {operation} :: {program}"); - for arg in args { + pub fn command(&self, record: CommandRecord<'_>) { + let mut line = format!( + "[{}] {} :: {}", + record.stage, record.operation, record.program + ); + for arg in record.args { line.push(' '); line.push_str(&shell_quote(arg)); } - if stdin_hidden { + if record.stdin_hidden { line.push_str(" (stdin hidden)"); } line.push_str(&format!( - " :: exit {status} in {:.3}s", - duration.as_secs_f64() + " :: exit {} in {:.3}s", + record.status, + record.duration.as_secs_f64() )); self.write_line(Level::Info, &line); } @@ -284,15 +291,15 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("install.log"); let logger = Logger::open(&path, Redactor::new(), false); - logger.command( - "storage_prepare", - "create GPT", - "sgdisk", - &["--zap-all".into(), "/dev/vda".into()], - 0, - Duration::from_millis(12), - false, - ); + logger.command(CommandRecord { + stage: "storage_prepare", + operation: "create GPT", + program: "sgdisk", + args: &["--zap-all".into(), "/dev/vda".into()], + status: 0, + duration: Duration::from_millis(12), + stdin_hidden: false, + }); let text = std::fs::read_to_string(&path).unwrap(); assert!(text.contains("[storage_prepare] create GPT :: sgdisk")); assert!(text.contains("/dev/vda")); diff --git a/installer-rs/crates/phoebus-executor/src/update.rs b/installer-rs/crates/phoebus-executor/src/update.rs index e52cdb6..4fea69f 100644 --- a/installer-rs/crates/phoebus-executor/src/update.rs +++ b/installer-rs/crates/phoebus-executor/src/update.rs @@ -144,8 +144,8 @@ pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result String { match error { - ExecError::Command { stderr, .. } if !stderr.trim().is_empty() => { - let lines: Vec<&str> = stderr.lines().collect(); + ExecError::Command(details) if !details.stderr.trim().is_empty() => { + let lines: Vec<&str> = details.stderr.lines().collect(); let tail = lines[lines.len().saturating_sub(5)..].join("\n"); format!("{error}: {tail}") } @@ -422,7 +422,7 @@ mod tests { let exec = make_exec(runner); let root = Path::new(&exec.root); let err = prepare(&exec, root, 8, true).unwrap_err(); - assert!(matches!(err, ExecError::Command { .. })); + assert!(matches!(err, ExecError::Command(_))); let state = load_state(root); assert_eq!(state.status, PrepareStatus::Failed); assert!( diff --git a/installer-rs/crates/phoebus-installer/src/gui_bridge.rs b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs index 479b0ba..bd77a39 100644 --- a/installer-rs/crates/phoebus-installer/src/gui_bridge.rs +++ b/installer-rs/crates/phoebus-installer/src/gui_bridge.rs @@ -122,13 +122,13 @@ impl InstallObserver for JsonObserver { fn stage_started(&mut self, step: InstallStep) { self.last_stage.set(Some(step)); if step == InstallStep::StoragePrepare { - self.phase.set(DiskPhase::InStorage); + self.phase.set(DiskPhase::During); } self.emit(step, "started", None); } fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) { if step == InstallStep::StoragePrepare && error.is_none() { - self.phase.set(DiskPhase::AfterStorage); + self.phase.set(DiskPhase::After); } self.emit( step, @@ -199,7 +199,7 @@ impl Bridge { opencode_password: None, approved_digest: None, validated_ai: None, - phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), + phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::Before)), last_stage: std::rc::Rc::new(std::cell::Cell::new(None)), installing: false, installed: false, @@ -218,7 +218,7 @@ impl Bridge { opencode_password: None, approved_digest: None, validated_ai: None, - phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)), + phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::Before)), last_stage: std::rc::Rc::new(std::cell::Cell::new(None)), installing: false, installed: false, @@ -919,7 +919,7 @@ impl Bridge { }); self.installer.exec.logger.add_listener(log_listener); - self.phase.set(DiskPhase::BeforeStorage); + self.phase.set(DiskPhase::Before); // Consume the approval and mark the session busy before any destructive // work: a replay or a second frontend can never reach storage_prepare. self.approved_digest = None; @@ -1038,25 +1038,25 @@ fn contains_secret_marker(toml: &str) -> bool { /// disk changes occurred. Updated by the observer from the real stage order. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum DiskPhase { - BeforeStorage, - InStorage, - AfterStorage, + Before, + During, + After, } fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) { match phase { - DiskPhase::BeforeStorage => ( + DiskPhase::Before => ( "none", vec!["Review the installer log, then retry the installation."], ), - DiskPhase::InStorage => ( + DiskPhase::During => ( "partial", vec![ "The target disk may have been partially modified.", "Review the installer log before retrying.", ], ), - DiskPhase::AfterStorage => ( + DiskPhase::After => ( "yes", vec![ "The target disk was re-partitioned.",