diff --git a/crates/vt/src/session/event.rs b/crates/vt/src/session/event.rs index ff1818e2a..01d206f04 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,94 @@ 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), +} + +/// 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). +/// +/// 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 { + /// Cache hit: no process ran. Captured outputs were replayed, except in a + /// dry run. + 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, + /// 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`), @@ -164,20 +245,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..f357fac85 100644 --- a/crates/vt/src/session/execute/mod.rs +++ b/crates/vt/src/session/execute/mod.rs @@ -16,8 +16,9 @@ mod win_job; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, + num::NonZeroI32, sync::Arc, - time::Instant, + time::{Duration, Instant}, }; use futures_util::future::LocalBoxFuture; @@ -34,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, CacheUpdateStatus, - ExecutionError, RunKind, + CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason, CacheStatus, + CacheUpdateOutcome, ExecutionError, LeafOutcome, LiveSpawnCacheStatus, RunKind, + SpawnLeafOutcome, non_zero_exit_code, }, reporter::{LeafExecutionReporter, PipeWriters, StdioConfig, StdioSuggestion}, }; @@ -54,12 +59,15 @@ 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), - /// An infrastructure error prevented the process from running - /// (cache lookup failure or spawn failure). - /// Already reported through the leaf reporter. - Failed, + /// 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, 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. @@ -263,82 +271,59 @@ impl<'a> ExecutionMode<'a> { } } -/// Everything the pipeline reports through the single +/// Everything the spawn 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. +/// 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 { - exit_status: std::process::ExitStatus, - cache_update: CacheUpdateStatus, - error: Option, + cache_status: LiveSpawnCacheStatus, + outcome: SpawnLeafOutcome, }, - /// The run was cancelled before the process started. + FailedBeforeStart(ExecutionError), 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. +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 { - 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 + 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::WouldSpawn => { - reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::DryRun), - None, - ); - SpawnOutcome::WouldSpawn + 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::Spawned { exit_status, cache_update, error } => { - reporter.finish(Some(exit_status), cache_update, error); - SpawnOutcome::Spawned(exit_status) + Self::FailedBeforeStart(error) => { + (SpawnOutcome::InfraError, LeafOutcome::FailedBeforeStart(error)) } - // `start()` wasn't called, so the reporter shows and saves nothing. - Self::Cancelled => { - reporter.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::Cancelled), - None, - ); - SpawnOutcome::Cancelled - } - } + Self::Cancelled => (SpawnOutcome::Cancelled, LeafOutcome::Cancelled), + }; + reporter.finish(leaf_outcome); + spawn_outcome } } @@ -350,7 +335,7 @@ impl Report { /// 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 @@ -407,11 +392,11 @@ pub async fn execute_spawn( /// 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 [`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 +/// 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 +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 @@ -444,26 +429,30 @@ async fn run( ) .await?; if cancel_token.is_cancelled() { - return Err(Report::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(Report::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, @@ -473,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(Report::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(Report::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(); @@ -494,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, @@ -502,7 +503,10 @@ async fn run( mode.injected_envs(), ) .await - .map_err(|err| Report::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. @@ -527,9 +531,22 @@ 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 = 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(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Failed { + 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 +557,30 @@ 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(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 ran, so we return its actual status. - let (cache_update, error) = match mode { + // 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( cache, workspace_root, cache_dir, state, - &outcome, + #[cfg(fspy)] + outcome.path_accesses.as_ref(), reports.as_ref(), duration, &cancel_token, @@ -569,11 +589,14 @@ 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(SpawnReport::Spawned { + cache_status: spawn_cache_status, + outcome: SpawnLeafOutcome::Success { cache_update }, + }) } /// Outcome of the cache-lookup phase. Each variant carries exactly what that @@ -595,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 [`Report::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, @@ -604,7 +627,7 @@ async fn lookup_cache<'a>( run_kind: RunKind, file_check: FileCheck, cancel_token: &CancellationToken, -) -> Result, Report> { +) -> Result, SpawnReport> { let Some(cache_metadata) = cache_metadata else { return Ok(CacheLookup::Disabled); }; @@ -627,9 +650,12 @@ async fn lookup_cache<'a>( anyhow::Ok(globbed_inputs) }) .await - .ok_or(Report::Cancelled)?; + .ok_or(SpawnReport::Cancelled)?; let globbed_inputs = Arc::new(hashed.map_err(|err| { - Report::failed(ExecutionError::Cache { kind: CacheErrorKind::Lookup, source: err }) + SpawnReport::FailedBeforeStart(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: err, + }) })?); match cache @@ -650,10 +676,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(SpawnReport::Cancelled), + Err(err) => Err(SpawnReport::FailedBeforeStart(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: err, + })), } } @@ -661,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, -) -> Report { +) -> 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, @@ -680,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 } @@ -690,13 +717,14 @@ async fn replay_cache_hit( ExecutionError::Cache { kind: CacheErrorKind::Restore, source: err } } }; - return Report::Failed { - cache_update: CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheHit), - error, - }; + return SpawnReport::RestoreFailed { source: hit.source, error }; } - Report::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 f58a36c4b..3d0dc524d 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}, }, }; @@ -236,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 { @@ -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::InfraError => true, } } }; diff --git a/crates/vt/src/session/mod.rs b/crates/vt/src/session/mod.rs index 3f94046c9..10a7cd1eb 100644 --- a/crates/vt/src/session/mod.rs +++ b/crates/vt/src/session/mod.rs @@ -791,25 +791,23 @@ 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. - 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 737499a97..ec5592432 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, 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, ); @@ -127,12 +127,9 @@ impl LeafExecutionReporter for GroupedLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + let error = outcome.into_error(); + // Build grouped block: header + buffered output. let mut extra = Vec::new(); if let Some(ref grouped_buffer) = self.grouped_buffer { @@ -186,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 8358574b7..f3f7982b7 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, 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, ); @@ -130,12 +130,8 @@ impl LeafExecutionReporter for InterleavedLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + 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 @@ -158,7 +154,10 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheDisabledReason, CacheErrorKind, CacheNotUpdatedReason}, + event::{ + CacheDisabledReason, CacheErrorKind, ExecutionError, LiveSpawnCacheStatus, + SpawnLeafOutcome, + }, reporter::{ StdioSuggestion, test_fixtures::{SharedBuffer, in_process_task, spawn_task, test_path}, @@ -184,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] @@ -219,19 +218,20 @@ 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.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(None, not_updated(), Some(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 047e001b3..4e724f4fa 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, LeafOutcome}, json::{self, Version, path_key, task_id}, }; @@ -263,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, @@ -280,13 +277,8 @@ 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 { + fn finish(self: Box, outcome: LeafOutcome) { + 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}"), @@ -502,7 +494,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 +524,7 @@ mod tests { kind: CacheErrorKind::Lookup, source: anyhow::anyhow!("database is locked"), }; - leaf.finish( - None, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::DryRun), - Some(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 22f1c75a7..104ee58ca 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, 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, ); @@ -123,12 +123,8 @@ impl LeafExecutionReporter for LabeledLeafReporter { } } - fn finish( - self: Box, - _status: Option, - _cache_update_status: CacheUpdateStatus, - error: Option, - ) { + fn finish(self: Box, outcome: LeafOutcome) { + let error = outcome.into_error(); write_leaf_trailing_output(&self.writer, error, self.started, &[]); } } @@ -166,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 6c03c3d4a..aec4e5e07 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}, }; // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ @@ -214,22 +214,12 @@ 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. - /// - /// - `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..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, CacheUpdateStatus, ExecutionError}; +use crate::session::event::{CacheStatus, 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 { .. }); + 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. // 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,20 @@ 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 { + fn finish(mut self: Box, outcome: LeafOutcome) { + 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(); + } + } 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(); - 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(); } } } @@ -131,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); } @@ -140,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 dac339713..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,9 +26,12 @@ 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::{ + CacheNotUpdatedReason, CacheUpdateOutcome, LeafOutcome, LiveSpawnCacheStatus, RunKind, + SpawnLeafOutcome, }, - event::{CacheDisabledReason, CacheNotUpdatedReason, CacheStatus, CacheUpdateStatus, RunKind}, }; // ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ @@ -106,42 +110,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. + NotUpdated(SavedCacheNotUpdatedReason), + /// 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 SavedCacheNotUpdatedReason { + /// 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 +253,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::NotUpdated(_)) + | SpawnOutcome::WouldSpawn => {} } } } @@ -284,134 +312,129 @@ impl SavedCacheMissReason { } } -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)) +impl SavedCacheOutcome { + fn from_cache_update(cache_update: &CacheUpdateOutcome) -> Self { + match cache_update { + CacheUpdateOutcome::Updated { .. } => Self::Updated { upload_error: None }, + CacheUpdateOutcome::NotUpdated(reason) => { + Self::NotUpdated(SavedCacheNotUpdatedReason::from_reason(reason)) } - _ => None, - }; - let tool_disabled_cache = matches!( - cache_update_status, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::ToolRequested) - ); - let tracking_incomplete = matches!( - cache_update_status, - CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete) - ); + CacheUpdateOutcome::Failed(error) => Self::Failed(SavedError::new(error)), + } + } +} - 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::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, - ), +impl SavedCacheNotUpdatedReason { + 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, + } + } +} + +/// 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(), + }, + upload_error: None, }, - 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, - ), + 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 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 { 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. -/// 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), - } - } - // 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, - }, - } -} - #[expect( clippy::cast_possible_truncation, reason = "value is clamped to u64::MAX before casting, so no data loss" @@ -509,14 +532,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 +551,84 @@ 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::NotUpdated(reason)), + } => match reason { + SavedCacheNotUpdatedReason::ToolRequested => { + (Str::from("→ Not cached: the task opted out of caching"), Vec::new(), &[]) + } + 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(), + &[], + ), + SavedCacheNotUpdatedReason::FspyUnsupported => ( + Str::from( + "→ Not cached: `input` auto-inference isn't supported on this OS. Configure `input` manually to enable caching.", + ), + Vec::new(), + &[], + ), + SavedCacheNotUpdatedReason::IpcServerError(error) => ( + vt_str::format!("→ Not cached: task communication failed: {}", error.message), + Vec::new(), + &error.causes, + ), + SavedCacheNotUpdatedReason::CacheDisabled + | SavedCacheNotUpdatedReason::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), + } + } + + /// 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 @@ -637,22 +663,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 +680,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::NotUpdated(_), + ) + | 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 { @@ -1212,14 +1254,9 @@ mod tests { cwd: Str::default(), result: TaskResult::Spawned { cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), - outcome: SpawnOutcome::Success { - infra_error: None, - fspy_unsupported: false, - ipc_server_error: None, - tracking_incomplete: false, - tool_disabled_cache: false, + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error: Some(error), - }, + }), }, } } @@ -1246,24 +1283,24 @@ mod tests { cwd: Str::default(), result: TaskResult::Spawned { cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), - outcome: SpawnOutcome::Success { - infra_error: None, - fspy_unsupported: false, - ipc_server_error: None, - tracking_incomplete: false, - tool_disabled_cache: false, - upload_error: None, - }, + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { upload_error: None }), }, } } fn cache_disabled_task(task_name: &str) -> 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::NotUpdated( + SavedCacheNotUpdatedReason::CacheDisabled, + )), + }, } - task } fn compact_summary(tasks: Vec) -> Str { @@ -1569,4 +1606,337 @@ 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 last_run_summary_round_trips_new_spawn_and_cache_outcomes() { + let dir = tempfile::tempdir().unwrap(); + let path = vt_path::AbsolutePathBuf::new(dir.path().join("last-summary.json")).unwrap(); + let original = LastRunSummary { + tasks: vec![ + cache_miss_task("updated-ok"), + upload_failed_task("updated-upload-err", saved_error("unauthorized", &[])), + TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from("ipc-err"), + command: Str::from("build"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotUpdated( + SavedCacheNotUpdatedReason::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"], + ))), + }, + }, + TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from("dry"), + command: Str::from("build"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Disabled, + outcome: SpawnOutcome::WouldSpawn, + }, + }, + ], + exit_code: 1, + }; + + let json = serde_json::to_string(&original).unwrap(); + std::fs::write(&path, &json).unwrap(); + let Ok(Some(loaded)) = LastRunSummary::read_from_path(&path) else { + panic!("expected saved summary to deserialize"); + }; + + assert_eq!(loaded.exit_code, 1); + assert_eq!(loaded.tasks.len(), original.tasks.len()); + assert_eq!( + strip(&format_full_summary(&loaded, RunKind::Real)), + strip(&format_full_summary(&original, RunKind::Real)) + ); + } + + #[test] + fn from_leaf_outcome_maps_non_spawn_variants() { + let hit = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::CacheHit { + replayed_duration: Duration::from_millis(250), + source: CacheHitSource::Remote, + baseline: None, + }); + assert!(matches!( + hit, + LeafSummaryOutcome::Recorded { + result: TaskResult::CacheHit { + saved_duration_ms: 250, + source: CacheHitSource::Remote, + baseline: None, + }, + upload_error: None, + } + )); + + let restore_failed = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::RestoreFailed { + source: CacheHitSource::Local, + error: ExecutionError::LocalCacheRestore { + program_name: Str::from("vp"), + source: anyhow::anyhow!("missing archive"), + }, + }); + assert!(matches!( + restore_failed, + LeafSummaryOutcome::Recorded { + result: TaskResult::RestoreFailed { source: CacheHitSource::Local, .. }, + upload_error: None, + } + )); + + let in_process = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::InProcess); + assert!(matches!( + in_process, + LeafSummaryOutcome::Recorded { result: TaskResult::InProcess, upload_error: None } + )); + + let failed_before_start = + LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::FailedBeforeStart( + ExecutionError::Spawn(anyhow::anyhow!("lookup failed")), + )); + assert!(matches!(failed_before_start, LeafSummaryOutcome::FailedBeforeStart)); + + let cancelled = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Cancelled); + assert!(matches!(cancelled, LeafSummaryOutcome::Cancelled)); + } + + #[test] + fn from_leaf_outcome_maps_spawned_variants() { + let updated = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::Updated { + upload_error: Arc::new(OnceLock::new()), + }, + }, + }); + assert!(matches!( + updated, + LeafSummaryOutcome::Recorded { + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::Updated { + upload_error: None, + }), + }, + upload_error: Some(_), + } + )); + + let cache_disabled = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Disabled, + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::NotUpdated(CacheNotUpdatedReason::CacheDisabled), + }, + }); + assert!(matches!( + cache_disabled, + LeafSummaryOutcome::Recorded { + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Disabled, + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotUpdated( + SavedCacheNotUpdatedReason::CacheDisabled, + )), + }, + upload_error: None, + } + )); + + let update_failed = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::Success { + cache_update: CacheUpdateOutcome::Failed(ExecutionError::PostRunFingerprint( + anyhow::anyhow!("hash failed"), + )), + }, + }); + let LeafSummaryOutcome::Recorded { result: update_failed_result, upload_error: None } = + update_failed + else { + panic!("expected recorded result without upload handle"); + }; + assert!(matches!( + update_failed_result, + TaskResult::Spawned { + outcome: SpawnOutcome::Success(SavedCacheOutcome::Failed(_)), + .. + } + )); + assert!(update_failed_result.error().is_some()); + + let exited_non_zero = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::Failed { exit_code: NonZeroI32::new(2).unwrap() }, + }); + assert!(matches!( + exited_non_zero, + LeafSummaryOutcome::Recorded { + result: TaskResult::Spawned { outcome: SpawnOutcome::Failed { exit_code }, .. }, + upload_error: None, + } if exit_code.get() == 2 + )); + + let dry_run = LeafSummaryOutcome::from_leaf_outcome(&LeafOutcome::Spawned { + cache_status: LiveSpawnCacheStatus::Miss(CacheMiss::NotFound), + outcome: SpawnLeafOutcome::WouldSpawn, + }); + assert!(matches!( + dry_run, + LeafSummaryOutcome::Recorded { + result: TaskResult::Spawned { outcome: SpawnOutcome::WouldSpawn, .. }, + upload_error: None, + } + )); + } + + #[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_updated_reasons_and_update_error() { + let not_updated = |task_name: &str, reason: SavedCacheNotUpdatedReason| 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::NotUpdated(reason)), + }, + }; + + let summary = full_summary(vec![ + not_updated("opt-out", SavedCacheNotUpdatedReason::ToolRequested), + not_updated("incomplete", SavedCacheNotUpdatedReason::TrackingIncomplete), + not_updated("no-fspy", SavedCacheNotUpdatedReason::FspyUnsupported), + not_updated( + "ipc", + SavedCacheNotUpdatedReason::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..a2f09b821 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,10 +22,10 @@ use super::{ }; use crate::session::{ cache::remote::UploadError, - event::{CacheStatus, CacheUpdateStatus, ExecutionError, RunKind}, + event::{CacheStatus, LeafOutcome, RunKind}, reporter::summary::{ - LastRunSummary, SavedError, SpawnOutcome, TaskResult, TaskSummary, format_compact_summary, - format_full_summary, format_uploads_pending, + LastRunSummary, LeafSummaryOutcome, SavedError, SpawnOutcome, TaskResult, TaskSummary, + format_compact_summary, format_full_summary, format_uploads_pending, }, }; @@ -119,7 +118,6 @@ impl GraphExecutionReporter for SummaryGraphReporter { failed_before_start: Rc::clone(&self.failed_before_start), display: display.clone(), workspace_path: Arc::clone(&self.workspace_path), - cache_status: None, }) } @@ -211,55 +209,40 @@ struct SummaryLeafReporter { failed_before_start: Rc>, 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, - 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) { - 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, - status, - saved_error.as_ref(), - &cache_update_status, - ), - }; - let upload_error = match &cache_update_status { - CacheUpdateStatus::Updated { upload_error } => Some(Arc::clone(upload_error)), - CacheUpdateStatus::NotUpdated(_) => None, - }; - - self.tasks.borrow_mut().push(RecordedTask { summary, upload_error }); - } else if error.is_some() { - self.failed_before_start.set(true); + self.tasks.borrow_mut().push(RecordedTask { summary, upload_error }); + } + LeafSummaryOutcome::FailedBeforeStart => { + self.failed_before_start.set(true); + } + LeafSummaryOutcome::Cancelled => {} } - self.inner.finish(status, cache_update_status, error); + self.inner.finish(outcome); } } @@ -270,7 +253,10 @@ mod tests { use super::*; use crate::session::{ cache::CacheMiss, - event::{CacheErrorKind, CacheNotUpdatedReason}, + event::{ + CacheErrorKind, CacheUpdateOutcome, ExecutionError, LiveSpawnCacheStatus, + SpawnLeafOutcome, + }, reporter::{ ColorSupport, InterleavedReporterBuilder, test_fixtures::{SharedBuffer, spawn_task, test_path}, @@ -310,12 +296,15 @@ 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.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(); reporter.finish().unwrap(); @@ -355,14 +344,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::FailedBeforeStart(ExecutionError::Cache { + kind: CacheErrorKind::Lookup, + source: anyhow::anyhow!("the cache database can't be read"), + })); assert_eq!(reporter.finish(), Err(ExitStatus::FAILURE), "{run_kind:?}"); } }