diff --git a/CHANGELOG.md b/CHANGELOG.md index 671a8a929..fe274ce3e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Fixed** Tasks that list `node_modules`, the workspace root, or `node_modules/.vite` no longer miss the cache when pnpm's `node_modules/.pnpm-workspace-state-*.json`, Vite's `node_modules/.vite-temp`, the workspace root's `.git`, or the task cache directory appear or disappear. Direct accesses to `node_modules/.vite-temp` and `.DS_Store` are now skipped as well, so they are neither tracked as inputs nor archived as outputs ([#1014](https://github.com/voidzero-dev/vite-task/pull/1014)). - **Fixed** When a command handler sets a working directory for a command it generates, `vp run` now runs that command in the selected directory and includes the directory in its cache fingerprint ([#1005](https://github.com/voidzero-dev/vite-task/pull/1005)). - **Fixed** On Windows, tasks with automatic file-access tracking can now run Git Bash's `sh` and other MSYS2 or Cygwin programs, which aborted with `fatal error - MapViewOfFileEx 'shared.5'(…) Win32 error 487` ([#830](https://github.com/voidzero-dev/vite-task/issues/830), [#952](https://github.com/voidzero-dev/vite-task/pull/952)). - **Fixed** On Linux, cached tasks no longer fail to spawn child processes in restricted sandboxes, for example rootless bubblewrap that denies the `seccomp` syscall. When the `seccomp` filter for file-access tracking cannot be installed, the process runs untracked instead and the run is reported as not cached. The not-cached message now reads "automatic file tracking couldn't record everything this task did", which fits both this case and a full tracking channel ([#700](https://github.com/voidzero-dev/vite-task/issues/700), [#701](https://github.com/voidzero-dev/vite-task/pull/701)). diff --git a/crates/vt/src/session/cache/mod.rs b/crates/vt/src/session/cache/mod.rs index d3cd3f2bf..820ad8ea6 100644 --- a/crates/vt/src/session/cache/mod.rs +++ b/crates/vt/src/session/cache/mod.rs @@ -44,6 +44,7 @@ use super::{ event::RunKind, execute::{ fingerprint::{PathFingerprint, PostRunFingerprint}, + ignored_paths::relative_cache_root, pipe::StdOutput, }, }; @@ -468,7 +469,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 = 23; +const CACHE_SCHEMA_VERSION: u32 = 24; /// Name of the per-version subdirectory (e.g. `v14`) under the task-cache /// directory that holds the database and output archives for the current @@ -551,6 +552,8 @@ struct Validation { globbed_inputs: Arc>, input_negative_globs: Arc>, workspace_root: Arc, + /// Workspace-relative task cache root, left out of directory listings. + cache_root: Option, /// How many changed files to look for. file_check: FileCheck, } @@ -563,6 +566,7 @@ impl Validation { &self.globbed_inputs, &self.input_negative_globs, &self.workspace_root, + self.cache_root.as_deref(), self.file_check, ) } @@ -649,6 +653,7 @@ impl ExecutionCache { PathGlobSet::new(&cache_metadata.input_config.negative_globs)?.into_owned(), ), workspace_root: Arc::clone(workspace_root), + cache_root: relative_cache_root(cache_dir, workspace_root), file_check, }; diff --git a/crates/vt/src/session/cache/remote.rs b/crates/vt/src/session/cache/remote.rs index 44c933b86..e9864f849 100644 --- a/crates/vt/src/session/cache/remote.rs +++ b/crates/vt/src/session/cache/remote.rs @@ -666,6 +666,7 @@ mod tests { &globbed_inputs, &PathGlobSet::default(), &workspace_root, + None, FileCheck::First, ) } diff --git a/crates/vt/src/session/cache/validation.rs b/crates/vt/src/session/cache/validation.rs index 93a67c377..c4eb77666 100644 --- a/crates/vt/src/session/cache/validation.rs +++ b/crates/vt/src/session/cache/validation.rs @@ -5,7 +5,7 @@ use std::{collections::BTreeMap, ffi::OsStr, sync::Arc}; use rustc_hash::{FxHashMap, FxHashSet}; use vt_casefold::EnvName; use vt_glob::path::PathGlobSet; -use vt_path::{AbsolutePath, RelativePathBuf}; +use vt_path::{AbsolutePath, RelativePath, RelativePathBuf}; use vt_plan::cache_metadata::SpawnFingerprint; use super::{ @@ -35,6 +35,7 @@ impl CacheEntryValue { globbed_inputs: &BTreeMap, input_negative_globs: &PathGlobSet<'_>, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, file_check: FileCheck, ) -> anyhow::Result { // Without `-v`, the first changed file is enough to know it's a miss. @@ -45,6 +46,7 @@ impl CacheEntryValue { let input_changes = self.post_run_fingerprint.input_changes( workspace_root, input_negative_globs, + cache_root, file_check, ); partial |= add_checked(&mut changes, input_changes, "inferred inputs")?; @@ -232,6 +234,7 @@ mod tests { &inputs, &PathGlobSet::default(), &workspace_root, + None, FileCheck::First, ) }; @@ -276,6 +279,7 @@ mod tests { &BTreeMap::new(), &PathGlobSet::default(), &workspace_root, + None, FileCheck::First, ) .unwrap(); @@ -310,6 +314,7 @@ mod tests { ¤t, &PathGlobSet::default(), &workspace_root, + None, file_check, ) .unwrap() @@ -371,6 +376,7 @@ mod tests { &BTreeMap::new(), &PathGlobSet::default(), &workspace_root, + None, file_check, ) }; diff --git a/crates/vt/src/session/execute/cache_update.rs b/crates/vt/src/session/execute/cache_update.rs index c0a87c77a..95ddb7738 100644 --- a/crates/vt/src/session/execute/cache_update.rs +++ b/crates/vt/src/session/execute/cache_update.rs @@ -10,7 +10,7 @@ use std::{ use rustc_hash::FxHashSet; use tokio_util::sync::CancellationToken; use vt_glob::path::PathGlobSet; -use vt_path::{AbsolutePath, RelativePathBuf}; +use vt_path::{AbsolutePath, RelativePath, RelativePathBuf}; use vt_plan::cache_metadata::{CacheMetadata, EnvValueHash}; use vt_server::Reports; use vt_str::Str; @@ -19,6 +19,7 @@ use super::{ CacheState, fingerprint::{PathRead, PostRunFingerprint, TrackedEnvQuery}, glob, + ignored_paths::relative_cache_root, rebuildable::Rebuildable, spawn::ChildOutcome, }; @@ -112,6 +113,9 @@ pub(super) async fn update_cache( return (CacheUpdateStatus::NotUpdated(CacheNotUpdatedReason::TrackingIncomplete), None); }; + // Every schema version's folder is in the task cache, not only this one. + let cache_root = relative_cache_root(cache_dir, workspace_root); + let fspy_outcome = observe_fspy( #[cfg(fspy)] path_accesses, @@ -120,7 +124,7 @@ pub(super) async fn update_cache( &ignored_input_rels, &ignored_output_rels, workspace_root, - cache_dir, + cache_root.as_deref(), ); if fspy_outcome.is_none() && fspy.is_some() { @@ -146,12 +150,11 @@ pub(super) async fn update_cache( // Paths already in globbed_inputs are skipped: they are hashed before // the run, so one that the task rewrote makes the next run miss instead // of hitting a stale entry. - let empty_path_reads = HashMap::default(); + let (empty_path_reads, no_writes, no_globs) = + (HashMap::default(), Rebuildable::default(), PathGlobSet::default()); let path_reads = fspy_outcome.as_ref().map_or(&empty_path_reads, |o| &o.path_reads); - let no_writes = Rebuildable::default(); let rebuildable = fspy_outcome.as_ref().map_or(&no_writes, |o| &o.rebuildable); // Listings leave out the entries input exclusions match, as reads do. - let no_globs = PathGlobSet::default(); let input_negative_globs = fspy.map_or(&no_globs, |fspy| &fspy.input_negative_globs); let post_run_fingerprint = match PostRunFingerprint::create( path_reads, @@ -159,6 +162,7 @@ pub(super) async fn update_cache( input_negative_globs, &ignored_input_rels, workspace_root, + cache_root.as_deref(), &globbed_inputs, tracked_envs, tracked_env_queries, @@ -229,14 +233,12 @@ fn observe_fspy( ignored_input_rels: &FxHashSet, ignored_output_rels: &FxHashSet, workspace_root: &AbsolutePath, - cache_dir: &AbsolutePath, + cache_root: Option<&RelativePath>, ) -> Option { #[cfg(fspy)] { use super::tracked_accesses::TrackedPathAccesses; - // Every schema version's folder is in the task cache, not only this one. - let cache_root = cache_dir.parent().unwrap_or(cache_dir); path_accesses.map(|raw| { let tracked = TrackedPathAccesses::from_raw(raw, workspace_root, cache_root); let mut rebuildable = Rebuildable::new( @@ -244,6 +246,7 @@ fn observe_fspy( tracked.rename_targets, tracked.mkdirs, workspace_root, + cache_root, ); let filtered_path_reads: HashMap = // fspy can be attached for auto-output-only tasks. In that @@ -280,9 +283,9 @@ fn observe_fspy( // without them, the archive still takes the empty folders the // task made. rebuildable = if filtered_path_reads.is_empty() { - rebuildable.with_empty_folders(workspace_root) + rebuildable.with_empty_folders(workspace_root, cache_root) } else { - rebuildable.with_folders(workspace_root) + rebuildable.with_folders(workspace_root, cache_root) }; TrackingOutcome { path_reads: filtered_path_reads, @@ -301,7 +304,7 @@ fn observe_fspy( #[cfg(not(fspy))] { let _ = - (metadata, fspy, ignored_input_rels, ignored_output_rels, workspace_root, cache_dir); + (metadata, fspy, ignored_input_rels, ignored_output_rels, workspace_root, cache_root); None } } diff --git a/crates/vt/src/session/execute/fingerprint.rs b/crates/vt/src/session/execute/fingerprint.rs index 5ffc35745..6b48dad69 100644 --- a/crates/vt/src/session/execute/fingerprint.rs +++ b/crates/vt/src/session/execute/fingerprint.rs @@ -22,7 +22,7 @@ use vt_plan::cache_metadata::EnvValueHash; use vt_str::Str; use wincode::{SchemaRead, SchemaWrite}; -use super::rebuildable::Rebuildable; +use super::{ignored_paths::IgnoredDirEntries, rebuildable::Rebuildable}; use crate::{ collections::HashMap, session::cache::{Change, EnvMismatch, EnvSource, FileCheck, InputChangeKind}, @@ -96,16 +96,18 @@ pub enum PathFingerprint { /// The entries of a listed directory. #[derive(SchemaWrite, SchemaRead, PartialEq, Eq, Debug, Clone, Serialize, Deserialize)] pub struct DirListing { - /// The entries sorted by name, without those in `ignored_entries` and - /// those the input negative globs exclude. + /// The entries sorted by name, without those in `ignored_entries`, + /// built-in ignored paths (see [`super::ignored_paths`]), and those the + /// input negative globs exclude. pub entries: BTreeMap, /// Names left out of `entries` that a later run may find missing or /// present: the entries the task can rebuild, and those that /// tool-reported `ignoreInput` paths name, whether or not they were there /// after the run. They're left out of the current listing before - /// comparing, and so are the entries the input negative globs exclude, - /// which aren't recorded: the globs are part of the cache key, so - /// validation has the same ones. + /// comparing, along with built-in ignored paths and the entries the input + /// negative globs exclude, which aren't recorded: the built-in rules are + /// fixed and the globs are part of the cache key, so validation has the + /// same ones. pub ignored_entries: BTreeSet, } @@ -138,6 +140,7 @@ impl PostRunFingerprint { /// * `input_negative_globs` - The input negative globs, which also exclude listing entries /// * `ignored_inputs` - Tool-reported `ignoreInput` paths, which also exclude listing entries /// * `base_dir` - Workspace root for resolving relative paths + /// * `cache_root` - Workspace-relative task cache root, left out of listings /// * `globbed_inputs` - Prerun glob fingerprint; paths here are skipped /// * `tracked_envs` - Tool-requested env vars (name -> value hash), validated on lookup /// * `tracked_env_queries` - Tool-requested bulk env queries (query -> match-set hashes) @@ -152,6 +155,7 @@ impl PostRunFingerprint { input_negative_globs: &PathGlobSet<'_>, ignored_inputs: &FxHashSet, base_dir: &AbsolutePath, + cache_root: Option<&RelativePath>, globbed_inputs: &BTreeMap, tracked_envs: BTreeMap>, tracked_env_queries: BTreeMap>, @@ -189,7 +193,12 @@ impl PostRunFingerprint { listing .ignored_entries .extend(ignored_input_names(relative_path, ignored_inputs)); - leave_out_excluded_entries(listing, relative_path, input_negative_globs); + leave_out_excluded_entries( + listing, + relative_path, + input_negative_globs, + cache_root, + ); } let may_be_missing = rebuildable.may_be_missing(relative_path, &fingerprint, base_dir); @@ -213,12 +222,15 @@ impl PostRunFingerprint { /// from a listed folder. The inputs are checked in parallel, so when /// several changed, which one is found first isn't defined. `input_negative_globs` are the /// task's input negative globs, part of the cache key and so the same as - /// when the fingerprint was created. + /// when the fingerprint was created. `cache_root` is the workspace-relative + /// task cache root, left out of listings alongside other built-in ignored + /// paths. #[tracing::instrument(level = "debug", skip_all)] pub fn input_changes( &self, base_dir: &AbsolutePath, input_negative_globs: &PathGlobSet<'_>, + cache_root: Option<&RelativePath>, file_check: FileCheck, ) -> Vec> { let start = Instant::now(); @@ -238,13 +250,18 @@ impl PostRunFingerprint { Err(err) => return vec![Err(err)], }; // The ignored entries may be missing or present, so the current - // listing records and leaves out the same names, and the entries - // the input negative globs exclude. + // listing records and leaves out the same names, built-in ignored + // paths, and the entries the input negative globs exclude. if let (PathFingerprint::Folder(Some(stored)), PathFingerprint::Folder(Some(current))) = (path_fingerprint, &mut current_path_fingerprint) { current.ignored_entries.clone_from(&stored.ignored_entries); - leave_out_excluded_entries(current, input_relative_path, input_negative_globs); + leave_out_excluded_entries( + current, + input_relative_path, + input_negative_globs, + cache_root, + ); } let unchanged = path_fingerprint == ¤t_path_fingerprint || (*may_be_missing && current_path_fingerprint == PathFingerprint::NotFound); @@ -508,23 +525,30 @@ fn ignored_input_names<'a>( }) } -/// Leaves out of `listing`, a listing of the folder `dir`, the entries named -/// in its `ignored_entries` and those whose path `input_negative_globs` -/// match. A folder entry is matched by its own path: `build/**` matches the -/// `build` folder itself, since `**` matches zero or more components, so it -/// leaves out the entry, while `build/*` or `build/**/*.js` exclude only -/// what is in the folder and leave the entry in. +/// Leaves out of `listing`, a listing of the folder `dir`, built-in ignored +/// paths (see [`super::ignored_paths`]), the entries named in its +/// `ignored_entries`, and those whose path `input_negative_globs` match. A +/// folder entry is matched by its own path: `build/**` matches the `build` +/// folder itself, since `**` matches zero or more components, so it leaves out +/// the entry, while `build/*` or `build/**/*.js` exclude only what is in the +/// folder and leave the entry in. fn leave_out_excluded_entries( listing: &mut DirListing, dir: &RelativePath, input_negative_globs: &PathGlobSet<'_>, + cache_root: Option<&RelativePath>, ) { let DirListing { entries, ignored_entries } = listing; - if ignored_entries.is_empty() && input_negative_globs.is_empty() { + let built_in = IgnoredDirEntries::for_dir(dir, cache_root); + if !built_in.has_non_ds_store_rules() + && ignored_entries.is_empty() + && input_negative_globs.is_empty() + { return; } entries.retain(|name, _| { - !ignored_entries.contains(name) + !built_in.is_ignored(name.as_str()) + && !ignored_entries.contains(name) && (input_negative_globs.is_empty() || !RelativePathBuf::new(name.as_str()) .is_ok_and(|name| input_negative_globs.is_match(dir.join(name)))) @@ -874,10 +898,12 @@ mod tests { FxHashSet::default(), FxHashSet::default(), &workspace_root, + None, ), &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -888,7 +914,7 @@ mod tests { let read_only = create(FxHashSet::default()); let validate = |fingerprint: &PostRunFingerprint| { fingerprint - .input_changes(&workspace_root, &PathGlobSet::default(), FileCheck::First) + .input_changes(&workspace_root, &PathGlobSet::default(), None, FileCheck::First) .pop() .map(Result::unwrap) }; @@ -931,11 +957,13 @@ mod tests { FxHashSet::default(), FxHashSet::default(), &workspace_root, + None, ) - .with_folders(&workspace_root), + .with_folders(&workspace_root, None), &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -963,8 +991,9 @@ mod tests { FxHashSet::default(), FxHashSet::default(), &workspace_root, + None, ) - .with_folders(&workspace_root); + .with_folders(&workspace_root, None); assert!(rebuildable.is_rebuildable_folder(&rel("out"))); assert!(!rebuildable.is_rebuildable_folder(&rel("out/tmp"))); } @@ -992,13 +1021,14 @@ mod tests { .map(rel) .collect(), &workspace_root, + None, ) }; let empty_folders = FxHashSet::from_iter([rel("out/empty"), rel("out/drained")]); - let rebuildable = new().with_folders(&workspace_root); + let rebuildable = new().with_folders(&workspace_root, None); assert_eq!(rebuildable.empty_folders(), &empty_folders); // Without climbing, the archive gets the same empty folders. - assert_eq!(new().with_empty_folders(&workspace_root).empty_folders(), &empty_folders); + assert_eq!(new().with_empty_folders(&workspace_root, None).empty_folders(), &empty_folders); let path_reads = ["out", "out/empty", "mixed", "mixed/made"] .into_iter() @@ -1010,6 +1040,7 @@ mod tests { &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1038,8 +1069,9 @@ mod tests { FxHashSet::from_iter([rel("deps")]), FxHashSet::default(), &workspace_root, + None, ) - .with_folders(&workspace_root); + .with_folders(&workspace_root, None); let mut written: Vec<&str> = rebuildable.written().iter().map(|path| path.as_str()).collect(); written.sort_unstable(); @@ -1055,6 +1087,7 @@ mod tests { &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1095,11 +1128,13 @@ mod tests { FxHashSet::from_iter([rel(".vite/deps")]), FxHashSet::from_iter([rel(".vite/deps_temp_1a2b")]), &workspace_root, + None, ) - .with_folders(&workspace_root), + .with_folders(&workspace_root, None), &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1129,8 +1164,9 @@ mod tests { FxHashSet::default(), FxHashSet::default(), &workspace_root, + None, ) - .with_folders(&workspace_root); + .with_folders(&workspace_root, None); let file = PathFingerprint::FileContentHash(0); assert!(!rebuildable.may_be_missing(&rel("deps/a.js"), &file, &workspace_root)); assert!(!rebuildable.may_be_missing( @@ -1146,6 +1182,7 @@ mod tests { &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1175,11 +1212,13 @@ mod tests { FxHashSet::default(), FxHashSet::default(), &workspace_root, + None, ) - .with_folders(&workspace_root), + .with_folders(&workspace_root, None), &PathGlobSet::default(), &FxHashSet::default(), &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1195,7 +1234,7 @@ mod tests { let validate = || { fingerprint - .input_changes(&workspace_root, &PathGlobSet::default(), FileCheck::First) + .input_changes(&workspace_root, &PathGlobSet::default(), None, FileCheck::First) .pop() .map(Result::unwrap) }; @@ -1236,6 +1275,7 @@ mod tests { &input_negative_globs, &ignored_inputs, &workspace_root, + None, &BTreeMap::new(), BTreeMap::new(), BTreeMap::new(), @@ -1254,7 +1294,7 @@ mod tests { let validate = || { fingerprint - .input_changes(&workspace_root, &input_negative_globs, FileCheck::First) + .input_changes(&workspace_root, &input_negative_globs, None, FileCheck::First) .pop() .map(Result::unwrap) }; @@ -1271,4 +1311,148 @@ mod tests { other => panic!("expected `pkg/notes.txt` added, got {other:?}"), } } + + #[test] + fn listings_leave_out_built_in_ignored_entries() { + let tmp = tempfile::TempDir::new().unwrap(); + let workspace_root = AbsolutePathBuf::new(tmp.path().to_path_buf()).unwrap(); + let rel = |path: &str| RelativePathBuf::new(path).unwrap(); + for dir in [ + ".git", + "node_modules/.vite/task-cache", + "node_modules/.vite-temp", + "node_modules/pkg", + "packages/app/node_modules/dep", + ] { + std::fs::create_dir_all(workspace_root.join(dir).as_path()).unwrap(); + } + std::fs::write( + workspace_root.join("node_modules/.pnpm-workspace-state-v1.json").as_path(), + "{}", + ) + .unwrap(); + + let cache_root = rel("node_modules/.vite/task-cache"); + let path_reads = HashMap::from([ + (rel(""), PathRead { read_dir_entries: true }), + (rel("node_modules"), PathRead { read_dir_entries: true }), + (rel("node_modules/.vite"), PathRead { read_dir_entries: true }), + (rel("packages/app/node_modules"), PathRead { read_dir_entries: true }), + ]); + let fingerprint = PostRunFingerprint::create( + &path_reads, + &Rebuildable::default(), + &PathGlobSet::default(), + &FxHashSet::default(), + &workspace_root, + Some(&cache_root), + &BTreeMap::new(), + BTreeMap::new(), + BTreeMap::new(), + ) + .unwrap(); + + let entries_of = |dir: &str| match &fingerprint.inferred_inputs[&rel(dir)].fingerprint { + PathFingerprint::Folder(Some(listing)) => { + listing.entries.keys().map(Str::as_str).collect::>() + } + other => panic!("expected folder listing for `{dir}`, got {other:?}"), + }; + assert_eq!(entries_of(""), ["node_modules", "packages"]); + assert_eq!(entries_of("node_modules"), [".vite", "pkg"]); + assert!(entries_of("node_modules/.vite").is_empty()); + assert_eq!(entries_of("packages/app/node_modules"), ["dep"]); + + let validate = || { + fingerprint + .input_changes( + &workspace_root, + &PathGlobSet::default(), + Some(&cache_root), + FileCheck::First, + ) + .pop() + .map(Result::unwrap) + }; + + // Removing existing ignored entries and adding new ones still hits. + std::fs::remove_dir(workspace_root.join(".git").as_path()).unwrap(); + std::fs::write(workspace_root.join(".git").as_path(), "gitdir: ../main/.git").unwrap(); + std::fs::remove_file( + workspace_root.join("node_modules/.pnpm-workspace-state-v1.json").as_path(), + ) + .unwrap(); + std::fs::remove_dir(workspace_root.join("node_modules/.vite-temp").as_path()).unwrap(); + std::fs::remove_dir(workspace_root.join("node_modules/.vite/task-cache").as_path()) + .unwrap(); + std::fs::write( + workspace_root + .join("packages/app/node_modules/.pnpm-workspace-state-v2.json") + .as_path(), + "{}", + ) + .unwrap(); + std::fs::create_dir(workspace_root.join("packages/app/node_modules/.vite-temp").as_path()) + .unwrap(); + assert!(validate().is_none()); + + // A real entry added to a listed `node_modules` folder still misses. + std::fs::create_dir(workspace_root.join("packages/app/node_modules/extra").as_path()) + .unwrap(); + match validate() { + Some(Change::File { kind: InputChangeKind::Added, path }) => { + assert_eq!(path.as_str(), "packages/app/node_modules/extra"); + } + other => panic!("expected `packages/app/node_modules/extra` added, got {other:?}"), + } + } + + #[test] + fn rebuildable_skips_built_in_ignored_entries() { + let tmp = tempfile::TempDir::new().unwrap(); + let workspace_root = AbsolutePathBuf::new(tmp.path().to_path_buf()).unwrap(); + let rel = |path: &str| RelativePathBuf::new(path).unwrap(); + let cache_root = rel("node_modules/.vite/task-cache"); + + // `node_modules` holds a task-written file under `.vite/deps`, plus + // built-in ignored entries (`.vite-temp`, `.pnpm-workspace-state-*`, + // and the task cache). Those ignored entries don't block rebuildability. + for dir in [ + "node_modules/.vite/deps", + "node_modules/.vite/task-cache/v24", + "node_modules/.vite-temp", + "renamed/node_modules/.vite-temp", + ] { + std::fs::create_dir_all(workspace_root.join(dir).as_path()).unwrap(); + } + for file in [ + "node_modules/.vite/deps/a.js", + "node_modules/.vite/task-cache/v24/cache.db", + "node_modules/.pnpm-workspace-state-v1.json", + "renamed/node_modules/out.js", + "renamed/node_modules/.pnpm-workspace-state-v1.json", + "renamed/node_modules/.vite-temp/config.timestamp.mjs", + ] { + std::fs::write(workspace_root.join(file).as_path(), "x").unwrap(); + } + + let rebuildable = Rebuildable::new( + FxHashSet::from_iter([rel("node_modules/.vite/deps/a.js")]), + FxHashSet::from_iter([rel("renamed")]), + FxHashSet::from_iter([rel("node_modules/.vite")]), + &workspace_root, + Some(&cache_root), + ) + .with_folders(&workspace_root, Some(&cache_root)); + + assert!(rebuildable.is_rebuildable_folder(&rel("node_modules/.vite/deps"))); + assert!(rebuildable.is_rebuildable_folder(&rel("node_modules/.vite"))); + assert!(rebuildable.is_rebuildable_folder(&rel("node_modules"))); + + // Renamed folders don't pull built-in ignored files into the archive. + let mut written: Vec<&str> = + rebuildable.written().iter().map(|path| path.as_str()).collect(); + written.sort_unstable(); + assert_eq!(written, ["node_modules/.vite/deps/a.js", "renamed/node_modules/out.js"]); + } } diff --git a/crates/vt/src/session/execute/ignored_paths.rs b/crates/vt/src/session/execute/ignored_paths.rs new file mode 100644 index 000000000..9b9cd30d5 --- /dev/null +++ b/crates/vt/src/session/execute/ignored_paths.rs @@ -0,0 +1,266 @@ +//! Built-in workspace-relative paths ignored by automatic tracking, directory +//! listing fingerprints, and rebuildable-folder scans. +//! +//! Direct fspy path accesses (`tracked_accesses`), directory listing entries +//! ([`super::fingerprint`]), and rebuildable folder scans +//! ([`super::rebuildable`]) all filter through this module so they agree on +//! which volatile or internal workspace paths never participate in cache keys, +//! inferred inputs, or outputs. + +use vt_path::{AbsolutePath, RelativePath, RelativePathBuf}; + +/// The task cache root (the parent of the schema-version folder `cache_dir`), +/// relative to `workspace_root`, or `None` when it is outside the workspace or +/// is the workspace root itself (skipping the root would skip every access). +#[must_use] +pub fn relative_cache_root( + cache_dir: &AbsolutePath, + workspace_root: &AbsolutePath, +) -> Option { + let cache_root = cache_dir.parent().unwrap_or(cache_dir); + cache_root + .strip_prefix(workspace_root) + .ok() + .flatten() + .filter(|cache_root| !cache_root.as_str().is_empty()) +} + +/// Built-in ignored entry matcher precomputed for one workspace-relative +/// directory, so per-entry checks in large directories avoid repeating +/// directory-level prefix checks. +pub(super) struct IgnoredDirEntries<'a> { + /// Every entry in this directory is ignored because the directory itself + /// lies inside an ignored subtree (root `.git`, `node_modules/.vite-temp`, + /// or `cache_root`). + all: bool, + /// The directory is the workspace root (`""`), where `.git` is ignored. + is_root: bool, + /// The directory is a `node_modules` directory, where + /// `.pnpm-workspace-state-*.json` and `.vite-temp` are ignored. + is_node_modules: bool, + /// The entry name of `cache_root` when the directory is its immediate + /// parent. + cache_root_name: Option<&'a str>, +} + +impl<'a> IgnoredDirEntries<'a> { + /// Build a matcher for entries directly inside `dir`. + #[must_use] + pub(super) fn for_dir(dir: &RelativePath, cache_root: Option<&'a RelativePath>) -> Self { + let dir_str = dir.as_str(); + let all = is_under_root_git(dir) + || is_under_node_modules_vite_temp(dir_str) + || cache_root + .is_some_and(|root| !root.as_str().is_empty() && dir.strip_prefix(root).is_some()); + let cache_root_name = cache_root + .filter(|root| !root.as_str().is_empty() && root.parent() == Some(dir)) + .and_then(RelativePath::file_name); + Self { + all, + is_root: dir_str.is_empty(), + is_node_modules: is_node_modules_dir(dir_str), + cache_root_name, + } + } + + /// Whether this directory has any built-in ignored entries beyond + /// `.DS_Store`, which raw directory listing already skips. + #[must_use] + pub(super) const fn has_non_ds_store_rules(&self) -> bool { + self.all || self.is_root || self.is_node_modules || self.cache_root_name.is_some() + } + + /// Whether the entry `name` in this directory is a built-in ignored path: + /// + /// - `.DS_Store` (Finder metadata in any folder on macOS) + /// - `.git` at the workspace root (workaround for tools like oxlint, and + /// keeps worktrees/clones/exports with different `.git` layouts from + /// busting the cache) + /// - `node_modules/.pnpm-workspace-state-*.json` (pnpm's dependency check + /// record before `pnpm run`/`pnpm exec`, rewritten with timestamps and + /// absolute paths) + /// - `node_modules/.vite-temp` and anything under it (Vite's transient + /// compiled `vite.config.*` folder) + /// - `cache_root` and anything under it (the task cache `vp` rewrites + /// after every run) + #[must_use] + pub(super) fn is_ignored(&self, name: &str) -> bool { + self.all + || name == ".DS_Store" + || (self.is_root && name == ".git") + || (self.is_node_modules + && (name == ".vite-temp" || is_pnpm_workspace_state_file(name))) + || self.cache_root_name == Some(name) + } +} + +/// Whether `path`, relative to the workspace root, is a built-in ignored path. +#[cfg_attr( + all(not(fspy), not(test)), + expect(dead_code, reason = "only called when filtering fspy path accesses") +)] +#[must_use] +pub(super) fn is_ignored_workspace_path( + path: &RelativePath, + cache_root: Option<&RelativePath>, +) -> bool { + let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else { + return false; + }; + IgnoredDirEntries::for_dir(dir, cache_root).is_ignored(name) +} + +fn is_under_root_git(dir: &RelativePath) -> bool { + dir.as_path().strip_prefix(".git").is_ok() +} + +fn is_node_modules_dir(dir: &str) -> bool { + dir == "node_modules" || dir.ends_with("/node_modules") +} + +fn is_pnpm_workspace_state_file(name: &str) -> bool { + name.strip_prefix(".pnpm-workspace-state-") + .is_some_and(|rest| rest.strip_suffix(".json").is_some()) +} + +fn is_under_node_modules_vite_temp(dir: &str) -> bool { + dir == "node_modules/.vite-temp" + || dir.starts_with("node_modules/.vite-temp/") + || dir.ends_with("/node_modules/.vite-temp") + || dir.contains("/node_modules/.vite-temp/") +} + +#[cfg(test)] +mod tests { + use vt_path::{AbsolutePath, RelativePathBuf}; + + use super::*; + + fn rel(path: &str) -> RelativePathBuf { + RelativePathBuf::new(path).unwrap() + } + + fn assert_both(path: &str, cache_root: Option<&RelativePath>, expected: bool) { + let relative = rel(path); + assert_eq!( + is_ignored_workspace_path(&relative, cache_root), + expected, + "workspace path `{path}`" + ); + if let (Some(parent), Some(name)) = (relative.parent(), relative.file_name()) { + assert_eq!( + IgnoredDirEntries::for_dir(parent, cache_root).is_ignored(name), + expected, + "dir entry `{name}` in `{}`", + parent.as_str() + ); + } + } + + #[test] + fn ds_store_is_ignored() { + assert_both(".DS_Store", None, true); + assert_both("packages/a/.DS_Store", None, true); + assert_both("node_modules/.DS_Store", None, true); + assert_both(".DS_Store.bak", None, false); + } + + #[test] + fn root_git_is_ignored() { + assert_both(".git", None, true); + assert_both(".git/HEAD", None, true); + assert_both(".git/objects/ab/cd", None, true); + assert_both(".gitignore", None, false); + assert_both("packages/a/.git", None, false); + } + + #[test] + fn pnpm_workspace_state_is_ignored() { + assert_both("node_modules/.pnpm-workspace-state-v1.json", None, true); + assert_both("node_modules/.pnpm-workspace-state-v2.json", None, true); + assert_both("packages/a/node_modules/.pnpm-workspace-state-v1.json", None, true); + assert_both("node_modules/.modules.yaml", None, false); + assert_both(".pnpm-workspace-state-v1.json", None, false); + assert_both("node_modules/a/.pnpm-workspace-state-v1.json", None, false); + assert_both("my_node_modules/.pnpm-workspace-state-v1.json", None, false); + } + + #[test] + fn vite_temp_is_ignored() { + assert_both("node_modules/.vite-temp", None, true); + assert_both("node_modules/.vite-temp/vite.config.ts.timestamp-123.mjs", None, true); + assert_both("packages/void/node_modules/.vite-temp", None, true); + assert_both("packages/void/node_modules/.vite-temp/sub/file.mjs", None, true); + assert_both("packages/void/node_modules/pkg/node_modules/.vite-temp", None, true); + assert_both(".vite-temp", None, false); + assert_both(".vite-temp/file.mjs", None, false); + assert_both("node_modules/.vite-temp-other", None, false); + assert_both("node_modules/a/.vite-temp", None, false); + assert_both("my_node_modules/.vite-temp", None, false); + assert_both("node_modules/.vite", None, false); + assert_both("node_modules/.vite/deps/react.js", None, false); + } + + #[test] + fn task_cache_is_ignored() { + let cache_root = rel("node_modules/.vite/task-cache"); + assert_both("node_modules/.vite/task-cache", Some(&cache_root), true); + assert_both("node_modules/.vite/task-cache/v24/cache.db", Some(&cache_root), true); + assert_both("node_modules/.vite", Some(&cache_root), false); + assert_both("node_modules/.vite/task-cache-old", Some(&cache_root), false); + assert_both("node_modules/.vite/task-cache-old/cache.db", Some(&cache_root), false); + assert_both("node_modules/.vite/deps/react.js", Some(&cache_root), false); + + let top_level_cache = rel("cache"); + assert_both("cache", Some(&top_level_cache), true); + assert_both("cache/v24/cache.db", Some(&top_level_cache), true); + assert_both("cache-old", Some(&top_level_cache), false); + } + + #[test] + fn workspace_root_is_never_ignored() { + let empty = rel(""); + assert!(!is_ignored_workspace_path(&empty, None)); + assert!(!is_ignored_workspace_path(&empty, Some(&empty))); + } + + #[test] + fn non_special_dir_has_no_non_ds_store_rules() { + let cache_root = rel("node_modules/.vite/task-cache"); + assert!( + !IgnoredDirEntries::for_dir(&rel("src"), Some(&cache_root)).has_non_ds_store_rules() + ); + assert!( + !IgnoredDirEntries::for_dir(&rel("packages/a/src"), Some(&cache_root)) + .has_non_ds_store_rules() + ); + assert!(IgnoredDirEntries::for_dir(&rel(""), Some(&cache_root)).has_non_ds_store_rules()); + assert!( + IgnoredDirEntries::for_dir(&rel("node_modules"), Some(&cache_root)) + .has_non_ds_store_rules() + ); + assert!( + IgnoredDirEntries::for_dir(&rel("node_modules/.vite"), Some(&cache_root)) + .has_non_ds_store_rules() + ); + } + + #[test] + fn relative_cache_root_drops_outside_and_workspace_root() { + let workspace_root = + AbsolutePath::new(if cfg!(windows) { r"C:\repo" } else { "/repo" }).unwrap(); + let default_cache_dir = workspace_root.join("node_modules/.vite/task-cache/v24"); + assert_eq!( + relative_cache_root(&default_cache_dir, workspace_root), + Some(rel("node_modules/.vite/task-cache")) + ); + + let at_root_cache_dir = workspace_root.join("v24"); + assert_eq!(relative_cache_root(&at_root_cache_dir, workspace_root), None); + + let outside_cache_dir = + AbsolutePath::new(if cfg!(windows) { r"C:\tmp\cache\v24" } else { "/tmp/cache/v24" }) + .unwrap(); + assert_eq!(relative_cache_root(outside_cache_dir, workspace_root), None); + } +} diff --git a/crates/vt/src/session/execute/mod.rs b/crates/vt/src/session/execute/mod.rs index 86cc5115e..702893061 100644 --- a/crates/vt/src/session/execute/mod.rs +++ b/crates/vt/src/session/execute/mod.rs @@ -2,6 +2,7 @@ mod cache_update; pub mod fingerprint; pub mod glob; mod hash; +pub mod ignored_paths; pub mod pipe; mod rebuildable; mod redact; diff --git a/crates/vt/src/session/execute/rebuildable.rs b/crates/vt/src/session/execute/rebuildable.rs index 84a67a5a8..67d743289 100644 --- a/crates/vt/src/session/execute/rebuildable.rs +++ b/crates/vt/src/session/execute/rebuildable.rs @@ -6,18 +6,18 @@ //! would write them again, so a later run may find them missing. A file that //! is there must still be as the task left it. //! -//! The same goes for an empty folder the task made (`.DS_Store` aside), and -//! for a folder that holds only what the task can rebuild: every file (or -//! symlink) in it is one the task wrote, and every folder in it is rebuildable -//! too. None of these is fingerprinted at all. A hit restores the files and -//! the empty folders, which are archived as folders, if they're among the -//! task's outputs, and the files recreate the folders holding them; explicit -//! output config can leave them out. Such folders are found after the run by -//! climbing from the written paths and the empty folders through their parent -//! folders inside the workspace, listing each one once in the real file -//! system. A written path or folder that is gone by then plays no part. A -//! listing of any other folder leaves out its entries that the task can -//! rebuild, which a later run may find missing too. +//! The same goes for an empty folder the task made (built-in ignored paths +//! such as `.DS_Store` aside), and for a folder that holds only what the task +//! can rebuild: every file (or symlink) in it is one the task wrote, and every +//! folder in it is rebuildable too. None of these is fingerprinted at all. A hit +//! restores the files and the empty folders, which are archived as folders, if +//! they're among the task's outputs, and the files recreate the folders holding +//! them; explicit output config can leave them out. Such folders are found after +//! the run by climbing from the written paths and the empty folders through +//! their parent folders inside the workspace, listing each one once in the real +//! file system. A written path or folder that is gone by then plays no part. A +//! listing of any other folder leaves out its entries that the task can rebuild, +//! which a later run may find missing too. //! //! The written paths are fspy's records before output exclusions and //! tool-reported `ignoreOutput` paths are applied: those decide what is @@ -43,7 +43,7 @@ use std::{cmp::Reverse, fs, io}; use rustc_hash::FxHashSet; use vt_path::{AbsolutePath, RelativePath, RelativePathBuf}; -use super::fingerprint::PathFingerprint; +use super::{fingerprint::PathFingerprint, ignored_paths::IgnoredDirEntries}; /// The paths a task wrote, the empty folders it made, and the folders /// holding only what it can rebuild, relative to the workspace root. @@ -71,8 +71,9 @@ impl Rebuildable { rename_targets: FxHashSet, mkdirs: FxHashSet, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, ) -> Self { - let written = files_written(written, rename_targets, workspace_root); + let written = files_written(written, rename_targets, workspace_root, cache_root); let mut written_in = FxHashSet::default(); for path in &written { let mut dir = path.parent(); @@ -100,9 +101,13 @@ impl Rebuildable { /// Only fingerprints of the paths the task read ask about folders, so a /// run without such reads takes [`Self::with_empty_folders`] instead. #[must_use] - pub fn with_folders(mut self, workspace_root: &AbsolutePath) -> Self { + pub fn with_folders( + mut self, + workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, + ) -> Self { (self.folders, self.empty_folders) = - find_folders(&self.written, &self.mkdirs, workspace_root); + find_folders(&self.written, &self.mkdirs, workspace_root, cache_root); self } @@ -110,11 +115,15 @@ impl Rebuildable { /// listing the folders it made under `workspace_root`, which must be done /// after the run, without climbing to the folders above them. #[must_use] - pub fn with_empty_folders(mut self, workspace_root: &AbsolutePath) -> Self { + pub fn with_empty_folders( + mut self, + workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, + ) -> Self { self.empty_folders = self .mkdirs .iter() - .filter(|dir| is_empty_folder(dir, workspace_root)) + .filter(|dir| is_empty_folder(dir, workspace_root, cache_root)) .cloned() .collect(); self @@ -190,10 +199,11 @@ fn files_written( mut written: FxHashSet, rename_targets: FxHashSet, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, ) -> FxHashSet { for path in rename_targets { if fs::symlink_metadata(workspace_root.join(&path)).is_ok_and(|meta| meta.is_dir()) { - add_files_under(&path, workspace_root, &mut written); + add_files_under(&path, workspace_root, cache_root, &mut written); } else { written.insert(path); } @@ -201,22 +211,28 @@ fn files_written( written } -/// Adds every file (or symlink) under the folder `dir` to `files`. `.DS_Store` -/// doesn't count, as in directory listing fingerprints. +/// Adds every file (or symlink) under the folder `dir` to `files`. Built-in +/// ignored paths (see [`super::ignored_paths`]) don't count, as in directory +/// listing fingerprints. fn add_files_under( dir: &RelativePath, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, files: &mut FxHashSet, ) { let Ok(entries) = fs::read_dir(workspace_root.join(dir)) else { return; }; + let ignored = IgnoredDirEntries::for_dir(dir, cache_root); for entry in entries.flatten() { let name = entry.file_name(); - if name == ".DS_Store" { + let Some(name) = name.to_str() else { + continue; + }; + if ignored.is_ignored(name) { continue; } - let (Some(name), Ok(file_type)) = (name.to_str(), entry.file_type()) else { + let Ok(file_type) = entry.file_type() else { continue; }; let Ok(name) = RelativePathBuf::new(name) else { @@ -224,7 +240,7 @@ fn add_files_under( }; let path = dir.join(name); if file_type.is_dir() { - add_files_under(&path, workspace_root, files); + add_files_under(&path, workspace_root, cache_root, files); } else { files.insert(path); } @@ -232,12 +248,22 @@ fn add_files_under( } /// Whether `dir` is a folder under `workspace_root` holding nothing but -/// `.DS_Store`, which doesn't count, as in directory listing fingerprints. -fn is_empty_folder(dir: &RelativePath, workspace_root: &AbsolutePath) -> bool { +/// built-in ignored paths (see [`super::ignored_paths`]), which don't count, +/// as in directory listing fingerprints. +fn is_empty_folder( + dir: &RelativePath, + workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, +) -> bool { let path = workspace_root.join(dir); + let ignored = IgnoredDirEntries::for_dir(dir, cache_root); fs::symlink_metadata(&path).is_ok_and(|meta| meta.is_dir()) && fs::read_dir(path).is_ok_and(|mut entries| { - entries.all(|entry| entry.is_ok_and(|entry| entry.file_name() == ".DS_Store")) + entries.all(|entry| { + entry.is_ok_and(|entry| { + entry.file_name().to_str().is_some_and(|name| ignored.is_ignored(name)) + }) + }) }) } @@ -254,6 +280,7 @@ fn find_folders( written: &FxHashSet, mkdirs: &FxHashSet, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, ) -> (FxHashSet, FxHashSet) { let mut candidates = FxHashSet::default(); for path in written { @@ -268,7 +295,7 @@ fn find_folders( sort_deepest_first(&mut made); for dir in made { // A folder holding an empty folder found here is a candidate by now. - if !candidates.contains(dir) && is_empty_folder(dir, workspace_root) { + if !candidates.contains(dir) && is_empty_folder(dir, workspace_root, cache_root) { add_parents(dir, &mut candidates); empty_folders.insert(dir.to_relative_path_buf()); } @@ -282,7 +309,7 @@ fn find_folders( let contents = if above_unrebuildable.contains(dir) { Some(Holds::Other) } else { - holds(dir, workspace_root, written, &folders) + holds(dir, workspace_root, cache_root, written, &folders) }; match contents { Some(Holds::OnlyRebuildable) => { @@ -320,8 +347,8 @@ fn sort_deepest_first(dirs: &mut [&RelativePath]) { dirs.sort_unstable_by_key(|dir| Reverse(dir.as_str().matches('/').count())); } -/// What a folder holds, `.DS_Store` aside, which doesn't count, as in -/// directory listing fingerprints. +/// What a folder holds, built-in ignored paths (see [`super::ignored_paths`]) +/// aside, which don't count, as in directory listing fingerprints. enum Holds { Nothing, /// At least one entry, each a file (or symlink) the task wrote or a @@ -337,6 +364,7 @@ enum Holds { fn holds( dir: &RelativePath, workspace_root: &AbsolutePath, + cache_root: Option<&RelativePath>, written: &FxHashSet, folders: &FxHashSet, ) -> Option { @@ -350,16 +378,20 @@ fn holds( } Err(_) => return Some(Holds::Other), }; + let ignored = IgnoredDirEntries::for_dir(dir, cache_root); let mut holds = Holds::Nothing; for entry in entries { let Ok(entry) = entry else { return Some(Holds::Other); }; let name = entry.file_name(); - if name == ".DS_Store" { + let Some(name) = name.to_str() else { + return Some(Holds::Other); + }; + if ignored.is_ignored(name) { continue; } - let (Some(name), Ok(file_type)) = (name.to_str(), entry.file_type()) else { + let Ok(file_type) = entry.file_type() else { return Some(Holds::Other); }; let Ok(name) = RelativePathBuf::new(name) else { diff --git a/crates/vt/src/session/execute/tracked_accesses.rs b/crates/vt/src/session/execute/tracked_accesses.rs index 392aef09d..1561913c2 100644 --- a/crates/vt/src/session/execute/tracked_accesses.rs +++ b/crates/vt/src/session/execute/tracked_accesses.rs @@ -9,7 +9,7 @@ use fspy::{IpcPath, PathAccess, PathAccessIterable}; use rustc_hash::FxHashSet; use vt_path::{AbsolutePath, RelativePath, RelativePathBuf}; -use super::fingerprint::PathRead; +use super::{fingerprint::PathRead, ignored_paths::is_ignored_workspace_path}; use crate::collections::HashMap; /// Tracked file accesses from fspy, normalized to workspace-relative paths. @@ -31,25 +31,18 @@ pub struct TrackedPathAccesses { impl TrackedPathAccesses { /// Build from fspy's raw iterable by resolving `..` components and then /// stripping the workspace prefix, so paths outside the workspace are - /// skipped. `.git/*` paths, pnpm's workspace state files and paths in the - /// task cache at `cache_root` are skipped too. + /// skipped. Built-in ignored paths (see [`super::ignored_paths`]), + /// including `.git/*`, pnpm's workspace state files, Vite's `.vite-temp`, + /// `.DS_Store`, and paths in the task cache at `cache_root`, are skipped + /// too. /// User-configured negatives are applied by the caller (see module docs). pub fn from_raw( raw: &PathAccessIterable, workspace_root: &AbsolutePath, - cache_root: &AbsolutePath, + cache_root: Option<&RelativePath>, ) -> Self { - // The task cache, when it's inside the workspace. A cache at the - // workspace root itself isn't skipped, since that would skip every - // access. - let cache_root = cache_root - .strip_prefix(workspace_root) - .ok() - .flatten() - .filter(|cache_root| !cache_root.as_str().is_empty()); - let relative_path = - |path: &IpcPath| tracked_workspace_path(path, workspace_root, cache_root.as_deref()); + |path: &IpcPath| tracked_workspace_path(path, workspace_root, cache_root); let mut accesses = Self::default(); for access in raw.iter() { @@ -124,38 +117,13 @@ fn normalize_tracked_workspace_path( // Ignore paths that aren't portable, like ones with non-UTF-8 names. let relative = RelativePathBuf::new(stripped_path).ok()?; - // Skip .git directory accesses (workaround for tools like oxlint) - if relative.as_path().strip_prefix(".git").is_ok() { - return None; - } - - if is_pnpm_workspace_state(&relative) { - return None; - } - - // Skip the task cache. vp rewrites it after every run, so a task that - // reads it, like a tool crawling the project, would never hit. - if cache_root.is_some_and(|cache_root| relative.strip_prefix(cache_root).is_some()) { + if is_ignored_workspace_path(&relative, cache_root) { return None; } Some(relative) } -/// Whether `relative` is a `node_modules/.pnpm-workspace-state-*.json` file, -/// pnpm's record of its dependency check before `pnpm run` and `pnpm exec`. -/// pnpm rewrites it with a new timestamp whenever it rechecks dependencies, -/// and it holds absolute project paths. Whether the check passes doesn't -/// change what a cached task outputs. -fn is_pnpm_workspace_state(relative: &RelativePathBuf) -> bool { - let path = relative.as_str(); - let (dir, file_name) = path.rsplit_once('/').unwrap_or(("", path)); - (dir == "node_modules" || dir.ends_with("/node_modules")) - && file_name - .strip_prefix(".pnpm-workspace-state-") - .is_some_and(|rest| rest.strip_suffix(".json").is_some()) -} - #[cfg(test)] mod tests { use super::*; @@ -208,6 +176,22 @@ mod tests { assert!(normalize("node_modules/a/.pnpm-workspace-state-v1.json").is_some()); } + #[test] + fn vite_temp_is_ignored() { + #[expect( + clippy::disallowed_types, + reason = "normalize_tracked_workspace_path requires std::path::Path for fspy strip_path_prefix output" + )] + let normalize = + |path: &str| normalize_tracked_workspace_path(std::path::Path::new(path), None); + assert!(normalize("node_modules/.vite-temp").is_none()); + assert!(normalize("node_modules/.vite-temp/vite.config.ts.timestamp-1.mjs").is_none()); + assert!(normalize("packages/void/node_modules/.vite-temp").is_none()); + assert!(normalize("packages/void/node_modules/.vite-temp/sub/config.mjs").is_none()); + assert!(normalize(".vite-temp/config.mjs").is_some()); + assert!(normalize("node_modules/.vite-temp-other").is_some()); + } + #[test] fn task_cache_is_ignored() { let cache_root = RelativePathBuf::new("node_modules/.vite/task-cache").unwrap(); diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/package.json new file mode 100644 index 000000000..5e67217fd --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/package.json @@ -0,0 +1,4 @@ +{ + "name": "node-modules-listing-ignores-volatile-entries", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots.toml new file mode 100644 index 000000000..35df104a5 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots.toml @@ -0,0 +1,68 @@ +[[e2e]] +name = "node_modules_listing_ignores_volatile_entries" +comment = """ +A task walks `node_modules`. pnpm's `.pnpm-workspace-state-*.json` and Vite's `.vite-temp` appearing or disappearing there don't invalidate the cache, while a real package entry added to `node_modules` still causes a cache miss. +""" +steps = [ + { argv = [ + "vtt", + "mkdir", + "-p", + "node_modules/real-pkg", + ], comment = "seed a real package under node_modules" }, + { argv = [ + "vtt", + "write-file", + "node_modules/.pnpm-workspace-state-v1.json", + "{}", + ], comment = "pnpm workspace state file exists before the first run" }, + { argv = [ + "vt", + "run", + "list", + ], comment = "first run: cache miss" }, + { argv = [ + "vtt", + "rm", + "node_modules/.pnpm-workspace-state-v1.json", + ], comment = "pnpm workspace state file is removed" }, + { argv = [ + "vtt", + "write-file", + "node_modules/.vite-temp/vite.config.ts.timestamp-1.mjs", + "export default {}", + ], comment = "Vite creates its transient config temp folder and file" }, + { argv = [ + "vt", + "run", + "list", + ], comment = "cache hit despite volatile entries appearing and disappearing" }, + { argv = [ + "vtt", + "write-file", + "node_modules/.pnpm-workspace-state-v2.json", + "{}", + ], comment = "pnpm writes a workspace state file" }, + { argv = [ + "vtt", + "rm", + "-rf", + "node_modules/.vite-temp", + ], comment = "Vite temp folder is removed" }, + { argv = [ + "vt", + "run", + "list", + ], comment = "cache hit again" }, + { argv = [ + "vtt", + "mkdir", + "-p", + "node_modules/another-pkg", + ], comment = "a real package appears in node_modules" }, + { argv = [ + "vt", + "run", + "list", + ], comment = "cache miss for the real package" }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots/node_modules_listing_ignores_volatile_entries.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots/node_modules_listing_ignores_volatile_entries.md new file mode 100644 index 000000000..d4c1362f3 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/snapshots/node_modules_listing_ignores_volatile_entries.md @@ -0,0 +1,90 @@ +# node_modules_listing_ignores_volatile_entries + +A task walks `node_modules`. pnpm's `.pnpm-workspace-state-*.json` and Vite's `.vite-temp` appearing or disappearing there don't invalidate the cache, while a real package entry added to `node_modules` still causes a cache miss. + +## `vtt mkdir -p node_modules/real-pkg` + +seed a real package under node_modules + +``` +``` + +## `vtt write-file node_modules/.pnpm-workspace-state-v1.json {}` + +pnpm workspace state file exists before the first run + +``` +``` + +## `vt run list` + +first run: cache miss + +``` +$ vtt fs walk node_modules write out.txt listed +``` + +## `vtt rm node_modules/.pnpm-workspace-state-v1.json` + +pnpm workspace state file is removed + +``` +``` + +## `vtt write-file node_modules/.vite-temp/vite.config.ts.timestamp-1.mjs 'export default {}'` + +Vite creates its transient config temp folder and file + +``` +``` + +## `vt run list` + +cache hit despite volatile entries appearing and disappearing + +``` +$ vtt fs walk node_modules write out.txt listed ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt write-file node_modules/.pnpm-workspace-state-v2.json {}` + +pnpm writes a workspace state file + +``` +``` + +## `vtt rm -rf node_modules/.vite-temp` + +Vite temp folder is removed + +``` +``` + +## `vt run list` + +cache hit again + +``` +$ vtt fs walk node_modules write out.txt listed ◉ cache hit, replaying + +--- +vt run: cache hit. +``` + +## `vtt mkdir -p node_modules/another-pkg` + +a real package appears in node_modules + +``` +``` + +## `vt run list` + +cache miss for the real package + +``` +$ vtt fs walk node_modules write out.txt listed ○ cache miss: 'another-pkg' added in 'node_modules', executing +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/vite-task.json new file mode 100644 index 000000000..dda2dc1b4 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/node_modules_listing_ignores_volatile_entries/vite-task.json @@ -0,0 +1,8 @@ +{ + "tasks": { + "list": { + "command": "vtt fs walk node_modules write out.txt listed", + "cache": true + } + } +} diff --git a/crates/vt_path/src/relative.rs b/crates/vt_path/src/relative.rs index 4c95b5b16..e94a444d4 100644 --- a/crates/vt_path/src/relative.rs +++ b/crates/vt_path/src/relative.rs @@ -76,6 +76,13 @@ impl RelativePath { Some(unsafe { Self::assume_portable(parent) }) } + /// Returns the final normal component of `self`, or [`None`] if `self` is + /// empty or ends in `..`. + #[must_use] + pub fn file_name(&self) -> Option<&str> { + self.as_path().file_name().and_then(std::ffi::OsStr::to_str) + } + /// Lexically normalizes the path by resolving `..` components without /// accessing the filesystem. (`.` components are already stripped by /// [`RelativePathBuf::new`].) @@ -486,6 +493,15 @@ mod tests { assert!(root.parent().is_none()); } + #[test] + fn file_name() { + assert_eq!(RelativePathBuf::new("foo/bar").unwrap().file_name(), Some("bar")); + assert_eq!(RelativePathBuf::new("bar").unwrap().file_name(), Some("bar")); + assert_eq!(RelativePathBuf::new("").unwrap().file_name(), None); + assert_eq!(RelativePathBuf::new("..").unwrap().file_name(), None); + assert_eq!(RelativePathBuf::new("foo/..").unwrap().file_name(), None); + } + #[test] fn strip_prefix() { let rel_path = RelativePathBuf::new("foo/bar/baz").unwrap(); diff --git a/docs/inputs.md b/docs/inputs.md index 4a0ac325b..84bb32678 100644 --- a/docs/inputs.md +++ b/docs/inputs.md @@ -205,7 +205,7 @@ Files matching `*.generated.ts` are excluded whether they come from the `src/**` ### Auto-Inference Behavior -The auto-inference (fspy) is intentionally **cautious** - it tracks all files that a command reads, even auxiliary files. This means **negative patterns are expected to be useful** for filtering out files you don't want to trigger cache invalidation. +The auto-inference (fspy) is intentionally **cautious** - it tracks all files that a command reads, even auxiliary files. A small set of workspace-internal or transient paths are always ignored automatically (for both direct accesses and directory listings): `.git` at the workspace root, `.DS_Store`, `node_modules/.pnpm-workspace-state-*.json`, `node_modules/.vite-temp`, and the task cache directory (`node_modules/.vite/task-cache`, or `VITE_CACHE_PATH` when inside the workspace). For other tool caches or generated files, **negative patterns are expected to be useful** for filtering out files you don't want to trigger cache invalidation. Common files you might want to exclude: