GeezerVison is showing github.com — feat(cache): fingerprint tracked getEnv reads by wan9chi · Pull Request #454 · voidzero-dev/vite-task
feat(cache): fingerprint tracked getEnv reads
#454
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.json
(1)
.md
(3)
.rs
(10)
.toml
(1)
All 4 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,7 @@
# Changelog
- **Changed** Tracked environment values in task cache fingerprints are now stored only as SHA-256 digests, and env-related cache miss details report names without values.
- **Fixed** Runner-aware `getEnv` reads now affect task cache fingerprints, so changing a tool-served env value invalidates cached output and names the env var in the miss message ([#454](https://github.com/voidzero-dev/vite-task/pull/454)).
- **Added** Runner-aware tools can now opt the current task run out of caching through the new IPC channel; Vite dev server integration uses this automatically ([#441](https://github.com/voidzero-dev/vite-task/pull/441))
- **Fixed** Prefix environment assignments like `PATH=... command` now affect executable lookup during task planning, so tools provided only by the prefixed `PATH` can be resolved correctly ([#440](https://github.com/voidzero-dev/vite-task/pull/440))
- **Changed** Cache misses caused by a tracked env var now name the env var inline, for example `cache miss: env 'NODE_ENV' changed`, instead of the generic `envs changed` message ([#438](https://github.com/voidzero-dev/vite-task/pull/438))
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -186,6 +186,9 @@ pub fn format_cache_status_inline(cache_status: &CacheStatus) -> Option<Str> {
FingerprintMismatch::InputChanged { kind, path } => {
format_input_change_str(*kind, path.as_str())
}
FingerprintMismatch::TrackedEnvChanged(mismatch) => {
format_env_changed_inline(&[mismatch.name()])
}
};
Some(vite_str::format!("○ cache miss: {reason}, executing"))
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -163,6 +163,21 @@ impl EnvMismatch {
Self::Added { name } | Self::Removed { name } | Self::Changed { name } => name,
}
}
/// Compare a stored env value against the current one, returning the
/// mismatch if they differ. `None` on either side means the env is unset
/// there; two unset or two equal values are not a mismatch.
#[must_use]
pub fn compare<T: Eq>(name: &Str, stored: Option<&T>, current: Option<&T>) -> Option<Self> {
match (stored, current) {
(None, Some(_)) => Some(Self::Added { name: name.clone() }),
(Some(_), None) => Some(Self::Removed { name: name.clone() }),
(Some(old_value), Some(new_value)) if old_value != new_value => {
Some(Self::Changed { name: name.clone() })
}
_ => None,
}
}
}
impl Display for EnvMismatch {
Expand Down
Expand Up
@@ -194,23 +209,16 @@ pub enum FingerprintMismatch {
kind: InputChangeKind,
path: RelativePathBuf,
},
/// A runner-aware tool-tracked env var changed between runs.
TrackedEnvChanged(EnvMismatch),
}
impl Display for FingerprintMismatch {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SpawnFingerprint { old, new } => {
write!(f, "Spawn fingerprint changed: old={old:?}, new={new:?}")
}
Self::InputConfig => {
write!(f, "input configuration changed")
}
Self::OutputConfig => {
write!(f, "output configuration changed")
}
Self::InputChanged { kind, path } => {
write!(f, "{}", display::format_input_change_str(*kind, path.as_str()))
}
impl From<crate::session::execute::fingerprint::PostRunMismatch> for FingerprintMismatch {
fn from(mismatch: crate::session::execute::fingerprint::PostRunMismatch) -> Self {
use crate::session::execute::fingerprint::PostRunMismatch;
match mismatch {
PostRunMismatch::InputChanged { kind, path } => Self::InputChanged { kind, path },
PostRunMismatch::TrackedEnvChanged(mismatch) => Self::TrackedEnvChanged(mismatch),
}
}
}
Expand All
@@ -236,7 +244,7 @@ pub fn split_path(path: &str) -> (Option<&str>, &str) {
/// its own cache warm across branch switches, and a cache from a different
/// version is simply ignored (it lives in a directory this build never looks
/// at) rather than aborting the run. Bumping the version starts a fresh cache.
const CACHE_SCHEMA_VERSION: u32 = 14 ;
const CACHE_SCHEMA_VERSION: u32 = 15 ;
/// Name of the per-version subdirectory (e.g. `v14`) under the task-cache
/// directory that holds the database and output archives for the current
Expand Down
Expand Up
@@ -303,11 +311,12 @@ impl ExecutionCache {
return Ok(Err(CacheMiss::FingerprintMismatch(mismatch)));
}
// Validate post-run fingerprint (inferred inputs from fspy)
if let Some((kind, path)) = cache_value.post_run_fingerprint.validate(workspace_root)? {
return Ok(Err(CacheMiss::FingerprintMismatch(
FingerprintMismatch::InputChanged { kind, path },
)));
// Validate post-run fingerprint (inferred inputs + tracked envs)
if let Some(mismatch) = cache_value
.post_run_fingerprint
.validate(workspace_root, &cache_metadata.unfiltered_envs)?
{
return Ok(Err(CacheMiss::FingerprintMismatch(mismatch.into())));
}
// Associate the execution key to the cache entry key if not already,
// so that next time we can find it and report what changed
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,11 +1,11 @@
//! Post-run cache update: decide whether a finished spawn may be cached and,
//! if so, store its fingerprint, captured output, and output archive.
use std::{sync::Arc, time::Duration};
use std::{collections::BTreeMap, sync::Arc, time::Duration};
use vite_path::{AbsolutePath, RelativePathBuf};
use vite_str::Str;
use vite_task_plan::cache_metadata::CacheMetadata;
use vite_task_plan::cache_metadata::{ CacheMetadata, EnvValueHash} ;
use vite_task_server::Reports;
use super::{
Expand Down
Expand Up
@@ -97,13 +97,27 @@ pub(super) async fn update_cache(
return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::FspyUnsupported), None);
}
// 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 = match collect_tracked_reports(reports, metadata) {
Ok(tracked_envs) => tracked_envs,
Err(err) => {
return (
CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::CacheDisabled),
Some(ExecutionError::PostRunFingerprint(err)),
);
}
};
// Paths already in globbed_inputs are skipped: the overlap check above
// guarantees no input modification, so the prerun hash is the correct
// post-exec hash.
let empty_path_reads = HashMap::default();
let path_reads = fspy_outcome.as_ref().map_or(&empty_path_reads, |o| &o.path_reads);
let post_run_fingerprint =
match PostRunFingerprint::create(path_reads, workspace_root, &globbed_inputs) {
match PostRunFingerprint::create(path_reads, workspace_root, &globbed_inputs, tracked_envs)
{
Ok(fingerprint) => fingerprint,
Err(err) => {
return (
Expand Down
Expand Up
@@ -166,6 +180,44 @@ fn observe_fspy(
}
}
fn collect_tracked_reports(
reports: Option<&Reports>,
metadata: &CacheMetadata,
) -> anyhow::Result<BTreeMap<Str, Option<EnvValueHash>>> {
reports.map(|r| collect_tracked_envs(r, metadata)).transpose().map(Option::unwrap_or_default)
}
/// Select tool-reported env records to embed in the post-run fingerprint.
/// Only `tracked: true` records are included, and names that the user already
/// declared as fingerprinted are skipped.
fn collect_tracked_envs(
reports: &Reports,
metadata: &CacheMetadata,
) -> anyhow::Result<BTreeMap<Str, Option<EnvValueHash>>> {
let fingerprinted = &metadata.spawn_fingerprint.env_fingerprints().fingerprinted_envs;
let mut tracked_envs = BTreeMap::new();
for (name, value) in &reports.env_records {
let name_str =
name.to_str().ok_or_else(|| anyhow::anyhow!("tracked env name is not valid UTF-8"))?;
if fingerprinted.contains_key(name_str) {
continue;
}
let value = value
.as_ref()
.map(|value| {
let value_str = value.to_str().ok_or_else(|| {
anyhow::anyhow!("tracked env value for {name_str} is not valid UTF-8")
})?;
Ok::<_, anyhow::Error>(EnvValueHash::new(value_str))
})
.transpose()?;
tracked_envs.insert(Str::from(name_str), value);
}
Ok(tracked_envs)
}
/// Collect output files matching the configured globs and create a tar.zst
/// archive in the cache directory.
///
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -5,18 +5,24 @@
use std::{
collections::BTreeMap,
ffi::OsStr,
fs::File,
io::{self, BufRead},
sync::Arc,
};
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use vite_path::{AbsolutePath, RelativePathBuf};
use vite_str::Str;
use vite_task_plan::cache_metadata::EnvValueHash;
use wincode::{SchemaRead, SchemaWrite};
use crate::{collections::HashMap, session::cache::InputChangeKind};
use crate::{
collections::HashMap,
session::cache::{EnvMismatch, InputChangeKind},
};
/// Path read access info
#[derive(Debug, Clone, Copy)]
Expand All
@@ -26,11 +32,26 @@ pub struct PathRead {
/// Post-run fingerprint capturing file state after execution.
/// Used to validate whether cached outputs are still valid.
#[derive(SchemaWrite, SchemaRead, Debug, Serialize)]
#[derive(SchemaWrite, SchemaRead, Debug, Default, Serialize)]
pub struct PostRunFingerprint {
/// Paths inferred from fspy during execution with their content fingerprints.
/// Only populated when `input_config.includes_auto` is true.
pub inferred_inputs: HashMap<RelativePathBuf, PathFingerprint>,
/// Env vars observed via runner-aware IPC `getEnv` with `tracked: true`.
/// Key is the env name; value is the env value hash at execution time, or
/// `None` if unset. Validated at cache lookup against the same plan env
/// context that served the original request.
pub tracked_envs: BTreeMap<Str, Option<EnvValueHash>>,
}
/// A mismatch between the stored post-run fingerprint and the current state.
#[derive(Debug, Clone)]
pub enum PostRunMismatch {
/// An inferred input file or directory changed.
InputChanged { kind: InputChangeKind, path: RelativePathBuf },
/// A tool-tracked env var changed value, appeared, or disappeared.
TrackedEnvChanged(EnvMismatch),
}
/// Fingerprint for a single path (file or directory)
Expand Down
Expand Up
@@ -69,11 +90,13 @@ impl PostRunFingerprint {
/// * `inferred_path_reads` - Map of paths that were read during execution (from fspy)
/// * `base_dir` - Workspace root for resolving relative paths
/// * `globbed_inputs` - Prerun glob fingerprint; paths here are skipped
/// * `tracked_envs` - Tool-requested env vars (name -> value hash), validated on lookup
#[tracing::instrument(level = "debug", skip_all, name = "create_post_run_fingerprint")]
pub fn create(
inferred_path_reads: &HashMap<RelativePathBuf, PathRead>,
base_dir: &AbsolutePath,
globbed_inputs: &BTreeMap<RelativePathBuf, u64>,
tracked_envs: BTreeMap<Str, Option<EnvValueHash>>,
) -> anyhow::Result<Self> {
let inferred_inputs = inferred_path_reads
.par_iter()
Expand All
@@ -85,16 +108,24 @@ impl PostRunFingerprint {
})
.collect::<anyhow::Result<HashMap<_, _>>>()?;
Ok(Self { inferred_inputs })
Ok(Self { inferred_inputs, tracked_envs })
}
/// Validates the fingerprint against current filesystem state.
/// Returns `Some((kind, path))` if an input changed, `None` if all valid.
/// Validates the fingerprint against current filesystem state and the
/// unfiltered env context used by runner-aware IPC. `unfiltered_envs` must
/// be the same plan env context that served the original `getEnv` request,
/// not the filtered env passed to the spawned process.
///
/// Returns `Some(mismatch)` if anything changed, `None` if all valid.
/// Returns an error if a tracked env is currently present but cannot be
/// represented as UTF-8; treating that value as unset would make cache
/// validation unsound.
#[tracing::instrument(level = "debug", skip_all, name = "validate_post_run_fingerprint")]
pub fn validate(
&self,
base_dir: &AbsolutePath,
) -> anyhow::Result<Option<(InputChangeKind, RelativePathBuf)>> {
unfiltered_envs: &FxHashMap<Arc<OsStr>, Arc<OsStr>>,
) -> anyhow::Result<Option<PostRunMismatch>> {
let input_mismatch = self.inferred_inputs.par_iter().find_map_any(
|(input_relative_path, path_fingerprint)| {
let input_full_path = Arc::<AbsolutePath>::from(base_dir.join(input_relative_path));
Expand All
@@ -120,11 +151,32 @@ impl PostRunFingerprint {
} else {
input_relative_path.clone()
};
Some(Ok(( kind, path) ))
Some(Ok(PostRunMismatch::InputChanged { kind, path } ))
}
},
);
input_mismatch.transpose()
if let Some(result) = input_mismatch {
return result.map(Some);
}
for (name, stored_value) in &self.tracked_envs {
let current_value = unfiltered_envs
.get(OsStr::new(name.as_str()))
.map(|value| {
let value_str = value.to_str().ok_or_else(|| {
anyhow::anyhow!("tracked env value for {name} is not valid UTF-8")
})?;
Ok::<_, anyhow::Error>(EnvValueHash::new(value_str))
})
.transpose()?;
if let Some(mismatch) =
EnvMismatch::compare(name, stored_value.as_ref(), current_value.as_ref())
{
return Ok(Some(PostRunMismatch::TrackedEnvChanged(mismatch)));
}
}
Ok(None)
}
}
Expand Down
Expand Up
@@ -320,3 +372,44 @@ fn process_directory_unix(file: &File, path_read: PathRead) -> anyhow::Result<Pa
Ok(PathFingerprint::Folder(Some(entries)))
}
#[cfg(test)]
mod tests {
use std::ffi::{OsStr, OsString};
use super::*;
#[cfg(unix)]
fn non_utf8_os_string() -> OsString {
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(vec![0xFF])
}
#[cfg(windows)]
fn non_utf8_os_string() -> OsString {
use std::os::windows::ffi::OsStringExt;
OsString::from_wide(&[0xD800])
}
#[test]
fn validate_errors_on_current_non_utf8_tracked_env_value() {
let mut tracked_envs = BTreeMap::new();
tracked_envs.insert(Str::from("PROBE_ENV"), None);
let fingerprint = PostRunFingerprint { tracked_envs, ..PostRunFingerprint::default() };
let mut unfiltered_envs = FxHashMap::default();
unfiltered_envs.insert(
Arc::<OsStr>::from(OsStr::new("PROBE_ENV")),
Arc::<OsStr>::from(non_utf8_os_string()),
);
let workspace_root = vite_path::current_dir().expect("cwd");
let err = fingerprint
.validate(&workspace_root, &unfiltered_envs)
.expect_err("non-UTF-8 tracked env values must error");
assert!(err.to_string().contains("tracked env value for PROBE_ENV is not valid UTF-8"));
}
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.