Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
127 changes: 105 additions & 22 deletions crates/vt/src/session/event.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::{
num::NonZeroI32,
process::ExitStatus,
sync::{Arc, OnceLock},
time::Duration,
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -136,10 +133,94 @@ pub enum CacheUpdateStatus {
/// returns.
upload_error: Arc<OnceLock<UploadError>>,
},
/// 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<Arc<BaselineDetails>>,
},
/// 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<ExecutionError> {
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`),
Expand All @@ -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() })
}
75 changes: 31 additions & 44 deletions crates/vt/src/session/execute/cache_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
},
};

Expand All @@ -53,27 +52,30 @@ struct TrackingOutcome {
type TrackedEnvValues = BTreeMap<Str, Option<EnvValueHash>>;
type TrackedEnvQueryValues = BTreeMap<TrackedEnvQuery, BTreeMap<Str, EnvValueHash>>;

/// 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<AbsolutePath>,
cache_dir: &AbsolutePath,
state: CacheState<'_>,
outcome: &ChildOutcome,
#[cfg(fspy)] path_accesses: Option<&Result<fspy::PathAccessIterable, fspy::TrackingIncomplete>>,
reports: Option<&Reports>,
duration: Duration,
cancel_token: &CancellationToken,
) -> (CacheUpdateStatus, Option<ExecutionError>) {
) -> CacheUpdateOutcome {
let CacheState { metadata, globbed_inputs, std_outputs, tracking } = state;
let fspy = tracking.fspy.as_ref();

Expand All @@ -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
Expand All @@ -96,21 +98,16 @@ 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
// `Err` means tracking could not record everything it did, so what
// 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.
Expand All @@ -131,20 +128,15 @@ 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
// names that the user already declared are skipped because their values
// 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
Expand All @@ -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(
Expand All @@ -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,
});
}
};

Expand All @@ -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,
}),
}
}

Expand Down
Loading
Loading