refactor(executor): box ExecError command details, clear Clippy -D warnings gate

Box the CommandFailure payload so ExecError shrinks 128 -> 96 bytes and
Result<T, ExecError> 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).
This commit is contained in:
Phoebus 2026-09-25 18:26:08 -07:00
parent 7c5d4c5ca6
commit e69bfb9aef
7 changed files with 148 additions and 62 deletions

View file

@ -459,9 +459,10 @@ pub(crate) fn flatpak_update_transactions(
/// revision is the immutable identity and the tracking channel is the scope. /// revision is the immutable identity and the tracking channel is the scope.
pub(crate) fn parse_snap_transactions(refresh: &str, installed: &str) -> Vec<UpdateTransaction> { pub(crate) fn parse_snap_transactions(refresh: &str, installed: &str) -> Vec<UpdateTransaction> {
use std::collections::BTreeMap; use std::collections::BTreeMap;
/// Installed snap entry: (version, revision, tracking, notes).
type InstalledSnapEntry = (Option<String>, Option<String>, Option<String>, String);
// name -> (version, revision, tracking, notes) // name -> (version, revision, tracking, notes)
let mut current: BTreeMap<String, (Option<String>, Option<String>, Option<String>, String)> = let mut current: BTreeMap<String, InstalledSnapEntry> = BTreeMap::new();
BTreeMap::new();
for line in installed.lines().skip(1) { for line in installed.lines().skip(1) {
let cols: Vec<&str> = line.split_whitespace().collect(); let cols: Vec<&str> = line.split_whitespace().collect();
if cols.len() < 4 || cols[0].is_empty() { 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), Path::new(&exec.root),
) )
.unwrap_err(); .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 // The mutation must not run, and no snapshot may be recorded as
// committed when creation failed. // committed when creation failed.
assert!(!runner.programs().iter().any(|p| p == "emerge")); assert!(!runner.programs().iter().any(|p| p == "emerge"));

View file

@ -7,17 +7,33 @@ use phoebus_core::CoreError;
pub type Result<T> = std::result::Result<T, ExecError>; pub type Result<T> = std::result::Result<T, ExecError>;
/// Heap-allocated command failure details. Kept on the heap so `ExecError`
/// stays small enough for `Result<T, ExecError>` 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)] #[derive(Debug, thiserror::Error)]
pub enum ExecError { pub enum ExecError {
#[error("[{stage}] {operation} failed (exit {status}): {program}")] #[error("{0}")]
Command { Command(Box<CommandFailure>),
stage: String,
operation: String,
program: String,
status: i32,
stdout: String,
stderr: String,
},
#[error("[{stage}] {operation}: {message}")] #[error("[{stage}] {operation}: {message}")]
Operation { Operation {
@ -51,6 +67,17 @@ pub enum ExecError {
} }
impl 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<PathBuf>, source: std::io::Error) -> Self { pub fn io(path: impl Into<PathBuf>, source: std::io::Error) -> Self {
ExecError::Io { ExecError::Io {
path: path.into(), 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::<ExecError>() <= 96,
"ExecError is {} bytes",
std::mem::size_of::<ExecError>()
);
}
#[test]
fn non_command_errors_have_no_command_details() {
let err = ExecError::operation("stage", "op", "message");
assert!(err.command_details().is_none());
}
}

View file

@ -61,15 +61,15 @@ impl Exec {
stdin_hidden, stdin_hidden,
); );
let output = self.runner.execute(&spec)?; let output = self.runner.execute(&spec)?;
self.logger.command( self.logger.command(crate::log::CommandRecord {
&spec.stage, stage: &spec.stage,
&spec.operation, operation: &spec.operation,
&spec.program, program: &spec.program,
&spec.args, args: &spec.args,
output.status, status: output.status,
output.duration, duration: output.duration,
stdin_hidden, stdin_hidden,
); });
if !self.runner.is_streaming() { if !self.runner.is_streaming() {
if !output.stdout.is_empty() { if !output.stdout.is_empty() {
self.logger.output(&output.stdout); self.logger.output(&output.stdout);
@ -79,14 +79,14 @@ impl Exec {
} }
} }
if !output.success { if !output.success {
return Err(ExecError::Command { return Err(ExecError::command(crate::error::CommandFailure {
stage: spec.stage.clone(), stage: spec.stage.clone(),
operation: spec.operation.clone(), operation: spec.operation.clone(),
program: spec.program.clone(), program: spec.program.clone(),
status: output.status, status: output.status,
stdout: self.redactor().redact(&output.stdout_lossy()), stdout: self.redactor().redact(&output.stdout_lossy()),
stderr: self.redactor().redact(&output.stderr_lossy()), stderr: self.redactor().redact(&output.stderr_lossy()),
}); }));
} }
Ok(output) Ok(output)
} }

View file

@ -46,6 +46,6 @@ pub use auth::{authorize, AutoConfirm, Confirmation, DenyConfirm, DestructiveAut
pub use command::{ pub use command::{
CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner, CommandOutput, CommandSpec, NeverRunner, ProcessRunner, RealRunner, RecordingRunner,
}; };
pub use error::{ExecError, Result}; pub use error::{CommandFailure, ExecError, Result};
pub use exec::Exec; pub use exec::Exec;
pub use log::Logger; pub use log::{CommandRecord, Logger};

View file

@ -35,6 +35,18 @@ use std::sync::Arc;
pub type LogListener = Arc<dyn Fn(&str) + Send + Sync>; pub type LogListener = Arc<dyn Fn(&str) + Send + Sync>;
/// 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 { struct LoggerInner {
path: PathBuf, path: PathBuf,
file: Mutex<Option<File>>, file: Mutex<Option<File>>,
@ -152,27 +164,22 @@ impl Logger {
} }
/// Log a command with its exit status and duration (all redacted). /// Log a command with its exit status and duration (all redacted).
pub fn command( pub fn command(&self, record: CommandRecord<'_>) {
&self, let mut line = format!(
stage: &str, "[{}] {} :: {}",
operation: &str, record.stage, record.operation, record.program
program: &str, );
args: &[String], for arg in record.args {
status: i32,
duration: Duration,
stdin_hidden: bool,
) {
let mut line = format!("[{stage}] {operation} :: {program}");
for arg in args {
line.push(' '); line.push(' ');
line.push_str(&shell_quote(arg)); line.push_str(&shell_quote(arg));
} }
if stdin_hidden { if record.stdin_hidden {
line.push_str(" (stdin hidden)"); line.push_str(" (stdin hidden)");
} }
line.push_str(&format!( line.push_str(&format!(
" :: exit {status} in {:.3}s", " :: exit {} in {:.3}s",
duration.as_secs_f64() record.status,
record.duration.as_secs_f64()
)); ));
self.write_line(Level::Info, &line); self.write_line(Level::Info, &line);
} }
@ -284,15 +291,15 @@ mod tests {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("install.log"); let path = dir.path().join("install.log");
let logger = Logger::open(&path, Redactor::new(), false); let logger = Logger::open(&path, Redactor::new(), false);
logger.command( logger.command(CommandRecord {
"storage_prepare", stage: "storage_prepare",
"create GPT", operation: "create GPT",
"sgdisk", program: "sgdisk",
&["--zap-all".into(), "/dev/vda".into()], args: &["--zap-all".into(), "/dev/vda".into()],
0, status: 0,
Duration::from_millis(12), duration: Duration::from_millis(12),
false, stdin_hidden: false,
); });
let text = std::fs::read_to_string(&path).unwrap(); let text = std::fs::read_to_string(&path).unwrap();
assert!(text.contains("[storage_prepare] create GPT :: sgdisk")); assert!(text.contains("[storage_prepare] create GPT :: sgdisk"));
assert!(text.contains("/dev/vda")); assert!(text.contains("/dev/vda"));

View file

@ -144,8 +144,8 @@ pub fn prepare(exec: &Exec, root: &Path, cores: u32, force: bool) -> Result<Prep
/// explains *why* preparation failed instead of only the exit status. /// explains *why* preparation failed instead of only the exit status.
fn describe_failure(error: &ExecError) -> String { fn describe_failure(error: &ExecError) -> String {
match error { match error {
ExecError::Command { stderr, .. } if !stderr.trim().is_empty() => { ExecError::Command(details) if !details.stderr.trim().is_empty() => {
let lines: Vec<&str> = stderr.lines().collect(); let lines: Vec<&str> = details.stderr.lines().collect();
let tail = lines[lines.len().saturating_sub(5)..].join("\n"); let tail = lines[lines.len().saturating_sub(5)..].join("\n");
format!("{error}: {tail}") format!("{error}: {tail}")
} }
@ -422,7 +422,7 @@ mod tests {
let exec = make_exec(runner); let exec = make_exec(runner);
let root = Path::new(&exec.root); let root = Path::new(&exec.root);
let err = prepare(&exec, root, 8, true).unwrap_err(); let err = prepare(&exec, root, 8, true).unwrap_err();
assert!(matches!(err, ExecError::Command { .. })); assert!(matches!(err, ExecError::Command(_)));
let state = load_state(root); let state = load_state(root);
assert_eq!(state.status, PrepareStatus::Failed); assert_eq!(state.status, PrepareStatus::Failed);
assert!( assert!(

View file

@ -122,13 +122,13 @@ impl InstallObserver for JsonObserver {
fn stage_started(&mut self, step: InstallStep) { fn stage_started(&mut self, step: InstallStep) {
self.last_stage.set(Some(step)); self.last_stage.set(Some(step));
if step == InstallStep::StoragePrepare { if step == InstallStep::StoragePrepare {
self.phase.set(DiskPhase::InStorage); self.phase.set(DiskPhase::During);
} }
self.emit(step, "started", None); self.emit(step, "started", None);
} }
fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) { fn stage_finished(&mut self, step: InstallStep, error: Option<&str>) {
if step == InstallStep::StoragePrepare && error.is_none() { if step == InstallStep::StoragePrepare && error.is_none() {
self.phase.set(DiskPhase::AfterStorage); self.phase.set(DiskPhase::After);
} }
self.emit( self.emit(
step, step,
@ -199,7 +199,7 @@ impl Bridge {
opencode_password: None, opencode_password: None,
approved_digest: None, approved_digest: None,
validated_ai: 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)), last_stage: std::rc::Rc::new(std::cell::Cell::new(None)),
installing: false, installing: false,
installed: false, installed: false,
@ -218,7 +218,7 @@ impl Bridge {
opencode_password: None, opencode_password: None,
approved_digest: None, approved_digest: None,
validated_ai: 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)), last_stage: std::rc::Rc::new(std::cell::Cell::new(None)),
installing: false, installing: false,
installed: false, installed: false,
@ -919,7 +919,7 @@ impl Bridge {
}); });
self.installer.exec.logger.add_listener(log_listener); 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 // Consume the approval and mark the session busy before any destructive
// work: a replay or a second frontend can never reach storage_prepare. // work: a replay or a second frontend can never reach storage_prepare.
self.approved_digest = None; 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. /// disk changes occurred. Updated by the observer from the real stage order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DiskPhase { enum DiskPhase {
BeforeStorage, Before,
InStorage, During,
AfterStorage, After,
} }
fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) { fn disk_change_report(phase: DiskPhase) -> (&'static str, Vec<&'static str>) {
match phase { match phase {
DiskPhase::BeforeStorage => ( DiskPhase::Before => (
"none", "none",
vec!["Review the installer log, then retry the installation."], vec!["Review the installer log, then retry the installation."],
), ),
DiskPhase::InStorage => ( DiskPhase::During => (
"partial", "partial",
vec![ vec![
"The target disk may have been partially modified.", "The target disk may have been partially modified.",
"Review the installer log before retrying.", "Review the installer log before retrying.",
], ],
), ),
DiskPhase::AfterStorage => ( DiskPhase::After => (
"yes", "yes",
vec![ vec![
"The target disk was re-partitioned.", "The target disk was re-partitioned.",