From 5553ce6f1de317bfe6b12025338d9da8664d628d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 22:42:04 +0800 Subject: [PATCH 1/2] refactor(vt): make leaf reporting and summary outcomes exhaustive Replace the flattened 3-argument LeafExecutionReporter::finish signature, CacheUpdateStatus/Option tuple, and 6 coupled fields on summary::SpawnOutcome::Success with exhaustive enums (LeafOutcome, CacheUpdateOutcome, and SavedCacheOutcome) so invalid pairings are unrepresentable. Co-authored-by: Gemini 4 Neon --- crates/vt/src/session/event.rs | 71 +- crates/vt/src/session/execute/cache_update.rs | 75 +- crates/vt/src/session/execute/mod.rs | 184 ++--- crates/vt/src/session/execute/scheduler.rs | 20 +- crates/vt/src/session/mod.rs | 16 +- crates/vt/src/session/reporter/grouped/mod.rs | 26 +- .../src/session/reporter/interleaved/mod.rs | 33 +- crates/vt/src/session/reporter/json/mod.rs | 47 +- crates/vt/src/session/reporter/labeled/mod.rs | 25 +- crates/vt/src/session/reporter/mod.rs | 18 +- crates/vt/src/session/reporter/plain.rs | 60 +- crates/vt/src/session/reporter/summary.rs | 705 +++++++++++------- .../src/session/reporter/summary_reporter.rs | 77 +- 13 files changed, 757 insertions(+), 600 deletions(-) diff --git a/crates/vt/src/session/event.rs b/crates/vt/src/session/event.rs index ff1818e2a..d394ec5ca 100644 --- a/crates/vt/src/session/event.rs +++ b/crates/vt/src/session/event.rs @@ -1,4 +1,5 @@ use std::{ + num::NonZeroI32, process::ExitStatus, sync::{Arc, OnceLock}, time::Duration, @@ -84,17 +85,11 @@ pub enum CacheDisabledReason { NoCacheMetadata, } +/// Why the cache was not updated after a spawned process exited with status 0. #[derive(Debug)] pub enum CacheNotUpdatedReason { - /// Cache was hit - task was replayed from cache, no update needed - CacheHit, - /// A dry run (`vp run --dry-run`) checked the cache without running the - /// command. - DryRun, - /// Caching was disabled for this task + /// Caching was disabled for this task. CacheDisabled, - /// Execution exited with non-zero status - NonZeroExitStatus, /// Execution was cancelled before the result could be trusted. /// Two possible causes: /// - Ctrl-C: the user interrupted execution; the task may have @@ -103,8 +98,8 @@ pub enum CacheNotUpdatedReason { /// while this task was still running. Cancelled, /// fspy isn't compiled in on this build and the task requires fspy - /// (its `input` config includes auto-inference). Task ran but cannot - /// be cached without tracked path accesses. + /// (its `input` or `output` config includes auto-inference). Task ran but + /// cannot be cached without tracked path accesses. FspyUnsupported, /// The runner's IPC server failed during execution, so the collected /// reports may be incomplete. Caching such a run would risk stale @@ -124,9 +119,11 @@ pub enum CacheNotUpdatedReason { TrackingIncomplete, } +/// Outcome of the post-run cache update after a spawned process exited with +/// status 0. #[derive(Debug)] -pub enum CacheUpdateStatus { - /// Cache was successfully updated with new fingerprint and outputs +pub enum CacheUpdateOutcome { + /// Cache was successfully updated with new fingerprint and outputs. Updated { /// Why uploading the entry to the remote cache failed. It's set only /// if the upload fails, which can happen in the background after the @@ -136,10 +133,38 @@ pub enum CacheUpdateStatus { /// returns. upload_error: Arc>, }, - /// Cache was not updated (with reason). - /// The reason is part of the `LeafExecutionReporter` trait contract — reporters - /// can use it for detailed logging, even if current implementations don't. + /// Cache was not updated for a non-error reason. NotUpdated(CacheNotUpdatedReason), + /// Updating the cache failed with an infrastructure error (post-run + /// fingerprint creation, output archiving, or writing the cache entry). + Failed(ExecutionError), +} + +/// Final outcome of a single leaf execution, passed to +/// [`LeafExecutionReporter::finish`](super::reporter::LeafExecutionReporter::finish). +/// +/// Each variant carries only the data valid for that outcome, so invalid +/// combinations (such as an execution error paired with a cache update, or a +/// cache update on a non-zero exit) are unrepresentable. +#[derive(Debug)] +pub enum LeafOutcome { + /// An infrastructure error prevented the process from running, prevented + /// observing it to completion, or prevented restoring a cache hit's outputs. + Failed(ExecutionError), + /// Cache hit: no process ran. Captured outputs were replayed, except in a + /// dry run. + CacheHit, + /// In a dry run, a miss or a task without caching: nothing ran. + WouldSpawn, + /// An in-process (built-in) command completed (or was skipped in a dry run). + InProcess, + /// The spawned process exited with status 0. + SpawnedSuccess { cache_update: CacheUpdateOutcome }, + /// The spawned process exited with a non-zero status; the cache is never + /// updated. + SpawnedFailed { exit_code: NonZeroI32 }, + /// The run was cancelled before the process started. + Cancelled, } /// Whether a run runs its commands, or is a dry run (`vp run --dry-run`), @@ -164,20 +189,22 @@ pub enum CacheStatus { }, } -/// Convert `ExitStatus` to an i32 exit code. -/// On Unix, if terminated by signal, returns 128 + `signal_number`. -pub fn exit_status_to_code(status: ExitStatus) -> i32 { +/// Convert a non-success `ExitStatus` to a non-zero exit code. +/// On Unix, if terminated by signal, returns `128 + signal_number`. +/// Falls back to `1` if the OS reports neither a non-zero code nor a signal. +pub fn non_zero_exit_code(status: ExitStatus) -> NonZeroI32 { #[cfg(unix)] - { + let code = { use std::os::unix::process::ExitStatusExt; status.code().unwrap_or_else(|| { // Process was terminated by signal, use Unix convention: 128 + signal status.signal().map_or(1, |sig| 128 + sig) }) - } + }; #[cfg(not(unix))] - { + let code = { // Windows always has an exit code status.code().unwrap_or(1) - } + }; + NonZeroI32::new(code).unwrap_or(const { NonZeroI32::new(1).unwrap() }) } diff --git a/crates/vt/src/session/execute/cache_update.rs b/crates/vt/src/session/execute/cache_update.rs index 95ddb7738..5f084ce67 100644 --- a/crates/vt/src/session/execute/cache_update.rs +++ b/crates/vt/src/session/execute/cache_update.rs @@ -21,13 +21,12 @@ use super::{ glob, ignored_paths::relative_cache_root, rebuildable::Rebuildable, - spawn::ChildOutcome, }; use crate::{ collections::HashMap, session::{ cache::{CacheEntryValue, ExecutionCache, archive}, - event::{CacheErrorKind, CacheNotUpdatedReason, CacheUpdateStatus, ExecutionError}, + event::{CacheErrorKind, CacheNotUpdatedReason, CacheUpdateOutcome, ExecutionError}, }, }; @@ -53,27 +52,30 @@ struct TrackingOutcome { type TrackedEnvValues = BTreeMap>; type TrackedEnvQueryValues = BTreeMap>; -/// Decide whether the finished run may be cached, and store it if so. +/// Decide whether a finished, exit-0 spawn may be cached, and store it if so. /// -/// Every outcome returns a `(status, error)` pair for the caller's single -/// `finish()` call; this function never reports by itself. The guard clauses -/// run in priority order — each names the reason the run is *not* cached, and -/// only a run that passes them all is stored. A run cancelled by Ctrl-C or -/// fast-fail (`cancel_token`) isn't cached. -#[expect( - clippy::too_many_arguments, - reason = "the run's full context is genuinely needed to decide and store the cache entry" +/// Returns a single [`CacheUpdateOutcome`] for the caller's `finish()` call; +/// this function never reports by itself. The guard clauses run in priority +/// order — each names the reason the run is *not* cached, and only a run that +/// passes them all is stored. A run cancelled by Ctrl-C or fast-fail +/// (`cancel_token`) isn't cached. +#[cfg_attr( + fspy, + expect( + clippy::too_many_arguments, + reason = "the run's full context is genuinely needed to decide and store the cache entry" + ) )] pub(super) async fn update_cache( cache: &ExecutionCache, workspace_root: &Arc, cache_dir: &AbsolutePath, state: CacheState<'_>, - outcome: &ChildOutcome, + #[cfg(fspy)] path_accesses: Option<&Result>, reports: Option<&Reports>, duration: Duration, cancel_token: &CancellationToken, -) -> (CacheUpdateStatus, Option) { +) -> CacheUpdateOutcome { let CacheState { metadata, globbed_inputs, std_outputs, tracking } = state; let fspy = tracking.fspy.as_ref(); @@ -82,7 +84,7 @@ pub(super) async fn update_cache( { // A runner-aware tool short-circuited caching via `disableCache()` // (e.g. a dev server with no deterministic output). - return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::ToolRequested), None); + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::ToolRequested); } // Tool-reported paths to exclude from auto input tracking. Absolute paths @@ -96,12 +98,7 @@ pub(super) async fn update_cache( if cancel_token.is_cancelled() { // Cancelled (Ctrl-C or sibling failure) — result is untrustworthy. - return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::Cancelled), None); - } - - if !outcome.exit_status.success() { - // Execution failed with non-zero exit status — don't update cache. - return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::NonZeroExitStatus), None); + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::Cancelled); } // The accesses, or `None` when the task was not tracked at all. An @@ -109,8 +106,8 @@ pub(super) async fn update_cache( // arrived is a subset of what it touched, and an entry // built from a subset would replay with inputs and outputs missing. #[cfg(fspy)] - let Ok(path_accesses) = outcome.path_accesses.as_ref().map(Result::as_ref).transpose() else { - return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete), None); + let Ok(path_accesses) = path_accesses.map(Result::as_ref).transpose() else { + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete); }; // Every schema version's folder is in the task cache, not only this one. @@ -131,7 +128,7 @@ pub(super) async fn update_cache( // Task requested fspy auto-inference but this binary was built without // `cfg(fspy)`. Task ran, but we can't compute a valid cache entry // without tracked path accesses. - return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::FspyUnsupported), None); + return CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::FspyUnsupported); } // Collect tool-reported tracked envs for the post-run fingerprint. Env @@ -139,12 +136,7 @@ pub(super) async fn update_cache( // are already part of the spawn fingerprint. let (tracked_envs, tracked_env_queries) = match collect_tracked_reports(reports, metadata) { Ok(tracked_reports) => tracked_reports, - Err(err) => { - return ( - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - Some(ExecutionError::PostRunFingerprint(err)), - ); - } + Err(err) => return CacheUpdateOutcome::Failed(ExecutionError::PostRunFingerprint(err)), }; // Paths already in globbed_inputs are skipped: they are hashed before @@ -168,12 +160,7 @@ pub(super) async fn update_cache( tracked_env_queries, ) { Ok(fingerprint) => fingerprint, - Err(err) => { - return ( - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - Some(ExecutionError::PostRunFingerprint(err)), - ); - } + Err(err) => return CacheUpdateOutcome::Failed(ExecutionError::PostRunFingerprint(err)), }; let output_archive = match collect_and_archive_outputs( @@ -184,10 +171,10 @@ pub(super) async fn update_cache( ) { Ok(archive) => archive, Err(err) => { - return ( - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - Some(ExecutionError::Cache { kind: CacheErrorKind::Update, source: err }), - ); + return CacheUpdateOutcome::Failed(ExecutionError::Cache { + kind: CacheErrorKind::Update, + source: err, + }); } }; @@ -199,11 +186,11 @@ pub(super) async fn update_cache( output_archive, }; match cache.update(metadata, new_cache_value, cache_dir).await { - Ok(upload_error) => (CacheUpdateStatus::Updated { upload_error }, None), - Err(err) => ( - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - Some(ExecutionError::Cache { kind: CacheErrorKind::Update, source: err }), - ), + Ok(upload_error) => CacheUpdateOutcome::Updated { upload_error }, + Err(err) => CacheUpdateOutcome::Failed(ExecutionError::Cache { + kind: CacheErrorKind::Update, + source: err, + }), } } diff --git a/crates/vt/src/session/execute/mod.rs b/crates/vt/src/session/execute/mod.rs index 702893061..4395bf33d 100644 --- a/crates/vt/src/session/execute/mod.rs +++ b/crates/vt/src/session/execute/mod.rs @@ -16,6 +16,7 @@ mod win_job; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, + num::NonZeroI32, sync::Arc, time::Instant, }; @@ -36,8 +37,8 @@ use self::{ use super::{ cache::{CacheHit, CacheHitSource, CacheMiss, ExecutionCache, FileCheck, run_off_thread}, event::{ - CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason, CacheStatus, CacheUpdateStatus, - ExecutionError, RunKind, + CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason, CacheStatus, + CacheUpdateOutcome, ExecutionError, LeafOutcome, RunKind, non_zero_exit_code, }, reporter::{LeafExecutionReporter, PipeWriters, StdioConfig, StdioSuggestion}, }; @@ -54,8 +55,10 @@ pub enum SpawnOutcome { /// In a dry run, the cache missed or is disabled, so a real run would /// spawn the process. Nothing was spawned. WouldSpawn, - /// Process was spawned and exited with this status. - Spawned(std::process::ExitStatus), + /// Process was spawned and exited with status 0. + SpawnedSuccess, + /// Process was spawned and exited with a non-zero exit code. + SpawnedFailed(NonZeroI32), /// An infrastructure error prevented the process from running /// (cache lookup failure or spawn failure). /// Already reported through the leaf reporter. @@ -263,82 +266,17 @@ impl<'a> ExecutionMode<'a> { } } -/// Everything the pipeline reports through the single -/// `LeafExecutionReporter::finish()` call at the end of [`execute_spawn`]. -/// -/// Phases construct a `Report` instead of reporting in place, so finishing — -/// which consumes the boxed reporter — happens in exactly one spot. Each -/// variant carries exactly the data its outcome can be accompanied by: -/// a failure always has an error and never an exit status, a cache hit has -/// neither, and a spawned process always has its exit status. Nonsense -/// pairings are unrepresentable. -enum Report { - /// An infrastructure error prevented the process from running (or from - /// being observed to completion). - Failed { cache_update: CacheUpdateStatus, error: ExecutionError }, - /// Cache hit: no process ran. Captured outputs were replayed, except in a - /// dry run. - CacheHit, - /// In a dry run, a miss or a task without caching: nothing ran. - WouldSpawn, - /// The process ran to completion; its exit status is reported regardless - /// of how the cache update went. - Spawned { - exit_status: std::process::ExitStatus, - cache_update: CacheUpdateStatus, - error: Option, - }, - /// The run was cancelled before the process started. - Cancelled, -} - -impl Report { - /// An infrastructure failure outside any cache-specific context. - const fn failed(error: ExecutionError) -> Self { - Self::Failed { - cache_update: CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - error, - } - } - - /// Perform the pipeline's single `finish()` call and yield the outcome - /// [`execute_spawn`] returns to its caller. - fn finish(self, reporter: Box) -> SpawnOutcome { - match self { - Self::Failed { cache_update, error } => { - reporter.finish(None, cache_update, Some(error)); - SpawnOutcome::Failed - } - Self::CacheHit => { - reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheHit), - None, - ); - SpawnOutcome::CacheHit - } - Self::WouldSpawn => { - reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::DryRun), - None, - ); - SpawnOutcome::WouldSpawn - } - Self::Spawned { exit_status, cache_update, error } => { - reporter.finish(Some(exit_status), cache_update, error); - SpawnOutcome::Spawned(exit_status) - } - // `start()` wasn't called, so the reporter shows and saves nothing. - Self::Cancelled => { - reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::Cancelled), - None, - ); - SpawnOutcome::Cancelled - } - } +/// Map a spawn pipeline's [`LeafOutcome`] to the [`SpawnOutcome`] returned by +/// [`execute_spawn`]. +fn spawn_outcome_of(outcome: &LeafOutcome) -> SpawnOutcome { + match outcome { + LeafOutcome::Failed(_) => SpawnOutcome::Failed, + LeafOutcome::CacheHit => SpawnOutcome::CacheHit, + LeafOutcome::WouldSpawn => SpawnOutcome::WouldSpawn, + LeafOutcome::SpawnedSuccess { .. } => SpawnOutcome::SpawnedSuccess, + LeafOutcome::SpawnedFailed { exit_code } => SpawnOutcome::SpawnedFailed(*exit_code), + LeafOutcome::Cancelled => SpawnOutcome::Cancelled, + LeafOutcome::InProcess => unreachable!("execute_spawn only runs spawned processes"), } } @@ -399,19 +337,21 @@ pub async fn execute_spawn( fast_fail_token, cancel_token, ); - let report = match pipeline.await { - Ok(report) | Err(report) => report, + let outcome = match pipeline.await { + Ok(outcome) | Err(outcome) => outcome, }; - report.finish(leaf_reporter) + let spawn_outcome = spawn_outcome_of(&outcome); + leaf_reporter.finish(outcome); + spawn_outcome } /// The spawn pipeline. /// -/// Both sides of the `Result` carry the same [`Report`] on purpose: `Err` is -/// the `?`-short-circuit channel for phases that already determined the final -/// report, `Ok` is the report of a pipeline that ran to the end. The caller -/// unwraps both into the same single `finish()`, so the distinction is pure -/// control flow and a value on either side is equally valid. +/// Both sides of the `Result` carry the same [`LeafOutcome`] on purpose: `Err` +/// is the `?`-short-circuit channel for phases that already determined the +/// final outcome, `Ok` is the outcome of a pipeline that ran to the end. The +/// caller unwraps both into the same single `finish()`, so the distinction is +/// pure control flow and a value on either side is equally valid. #[expect(clippy::too_many_arguments, reason = "forwarded verbatim from `execute_spawn`")] #[expect(clippy::too_many_lines, reason = "the phases of one spawn, in order")] async fn run( @@ -425,7 +365,7 @@ async fn run( file_check: FileCheck, fast_fail_token: CancellationToken, cancel_token: CancellationToken, -) -> Result { +) -> Result { let cache_metadata = spawn_execution.cache_metadata.as_ref(); // 1. Determine cache status FIRST by trying cache hit, so the reporter can @@ -444,7 +384,7 @@ async fn run( ) .await?; if cancel_token.is_cancelled() { - return Err(Report::Cancelled); + return Err(LeafOutcome::Cancelled); } // 2. Report execution start with the looked-up cache status (`start()` @@ -459,7 +399,7 @@ async fn run( baseline: hit.baseline.clone(), }); if run_kind == RunKind::Dry { - return Ok(Report::CacheHit); + return Ok(LeafOutcome::CacheHit); } return Ok(replay_cache_hit( &mut stdio_config, @@ -481,12 +421,12 @@ async fn run( ), }; if run_kind == RunKind::Dry { - return Ok(Report::WouldSpawn); + return Ok(LeafOutcome::WouldSpawn); } // 4. Fold the cache/fspy/stdio decisions into the typed mode. let mut mode = ExecutionMode::build(cache_metadata, stdio_config, globbed_inputs) - .map_err(Report::failed)?; + .map_err(LeafOutcome::Failed)?; // Measure end-to-end duration here — spawn() doesn't track time. let start = Instant::now(); @@ -502,7 +442,7 @@ async fn run( mode.injected_envs(), ) .await - .map_err(|err| Report::failed(ExecutionError::Spawn(err)))?; + .map_err(|err| LeafOutcome::Failed(ExecutionError::Spawn(err)))?; tracing::debug!(fspy = fspy_enabled, elapsed = ?start.elapsed(), "spawned the task process"); // 6. Drain the pipes and wait for exit, concurrently with the IPC driver. @@ -527,9 +467,16 @@ async fn run( let child_work = Box::pin(run_child(child, sinks, None, fast_fail_token.clone())); (child_work.await, None) }; - let outcome = wait_result.map_err(Report::failed)?; + let outcome = wait_result.map_err(LeafOutcome::Failed)?; let duration = start.elapsed(); + // Non-zero exit: cache is never updated. + if !outcome.exit_status.success() { + return Ok(LeafOutcome::SpawnedFailed { + exit_code: non_zero_exit_code(outcome.exit_status), + }); + } + // Extract reports, or short-circuit when the IPC server failed. An Err // here means reports may be incomplete: caching this run would risk // stale inputs/outputs, so skip all cache-related computation entirely. @@ -540,27 +487,26 @@ async fn run( } None => None, Some(Err(err)) => { - return Err(Report::Spawned { - exit_status: outcome.exit_status, - cache_update: CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::IpcServerError( - err, - )), - error: None, + return Ok(LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::NotUpdated( + CacheNotUpdatedReason::IpcServerError(err), + ), }); } }; // 7. Decide the cache update (only when we were in `Cached` mode). Cache // update errors are reported but do not affect the exit status we - // return — the process ran, so we return its actual status. - let (cache_update, error) = match mode { + // return — the process exited 0, so we still report `SpawnedSuccess`. + let cache_update = match mode { ExecutionMode::Cached { state, .. } => { cache_update::update_cache( cache, workspace_root, cache_dir, state, - &outcome, + #[cfg(fspy)] + outcome.path_accesses.as_ref(), reports.as_ref(), duration, &cancel_token, @@ -569,11 +515,11 @@ async fn run( } ExecutionMode::Uncached { .. } => { // Caching was disabled for this task. - (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), None) + CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::CacheDisabled) } }; - Ok(Report::Spawned { exit_status: outcome.exit_status, cache_update, error }) + Ok(LeafOutcome::SpawnedSuccess { cache_update }) } /// Outcome of the cache-lookup phase. Each variant carries exactly what that @@ -595,7 +541,7 @@ enum CacheLookup<'a> { /// downloads its output archive into `cache_dir`, except in a dry run. The /// inputs are hashed, and entries checked, off the scheduler's thread (see /// [`run_off_thread`]). The lookup stops when `cancel_token` is cancelled, and -/// is then [`Report::Cancelled`] or a miss that isn't reported. +/// is then [`LeafOutcome::Cancelled`] or a miss that isn't reported. async fn lookup_cache<'a>( cache_metadata: Option<&'a CacheMetadata>, cache: &ExecutionCache, @@ -604,7 +550,7 @@ async fn lookup_cache<'a>( run_kind: RunKind, file_check: FileCheck, cancel_token: &CancellationToken, -) -> Result, Report> { +) -> Result, LeafOutcome> { let Some(cache_metadata) = cache_metadata else { return Ok(CacheLookup::Disabled); }; @@ -627,9 +573,9 @@ async fn lookup_cache<'a>( anyhow::Ok(globbed_inputs) }) .await - .ok_or(Report::Cancelled)?; + .ok_or(LeafOutcome::Cancelled)?; let globbed_inputs = Arc::new(hashed.map_err(|err| { - Report::failed(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err }) + LeafOutcome::Failed(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err }) })?); match cache @@ -650,10 +596,11 @@ async fn lookup_cache<'a>( Ok(Some(Err(miss))) => { Ok(CacheLookup::Miss { miss, globbed_inputs: Arc::unwrap_or_clone(globbed_inputs) }) } - Ok(None) => Err(Report::Cancelled), - Err(err) => { - Err(Report::failed(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err })) - } + Ok(None) => Err(LeafOutcome::Cancelled), + Err(err) => Err(LeafOutcome::Failed(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: err, + })), } } @@ -667,7 +614,7 @@ async fn replay_cache_hit( workspace_root: &Arc, cache_dir: &AbsolutePath, program_name: &str, -) -> Report { +) -> LeafOutcome { for output in hit.value.std_outputs.iter() { let writer: &mut dyn std::io::Write = match output.kind { pipe::OutputKind::StdOut => &mut stdio_config.writers.stdout_writer, @@ -690,13 +637,10 @@ async fn replay_cache_hit( ExecutionError::Cache { kind: CacheErrorKind::Restore, source: err } } }; - return Report::Failed { - cache_update: CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheHit), - error, - }; + return LeafOutcome::Failed(error); } - Report::CacheHit + LeafOutcome::CacheHit } /// Phase 6: drain the child's pipes (if piped) and wait for exit. A pipe diff --git a/crates/vt/src/session/execute/scheduler.rs b/crates/vt/src/session/execute/scheduler.rs index f58a36c4b..d514e00c4 100644 --- a/crates/vt/src/session/execute/scheduler.rs +++ b/crates/vt/src/session/execute/scheduler.rs @@ -21,9 +21,7 @@ use crate::{ Session, session::{ cache::{ExecutionCache, FileCheck}, - event::{ - CacheDisabledReason, CacheNotUpdatedReason, CacheStatus, CacheUpdateStatus, RunKind, - }, + event::{CacheDisabledReason, CacheStatus, LeafOutcome, RunKind}, reporter::{ExitStatus, GraphExecutionReporter, GraphExecutionReporterBuilder, LeafPath}, }, }; @@ -246,11 +244,7 @@ impl ExecutionContext<'_> { let _ = stdio_config.writers.stdout_writer.flush(); } - leaf_reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - None, - ); + leaf_reporter.finish(LeafOutcome::InProcess); false } LeafExecutionKind::Spawn(spawn_execution) => { @@ -268,11 +262,11 @@ impl ExecutionContext<'_> { ) .await; match outcome { - SpawnOutcome::CacheHit | SpawnOutcome::WouldSpawn | SpawnOutcome::Cancelled => { - false - } - SpawnOutcome::Spawned(status) => !status.success(), - SpawnOutcome::Failed => true, + SpawnOutcome::CacheHit + | SpawnOutcome::WouldSpawn + | SpawnOutcome::SpawnedSuccess + | SpawnOutcome::Cancelled => false, + SpawnOutcome::SpawnedFailed(_) | SpawnOutcome::Failed => true, } } }; diff --git a/crates/vt/src/session/mod.rs b/crates/vt/src/session/mod.rs index 3f94046c9..81b132922 100644 --- a/crates/vt/src/session/mod.rs +++ b/crates/vt/src/session/mod.rs @@ -791,21 +791,19 @@ impl<'a> Session<'a> { // summary, so it isn't told about the upload or its result. cache.wait_for_uploads(&tokio_util::sync::CancellationToken::new()).await; match outcome { - // Cache hit — no process was spawned, success. This is a real run, + // Cache hit or process exited 0 — success. This is a real run, // so nothing is `WouldSpawn`. - execute::SpawnOutcome::CacheHit | execute::SpawnOutcome::WouldSpawn => { - Ok(ExitStatus::SUCCESS) - } - // Process ran successfully - execute::SpawnOutcome::Spawned(status) if status.success() => Ok(ExitStatus::SUCCESS), + execute::SpawnOutcome::CacheHit + | execute::SpawnOutcome::WouldSpawn + | execute::SpawnOutcome::SpawnedSuccess => Ok(ExitStatus::SUCCESS), // Process ran but exited with non-zero status - execute::SpawnOutcome::Spawned(status) => { - let code = event::exit_status_to_code(status); + execute::SpawnOutcome::SpawnedFailed(code) => + { #[expect( clippy::cast_sign_loss, reason = "value is clamped to 1..=255, always positive" )] - Ok(ExitStatus(code.clamp(1, 255) as u8)) + Ok(ExitStatus(code.get().clamp(1, 255) as u8)) } // Infrastructure error — already reported through the reporter's finish(). // Nothing cancels the tokens above, and a cancelled command wouldn't have run. diff --git a/crates/vt/src/session/reporter/grouped/mod.rs b/crates/vt/src/session/reporter/grouped/mod.rs index 737499a97..06b5477fd 100644 --- a/crates/vt/src/session/reporter/grouped/mod.rs +++ b/crates/vt/src/session/reporter/grouped/mod.rs @@ -1,6 +1,6 @@ //! Grouped reporter — buffers output per task, prints as a block on completion. -use std::{cell::RefCell, io::Write, process::ExitStatus as StdExitStatus, rc::Rc, sync::Arc}; +use std::{cell::RefCell, io::Write, rc::Rc, sync::Arc}; use owo_colors::Style; use vt_path::AbsolutePath; @@ -12,7 +12,7 @@ use super::{ format_command_with_cache_status, format_task_label, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}; +use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; mod writer; @@ -127,12 +127,22 @@ impl LeafExecutionReporter for GroupedLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + let error = match outcome { + LeafOutcome::Failed(error) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { + Some(error) + } + LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => None, + }; + // Build grouped block: header + buffered output. let mut extra = Vec::new(); if let Some(ref grouped_buffer) = self.grouped_buffer { diff --git a/crates/vt/src/session/reporter/interleaved/mod.rs b/crates/vt/src/session/reporter/interleaved/mod.rs index 8358574b7..72f96bc1e 100644 --- a/crates/vt/src/session/reporter/interleaved/mod.rs +++ b/crates/vt/src/session/reporter/interleaved/mod.rs @@ -5,7 +5,7 @@ //! would do next (`, executing` or `, replaying`), and no blank line follows //! it. -use std::{cell::RefCell, io::Write, process::ExitStatus as StdExitStatus, rc::Rc, sync::Arc}; +use std::{cell::RefCell, io::Write, rc::Rc, sync::Arc}; use vt_path::AbsolutePath; use vt_plan::{ExecutionItemDisplay, LeafExecutionKind}; @@ -17,7 +17,7 @@ use super::{ StdioConfig, StdioSuggestion, format_command_display, format_command_with_cache_status, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}; +use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; pub struct InterleavedReporterBuilder { workspace_path: Arc, @@ -130,12 +130,21 @@ impl LeafExecutionReporter for InterleavedLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + let error = match outcome { + LeafOutcome::Failed(error) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { + Some(error) + } + LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => None, + }; let (command_line, blank_line) = match self.run_kind { RunKind::Real => (Str::default(), self.started), // A dry run prints only the commands' lines. An error that comes @@ -158,7 +167,7 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason}, + event::{CacheDisabledReason, CacheErrorKind, ExecutionError}, reporter::{ StdioSuggestion, test_fixtures::{SharedBuffer, in_process_task, spawn_task, test_path}, @@ -219,19 +228,17 @@ mod tests { RunKind::Dry, )) .build(); - let not_updated = || CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::DryRun); - let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); leaf.start(CacheStatus::Miss(CacheMiss::NotFound)); - leaf.finish(None, not_updated(), None); + leaf.finish(LeafOutcome::WouldSpawn); let leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); let error = ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("database is locked"), }; - leaf.finish(None, not_updated(), Some(error)); + leaf.finish(LeafOutcome::Failed(error)); reporter.finish().unwrap(); assert_eq!( diff --git a/crates/vt/src/session/reporter/json/mod.rs b/crates/vt/src/session/reporter/json/mod.rs index 047e001b3..4a8b908ea 100644 --- a/crates/vt/src/session/reporter/json/mod.rs +++ b/crates/vt/src/session/reporter/json/mod.rs @@ -6,10 +6,7 @@ mod document; -use std::{ - cell::RefCell, collections::BTreeMap, io::Write, process::ExitStatus as StdExitStatus, rc::Rc, - sync::Arc, time::Duration, -}; +use std::{cell::RefCell, collections::BTreeMap, io::Write, rc::Rc, sync::Arc, time::Duration}; use document::{ Baseline, Cache, Change, Changed, CommandStep, Fingerprint, Hit, HowChanged, NestedStep, @@ -33,7 +30,7 @@ use crate::session::{ self, BaselineDetails, BaselineOutputs, BaselinePath, CacheMiss, Comparison, InputChangeKind, }, - event::{CacheDisabledReason, CacheStatus, CacheUpdateStatus, ExecutionError}, + event::{CacheDisabledReason, CacheStatus, CacheUpdateOutcome, LeafOutcome}, json::{self, Version, path_key, task_id}, }; @@ -280,19 +277,25 @@ impl LeafExecutionReporter for JsonLeafReporter { /// /// A lookup cancelled by Ctrl-C has neither, and also leaves its step /// unreported. - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { - if let Some(error) = error { - let message = vt_str::format!("{:#}", anyhow::Error::from(error)); - let message = match self.location.as_ref().and_then(|location| location.last()) { - Some((id, _)) => vt_str::format!("{id}: {message}"), - None => message, - }; - self.state.borrow_mut().errors.push(message); + fn finish(self: Box, outcome: LeafOutcome) { + match outcome { + LeafOutcome::Failed(error) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { + let message = vt_str::format!("{:#}", anyhow::Error::from(error)); + let message = match self.location.as_ref().and_then(|location| location.last()) { + Some((id, _)) => vt_str::format!("{id}: {message}"), + None => message, + }; + self.state.borrow_mut().errors.push(message); + } + LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => {} } } } @@ -502,7 +505,7 @@ fn change_of(change: &cache::Change) -> Change { mod tests { use super::*; use crate::session::{ - event::{CacheErrorKind, CacheNotUpdatedReason}, + event::{CacheErrorKind, ExecutionError}, json, reporter::test_fixtures::{spawn_task, test_path}, }; @@ -532,11 +535,7 @@ mod tests { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("database is locked"), }; - leaf.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::DryRun), - Some(error), - ); + leaf.finish(LeafOutcome::Failed(error)); assert!(reporter.finish().is_err()); } diff --git a/crates/vt/src/session/reporter/labeled/mod.rs b/crates/vt/src/session/reporter/labeled/mod.rs index 22f1c75a7..c849c4e37 100644 --- a/crates/vt/src/session/reporter/labeled/mod.rs +++ b/crates/vt/src/session/reporter/labeled/mod.rs @@ -1,6 +1,6 @@ //! Labeled reporter — prefixes each output line with `[pkg#task]`. -use std::{cell::RefCell, io::Write, process::ExitStatus as StdExitStatus, rc::Rc, sync::Arc}; +use std::{cell::RefCell, io::Write, rc::Rc, sync::Arc}; use vt_path::AbsolutePath; use vt_plan::{ExecutionItemDisplay, LeafExecutionKind}; @@ -11,7 +11,7 @@ use super::{ format_command_with_cache_status, format_task_label, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}; +use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; mod writer; @@ -123,12 +123,21 @@ impl LeafExecutionReporter for LabeledLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + let error = match outcome { + LeafOutcome::Failed(error) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { + Some(error) + } + LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => None, + }; write_leaf_trailing_output(&self.writer, error, self.started, &[]); } } diff --git a/crates/vt/src/session/reporter/mod.rs b/crates/vt/src/session/reporter/mod.rs index 6c03c3d4a..46e6244f0 100644 --- a/crates/vt/src/session/reporter/mod.rs +++ b/crates/vt/src/session/reporter/mod.rs @@ -38,7 +38,7 @@ mod retrying_writer; pub mod summary; mod summary_reporter; -use std::{io::Write, num::NonZeroUsize, process::ExitStatus as StdExitStatus}; +use std::{io::Write, num::NonZeroUsize}; pub use grouped::GroupedReporterBuilder; pub use interleaved::InterleavedReporterBuilder; @@ -54,7 +54,7 @@ use vt_str::Str; use super::{ cache::format_cache_status_inline, - event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}, + event::{CacheStatus, ExecutionError, LeafOutcome, RunKind}, }; // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ @@ -216,20 +216,10 @@ pub trait LeafExecutionReporter { /// metadata (caching disabled). fn start(&mut self, cache_status: CacheStatus) -> StdioConfig; - /// Finalize this leaf execution. - /// - /// - `status`: The process exit status, or `None` for cache hits and in-process commands. - /// - `cache_update_status`: Whether the cache was updated after execution. - /// - `error`: If `Some`, an error occurred during this leaf's execution (cache lookup - /// failure, spawn failure, fingerprint creation failure, cache update failure). + /// Finalize this leaf execution with its typed [`LeafOutcome`]. /// /// This method consumes the reporter — no further calls are possible after `finish()`. - fn finish( - self: Box, - status: Option, - cache_update_status: CacheUpdateStatus, - error: Option, - ); + fn finish(self: Box, outcome: LeafOutcome); } // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ diff --git a/crates/vt/src/session/reporter/plain.rs b/crates/vt/src/session/reporter/plain.rs index b23d53268..d0586bc55 100644 --- a/crates/vt/src/session/reporter/plain.rs +++ b/crates/vt/src/session/reporter/plain.rs @@ -12,7 +12,7 @@ use super::{ // `maybe_strip_writer` is used for the child-process pipe writers; reporter // output decides colour-vs-plain at format time via the `ColorizeExt` helpers // in [`super`]. -use crate::session::event::{CacheStatus, CacheUpdateStatus, ExecutionError}; +use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome}; /// A self-contained [`LeafExecutionReporter`] for single-leaf executions /// (e.g., `execute_synthetic`). @@ -31,8 +31,6 @@ pub struct PlainReporter { /// When true, suppresses all output (command line, process output, cache hit message) /// for executions that are cache hits. silent_if_cache_hit: bool, - /// Whether the current execution is a cache hit, set by `start()`. - is_cache_hit: bool, /// Per-stream colour support — stdout decides stripping of the reporter's /// own writes and stdout-bound pipe output; stderr decides stripping of /// the stderr pipe writer (kept independent so a TTY stderr doesn't get @@ -51,18 +49,13 @@ impl PlainReporter { writer: Box, color_support: ColorSupport, ) -> Self { - Self { writer, silent_if_cache_hit, is_cache_hit: false, color_support } - } - - /// Returns true if output should be suppressed for this execution. - const fn is_silent(&self) -> bool { - self.silent_if_cache_hit && self.is_cache_hit + Self { writer, silent_if_cache_hit, color_support } } } impl LeafExecutionReporter for PlainReporter { fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { - self.is_cache_hit = matches!(cache_status, CacheStatus::Hit { .. }); + let is_cache_hit = matches!(cache_status, CacheStatus::Hit { .. }); // PlainReporter is used for single-leaf synthetic executions (e.g., auto-install). // Always suggest inherited stdio so the spawned process can be interactive. // PlainReporter has no display info (synthetic executions), @@ -72,7 +65,7 @@ impl LeafExecutionReporter for PlainReporter { // sink writers that discard output — the cache replay in execute_spawn // writes directly to these writers, so this is the reporter's only way // to suppress replayed output. - if self.silent_if_cache_hit && self.is_cache_hit { + if self.silent_if_cache_hit && is_cache_hit { StdioConfig { suggestion: StdioSuggestion::Inherited, writers: PipeWriters { @@ -97,26 +90,31 @@ impl LeafExecutionReporter for PlainReporter { } } - fn finish( - mut self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { - // Handle errors — format the full error chain and print inline. - if let Some(error) = error { - let message = vt_str::format!("{:#}", anyhow::Error::from(error)); - let line = format_error_message(&message); - let _ = self.writer.write_all(line.as_bytes()); - let _ = self.writer.flush(); - return; - } - - // For cache hits, print the "cache hit" message (unless silent) - if self.is_cache_hit && !self.is_silent() { - let line = format_cache_hit_message(); - let _ = self.writer.write_all(line.as_bytes()); - let _ = self.writer.flush(); + fn finish(mut self: Box, outcome: LeafOutcome) { + match outcome { + // Handle errors — format the full error chain and print inline. + LeafOutcome::Failed(error) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { + let message = vt_str::format!("{:#}", anyhow::Error::from(error)); + let line = format_error_message(&message); + let _ = self.writer.write_all(line.as_bytes()); + let _ = self.writer.flush(); + } + // For cache hits, print the "cache hit" message (unless silent). + LeafOutcome::CacheHit => { + if !self.silent_if_cache_hit { + let line = format_cache_hit_message(); + let _ = self.writer.write_all(line.as_bytes()); + let _ = self.writer.flush(); + } + } + LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => {} } } } diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index dac339713..95d42441c 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -27,7 +27,10 @@ use crate::session::{ BaselineDetails, BaselineOutputs, BaselinePath, CacheHitSource, CacheMiss, Change, InputChangeKind, format_change, }, - event::{CacheDisabledReason, CacheNotUpdatedReason, CacheStatus, CacheUpdateStatus, RunKind}, + event::{ + CacheDisabledReason, CacheNotUpdatedReason, CacheStatus, CacheUpdateOutcome, LeafOutcome, + RunKind, + }, }; // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ @@ -106,42 +109,63 @@ pub enum SpawnedCacheStatus { Disabled, } -/// Outcome of a spawned process. +/// Outcome of a spawned process (or a dry-run task that would spawn). #[derive(Serialize, Deserialize)] pub enum SpawnOutcome { - /// Process exited successfully (exit code 0). - /// May have a post-execution infrastructure error (cache update or fingerprint failed). - /// These only run after exit 0, so this field only exists on the success path. - Success { - infra_error: Option, - /// `true` when the task required fspy auto-inference but the binary was - /// built without `cfg(fspy)` (e.g., cross-compiled to an unsupported OS). - /// Task ran successfully but cache was not updated. - #[serde(default)] - fspy_unsupported: bool, - /// The IPC server error that caused the cache to be skipped, if any. - ipc_server_error: Option, - /// `true` when automatic file tracking could not record everything - /// the task did, so the inferred inputs and outputs were a subset of - /// what it touched. Task ran successfully but cache was not - /// updated. - #[serde(default)] - tracking_incomplete: bool, - /// Set when a runner-aware tool called `disableCache()`, skipping - /// cache update. - tool_disabled_cache: bool, - /// Why uploading the entry to the remote cache failed, if it did. - /// The local cache was still updated. - upload_error: Option, - }, + /// Process exited successfully (exit code 0), with its post-run cache + /// outcome. + Success(SavedCacheOutcome), /// Process exited with non-zero status. /// [`NonZeroI32`] enforces that exit code 0 is unrepresentable here. - /// No `infra_error` field: cache operations are skipped on non-zero exit. + /// Cache operations are skipped on non-zero exit. Failed { exit_code: NonZeroI32 }, /// Execution failed without a usable process exit status. SpawnError(SavedError), + + /// Dry run (`vp run --dry-run`): the cache was checked and a real run + /// would spawn the process, so nothing ran. + WouldSpawn, +} + +/// Post-run cache outcome for a spawned process that exited with status 0. +/// +/// Mutually exclusive outcomes cannot coexist, and `upload_error` only exists +/// when the local cache was updated. +#[derive(Serialize, Deserialize)] +pub enum SavedCacheOutcome { + /// Local cache was updated. May have a remote-cache upload error recorded + /// after background uploads finish. + Updated { + /// Why uploading the entry to the remote cache failed, if it did. + /// The local cache was still updated. + upload_error: Option, + }, + /// Cache was not updated for a non-error reason. + NotCached(SavedNotCachedReason), + /// Updating the cache failed with a post-run infrastructure error + /// (fingerprint creation, output archiving, or cache write). + Failed(SavedError), +} + +/// Why the cache was not updated after a successful spawned execution. +#[derive(Serialize, Deserialize)] +pub enum SavedNotCachedReason { + /// Caching was disabled for this task. + CacheDisabled, + /// Execution was cancelled before the result could be cached. + Cancelled, + /// The task required fspy auto-inference but the binary was built without + /// `cfg(fspy)` (e.g., cross-compiled to an unsupported OS). + FspyUnsupported, + /// The runner's IPC server failed during execution. + IpcServerError(SavedError), + /// Automatic file tracking could not record everything the task did, so + /// the inferred inputs and outputs were a subset of what it touched. + TrackingIncomplete, + /// A runner-aware tool called `disableCache()`, skipping cache update. + ToolRequested, } /// Why a cache miss occurred. @@ -228,16 +252,19 @@ impl SummaryStats { SpawnedCacheStatus::Disabled => stats.cache_disabled += 1, } match outcome { - SpawnOutcome::Success { infra_error: Some(_), .. } + SpawnOutcome::Success(SavedCacheOutcome::Failed(_)) | SpawnOutcome::Failed { .. } | SpawnOutcome::SpawnError(_) => stats.failed += 1, - SpawnOutcome::Success { .. } => {} - } - if let SpawnOutcome::Success { upload_error: Some(error), .. } = outcome { - stats.upload_failures.push(UploadFailure { - task_name: task.format_task_display(), - reason: error.message.clone(), - }); + SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error }) => { + if let Some(error) = upload_error { + stats.upload_failures.push(UploadFailure { + task_name: task.format_task_display(), + reason: error.message.clone(), + }); + } + } + SpawnOutcome::Success(SavedCacheOutcome::NotCached(_)) + | SpawnOutcome::WouldSpawn => {} } } } @@ -284,131 +311,110 @@ impl SavedCacheMissReason { } } +impl SavedCacheOutcome { + fn from_cache_update(cache_update: &CacheUpdateOutcome) -> Self { + match cache_update { + CacheUpdateOutcome::Updated { .. } => Self::Updated { upload_error: None }, + CacheUpdateOutcome::NotUpdated(reason) => { + Self::NotCached(SavedNotCachedReason::from_reason(reason)) + } + CacheUpdateOutcome::Failed(error) => Self::Failed(SavedError::new(error)), + } + } +} + +impl SavedNotCachedReason { + fn from_reason(reason: &CacheNotUpdatedReason) -> Self { + match reason { + CacheNotUpdatedReason::CacheDisabled => Self::CacheDisabled, + CacheNotUpdatedReason::Cancelled => Self::Cancelled, + CacheNotUpdatedReason::FspyUnsupported => Self::FspyUnsupported, + CacheNotUpdatedReason::IpcServerError(err) => { + Self::IpcServerError(SavedError::new(err)) + } + CacheNotUpdatedReason::ToolRequested => Self::ToolRequested, + CacheNotUpdatedReason::TrackingIncomplete => Self::TrackingIncomplete, + } + } +} + impl TaskResult { /// Build a [`TaskResult`] from live execution data. /// /// `cache_status`: the cache status determined at `start()` time. - /// `exit_status`: the process exit status, or `None` for cache hit / in-process. - /// `saved_error`: an optional pre-converted execution error. - /// `cache_update_status`: the post-execution cache update result. - pub fn from_execution( - cache_status: &CacheStatus, - exit_status: Option, - saved_error: Option<&SavedError>, - cache_update_status: &CacheUpdateStatus, - ) -> Self { - let fspy_unsupported = matches!( - cache_update_status, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::FspyUnsupported) - ); - let ipc_server_error = match cache_update_status { - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::IpcServerError(err)) => { - Some(SavedError::new(err)) - } - _ => None, - }; - let tool_disabled_cache = matches!( - cache_update_status, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::ToolRequested) - ); - let tracking_incomplete = matches!( - cache_update_status, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete) - ); - + /// `outcome`: the leaf outcome reported to `finish()`. + pub fn from_execution(cache_status: &CacheStatus, outcome: &LeafOutcome) -> Self { match cache_status { // The only error a cache hit can have is a failed restore. - CacheStatus::Hit { replayed_duration, source, baseline, .. } => saved_error - .map_or_else( - || Self::CacheHit { - saved_duration_ms: duration_to_ms(*replayed_duration), - source: *source, - baseline: baseline.as_deref().cloned(), - }, - |error| Self::RestoreFailed { source: *source, error: error.clone() }, - ), - CacheStatus::Disabled(CacheDisabledReason::InProcessExecution) => Self::InProcess, + CacheStatus::Hit { replayed_duration, source, baseline, .. } => match outcome { + LeafOutcome::CacheHit => Self::CacheHit { + saved_duration_ms: duration_to_ms(*replayed_duration), + source: *source, + baseline: baseline.as_deref().cloned(), + }, + LeafOutcome::Failed(error) => { + Self::RestoreFailed { source: *source, error: SavedError::new(error) } + } + LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { .. } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => { + unreachable!("cache hit leaf cannot finish with {outcome:?}") + } + }, + CacheStatus::Disabled(CacheDisabledReason::InProcessExecution) => match outcome { + LeafOutcome::InProcess => Self::InProcess, + LeafOutcome::Failed(_) + | LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::SpawnedSuccess { .. } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => { + unreachable!("in-process leaf cannot finish with {outcome:?}") + } + }, CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata) => Self::Spawned { cache_status: SpawnedCacheStatus::Disabled, - outcome: spawn_outcome_from_execution( - exit_status, - saved_error, - fspy_unsupported, - ipc_server_error, - tool_disabled_cache, - tracking_incomplete, - ), + outcome: spawn_outcome_from_leaf(outcome), }, CacheStatus::Miss(cache_miss) => Self::Spawned { cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::from_cache_miss( cache_miss, )), - outcome: spawn_outcome_from_execution( - exit_status, - saved_error, - fspy_unsupported, - ipc_server_error, - tool_disabled_cache, - tracking_incomplete, - ), + outcome: spawn_outcome_from_leaf(outcome), }, } } /// Record why uploading the entry to the remote cache failed. The upload /// can fail after the task finishes, so this is set after - /// [`Self::from_execution`]. Only a successful spawned task uploads an - /// entry, so other results are left as they are. + /// [`Self::from_execution`]. Only a successful spawned task whose local + /// cache was updated uploads an entry, so other results are left as they are. pub fn set_upload_error(&mut self, error: SavedError) { - if let Self::Spawned { outcome: SpawnOutcome::Success { upload_error, .. }, .. } = self { + if let Self::Spawned { + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error }), + .. + } = self + { *upload_error = Some(error); } } } -/// Build a [`SpawnOutcome`] from process exit status and optional pre-converted error. +/// Build a [`SpawnOutcome`] from a spawned leaf's [`LeafOutcome`]. /// A failed upload is set later, with [`TaskResult::set_upload_error`]. -fn spawn_outcome_from_execution( - exit_status: Option, - saved_error: Option<&SavedError>, - fspy_unsupported: bool, - ipc_server_error: Option, - tool_disabled_cache: bool, - tracking_incomplete: bool, -) -> SpawnOutcome { - match (exit_status, saved_error) { - // Spawn error — process never ran - (None, Some(err)) => SpawnOutcome::SpawnError(err.clone()), - // Process exited successfully, possible infra error - (Some(status), _) if status.success() => SpawnOutcome::Success { - infra_error: saved_error.cloned(), - fspy_unsupported, - ipc_server_error, - tool_disabled_cache, - tracking_incomplete, - upload_error: None, - }, - // Process exited with non-zero code - (Some(status), _) => { - let code = crate::session::event::exit_status_to_code(status); - SpawnOutcome::Failed { - // exit_status_to_code returns 1..=255 for failed processes (see its - // implementation: always positive, non-zero for non-success status). - // NonZeroI32::new returns None only for 0, which cannot happen here. - exit_code: NonZeroI32::new(code).unwrap_or(NonZeroI32::MIN), - } +fn spawn_outcome_from_leaf(outcome: &LeafOutcome) -> SpawnOutcome { + match outcome { + LeafOutcome::Failed(err) => SpawnOutcome::SpawnError(SavedError::new(err)), + LeafOutcome::SpawnedSuccess { cache_update } => { + SpawnOutcome::Success(SavedCacheOutcome::from_cache_update(cache_update)) + } + LeafOutcome::SpawnedFailed { exit_code } => SpawnOutcome::Failed { exit_code: *exit_code }, + LeafOutcome::WouldSpawn => SpawnOutcome::WouldSpawn, + LeafOutcome::CacheHit | LeafOutcome::InProcess | LeafOutcome::Cancelled => { + unreachable!("spawned leaf cannot finish with {outcome:?}") } - // No exit status, no error — this is the cache hit / in-process path, - // handled by TaskResult::CacheHit / InProcess before reaching here. - // If we somehow get here, treat as success. - (None, None) => SpawnOutcome::Success { - infra_error: None, - fspy_unsupported: false, - ipc_server_error: None, - tool_disabled_cache: false, - tracking_incomplete: false, - upload_error: None, - }, } } @@ -509,14 +515,16 @@ impl TaskResult { match self { Self::CacheHit { .. } | Self::InProcess => true, Self::RestoreFailed { .. } => false, - Self::Spawned { outcome, .. } => matches!(outcome, SpawnOutcome::Success { .. }), + Self::Spawned { outcome, .. } => match outcome { + SpawnOutcome::Success(_) | SpawnOutcome::WouldSpawn => true, + SpawnOutcome::Failed { .. } | SpawnOutcome::SpawnError(_) => false, + }, } } /// Format the cache status detail line for the full summary, with the /// lines below it: the other changes of a miss, each aligned under the - /// first, and the causes. Only a remote read failure has causes. The - /// caller shows [`Self::ipc_server_error`] instead, if there is one. + /// first, and the causes (for remote read failures and IPC server errors). /// /// Examples: /// - "→ Cache hit - output replayed - 102.96ms saved" @@ -526,83 +534,68 @@ impl TaskResult { /// - "→ Cache miss: no previous cache entry found" /// - "→ Cache disabled in task configuration" fn format_cache_detail(&self, run_kind: RunKind) -> (Str, Vec, &[Str]) { - // Tool-reported cache disable — the tool said it shouldn't be cached. - if let Self::Spawned { - outcome: SpawnOutcome::Success { tool_disabled_cache: true, .. }, - .. - } = self - { - return (Str::from("→ Not cached: the task opted out of caching"), Vec::new(), &[]); - } - - // Tracking came up short, so the inferred inputs and outputs would - // have been a subset of what the task touched. - if let Self::Spawned { - outcome: SpawnOutcome::Success { tracking_incomplete: true, .. }, - .. - } = self - { - return ( - Str::from( - "→ Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching.", - ), - Vec::new(), - &[], - ); - } - // fspy-unsupported-on-this-OS message — same overrides precedence as above - if let Self::Spawned { - outcome: SpawnOutcome::Success { fspy_unsupported: true, .. }, .. - } = self - { - return ( - Str::from( - "→ Not cached: `input` auto-inference isn't supported on this OS. Configure `input` manually to enable caching.", - ), - Vec::new(), - &[], - ); - } - - let detail = match self { + match self { Self::CacheHit { saved_duration_ms, source, .. } => { let hit = format_hit(*source); - match run_kind { + let detail = match run_kind { RunKind::Real => { let d = Duration::from_millis(*saved_duration_ms); let formatted_duration = format_summary_duration(d); vt_str::format!("→ {hit} - output replayed - {formatted_duration} saved") } RunKind::Dry => vt_str::format!("→ {hit}"), - } + }; + (detail, Vec::new(), &[]) } - Self::RestoreFailed { source, .. } => { - vt_str::format!("→ {}, but the outputs couldn't be restored", format_hit(*source)) + Self::RestoreFailed { source, .. } => ( + vt_str::format!("→ {}, but the outputs couldn't be restored", format_hit(*source)), + Vec::new(), + &[], + ), + Self::InProcess => { + (Str::from("→ Cache disabled for built-in command"), Vec::new(), &[]) } - Self::InProcess => Str::from("→ Cache disabled for built-in command"), - Self::Spawned { cache_status, .. } => match cache_status { - SpawnedCacheStatus::Disabled => Str::from("→ Cache disabled in task configuration"), - SpawnedCacheStatus::Miss(reason) => match reason { - SavedCacheMissReason::NotFound => { - Str::from("→ Cache miss: no previous cache entry found") - } - SavedCacheMissReason::Changed { changes, .. } => { - let mut lines = changes.iter().map(format_change); - let first = - lines.next().unwrap_or_else(|| Str::from("configuration changed")); - return (vt_str::format!("→ Cache miss: {first}"), lines.collect(), &[]); - } - SavedCacheMissReason::RemoteReadFailed(error) => { - return ( - vt_str::format!("→ Cache miss: {}", error.message), - Vec::new(), - &error.causes, - ); - } - }, + Self::Spawned { + cache_status, + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotCached(reason)), + } => match reason { + SavedNotCachedReason::ToolRequested => { + (Str::from("→ Not cached: the task opted out of caching"), Vec::new(), &[]) + } + SavedNotCachedReason::TrackingIncomplete => ( + Str::from( + "→ Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching.", + ), + Vec::new(), + &[], + ), + SavedNotCachedReason::FspyUnsupported => ( + Str::from( + "→ Not cached: `input` auto-inference isn't supported on this OS. Configure `input` manually to enable caching.", + ), + Vec::new(), + &[], + ), + SavedNotCachedReason::IpcServerError(error) => ( + vt_str::format!("→ Not cached: task communication failed: {}", error.message), + Vec::new(), + &error.causes, + ), + SavedNotCachedReason::CacheDisabled | SavedNotCachedReason::Cancelled => { + format_spawned_cache_status(cache_status) + } }, - }; - (detail, Vec::new(), &[]) + Self::Spawned { + cache_status, + outcome: + SpawnOutcome::Success( + SavedCacheOutcome::Updated { .. } | SavedCacheOutcome::Failed(_), + ) + | SpawnOutcome::Failed { .. } + | SpawnOutcome::SpawnError(_) + | SpawnOutcome::WouldSpawn, + } => format_spawned_cache_status(cache_status), + } } /// With `vp run -vv`, the cached run the task was compared with, and the @@ -637,22 +630,13 @@ impl TaskResult { } } - /// The IPC server error that caused the cache to be skipped, if any. - const fn ipc_server_error(&self) -> Option<&SavedError> { - match self { - Self::Spawned { outcome: SpawnOutcome::Success { ipc_server_error, .. }, .. } => { - ipc_server_error.as_ref() - } - _ => None, - } - } - /// Why uploading the entry to the remote cache failed, if it did. const fn upload_error(&self) -> Option<&SavedError> { match self { - Self::Spawned { outcome: SpawnOutcome::Success { upload_error, .. }, .. } => { - upload_error.as_ref() - } + Self::Spawned { + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error }), + .. + } => upload_error.as_ref(), _ => None, } } @@ -663,14 +647,39 @@ impl TaskResult { Self::CacheHit { .. } | Self::InProcess => None, Self::RestoreFailed { error, .. } => Some(error), Self::Spawned { outcome, .. } => match outcome { - SpawnOutcome::Success { infra_error, .. } => infra_error.as_ref(), - SpawnOutcome::Failed { .. } => None, - SpawnOutcome::SpawnError(err) => Some(err), + SpawnOutcome::Success(SavedCacheOutcome::Failed(err)) + | SpawnOutcome::SpawnError(err) => Some(err), + SpawnOutcome::Success( + SavedCacheOutcome::Updated { .. } | SavedCacheOutcome::NotCached(_), + ) + | SpawnOutcome::Failed { .. } + | SpawnOutcome::WouldSpawn => None, }, } } } +fn format_spawned_cache_status(cache_status: &SpawnedCacheStatus) -> (Str, Vec, &[Str]) { + match cache_status { + SpawnedCacheStatus::Disabled => { + (Str::from("→ Cache disabled in task configuration"), Vec::new(), &[]) + } + SpawnedCacheStatus::Miss(reason) => match reason { + SavedCacheMissReason::NotFound => { + (Str::from("→ Cache miss: no previous cache entry found"), Vec::new(), &[]) + } + SavedCacheMissReason::Changed { changes, .. } => { + let mut lines = changes.iter().map(format_change); + let first = lines.next().unwrap_or_else(|| Str::from("configuration changed")); + (vt_str::format!("→ Cache miss: {first}"), lines.collect(), &[]) + } + SavedCacheMissReason::RemoteReadFailed(error) => { + (vt_str::format!("→ Cache miss: {}", error.message), Vec::new(), &error.causes) + } + }, + } +} + /// "Cache hit" or "Remote cache hit", for the full summary's detail line. const fn format_hit(source: CacheHitSource) -> &'static str { match source { @@ -836,27 +845,17 @@ pub fn format_full_summary(summary: &LastRunSummary, run_kind: RunKind) -> Vec TaskSummary { - let mut task = cache_miss_task(task_name); - if let TaskResult::Spawned { cache_status, .. } = &mut task.result { - *cache_status = SpawnedCacheStatus::Disabled; + TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from(task_name), + command: Str::from("build"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Disabled, + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotCached( + SavedNotCachedReason::CacheDisabled, + )), + }, } - task } fn compact_summary(tasks: Vec) -> Str { @@ -1569,4 +1563,199 @@ mod tests { ["failed to read stdout", "Resource temporarily unavailable (os error 11)"] ); } + + /// Older `last-summary.json` files that used the flat `SpawnOutcome::Success` + /// fields fail cleanly with `ReadSummaryError::IncompatibleVersion`. + #[test] + fn legacy_spawn_outcome_success_reads_as_incompatible_version() { + let dir = tempfile::tempdir().unwrap(); + let path = vt_path::AbsolutePathBuf::new(dir.path().join("last-summary.json")).unwrap(); + let legacy_json = r#"{ + "tasks": [{ + "package_name": "pkg", + "task_name": "build", + "command": "build", + "cwd": "", + "result": { + "Spawned": { + "cache_status": "Disabled", + "outcome": { + "Success": { + "infra_error": null, + "fspy_unsupported": false, + "ipc_server_error": null, + "tracking_incomplete": false, + "tool_disabled_cache": false, + "upload_error": null + } + } + } + } + }], + "exit_code": 0 + }"#; + std::fs::write(&path, legacy_json).unwrap(); + assert!(matches!( + LastRunSummary::read_from_path(&path), + Err(ReadSummaryError::IncompatibleVersion) + )); + } + + #[test] + fn from_execution_maps_leaf_outcomes_without_flag_unpacking() { + let miss = CacheStatus::Miss(CacheMiss::NotFound); + let disabled = CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata); + + let updated = TaskResult::from_execution( + &miss, + &LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { + upload_error: std::sync::Arc::new(std::sync::OnceLock::new()), + }, + }, + ); + assert!(matches!( + updated, + TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error: None }), + } + )); + + let cache_disabled = TaskResult::from_execution( + &disabled, + &LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::CacheDisabled), + }, + ); + assert!(matches!( + cache_disabled, + TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Disabled, + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotCached( + SavedNotCachedReason::CacheDisabled + )), + } + )); + + let update_failed = TaskResult::from_execution( + &miss, + &LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Failed(ExecutionError::PostRunFingerprint( + anyhow::anyhow!("hash failed"), + )), + }, + ); + assert!(matches!( + update_failed, + TaskResult::Spawned { + outcome: SpawnOutcome::Success(SavedCacheOutcome::Failed(_)), + .. + } + )); + assert!(update_failed.error().is_some()); + + let exited_non_zero = TaskResult::from_execution( + &miss, + &LeafOutcome::SpawnedFailed { exit_code: NonZeroI32::new(2).unwrap() }, + ); + assert!(matches!( + exited_non_zero, + TaskResult::Spawned { outcome: SpawnOutcome::Failed { exit_code }, .. } + if exit_code.get() == 2 + )); + + let dry_run = TaskResult::from_execution(&miss, &LeafOutcome::WouldSpawn); + assert!(matches!(dry_run, TaskResult::Spawned { outcome: SpawnOutcome::WouldSpawn, .. })); + } + + #[test] + fn set_upload_error_only_applies_to_updated_cache_outcome() { + let err = saved_error("network error", &[]); + + let mut updated = cache_miss_task("a").result; + updated.set_upload_error(err.clone()); + assert!(updated.upload_error().is_some()); + + let mut disabled = cache_disabled_task("b").result; + disabled.set_upload_error(err.clone()); + assert!(disabled.upload_error().is_none()); + + let mut failed_update = TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::Failed(saved_error( + "Cache update failed", + &[], + ))), + }; + failed_update.set_upload_error(err.clone()); + assert!(failed_update.upload_error().is_none()); + + let mut dry_run = TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::WouldSpawn, + }; + dry_run.set_upload_error(err); + assert!(dry_run.upload_error().is_none()); + } + + #[test] + fn full_summary_formats_not_cached_reasons_and_update_error() { + let not_cached = |task_name: &str, reason: SavedNotCachedReason| TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from(task_name), + command: Str::from("build"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotCached(reason)), + }, + }; + + let summary = full_summary(vec![ + not_cached("opt-out", SavedNotCachedReason::ToolRequested), + not_cached("incomplete", SavedNotCachedReason::TrackingIncomplete), + not_cached("no-fspy", SavedNotCachedReason::FspyUnsupported), + not_cached( + "ipc", + SavedNotCachedReason::IpcServerError(saved_error("broken pipe", &["os error 32"])), + ), + TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from("update-fail"), + command: Str::from("build"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::Failed(saved_error( + "Cache update failed", + &["disk full"], + ))), + }, + }, + ]); + + assert!(summary.as_str().contains("→ Not cached: the task opted out of caching")); + assert!( + summary + .as_str() + .contains("→ Not cached: automatic file tracking couldn't record everything") + ); + assert!( + summary + .as_str() + .contains("→ Not cached: `input` auto-inference isn't supported on this OS.") + ); + assert!( + summary.as_str().contains( + "→ Not cached: task communication failed: broken pipe\n ↳ os error 32\n" + ), + "{summary}" + ); + assert!( + summary.as_str().contains("✗ Error: Cache update failed\n ↳ disk full\n"), + "{summary}" + ); + assert!(summary.as_str().contains("• 1 failed"), "{summary}"); + } } diff --git a/crates/vt/src/session/reporter/summary_reporter.rs b/crates/vt/src/session/reporter/summary_reporter.rs index ea7e44fb6..59c06954e 100644 --- a/crates/vt/src/session/reporter/summary_reporter.rs +++ b/crates/vt/src/session/reporter/summary_reporter.rs @@ -8,7 +8,6 @@ use std::{ cell::{Cell, RefCell}, io::Write, num::NonZeroUsize, - process::ExitStatus as StdExitStatus, rc::Rc, sync::{Arc, OnceLock}, }; @@ -23,7 +22,7 @@ use super::{ }; use crate::session::{ cache::remote::UploadError, - event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}, + event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}, reporter::summary::{ LastRunSummary, SavedError, SpawnOutcome, TaskResult, TaskSummary, format_compact_summary, format_full_summary, format_uploads_pending, @@ -220,15 +219,8 @@ impl LeafExecutionReporter for SummaryLeafReporter { self.inner.start(cache_status) } - fn finish( - self: Box, - status: Option, - cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { // Record task summary before forwarding to inner. - let saved_error = error.as_ref().map(|error| SavedError::new(error)); - if let Some(ref cache_status) = self.cache_status { let cwd_relative = if let Ok(Some(rel)) = self.display.cwd.strip_prefix(&self.workspace_path) { @@ -242,24 +234,43 @@ impl LeafExecutionReporter for SummaryLeafReporter { task_name: self.display.task_display.task_name.clone(), command: self.display.command.clone(), cwd: cwd_relative, - result: TaskResult::from_execution( - cache_status, - status, - saved_error.as_ref(), - &cache_update_status, - ), + result: TaskResult::from_execution(cache_status, &outcome), }; - let upload_error = match &cache_update_status { - CacheUpdateStatus::Updated { upload_error } => Some(Arc::clone(upload_error)), - CacheUpdateStatus::NotUpdated(_) => None, + let upload_error = match &outcome { + LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { upload_error }, + } => Some(Arc::clone(upload_error)), + LeafOutcome::Failed(_) + | LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::NotUpdated(_) | CacheUpdateOutcome::Failed(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => None, }; self.tasks.borrow_mut().push(RecordedTask { summary, upload_error }); - } else if error.is_some() { - self.failed_before_start.set(true); + } else { + match &outcome { + LeafOutcome::Failed(_) + | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(_) } => { + self.failed_before_start.set(true); + } + LeafOutcome::CacheHit + | LeafOutcome::WouldSpawn + | LeafOutcome::InProcess + | LeafOutcome::SpawnedSuccess { + cache_update: + CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | LeafOutcome::SpawnedFailed { .. } + | LeafOutcome::Cancelled => {} + } } - self.inner.finish(status, cache_update_status, error); + self.inner.finish(outcome); } } @@ -270,7 +281,7 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheErrorKind, CacheNotUpdatedReason}, + event::{CacheErrorKind, ExecutionError}, reporter::{ ColorSupport, InterleavedReporterBuilder, test_fixtures::{SharedBuffer, spawn_task, test_path}, @@ -311,11 +322,9 @@ mod tests { let upload_error = Arc::new(OnceLock::new()); let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind); leaf.start(CacheStatus::Miss(CacheMiss::NotFound)); - leaf.finish( - Some(StdExitStatus::default()), - CacheUpdateStatus::Updated { upload_error: Arc::clone(&upload_error) }, - None, - ); + leaf.finish(LeafOutcome::SpawnedSuccess { + cache_update: CacheUpdateOutcome::Updated { upload_error: Arc::clone(&upload_error) }, + }); reporter.uploads_pending(NonZeroUsize::MIN); upload_error.set(UploadError::Interrupted).unwrap(); reporter.finish().unwrap(); @@ -355,14 +364,10 @@ mod tests { )) .build(); let leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind); - leaf.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled), - Some(ExecutionError::Cache { - kind: CacheErrorKind::Lookup, - source: anyhow::anyhow!("the cache database can't be read"), - }), - ); + leaf.finish(LeafOutcome::Failed(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: anyhow::anyhow!("the cache database can't be read"), + })); assert_eq!(reporter.finish(), Err(ExitStatus::FAILURE), "{run_kind:?}"); } } From c0c73b10a010b60028df6a706a206c53253f352e Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 25 Nov 2026 23:01:09 +0800 Subject: [PATCH 2/2] refactor(vt): eliminate unreachable branches via self-contained LeafOutcome - Borrow `&CacheStatus` in `LeafExecutionReporter::start` and make `LeafOutcome` self-contained (`CacheHit`, `RestoreFailed`, `InProcess`, `Spawned { cache_status, outcome }`, `FailedBeforeStart`, `Cancelled`), removing `SummaryLeafReporter.cache_status` and the `CacheStatus` x `LeafOutcome` cross-product `unreachable!`s in `summary.rs`. - Keep a private `SpawnReport` in `execute/mod.rs` (excluding `InProcess`) so `execute_spawn` has no `unreachable!` arm. - Add `LeafOutcome::into_error` to deduplicate error extraction across five reporters. - Align naming (`SavedCacheOutcome::NotUpdated(SavedCacheNotUpdatedReason)`, `execute::SpawnOutcome::InfraError`), preserve IPC-error rendering parity in `format_full_summary`, update doc comments, and add round-trip and non-spawn outcome tests. Co-authored-by: gemini-4-neon --- crates/vt/src/session/event.rs | 86 +++- crates/vt/src/session/execute/mod.rs | 208 ++++++--- crates/vt/src/session/execute/scheduler.rs | 4 +- crates/vt/src/session/mod.rs | 2 +- crates/vt/src/session/reporter/grouped/mod.rs | 23 +- .../src/session/reporter/interleaved/mod.rs | 37 +- crates/vt/src/session/reporter/json/mod.rs | 33 +- crates/vt/src/session/reporter/labeled/mod.rs | 23 +- crates/vt/src/session/reporter/mod.rs | 2 +- crates/vt/src/session/reporter/plain.rs | 39 +- crates/vt/src/session/reporter/summary.rs | 437 +++++++++++++----- .../src/session/reporter/summary_reporter.rs | 94 ++-- 12 files changed, 617 insertions(+), 371 deletions(-) diff --git a/crates/vt/src/session/event.rs b/crates/vt/src/session/event.rs index d394ec5ca..01d206f04 100644 --- a/crates/vt/src/session/event.rs +++ b/crates/vt/src/session/event.rs @@ -140,33 +140,89 @@ pub enum CacheUpdateOutcome { Failed(ExecutionError), } +/// Cache status for a leaf execution that proceeds to spawn a process (or would +/// spawn one in a dry run). +#[derive(Debug)] +pub enum LiveSpawnCacheStatus { + /// Cache lookup missed. + Miss(CacheMiss), + /// Caching was disabled for this task (no cache metadata). + Disabled, +} + +/// Outcome of a spawned process (or a dry-run leaf that would spawn). +#[derive(Debug)] +pub enum SpawnLeafOutcome { + /// The spawned process exited with status 0. + Success { cache_update: CacheUpdateOutcome }, + /// The spawned process exited with a non-zero status; the cache is never + /// updated. + Failed { exit_code: NonZeroI32 }, + /// An infrastructure error prevented spawning the process or observing it + /// to completion (e.g., IPC bind, spawn, output forwarding, or wait error). + SpawnError(ExecutionError), + /// In a dry run, a miss or a task without caching: nothing ran. + WouldSpawn, +} + /// Final outcome of a single leaf execution, passed to /// [`LeafExecutionReporter::finish`](super::reporter::LeafExecutionReporter::finish). /// -/// Each variant carries only the data valid for that outcome, so invalid -/// combinations (such as an execution error paired with a cache update, or a -/// cache update on a non-zero exit) are unrepresentable. +/// Self-contained: each variant carries both the cache-status context and the +/// outcome data valid for that path, so reporters never have to pair `start()`'s +/// [`CacheStatus`] with `finish()`'s outcome or guard against impossible +/// combinations. #[derive(Debug)] pub enum LeafOutcome { - /// An infrastructure error prevented the process from running, prevented - /// observing it to completion, or prevented restoring a cache hit's outputs. - Failed(ExecutionError), /// Cache hit: no process ran. Captured outputs were replayed, except in a /// dry run. - CacheHit, - /// In a dry run, a miss or a task without caching: nothing ran. - WouldSpawn, + CacheHit { + replayed_duration: Duration, + source: CacheHitSource, + baseline: Option>, + }, + /// Cache hit whose output files couldn't be restored. + RestoreFailed { source: CacheHitSource, error: ExecutionError }, /// An in-process (built-in) command completed (or was skipped in a dry run). InProcess, - /// The spawned process exited with status 0. - SpawnedSuccess { cache_update: CacheUpdateOutcome }, - /// The spawned process exited with a non-zero status; the cache is never - /// updated. - SpawnedFailed { exit_code: NonZeroI32 }, - /// The run was cancelled before the process started. + /// A process was spawned (or would spawn in a dry run). + Spawned { cache_status: LiveSpawnCacheStatus, outcome: SpawnLeafOutcome }, + /// An infrastructure error occurred before `start()` (e.g., cache lookup + /// failed). + FailedBeforeStart(ExecutionError), + /// The run was cancelled before `start()`. Cancelled, } +impl LeafOutcome { + /// Extract the infrastructure error carried by this outcome, if any. + pub fn into_error(self) -> Option { + match self { + Self::RestoreFailed { error, .. } + | Self::FailedBeforeStart(error) + | Self::Spawned { + outcome: + SpawnLeafOutcome::SpawnError(error) + | SpawnLeafOutcome::Success { cache_update: CacheUpdateOutcome::Failed(error) }, + .. + } => Some(error), + Self::CacheHit { .. } + | Self::InProcess + | Self::Cancelled + | Self::Spawned { + outcome: + SpawnLeafOutcome::Success { + cache_update: + CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), + } + | SpawnLeafOutcome::Failed { .. } + | SpawnLeafOutcome::WouldSpawn, + .. + } => None, + } + } +} + /// Whether a run runs its commands, or is a dry run (`vp run --dry-run`), /// which plans them and checks the cache without running anything. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/vt/src/session/execute/mod.rs b/crates/vt/src/session/execute/mod.rs index 4395bf33d..f357fac85 100644 --- a/crates/vt/src/session/execute/mod.rs +++ b/crates/vt/src/session/execute/mod.rs @@ -18,7 +18,7 @@ use std::{ ffi::{OsStr, OsString}, num::NonZeroI32, sync::Arc, - time::Instant, + time::{Duration, Instant}, }; use futures_util::future::LocalBoxFuture; @@ -35,10 +35,14 @@ use self::{ spawn::{ChildHandle, ChildOutcome, SpawnStdio, spawn}, }; use super::{ - cache::{CacheHit, CacheHitSource, CacheMiss, ExecutionCache, FileCheck, run_off_thread}, + cache::{ + BaselineDetails, CacheHit, CacheHitSource, CacheMiss, ExecutionCache, FileCheck, + run_off_thread, + }, event::{ CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason, CacheStatus, - CacheUpdateOutcome, ExecutionError, LeafOutcome, RunKind, non_zero_exit_code, + CacheUpdateOutcome, ExecutionError, LeafOutcome, LiveSpawnCacheStatus, RunKind, + SpawnLeafOutcome, non_zero_exit_code, }, reporter::{LeafExecutionReporter, PipeWriters, StdioConfig, StdioSuggestion}, }; @@ -59,10 +63,11 @@ pub enum SpawnOutcome { SpawnedSuccess, /// Process was spawned and exited with a non-zero exit code. SpawnedFailed(NonZeroI32), - /// An infrastructure error prevented the process from running - /// (cache lookup failure or spawn failure). - /// Already reported through the leaf reporter. - Failed, + /// An infrastructure error prevented the process from running, prevented + /// observing it to completion, or prevented restoring a cache hit's outputs + /// (cache lookup, cache restore, IPC bind, spawn, output forwarding, or + /// wait failure). Already reported through the leaf reporter. + InfraError, /// The run was cancelled during the cache lookup, so the process didn't /// start and no cached outputs were restored. Like a task that was never /// scheduled, it isn't reported. @@ -266,17 +271,59 @@ impl<'a> ExecutionMode<'a> { } } -/// Map a spawn pipeline's [`LeafOutcome`] to the [`SpawnOutcome`] returned by -/// [`execute_spawn`]. -fn spawn_outcome_of(outcome: &LeafOutcome) -> SpawnOutcome { - match outcome { - LeafOutcome::Failed(_) => SpawnOutcome::Failed, - LeafOutcome::CacheHit => SpawnOutcome::CacheHit, - LeafOutcome::WouldSpawn => SpawnOutcome::WouldSpawn, - LeafOutcome::SpawnedSuccess { .. } => SpawnOutcome::SpawnedSuccess, - LeafOutcome::SpawnedFailed { exit_code } => SpawnOutcome::SpawnedFailed(*exit_code), - LeafOutcome::Cancelled => SpawnOutcome::Cancelled, - LeafOutcome::InProcess => unreachable!("execute_spawn only runs spawned processes"), +/// Everything the spawn pipeline reports through the single +/// `LeafExecutionReporter::finish()` call at the end of [`execute_spawn`]. +/// +/// Separate from [`LeafOutcome`] so that in-process execution is unrepresentable +/// inside the spawn pipeline. +enum SpawnReport { + CacheHit { + replayed_duration: Duration, + source: CacheHitSource, + baseline: Option>, + }, + RestoreFailed { + source: CacheHitSource, + error: ExecutionError, + }, + Spawned { + cache_status: LiveSpawnCacheStatus, + outcome: SpawnLeafOutcome, + }, + FailedBeforeStart(ExecutionError), + Cancelled, +} + +impl SpawnReport { + /// Perform the pipeline's single `finish()` call and yield the + /// [`SpawnOutcome`] [`execute_spawn`] returns to its caller. + fn finish(self, reporter: Box) -> SpawnOutcome { + let (spawn_outcome, leaf_outcome) = match self { + Self::CacheHit { replayed_duration, source, baseline } => ( + SpawnOutcome::CacheHit, + LeafOutcome::CacheHit { replayed_duration, source, baseline }, + ), + Self::RestoreFailed { source, error } => { + (SpawnOutcome::InfraError, LeafOutcome::RestoreFailed { source, error }) + } + Self::Spawned { cache_status, outcome } => { + let spawn_outcome = match &outcome { + SpawnLeafOutcome::Success { .. } => SpawnOutcome::SpawnedSuccess, + SpawnLeafOutcome::Failed { exit_code } => { + SpawnOutcome::SpawnedFailed(*exit_code) + } + SpawnLeafOutcome::SpawnError(_) => SpawnOutcome::InfraError, + SpawnLeafOutcome::WouldSpawn => SpawnOutcome::WouldSpawn, + }; + (spawn_outcome, LeafOutcome::Spawned { cache_status, outcome }) + } + Self::FailedBeforeStart(error) => { + (SpawnOutcome::InfraError, LeafOutcome::FailedBeforeStart(error)) + } + Self::Cancelled => (SpawnOutcome::Cancelled, LeafOutcome::Cancelled), + }; + reporter.finish(leaf_outcome); + spawn_outcome } } @@ -288,7 +335,7 @@ fn spawn_outcome_of(outcome: &LeafOutcome) -> SpawnOutcome { /// The full lifecycle is: /// 1. Cache lookup (determines cache status). If the run was cancelled by /// the time it ends, nothing else happens. -/// 2. `leaf_reporter.start(cache_status)` → `StdioConfig` +/// 2. `leaf_reporter.start(&cache_status)` → `StdioConfig` /// 3. If cache hit: replay cached outputs via `StdioConfig` writers /// 4. Otherwise: `spawn()` with the chosen stdio mode, drain pipes and wait /// via [`run_child`], then decide the cache update @@ -337,17 +384,15 @@ pub async fn execute_spawn( fast_fail_token, cancel_token, ); - let outcome = match pipeline.await { - Ok(outcome) | Err(outcome) => outcome, + let report = match pipeline.await { + Ok(report) | Err(report) => report, }; - let spawn_outcome = spawn_outcome_of(&outcome); - leaf_reporter.finish(outcome); - spawn_outcome + report.finish(leaf_reporter) } /// The spawn pipeline. /// -/// Both sides of the `Result` carry the same [`LeafOutcome`] on purpose: `Err` +/// Both sides of the `Result` carry the same [`SpawnReport`] on purpose: `Err` /// is the `?`-short-circuit channel for phases that already determined the /// final outcome, `Ok` is the outcome of a pipeline that ran to the end. The /// caller unwraps both into the same single `finish()`, so the distinction is @@ -365,7 +410,7 @@ async fn run( file_check: FileCheck, fast_fail_token: CancellationToken, cancel_token: CancellationToken, -) -> Result { +) -> Result { let cache_metadata = spawn_execution.cache_metadata.as_ref(); // 1. Determine cache status FIRST by trying cache hit, so the reporter can @@ -384,26 +429,30 @@ async fn run( ) .await?; if cancel_token.is_cancelled() { - return Err(LeafOutcome::Cancelled); + return Err(SpawnReport::Cancelled); } // 2. Report execution start with the looked-up cache status (`start()` // runs exactly once on every arm) and either replay the hit — no need // to execute the command — or carry the globbed inputs into the run. - let (stdio_config, globbed_inputs) = match lookup { + let (stdio_config, spawn_cache_status, globbed_inputs) = match lookup { CacheLookup::Hit { hit, metadata } => { - let mut stdio_config = reporter.start(CacheStatus::Hit { + let mut stdio_config = reporter.start(&CacheStatus::Hit { replayed_duration: hit.value.duration, source: hit.source, restores_outputs: hit.value.output_archive.is_some(), baseline: hit.baseline.clone(), }); if run_kind == RunKind::Dry { - return Ok(LeafOutcome::CacheHit); + return Ok(SpawnReport::CacheHit { + replayed_duration: hit.value.duration, + source: hit.source, + baseline: hit.baseline, + }); } return Ok(replay_cache_hit( &mut stdio_config, - &hit, + hit, cache, metadata, workspace_root, @@ -413,20 +462,32 @@ async fn run( .await); } CacheLookup::Miss { miss, globbed_inputs } => { - (reporter.start(CacheStatus::Miss(miss)), globbed_inputs) + let stdio_config = reporter.start(&CacheStatus::Miss(miss.clone())); + (stdio_config, LiveSpawnCacheStatus::Miss(miss), globbed_inputs) + } + CacheLookup::Disabled => { + let stdio_config = + reporter.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); + (stdio_config, LiveSpawnCacheStatus::Disabled, BTreeMap::new()) } - CacheLookup::Disabled => ( - reporter.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)), - BTreeMap::new(), - ), }; if run_kind == RunKind::Dry { - return Ok(LeafOutcome::WouldSpawn); + return Ok(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::WouldSpawn, + }); } + let spawn_err = |cache_status, err| SpawnReport::Spawned { + cache_status, + outcome: SpawnLeafOutcome::SpawnError(err), + }; + // 4. Fold the cache/fspy/stdio decisions into the typed mode. - let mut mode = ExecutionMode::build(cache_metadata, stdio_config, globbed_inputs) - .map_err(LeafOutcome::Failed)?; + let mut mode = match ExecutionMode::build(cache_metadata, stdio_config, globbed_inputs) { + Ok(mode) => mode, + Err(err) => return Err(spawn_err(spawn_cache_status, err)), + }; // Measure end-to-end duration here — spawn() doesn't track time. let start = Instant::now(); @@ -434,7 +495,7 @@ async fn run( // 5. Spawn. Returns pipes (Piped) or `None` (Inherited) plus a // cancellation-aware wait future. let (spawn_stdio, fspy_enabled) = mode.spawn_config(); - let child = spawn( + let child = match spawn( &spawn_execution.spawn_command, fspy_enabled, spawn_stdio, @@ -442,7 +503,10 @@ async fn run( mode.injected_envs(), ) .await - .map_err(|err| LeafOutcome::Failed(ExecutionError::Spawn(err)))?; + { + Ok(child) => child, + Err(err) => return Err(spawn_err(spawn_cache_status, ExecutionError::Spawn(err))), + }; tracing::debug!(fspy = fspy_enabled, elapsed = ?start.elapsed(), "spawned the task process"); // 6. Drain the pipes and wait for exit, concurrently with the IPC driver. @@ -467,13 +531,19 @@ async fn run( let child_work = Box::pin(run_child(child, sinks, None, fast_fail_token.clone())); (child_work.await, None) }; - let outcome = wait_result.map_err(LeafOutcome::Failed)?; + let outcome = match wait_result { + Ok(outcome) => outcome, + Err(err) => return Err(spawn_err(spawn_cache_status, err)), + }; let duration = start.elapsed(); // Non-zero exit: cache is never updated. if !outcome.exit_status.success() { - return Ok(LeafOutcome::SpawnedFailed { - exit_code: non_zero_exit_code(outcome.exit_status), + return Ok(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Failed { + exit_code: non_zero_exit_code(outcome.exit_status), + }, }); } @@ -487,17 +557,21 @@ async fn run( } None => None, Some(Err(err)) => { - return Ok(LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::NotUpdated( - CacheNotUpdatedReason::IpcServerError(err), - ), + return Ok(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::NotUpdated( + CacheNotUpdatedReason::IpcServerError(err), + ), + }, }); } }; // 7. Decide the cache update (only when we were in `Cached` mode). Cache - // update errors are reported but do not affect the exit status we - // return — the process exited 0, so we still report `SpawnedSuccess`. + // update errors do not affect `SpawnOutcome` or fast-fail (the process + // exited 0, so we report `SpawnedSuccess`), though the summary reporter + // still turns post-run cache errors into a non-zero run exit code. let cache_update = match mode { ExecutionMode::Cached { state, .. } => { cache_update::update_cache( @@ -519,7 +593,10 @@ async fn run( } }; - Ok(LeafOutcome::SpawnedSuccess { cache_update }) + Ok(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Success { cache_update }, + }) } /// Outcome of the cache-lookup phase. Each variant carries exactly what that @@ -541,7 +618,7 @@ enum CacheLookup<'a> { /// downloads its output archive into `cache_dir`, except in a dry run. The /// inputs are hashed, and entries checked, off the scheduler's thread (see /// [`run_off_thread`]). The lookup stops when `cancel_token` is cancelled, and -/// is then [`LeafOutcome::Cancelled`] or a miss that isn't reported. +/// is then [`SpawnReport::Cancelled`] or a miss that isn't reported. async fn lookup_cache<'a>( cache_metadata: Option<&'a CacheMetadata>, cache: &ExecutionCache, @@ -550,7 +627,7 @@ async fn lookup_cache<'a>( run_kind: RunKind, file_check: FileCheck, cancel_token: &CancellationToken, -) -> Result, LeafOutcome> { +) -> Result, SpawnReport> { let Some(cache_metadata) = cache_metadata else { return Ok(CacheLookup::Disabled); }; @@ -573,9 +650,12 @@ async fn lookup_cache<'a>( anyhow::Ok(globbed_inputs) }) .await - .ok_or(LeafOutcome::Cancelled)?; + .ok_or(SpawnReport::Cancelled)?; let globbed_inputs = Arc::new(hashed.map_err(|err| { - LeafOutcome::Failed(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err }) + SpawnReport::FailedBeforeStart(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: err, + }) })?); match cache @@ -596,8 +676,8 @@ async fn lookup_cache<'a>( Ok(Some(Err(miss))) => { Ok(CacheLookup::Miss { miss, globbed_inputs: Arc::unwrap_or_clone(globbed_inputs) }) } - Ok(None) => Err(LeafOutcome::Cancelled), - Err(err) => Err(LeafOutcome::Failed(ExecutionError::Cache { + Ok(None) => Err(SpawnReport::Cancelled), + Err(err) => Err(SpawnReport::FailedBeforeStart(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err, })), @@ -608,13 +688,13 @@ async fn lookup_cache<'a>( /// output files. async fn replay_cache_hit( stdio_config: &mut StdioConfig, - hit: &CacheHit, + hit: CacheHit, cache: &ExecutionCache, cache_metadata: &CacheMetadata, workspace_root: &Arc, cache_dir: &AbsolutePath, program_name: &str, -) -> LeafOutcome { +) -> SpawnReport { for output in hit.value.std_outputs.iter() { let writer: &mut dyn std::io::Write = match output.kind { pipe::OutputKind::StdOut => &mut stdio_config.writers.stdout_writer, @@ -627,7 +707,7 @@ async fn replay_cache_hit( // Failure here means the archive is missing or unreadable, or its files // can't be written. The task fails because the cache promised the // outputs would be restored. - if let Err(err) = cache.restore(cache_metadata, hit, workspace_root, cache_dir).await { + if let Err(err) = cache.restore(cache_metadata, &hit, workspace_root, cache_dir).await { let error = match hit.source { CacheHitSource::Local => { ExecutionError::LocalCacheRestore { program_name: program_name.into(), source: err } @@ -637,10 +717,14 @@ async fn replay_cache_hit( ExecutionError::Cache { kind: CacheErrorKind::Restore, source: err } } }; - return LeafOutcome::Failed(error); + return SpawnReport::RestoreFailed { source: hit.source, error }; } - LeafOutcome::CacheHit + SpawnReport::CacheHit { + replayed_duration: hit.value.duration, + source: hit.source, + baseline: hit.baseline, + } } /// Phase 6: drain the child's pipes (if piped) and wait for exit. A pipe diff --git a/crates/vt/src/session/execute/scheduler.rs b/crates/vt/src/session/execute/scheduler.rs index d514e00c4..3d0dc524d 100644 --- a/crates/vt/src/session/execute/scheduler.rs +++ b/crates/vt/src/session/execute/scheduler.rs @@ -234,7 +234,7 @@ impl ExecutionContext<'_> { LeafExecutionKind::InProcess(in_process_execution) => { // In-process (built-in) commands: caching is disabled, execute synchronously let mut stdio_config = leaf_reporter - .start(CacheStatus::Disabled(CacheDisabledReason::InProcessExecution)); + .start(&CacheStatus::Disabled(CacheDisabledReason::InProcessExecution)); // A dry run doesn't run it. if self.run_kind == RunKind::Real { @@ -266,7 +266,7 @@ impl ExecutionContext<'_> { | SpawnOutcome::WouldSpawn | SpawnOutcome::SpawnedSuccess | SpawnOutcome::Cancelled => false, - SpawnOutcome::SpawnedFailed(_) | SpawnOutcome::Failed => true, + SpawnOutcome::SpawnedFailed(_) | SpawnOutcome::InfraError => true, } } }; diff --git a/crates/vt/src/session/mod.rs b/crates/vt/src/session/mod.rs index 81b132922..10a7cd1eb 100644 --- a/crates/vt/src/session/mod.rs +++ b/crates/vt/src/session/mod.rs @@ -807,7 +807,7 @@ impl<'a> Session<'a> { } // Infrastructure error — already reported through the reporter's finish(). // Nothing cancels the tokens above, and a cancelled command wouldn't have run. - execute::SpawnOutcome::Failed | execute::SpawnOutcome::Cancelled => { + execute::SpawnOutcome::InfraError | execute::SpawnOutcome::Cancelled => { Ok(ExitStatus::FAILURE) } } diff --git a/crates/vt/src/session/reporter/grouped/mod.rs b/crates/vt/src/session/reporter/grouped/mod.rs index 06b5477fd..ec5592432 100644 --- a/crates/vt/src/session/reporter/grouped/mod.rs +++ b/crates/vt/src/session/reporter/grouped/mod.rs @@ -12,7 +12,7 @@ use super::{ format_command_with_cache_status, format_task_label, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; +use crate::session::event::{CacheStatus, LeafOutcome, RunKind}; mod writer; @@ -92,11 +92,11 @@ struct GroupedLeafReporter { } impl LeafExecutionReporter for GroupedLeafReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { let line = format_command_with_cache_status( &self.display, &self.workspace_path, - &cache_status, + cache_status, RunKind::Real, ); @@ -128,20 +128,7 @@ impl LeafExecutionReporter for GroupedLeafReporter { } fn finish(self: Box, outcome: LeafOutcome) { - let error = match outcome { - LeafOutcome::Failed(error) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { - Some(error) - } - LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => None, - }; + let error = outcome.into_error(); // Build grouped block: header + buffered output. let mut extra = Vec::new(); @@ -196,7 +183,7 @@ mod tests { let mut reporter = builder.build(); let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); - let stdio_config = leaf.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); + let stdio_config = leaf.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); assert_eq!(stdio_config.suggestion, StdioSuggestion::Piped); } } diff --git a/crates/vt/src/session/reporter/interleaved/mod.rs b/crates/vt/src/session/reporter/interleaved/mod.rs index 72f96bc1e..f3f7982b7 100644 --- a/crates/vt/src/session/reporter/interleaved/mod.rs +++ b/crates/vt/src/session/reporter/interleaved/mod.rs @@ -17,7 +17,7 @@ use super::{ StdioConfig, StdioSuggestion, format_command_display, format_command_with_cache_status, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; +use crate::session::event::{CacheStatus, LeafOutcome, RunKind}; pub struct InterleavedReporterBuilder { workspace_path: Arc, @@ -101,11 +101,11 @@ struct InterleavedLeafReporter { } impl LeafExecutionReporter for InterleavedLeafReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { let line = format_command_with_cache_status( &self.display, &self.workspace_path, - &cache_status, + cache_status, self.run_kind, ); @@ -131,20 +131,7 @@ impl LeafExecutionReporter for InterleavedLeafReporter { } fn finish(self: Box, outcome: LeafOutcome) { - let error = match outcome { - LeafOutcome::Failed(error) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { - Some(error) - } - LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => None, - }; + let error = outcome.into_error(); let (command_line, blank_line) = match self.run_kind { RunKind::Real => (Str::default(), self.started), // A dry run prints only the commands' lines. An error that comes @@ -167,7 +154,10 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheDisabledReason, CacheErrorKind, ExecutionError}, + event::{ + CacheDisabledReason, CacheErrorKind, ExecutionError, LiveSpawnCacheStatus, + SpawnLeafOutcome, + }, reporter::{ StdioSuggestion, test_fixtures::{SharedBuffer, in_process_task, spawn_task, test_path}, @@ -193,7 +183,7 @@ mod tests { )); let mut reporter = builder.build(); let mut leaf = reporter.new_leaf_execution(&[], display, leaf_kind); - leaf.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)).suggestion + leaf.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)).suggestion } #[test] @@ -230,15 +220,18 @@ mod tests { .build(); let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); - leaf.start(CacheStatus::Miss(CacheMiss::NotFound)); - leaf.finish(LeafOutcome::WouldSpawn); + leaf.start(&CacheStatus::Miss(CacheMiss::NotFound)); + leaf.finish(LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::WouldSpawn, + }); let leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); let error = ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("database is locked"), }; - leaf.finish(LeafOutcome::Failed(error)); + leaf.finish(LeafOutcome::FailedBeforeStart(error)); reporter.finish().unwrap(); assert_eq!( diff --git a/crates/vt/src/session/reporter/json/mod.rs b/crates/vt/src/session/reporter/json/mod.rs index 4a8b908ea..4e724f4fa 100644 --- a/crates/vt/src/session/reporter/json/mod.rs +++ b/crates/vt/src/session/reporter/json/mod.rs @@ -30,7 +30,7 @@ use crate::session::{ self, BaselineDetails, BaselineOutputs, BaselinePath, CacheMiss, Comparison, InputChangeKind, }, - event::{CacheDisabledReason, CacheStatus, CacheUpdateOutcome, LeafOutcome}, + event::{CacheDisabledReason, CacheStatus, LeafOutcome}, json::{self, Version, path_key, task_id}, }; @@ -260,8 +260,8 @@ fn find_step<'a>( } impl LeafExecutionReporter for JsonLeafReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { - self.report(cache_of(&cache_status)); + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { + self.report(cache_of(cache_status)); // Nothing runs or is replayed, so nothing is written to these. StdioConfig { suggestion: StdioSuggestion::Piped, @@ -278,24 +278,13 @@ impl LeafExecutionReporter for JsonLeafReporter { /// A lookup cancelled by Ctrl-C has neither, and also leaves its step /// unreported. fn finish(self: Box, outcome: LeafOutcome) { - match outcome { - LeafOutcome::Failed(error) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { - let message = vt_str::format!("{:#}", anyhow::Error::from(error)); - let message = match self.location.as_ref().and_then(|location| location.last()) { - Some((id, _)) => vt_str::format!("{id}: {message}"), - None => message, - }; - self.state.borrow_mut().errors.push(message); - } - LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => {} + if let Some(error) = outcome.into_error() { + let message = vt_str::format!("{:#}", anyhow::Error::from(error)); + let message = match self.location.as_ref().and_then(|location| location.last()) { + Some((id, _)) => vt_str::format!("{id}: {message}"), + None => message, + }; + self.state.borrow_mut().errors.push(message); } } } @@ -535,7 +524,7 @@ mod tests { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("database is locked"), }; - leaf.finish(LeafOutcome::Failed(error)); + leaf.finish(LeafOutcome::FailedBeforeStart(error)); assert!(reporter.finish().is_err()); } diff --git a/crates/vt/src/session/reporter/labeled/mod.rs b/crates/vt/src/session/reporter/labeled/mod.rs index c849c4e37..104ee58ca 100644 --- a/crates/vt/src/session/reporter/labeled/mod.rs +++ b/crates/vt/src/session/reporter/labeled/mod.rs @@ -11,7 +11,7 @@ use super::{ format_command_with_cache_status, format_task_label, maybe_strip_writer, write_leaf_trailing_output, }; -use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome, RunKind}; +use crate::session::event::{CacheStatus, LeafOutcome, RunKind}; mod writer; @@ -84,12 +84,12 @@ struct LabeledLeafReporter { } impl LeafExecutionReporter for LabeledLeafReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { let label = format_task_label(&self.display); let line = format_command_with_cache_status( &self.display, &self.workspace_path, - &cache_status, + cache_status, RunKind::Real, ); @@ -124,20 +124,7 @@ impl LeafExecutionReporter for LabeledLeafReporter { } fn finish(self: Box, outcome: LeafOutcome) { - let error = match outcome { - LeafOutcome::Failed(error) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { - Some(error) - } - LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => None, - }; + let error = outcome.into_error(); write_leaf_trailing_output(&self.writer, error, self.started, &[]); } } @@ -175,7 +162,7 @@ mod tests { let mut reporter = builder.build(); let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind(item)); - let stdio_config = leaf.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); + let stdio_config = leaf.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); assert_eq!(stdio_config.suggestion, StdioSuggestion::Piped); } } diff --git a/crates/vt/src/session/reporter/mod.rs b/crates/vt/src/session/reporter/mod.rs index 46e6244f0..aec4e5e07 100644 --- a/crates/vt/src/session/reporter/mod.rs +++ b/crates/vt/src/session/reporter/mod.rs @@ -214,7 +214,7 @@ pub trait LeafExecutionReporter { /// AND whether caching is enabled — inherited stdio is only used when the /// suggestion is [`StdioSuggestion::Inherited`] AND the task has no cache /// metadata (caching disabled). - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig; + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig; /// Finalize this leaf execution with its typed [`LeafOutcome`]. /// diff --git a/crates/vt/src/session/reporter/plain.rs b/crates/vt/src/session/reporter/plain.rs index d0586bc55..55512df9e 100644 --- a/crates/vt/src/session/reporter/plain.rs +++ b/crates/vt/src/session/reporter/plain.rs @@ -12,7 +12,7 @@ use super::{ // `maybe_strip_writer` is used for the child-process pipe writers; reporter // output decides colour-vs-plain at format time via the `ColorizeExt` helpers // in [`super`]. -use crate::session::event::{CacheStatus, CacheUpdateOutcome, LeafOutcome}; +use crate::session::event::{CacheStatus, LeafOutcome}; /// A self-contained [`LeafExecutionReporter`] for single-leaf executions /// (e.g., `execute_synthetic`). @@ -54,7 +54,7 @@ impl PlainReporter { } impl LeafExecutionReporter for PlainReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { let is_cache_hit = matches!(cache_status, CacheStatus::Hit { .. }); // PlainReporter is used for single-leaf synthetic executions (e.g., auto-install). // Always suggest inherited stdio so the spawned process can be interactive. @@ -91,30 +91,19 @@ impl LeafExecutionReporter for PlainReporter { } fn finish(mut self: Box, outcome: LeafOutcome) { - match outcome { - // Handle errors — format the full error chain and print inline. - LeafOutcome::Failed(error) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(error) } => { - let message = vt_str::format!("{:#}", anyhow::Error::from(error)); - let line = format_error_message(&message); + if matches!(outcome, LeafOutcome::CacheHit { .. }) { + // For cache hits, print the "cache hit" message (unless silent). + if !self.silent_if_cache_hit { + let line = format_cache_hit_message(); let _ = self.writer.write_all(line.as_bytes()); let _ = self.writer.flush(); } - // For cache hits, print the "cache hit" message (unless silent). - LeafOutcome::CacheHit => { - if !self.silent_if_cache_hit { - let line = format_cache_hit_message(); - let _ = self.writer.write_all(line.as_bytes()); - let _ = self.writer.flush(); - } - } - LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => {} + } else if let Some(error) = outcome.into_error() { + // Handle errors — format the full error chain and print inline. + let message = vt_str::format!("{:#}", anyhow::Error::from(error)); + let line = format_error_message(&message); + let _ = self.writer.write_all(line.as_bytes()); + let _ = self.writer.flush(); } } } @@ -129,7 +118,7 @@ mod tests { let mut reporter = PlainReporter::new(false, Box::new(std::io::sink()), ColorSupport::uniform(false)); let stdio_config = - reporter.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); + reporter.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); assert_eq!(stdio_config.suggestion, StdioSuggestion::Inherited); } @@ -138,7 +127,7 @@ mod tests { let mut reporter = PlainReporter::new(true, Box::new(std::io::sink()), ColorSupport::uniform(false)); let stdio_config = - reporter.start(CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); + reporter.start(&CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata)); assert_eq!(stdio_config.suggestion, StdioSuggestion::Inherited); } } diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index 95d42441c..bef80fb4f 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -11,6 +11,7 @@ use std::{ fmt::Display, io::Write, num::{NonZeroI32, NonZeroUsize}, + sync::{Arc, OnceLock}, time::Duration, }; @@ -25,11 +26,11 @@ use super::{CACHE_MISS_STYLE, COMMAND_STYLE, ColorizeExt}; use crate::session::{ cache::{ BaselineDetails, BaselineOutputs, BaselinePath, CacheHitSource, CacheMiss, Change, - InputChangeKind, format_change, + InputChangeKind, format_change, remote::UploadError, }, event::{ - CacheDisabledReason, CacheNotUpdatedReason, CacheStatus, CacheUpdateOutcome, LeafOutcome, - RunKind, + CacheNotUpdatedReason, CacheUpdateOutcome, LeafOutcome, LiveSpawnCacheStatus, RunKind, + SpawnLeafOutcome, }, }; @@ -143,7 +144,7 @@ pub enum SavedCacheOutcome { upload_error: Option, }, /// Cache was not updated for a non-error reason. - NotCached(SavedNotCachedReason), + NotUpdated(SavedCacheNotUpdatedReason), /// Updating the cache failed with a post-run infrastructure error /// (fingerprint creation, output archiving, or cache write). Failed(SavedError), @@ -151,7 +152,7 @@ pub enum SavedCacheOutcome { /// Why the cache was not updated after a successful spawned execution. #[derive(Serialize, Deserialize)] -pub enum SavedNotCachedReason { +pub enum SavedCacheNotUpdatedReason { /// Caching was disabled for this task. CacheDisabled, /// Execution was cancelled before the result could be cached. @@ -263,7 +264,7 @@ impl SummaryStats { }); } } - SpawnOutcome::Success(SavedCacheOutcome::NotCached(_)) + SpawnOutcome::Success(SavedCacheOutcome::NotUpdated(_)) | SpawnOutcome::WouldSpawn => {} } } @@ -316,14 +317,14 @@ impl SavedCacheOutcome { match cache_update { CacheUpdateOutcome::Updated { .. } => Self::Updated { upload_error: None }, CacheUpdateOutcome::NotUpdated(reason) => { - Self::NotCached(SavedNotCachedReason::from_reason(reason)) + Self::NotUpdated(SavedCacheNotUpdatedReason::from_reason(reason)) } CacheUpdateOutcome::Failed(error) => Self::Failed(SavedError::new(error)), } } } -impl SavedNotCachedReason { +impl SavedCacheNotUpdatedReason { fn from_reason(reason: &CacheNotUpdatedReason) -> Self { match reason { CacheNotUpdatedReason::CacheDisabled => Self::CacheDisabled, @@ -338,59 +339,91 @@ impl SavedNotCachedReason { } } -impl TaskResult { - /// Build a [`TaskResult`] from live execution data. - /// - /// `cache_status`: the cache status determined at `start()` time. - /// `outcome`: the leaf outcome reported to `finish()`. - pub fn from_execution(cache_status: &CacheStatus, outcome: &LeafOutcome) -> Self { - match cache_status { - // The only error a cache hit can have is a failed restore. - CacheStatus::Hit { replayed_duration, source, baseline, .. } => match outcome { - LeafOutcome::CacheHit => Self::CacheHit { +/// How [`SummaryLeafReporter`](super::summary_reporter) records a finished leaf. +pub enum LeafSummaryOutcome { + /// The leaf started and produced a [`TaskResult`] for the summary, along + /// with an optional handle for an in-flight remote-cache upload error. + Recorded { result: TaskResult, upload_error: Option>> }, + /// The leaf failed before `start()` (e.g., cache lookup failed): it is not + /// added to `LastRunSummary::tasks`, but it fails the run. + FailedBeforeStart, + /// The leaf was cancelled before `start()`: nothing is recorded. + Cancelled, +} + +impl LeafSummaryOutcome { + /// Convert a self-contained [`LeafOutcome`] directly into its summary action. + pub fn from_leaf_outcome(outcome: &LeafOutcome) -> Self { + match outcome { + LeafOutcome::CacheHit { replayed_duration, source, baseline } => Self::Recorded { + result: TaskResult::CacheHit { saved_duration_ms: duration_to_ms(*replayed_duration), source: *source, baseline: baseline.as_deref().cloned(), }, - LeafOutcome::Failed(error) => { - Self::RestoreFailed { source: *source, error: SavedError::new(error) } - } - LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { .. } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => { - unreachable!("cache hit leaf cannot finish with {outcome:?}") - } + upload_error: None, }, - CacheStatus::Disabled(CacheDisabledReason::InProcessExecution) => match outcome { - LeafOutcome::InProcess => Self::InProcess, - LeafOutcome::Failed(_) - | LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::SpawnedSuccess { .. } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => { - unreachable!("in-process leaf cannot finish with {outcome:?}") - } - }, - CacheStatus::Disabled(CacheDisabledReason::NoCacheMetadata) => Self::Spawned { - cache_status: SpawnedCacheStatus::Disabled, - outcome: spawn_outcome_from_leaf(outcome), - }, - CacheStatus::Miss(cache_miss) => Self::Spawned { - cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::from_cache_miss( - cache_miss, - )), - outcome: spawn_outcome_from_leaf(outcome), + LeafOutcome::RestoreFailed { source, error } => Self::Recorded { + result: TaskResult::RestoreFailed { + source: *source, + error: SavedError::new(error), + }, + upload_error: None, }, + LeafOutcome::InProcess => { + Self::Recorded { result: TaskResult::InProcess, upload_error: None } + } + LeafOutcome::Spawned { cache_status, outcome } => { + let saved_cache_status = match cache_status { + LiveSpawnCacheStatus::Miss(miss) => { + SpawnedCacheStatus::Miss(SavedCacheMissReason::from_cache_miss(miss)) + } + LiveSpawnCacheStatus::Disabled => SpawnedCacheStatus::Disabled, + }; + let (saved_outcome, upload_error) = match outcome { + SpawnLeafOutcome::Success { cache_update } => { + let upload_error = match cache_update { + CacheUpdateOutcome::Updated { upload_error } => { + Some(Arc::clone(upload_error)) + } + CacheUpdateOutcome::NotUpdated(_) | CacheUpdateOutcome::Failed(_) => { + None + } + }; + ( + SpawnOutcome::Success(SavedCacheOutcome::from_cache_update( + cache_update, + )), + upload_error, + ) + } + SpawnLeafOutcome::Failed { exit_code } => { + (SpawnOutcome::Failed { exit_code: *exit_code }, None) + } + SpawnLeafOutcome::SpawnError(err) => { + (SpawnOutcome::SpawnError(SavedError::new(err)), None) + } + SpawnLeafOutcome::WouldSpawn => (SpawnOutcome::WouldSpawn, None), + }; + Self::Recorded { + result: TaskResult::Spawned { + cache_status: saved_cache_status, + outcome: saved_outcome, + }, + upload_error, + } + } + LeafOutcome::FailedBeforeStart(_) => Self::FailedBeforeStart, + LeafOutcome::Cancelled => Self::Cancelled, } } +} +impl TaskResult { /// Record why uploading the entry to the remote cache failed. The upload - /// can fail after the task finishes, so this is set after - /// [`Self::from_execution`]. Only a successful spawned task whose local - /// cache was updated uploads an entry, so other results are left as they are. + /// can fail after the task finishes, so this is set after recording the + /// task. Only a successful spawned task whose local cache was updated + /// uploads an entry, so other results are left as they are. pub fn set_upload_error(&mut self, error: SavedError) { if let Self::Spawned { outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error }), @@ -402,22 +435,6 @@ impl TaskResult { } } -/// Build a [`SpawnOutcome`] from a spawned leaf's [`LeafOutcome`]. -/// A failed upload is set later, with [`TaskResult::set_upload_error`]. -fn spawn_outcome_from_leaf(outcome: &LeafOutcome) -> SpawnOutcome { - match outcome { - LeafOutcome::Failed(err) => SpawnOutcome::SpawnError(SavedError::new(err)), - LeafOutcome::SpawnedSuccess { cache_update } => { - SpawnOutcome::Success(SavedCacheOutcome::from_cache_update(cache_update)) - } - LeafOutcome::SpawnedFailed { exit_code } => SpawnOutcome::Failed { exit_code: *exit_code }, - LeafOutcome::WouldSpawn => SpawnOutcome::WouldSpawn, - LeafOutcome::CacheHit | LeafOutcome::InProcess | LeafOutcome::Cancelled => { - unreachable!("spawned leaf cannot finish with {outcome:?}") - } - } -} - #[expect( clippy::cast_possible_truncation, reason = "value is clamped to u64::MAX before casting, so no data loss" @@ -557,31 +574,32 @@ impl TaskResult { } Self::Spawned { cache_status, - outcome: SpawnOutcome::Success(SavedCacheOutcome::NotCached(reason)), + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotUpdated(reason)), } => match reason { - SavedNotCachedReason::ToolRequested => { + SavedCacheNotUpdatedReason::ToolRequested => { (Str::from("→ Not cached: the task opted out of caching"), Vec::new(), &[]) } - SavedNotCachedReason::TrackingIncomplete => ( + SavedCacheNotUpdatedReason::TrackingIncomplete => ( Str::from( "→ Not cached: automatic file tracking couldn't record everything this task did. Configure `input` and `output` manually to enable caching.", ), Vec::new(), &[], ), - SavedNotCachedReason::FspyUnsupported => ( + SavedCacheNotUpdatedReason::FspyUnsupported => ( Str::from( "→ Not cached: `input` auto-inference isn't supported on this OS. Configure `input` manually to enable caching.", ), Vec::new(), &[], ), - SavedNotCachedReason::IpcServerError(error) => ( + SavedCacheNotUpdatedReason::IpcServerError(error) => ( vt_str::format!("→ Not cached: task communication failed: {}", error.message), Vec::new(), &error.causes, ), - SavedNotCachedReason::CacheDisabled | SavedNotCachedReason::Cancelled => { + SavedCacheNotUpdatedReason::CacheDisabled + | SavedCacheNotUpdatedReason::Cancelled => { format_spawned_cache_status(cache_status) } }, @@ -598,6 +616,21 @@ impl TaskResult { } } + /// IPC server error recorded when runner communication failed during a + /// successful spawned run. + const fn ipc_server_error(&self) -> Option<&SavedError> { + match self { + Self::Spawned { + outcome: + SpawnOutcome::Success(SavedCacheOutcome::NotUpdated( + SavedCacheNotUpdatedReason::IpcServerError(error), + )), + .. + } => Some(error), + _ => None, + } + } + /// With `vp run -vv`, the cached run the task was compared with, and the /// changes found, or `None` for them when some files or envs couldn't be /// checked, so what's unchanged isn't known. @@ -650,7 +683,7 @@ impl TaskResult { SpawnOutcome::Success(SavedCacheOutcome::Failed(err)) | SpawnOutcome::SpawnError(err) => Some(err), SpawnOutcome::Success( - SavedCacheOutcome::Updated { .. } | SavedCacheOutcome::NotCached(_), + SavedCacheOutcome::Updated { .. } | SavedCacheOutcome::NotUpdated(_), ) | SpawnOutcome::Failed { .. } | SpawnOutcome::WouldSpawn => None, @@ -845,17 +878,27 @@ pub fn format_full_summary(summary: &LastRunSummary, run_kind: RunKind) -> Vec>, display: ExecutionItemDisplay, workspace_path: Arc, - cache_status: Option, } impl LeafExecutionReporter for SummaryLeafReporter { - fn start(&mut self, cache_status: CacheStatus) -> StdioConfig { - self.cache_status = Some(cache_status.clone()); + fn start(&mut self, cache_status: &CacheStatus) -> StdioConfig { self.inner.start(cache_status) } fn finish(self: Box, outcome: LeafOutcome) { // Record task summary before forwarding to inner. - if let Some(ref cache_status) = self.cache_status { - let cwd_relative = - if let Ok(Some(rel)) = self.display.cwd.strip_prefix(&self.workspace_path) { - Str::from(rel.as_str()) - } else { - Str::default() + match LeafSummaryOutcome::from_leaf_outcome(&outcome) { + LeafSummaryOutcome::Recorded { result, upload_error } => { + let cwd_relative = + if let Ok(Some(rel)) = self.display.cwd.strip_prefix(&self.workspace_path) { + Str::from(rel.as_str()) + } else { + Str::default() + }; + + let summary = TaskSummary { + package_name: self.display.task_display.package_name.clone(), + task_name: self.display.task_display.task_name.clone(), + command: self.display.command.clone(), + cwd: cwd_relative, + result, }; - - let summary = TaskSummary { - package_name: self.display.task_display.package_name.clone(), - task_name: self.display.task_display.task_name.clone(), - command: self.display.command.clone(), - cwd: cwd_relative, - result: TaskResult::from_execution(cache_status, &outcome), - }; - let upload_error = match &outcome { - LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { upload_error }, - } => Some(Arc::clone(upload_error)), - LeafOutcome::Failed(_) - | LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::NotUpdated(_) | CacheUpdateOutcome::Failed(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => None, - }; - - self.tasks.borrow_mut().push(RecordedTask { summary, upload_error }); - } else { - match &outcome { - LeafOutcome::Failed(_) - | LeafOutcome::SpawnedSuccess { cache_update: CacheUpdateOutcome::Failed(_) } => { - self.failed_before_start.set(true); - } - LeafOutcome::CacheHit - | LeafOutcome::WouldSpawn - | LeafOutcome::InProcess - | LeafOutcome::SpawnedSuccess { - cache_update: - CacheUpdateOutcome::Updated { .. } | CacheUpdateOutcome::NotUpdated(_), - } - | LeafOutcome::SpawnedFailed { .. } - | LeafOutcome::Cancelled => {} + self.tasks.borrow_mut().push(RecordedTask { summary, upload_error }); } + LeafSummaryOutcome::FailedBeforeStart => { + self.failed_before_start.set(true); + } + LeafSummaryOutcome::Cancelled => {} } self.inner.finish(outcome); @@ -281,7 +253,10 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheErrorKind, ExecutionError}, + event::{ + CacheErrorKind, CacheUpdateOutcome, ExecutionError, LiveSpawnCacheStatus, + SpawnLeafOutcome, + }, reporter::{ ColorSupport, InterleavedReporterBuilder, test_fixtures::{SharedBuffer, spawn_task, test_path}, @@ -321,9 +296,14 @@ mod tests { let upload_error = Arc::new(OnceLock::new()); let mut leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind); - leaf.start(CacheStatus::Miss(CacheMiss::NotFound)); - leaf.finish(LeafOutcome::SpawnedSuccess { - cache_update: CacheUpdateOutcome::Updated { upload_error: Arc::clone(&upload_error) }, + leaf.start(&CacheStatus::Miss(CacheMiss::NotFound)); + leaf.finish(LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::Updated { + upload_error: Arc::clone(&upload_error), + }, + }, }); reporter.uploads_pending(NonZeroUsize::MIN); upload_error.set(UploadError::Interrupted).unwrap(); @@ -364,7 +344,7 @@ mod tests { )) .build(); let leaf = reporter.new_leaf_execution(&[], &item.execution_item_display, leaf_kind); - leaf.finish(LeafOutcome::Failed(ExecutionError::Cache { + leaf.finish(LeafOutcome::FailedBeforeStart(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("the cache database can't be read"), }));