From 0c021262936cef1bdfe2577b823f1cbae7d5d074 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 12:02:07 -0500 Subject: [PATCH 01/22] Stop vex judging the pnpm store entry an in-place install leaves behind After the `pnpm install` that a scan asks for, run over an existing `node_modules`, pnpm links the project to a new virtual-store entry and keeps the upstream one with nothing linking to it: `@socket-+` beside `@` after a hosted scan on pnpm 11.20 and later (the release is routed through the registry of its patch), and `@file+...` after a vendored scan on every pnpm. `vex` counted the leftover as an installed copy. It omitted the hosted patch as `not_applied` and exited 1, or warned `vendored_tree_out_of_sync` for the vendored one, and the reinstall it asked for changed nothing (#2353). The live-copy filter that skips Bun's orphaned store entries now skips pnpm's too. A pnpm entry is live when a link reaches it from an importer's `node_modules` (the root, and the members named by the lockfile in the store or by `pnpm-lock.yaml`), from the hoist directory `node_modules/.pnpm/node_modules`, from a live entry's own `node_modules`, or from the `node_modules` in which a checked copy was found. A copy that a link reaches is always judged, so an unpatched one still refuses or warns. Every entry is kept, as before, wherever the walk cannot be sure it read every link: on Windows, under `node-linker=hoisted` or `shamefully-hoist`, with a moved virtual store or another store layout, without the install record or the lockfile in the store, when a directory or a link cannot be read, when a lockfile lists its importers in a layout pnpm does not write or names a member that is no directory, when an importer's `node_modules` or the hoist directory holds a package as a real directory, and when no link reaches the store at all. `apply --check` verifies through the same copy lookup, so it follows the same rule. The scan's listing keeps its own test (the packages of the lockfile in the store), and `rollback` and `remove` resolve without the filter, so they still restore an unlinked entry. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/vex_consumed.rs | 2 +- .../src/ecosystem_dispatch.rs | 7 +- .../src/crawlers/npm_crawler.rs | 931 +++++++++++++++++- .../src/formats/pnpm/modules_yaml.rs | 140 +++ .../src/formats/pnpm/workspace.rs | 119 +++ 5 files changed, 1160 insertions(+), 39 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex_consumed.rs b/crates/socket-patch-cli/src/commands/vex_consumed.rs index eb184a5d61..8f66a589c3 100644 --- a/crates/socket-patch-cli/src/commands/vex_consumed.rs +++ b/crates/socket-patch-cli/src/commands/vex_consumed.rs @@ -115,7 +115,7 @@ pub(crate) async fn hosted_consumed_copies( }, ); } - // An orphaned Bun store entry is no consumed copy; the + // An orphaned Bun or pnpm store entry is no consumed copy; the // installed lookup dropped its own, this drops the ones the alias // and identity fallbacks' variant expansion added. socket_patch_core::crawlers::npm_crawler::retain_live_store_copies( diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index e5c28f452e..07c4533358 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -1361,9 +1361,10 @@ pub async fn find_manifest_package_copies_reusing( with_store_peer_variant_copies(common.read_scope(), std::mem::take(paths)).await; } } - // A Bun store entry nothing links any more (Bun never prunes `.bun`) - // is no copy the install loads, so the check skips it (#599). Rollback - // and remove, which resolve without this, still restore it. + // A Bun or pnpm store entry nothing links any more (Bun never prunes + // `.bun`; pnpm keeps the entry an in-place install replaced) is no + // copy the install loads, so the check skips it (#599, #2353). + // Rollback and remove, which resolve without this, still restore it. retain_live_store_copies( copies .iter_mut() diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 9a748c56d4..21a5dc8373 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -838,6 +838,11 @@ fn pnpm_current_lockfile_sync( /// by the entry (a registry `name@version` entry, or a `name@file+…` /// tarball entry) and confirmed by its package.json — is not in the /// current lockfile. An entry that cannot be named or read stays. +/// +/// This tells which packages the install holds, by name and version, +/// which is what the scan lists. Which of two entries holding the same +/// name and version the install loads is another question, answered by +/// [`live_pnpm_store_entries_sync`]. fn orphaned_pnpm_store_entry_sync( store_path: &Path, entry_name: &str, @@ -870,6 +875,242 @@ fn orphaned_pnpm_store_entry_sync( && !installed.contains(&name, &found_version) } +/// The `.pnpm` store entries an install can still load, by name (#2353); +/// `None` when the walk cannot tell, and every entry must be kept. pnpm +/// keeps an entry it no longer uses (see +/// [`orphaned_pnpm_store_entry_sync`]), and an in-place `pnpm install` +/// that takes a package from another source under the same name and +/// version (a hosted patch routed through its own registry, a vendored +/// `file:` tarball) writes a new entry, re-links every dependent to it +/// and leaves the old `@` dir behind. The current lockfile +/// still lists that name and version, so a check of each installed copy +/// (`vex`) judges an entry by the links instead, as for Bun (see +/// [`live_bun_store_entries_sync`]); rollback and remove still restore +/// the orphan. +/// +/// An entry is live when a link reaches it from an importer's +/// `node_modules`, from pnpm's hoist dir `.pnpm/node_modules` (every +/// store package resolves through it), or from a live entry's +/// `node_modules`. The importers are the root and the members the +/// current lockfile names (`.pnpm/lock.yaml`, which every install +/// rewrites with the importers it has linked so far), and, when those +/// leave some entry unreached, the members of the project's +/// `pnpm-lock.yaml` too: it names every member of the workspace, so also +/// one whose links the current lockfile does not record (an install that +/// did not finish). The entries in `linked` are live as well: the caller +/// found a copy in each through a link outside the store, in a +/// `node_modules` no lockfile may name. A stale link pnpm left behind +/// still counts: the runtime resolves through it. +/// +/// A link the walk misses would hide a copy the install loads, so the +/// walk keeps every entry wherever it cannot be sure it read them all: +/// +/// - on Windows, where pnpm links directories with junctions; +/// - when the store is not the one `node_modules/.modules.yaml` records, +/// or the record is not of the isolated linker over a flat store (see +/// [`Layout::is_isolated`](crate::formats::pnpm::modules_yaml::Layout::is_isolated): +/// `node-linker=hoisted`, `shamefully-hoist`, another layout version); +/// - without a current lockfile, or when it or `pnpm-lock.yaml` cannot be +/// read, lays its importers out in a way pnpm does not write, or names +/// a member that is no directory; +/// - when the store, a `node_modules` dir, a scope dir or a link cannot be +/// read; +/// - when an importer's `node_modules` or the hoist dir holds a package +/// as a real dir, which the isolated linker never writes there; +/// - when no link reaches any entry. +fn live_pnpm_store_entries_sync( + store_path: &Path, + linked: &HashSet, +) -> Option> { + use crate::constants::npm_family::PNPM_LOCK; + use crate::formats::pnpm::grammar::is_pnpm_lock_text; + use crate::formats::pnpm::modules_yaml::Layout; + use crate::formats::pnpm::workspace::lock_text_member_importers_exact; + use crate::utils::fs::read_regular_to_string_sync; + + if cfg!(windows) { + return None; + } + let store = std::fs::canonicalize(store_path).ok()?; + let nm = store.parent()?; + let root = nm.parent()?; + let record = read_regular_to_string_sync(&nm.join(PNPM_MODULES_YAML)).ok()?; + let layout = Layout::parse(&record).filter(Layout::is_isolated)?; + if std::fs::canonicalize(nm.join(layout.virtual_store_dir?)).ok()? != store { + return None; + } + let current = read_regular_to_string_sync(&store.join("lock.yaml")) + .ok() + .filter(|text| is_pnpm_lock_text(text))?; + let listing = list_dir_sync(&store); + if !listing.complete { + return None; + } + let entries: HashSet = listing + .entries + .into_iter() + .filter(|entry| { + !(entry.name_str.starts_with('.') || entry.name_str == "node_modules") + && entry.file_type.is_some_and(|ft| ft.is_dir()) + }) + .map(|entry| entry.name) + .collect(); + // The `node_modules` of each member a lock names. A member that is no + // directory may be a key read wrong, whose links would go unread. + let members = |lock: &str| -> Option> { + lock_text_member_importers_exact(lock)? + .into_iter() + .map(|member| { + let member = root.join(member); + is_dir_sync(&member).then(|| member.join("node_modules")) + }) + .collect() + }; + + let mut walk = PnpmStoreWalk { + store: &store, + entries: &entries, + live: HashSet::new(), + }; + let mut seeds = vec![store.join("node_modules"), nm.to_path_buf()]; + seeds.extend(members(¤t)?); + walk.reach(seeds, linked)?; + if walk.live.len() < entries.len() { + match read_regular_to_string_sync(&root.join(PNPM_LOCK)) { + Ok(wanted) => walk.reach(members(&wanted)?, &HashSet::new())?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + } + (!walk.live.is_empty()).then_some(walk.live) +} + +/// The walk of [`live_pnpm_store_entries_sync`] over one store. +struct PnpmStoreWalk<'a> { + /// The store's real path. + store: &'a Path, + /// The names of the store's entry dirs. + entries: &'a HashSet, + /// The entries reached so far. + live: HashSet, +} + +impl PnpmStoreWalk<'_> { + /// Add to `live` the entries of `linked` and every entry reachable + /// through links from the `seeds` dirs (importers' `node_modules`, the + /// hoist dir), following each reached entry's own `node_modules` + /// links, one frontier at a time and each frontier's dirs in + /// parallel. A seed that does not exist links nothing. `None` when a + /// dir or a link cannot be read. + fn reach(&mut self, seeds: Vec, linked: &HashSet) -> Option<()> { + let mut frontier: Vec<(PathBuf, bool)> = Vec::new(); + for seed in seeds { + match std::fs::canonicalize(seed) { + Ok(nm) => frontier.push((nm, true)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + } + let mut reached: Vec = linked + .iter() + .filter(|entry| self.entries.contains(*entry)) + .cloned() + .collect(); + loop { + for entry in reached { + if !self.live.contains(&entry) { + frontier.push((self.store.join(&entry).join("node_modules"), false)); + self.live.insert(entry); + } + } + if frontier.is_empty() { + return Some(()); + } + let reads = par_map(frontier, |(nm, seed)| self.link_targets(&nm, seed)); + frontier = Vec::new(); + reached = Vec::new(); + for targets in reads { + reached.extend(targets?); + } + } + } + + /// The entries the package links of the `node_modules` dir `nm` point + /// into (scoped ones under `@scope/`). `nm` is real: a `seed` was + /// canonicalized, and an entry's own `node_modules` must be a real + /// dir of the store. A dir that does not exist links nothing. `None` + /// when the dir, a scope dir or a link cannot be read, or when a + /// `seed` holds a package as a real dir (an entry's `node_modules` + /// holds the entry's own package that way). + fn link_targets(&self, nm: &Path, seed: bool) -> Option> { + if !seed { + match std::fs::symlink_metadata(nm) { + Ok(metadata) if metadata.is_dir() => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(Vec::new()), + _ => return None, + } + } + let mut targets = Vec::new(); + let mut dirs = vec![(nm.to_path_buf(), false)]; + while let Some((dir, scope)) = dirs.pop() { + for child in std::fs::read_dir(&dir).ok()? { + let child = child.ok()?; + let name = child.file_name(); + let file_type = child.file_type().ok()?; + if name.as_encoded_bytes().starts_with(b".") { + continue; + } + if file_type.is_symlink() { + targets.extend(self.link_target(&dir.join(name))?); + } else if file_type.is_dir() { + if !scope && name.as_encoded_bytes().starts_with(b"@") { + dirs.push((dir.join(name), true)); + } else if seed { + return None; + } + } + } + } + Some(targets) + } + + /// The entry the link at `link` points into: `Some(None)` for a link + /// to anywhere else (a workspace member, a dir that is gone), `None` + /// when it cannot be resolved. The link's own target is read first + /// and resolved lexically (pnpm writes relative targets, and `link` + /// sits in a real dir, so each `..` climbs a real dir); one that does + /// not land in an entry dir that way (an absolute target, a link to a + /// link) is canonicalized instead. + fn link_target(&self, link: &Path) -> Option> { + let lexical = std::fs::read_link(link) + .ok() + .and_then(|target| { + Some(crate::utils::relpath::normalize_lexically_keeping_escapes( + &link.parent()?.join(target), + )) + }) + .and_then(|path| self.entry_of(&path)); + if lexical.is_some() { + return Some(lexical); + } + match std::fs::canonicalize(link) { + Ok(real) => Some(self.entry_of(&real)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(None), + Err(_) => None, + } + } + + /// The entry dir of the store that `path` lies in. + fn entry_of(&self, path: &Path) -> Option { + match path.strip_prefix(self.store).ok()?.components().next()? { + std::path::Component::Normal(name) => { + self.entries.contains(name).then(|| name.to_os_string()) + } + _ => None, + } + } +} + /// What [`live_bun_store_entries_sync`] found, by index into the /// candidates it was given: the scan walks thousands of entries, so they /// are tracked by position instead of hashed and cloned by name (#578). @@ -1068,67 +1309,119 @@ fn expand_workspace_pattern_sync(root: &Path, pattern: &str) -> Option HashSet { - let mut stores: HashMap>> = HashMap::new(); +/// Paths among `paths` that are copies inside an orphaned `.bun` or +/// `.pnpm` store entry (see [`live_bun_store_entries_sync`] and +/// [`live_pnpm_store_entries_sync`]), judged by where each canonicalizes, +/// or, when that is out of every store (a Bun global store entry's shared +/// dir, #635), by the `.bun` entry the path itself names; each store is +/// walked once. +fn orphaned_store_copies_sync(paths: &[PathBuf]) -> HashSet { + // Each copy that lies in such a store, with its store and entry. + let copies: Vec<(&PathBuf, StoreLayout, PathBuf, OsString)> = paths + .iter() + .filter_map(|path| { + let real = std::fs::canonicalize(path).ok()?; + let (layout, store, entry) = unpruned_store_entry_of(&real).or_else(|| { + let (layout, store, entry) = unpruned_store_entry_of( + &crate::utils::relpath::normalize_lexically_keeping_escapes(path), + )?; + if layout != StoreLayout::Bun { + return None; + } + Some((layout, std::fs::canonicalize(store).ok()?, entry)) + })?; + Some((path, layout, store, entry)) + }) + .collect(); + // The pnpm entries a copy's own path links into from outside the + // store: live whatever the walk of the store finds. + let mut linked: HashMap<&Path, HashSet> = HashMap::new(); + for (path, layout, store, entry) in &copies { + if *layout == StoreLayout::Pnpm && enters_store_through_link_sync(path, store) { + linked + .entry(store.as_path()) + .or_default() + .insert(entry.clone()); + } + } + let mut stores: HashMap<&Path, Option>> = HashMap::new(); let mut orphans = HashSet::new(); - for path in paths { - let Ok(real) = std::fs::canonicalize(path) else { - continue; - }; - let Some((store, entry)) = bun_store_entry_of(&real).or_else(|| { - let (store, entry) = bun_store_entry_of( - &crate::utils::relpath::normalize_lexically_keeping_escapes(path), - )?; - Some((std::fs::canonicalize(store).ok()?, entry)) - }) else { - continue; - }; - let live = stores.entry(store).or_insert_with_key(|store| { + for (path, layout, store, entry) in &copies { + let live = stores.entry(store.as_path()).or_insert_with_key(|store| { + if *layout == StoreLayout::Pnpm { + let linked = linked.remove(store).unwrap_or_default(); + return live_pnpm_store_entries_sync(store, &linked); + } let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); live_bun_store_entries_sync(store, &candidates).map(|live| live.into_names(&candidates)) }); - if live.as_ref().is_some_and(|live| !live.contains(&entry)) { - orphans.insert(path.clone()); + if live.as_ref().is_some_and(|live| !live.contains(entry)) { + orphans.insert((*path).clone()); } } orphans } -/// The `node_modules/.bun` store a real path lies in, and the name of the -/// entry holding it. -fn bun_store_entry_of(real: &Path) -> Option<(PathBuf, OsString)> { +/// Whether `path`, which resolves into the real dir `store`, gets there +/// through a link that sits outside the store: the copy was found in some +/// `node_modules` whose link points into a store entry, never by listing +/// the store itself. +fn enters_store_through_link_sync(path: &Path, store: &Path) -> bool { + for link in path.ancestors() { + let Some(parent) = link.parent() else { + return false; + }; + let parent = if parent.as_os_str().is_empty() { + Path::new(".") + } else { + parent + }; + let Ok(real_parent) = std::fs::canonicalize(parent) else { + return false; + }; + if !real_parent.starts_with(store) { + // The first component on the way up that sits outside the + // store: a link into an entry, or the store dir itself. + return std::fs::canonicalize(link) + .is_ok_and(|real| real != store && real.starts_with(store)); + } + } + false +} + +/// The `node_modules/.bun` or `node_modules/.pnpm` store a real path lies +/// in (the stores that keep entries nothing links any more), its layout, +/// and the name of the entry holding the path. +fn unpruned_store_entry_of(real: &Path) -> Option<(StoreLayout, PathBuf, OsString)> { let mut child: Option<&OsStr> = None; for dir in real.ancestors() { - if dir + let layout = dir .file_name() .and_then(OsStr::to_str) .and_then(pnpm_shaped_store_layout) - == Some(StoreLayout::Bun) - && dir.parent().and_then(Path::file_name) == Some(OsStr::new("node_modules")) - { - return Some((dir.to_path_buf(), child?.to_os_string())); + .filter(|layout| matches!(layout, StoreLayout::Bun | StoreLayout::Pnpm)); + if let Some(layout) = layout { + if dir.parent().and_then(Path::file_name) == Some(OsStr::new("node_modules")) { + return Some((layout, dir.to_path_buf(), child?.to_os_string())); + } } child = dir.file_name(); } None } -/// Drop from each list every copy that sits in an orphaned Bun store entry -/// (#599): one no link from the install reaches, which nothing can load. -/// For a check of the live install (`vex`), never for an operation that -/// restores copies. Each store is walked once across all the lists. +/// Drop from each list every copy that sits in an orphaned Bun or pnpm +/// store entry (#599, #2353): one no link from the install reaches, which +/// nothing can load. For a check of the live install (`vex`), never for +/// an operation that restores copies. Each store is walked once across +/// all the lists. pub async fn retain_live_store_copies<'a>(lists: impl IntoIterator>) { let lists: Vec<&mut Vec> = lists.into_iter().collect(); let paths: Vec = lists.iter().flat_map(|list| list.iter().cloned()).collect(); if paths.is_empty() { return; } - let orphans = run_walk(move || orphaned_bun_store_copies_sync(&paths)).await; + let orphans = run_walk(move || orphaned_store_copies_sync(&paths)).await; if orphans.is_empty() { return; } @@ -7785,6 +8078,574 @@ mod tests { ); } + /// The record pnpm 12 leaves in `node_modules/.modules.yaml` for an + /// install with the isolated linker. + const PNPM_ISOLATED_RECORD: &str = r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm","virtualStoreDirMaxLength":120}"#; + + /// A pnpm lock (lockfileVersion 9.0) whose importers are the root and + /// `members`. + fn pnpm_lock_of(members: &[&str]) -> String { + let importers: String = std::iter::once(&".") + .chain(members) + .map(|importer| { + format!( + " {importer}:\n dependencies:\n dep:\n specifier: 1.0.0\n \ + version: 1.0.0\n\n" + ) + }) + .collect(); + format!( + "lockfileVersion: '9.0'\n\nimporters:\n\n{importers}packages:\n\n dep@1.0.0:\n \ + resolution: {{integrity: sha512-x}}\n\nsnapshots:\n\n dep@1.0.0: {{}}\n" + ) + } + + /// What a pnpm install leaves below `root` besides the packages: the + /// install record and the current lockfile, naming the root and + /// `members` as importers. Returns `node_modules` and its store. + fn pnpm_install(root: &Path, members: &[&str]) -> (PathBuf, PathBuf) { + let nm = root.join("node_modules"); + let store = nm.join(".pnpm"); + std::fs::create_dir_all(&store).unwrap(); + std::fs::write(nm.join(".modules.yaml"), PNPM_ISOLATED_RECORD).unwrap(); + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(members)).unwrap(); + (nm, store) + } + + /// The package dir of `name@version` in the entry `entry` of `store`. + fn pnpm_entry(store: &Path, entry: &str, name: &str, version: &str) -> PathBuf { + let dir = store.join(entry).join("node_modules").join(name); + write_pkg(&dir, name, version); + dir + } + + /// The copies of `copies` that `vex`'s live-copy filter keeps. + async fn live_copies(copies: &[&PathBuf]) -> Vec { + let mut copies: Vec = copies.iter().map(|path| (*path).clone()).collect(); + retain_live_store_copies([&mut copies]).await; + copies + } + + /// The store a hosted scan and the in-place `pnpm install` it asks for + /// leave (real pnpm 12.25.1 and 11.29.0): the importer links the entry + /// of the patch's registry, and the upstream `minimist@1.2.2` entry + /// stays behind with nothing linking to it. Returns `node_modules`, + /// the orphaned copy and the linked one. + fn pnpm_hosted_route_orphan(root: &Path) -> (PathBuf, PathBuf, PathBuf) { + let (nm, store) = pnpm_install(root, &[]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry( + &store, + "minimist@socket-642d7f02+1.2.2", + "minimist", + "1.2.2", + ); + rel_link( + ".pnpm/minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &nm.join("minimist"), + ); + (nm, stale, routed) + } + + /// #2353: on pnpm 11.20 and later a hosted scan routes a patched + /// release through the registry of its patch, so the in-place install + /// writes `minimist@socket-+1.2.2`, links the importer to it and + /// leaves the upstream `minimist@1.2.2` entry behind (a one-package + /// project has no hoist dir). The orphan is no installed copy for + /// `vex`, whatever it holds; the resolver still finds it, so rollback + /// restores it, and the scan still lists the package once. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_hosted_route_orphans_is_not_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + + assert_eq!( + live_copies(&[&nm.join("minimist"), &stale, &routed]).await, + vec![nm.join("minimist"), routed.clone()] + ); + // The orphan alone is dropped too: the walk needs no live copy in + // the list to find the importer's link. + assert_eq!(live_copies(&[&stale]).await, Vec::::new()); + + let purls = vec!["pkg:npm/minimist@1.2.2".to_string()]; + let found = NpmCrawler::new().find_by_purls(&nm, &purls).await.unwrap(); + let mut copies: Vec = found["pkg:npm/minimist@1.2.2"] + .iter() + .map(|copy| copy.path.clone()) + .collect(); + for copy in copies.clone() { + copies.extend( + find_store_peer_variant_copies( + crate::utils::repo_root::ReadScope::Workspace, + ©, + ) + .await, + ); + } + assert!(copies.contains(&stale), "{copies:?}"); + assert_eq!( + scan_paths(&root).await, + vec![("pkg:npm/minimist@1.2.2".to_string(), nm.join("minimist"))] + ); + } + + /// #2353: a vendored scan re-keys the package to its `file:` tarball on + /// every pnpm, so the in-place install links the importer to + /// `minimist@file+.socket+vendor+npm++minimist-1.2.2.tgz` and + /// leaves the upstream entry behind the same way. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_vendored_tarball_orphans_is_not_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, store) = pnpm_install(&root, &[]); + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let entry = + "minimist@file+.socket+vendor+npm+642d7f02-ebc1-4ab0-99e2-07f5dd8463cb+minimist-1.2.2.tgz"; + let vendored = pnpm_entry(&store, entry, "minimist", "1.2.2"); + rel_link( + &format!(".pnpm/{entry}/node_modules/minimist"), + &nm.join("minimist"), + ); + + assert_eq!( + live_copies(&[&stale, &vendored, &nm.join("minimist")]).await, + vec![vendored, nm.join("minimist")] + ); + } + + /// #2353 over the store of #1197: a removed package, an upgraded-away + /// version and the vendored entry of an old version stay in the store + /// with nothing linking to them, beside the entries the importer links + /// (a scoped one through its `@scope` dir) and one the hoist dir + /// links. The filter drops exactly the unlinked ones. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entries_an_upgrade_orphans_are_not_live_copies() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, store) = pnpm_install(&root, &[]); + let number = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + rel_link( + ".pnpm/is-number@7.0.0/node_modules/is-number", + &nm.join("is-number"), + ); + let scoped = pnpm_entry( + &store, + "@s+lp@file+.socket+vendor+npm+u+s-lp-1.0.0.tgz", + "@s/lp", + "1.0.0", + ); + rel_link( + "../.pnpm/@s+lp@file+.socket+vendor+npm+u+s-lp-1.0.0.tgz/node_modules/@s/lp", + &nm.join("@s/lp"), + ); + let hoisted = pnpm_entry(&store, "ms@2.1.2", "ms", "2.1.2"); + rel_link( + "../ms@2.1.2/node_modules/ms", + &store.join("node_modules/ms"), + ); + let removed = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + let old = pnpm_entry(&store, "@s+lp@0.9.0", "@s/lp", "0.9.0"); + let old_vendored = pnpm_entry( + &store, + "ms@file+.socket+vendor+npm+v+ms-2.1.3.tgz", + "ms", + "2.1.3", + ); + + assert_eq!( + live_copies(&[&removed, &number, &old, &scoped, &old_vendored, &hoisted]).await, + vec![number, scoped, hoisted] + ); + } + + /// #2353: a linked entry is an installed copy whatever its name. Before + /// the in-place install the importer still links the upstream + /// `minimist@1.2.2` entry, so that copy is the one `vex` must judge, + /// and an entry of the patch's registry that nothing links (a later + /// rollback's leftover) is the orphan. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_the_importer_links_stays_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, store) = pnpm_install(&root, &[]); + let upstream = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry( + &store, + "minimist@socket-642d7f02+1.2.2", + "minimist", + "1.2.2", + ); + rel_link( + ".pnpm/minimist@1.2.2/node_modules/minimist", + &nm.join("minimist"), + ); + + assert_eq!( + live_copies(&[&nm.join("minimist"), &upstream, &routed]).await, + vec![nm.join("minimist"), upstream] + ); + } + + /// The workspace real pnpm 12.25.1 leaves after a hosted scan and the + /// in-place install: the root depends on `mkdirp`, member `a` on + /// `minimist@1.2.2` and member `b` on `minimist@1.2.5` and on `a`. + /// Each routed `minimist` entry is linked from one place only: 1.2.2 + /// from member `a` (and the hoist dir), 1.2.5 from member `b` alone, + /// 0.0.8 from `mkdirp`'s entry alone. The three upstream entries are + /// left behind. Returns the root's store, and the routed and the stale + /// copy of each version in that order. + #[cfg(unix)] + fn pnpm_workspace_route_orphans(root: &Path) -> (PathBuf, [PathBuf; 3], [PathBuf; 3]) { + let (nm, store) = pnpm_install(root, &["packages/a", "packages/b"]); + let entry = |entry: &str, version: &str| pnpm_entry(&store, entry, "minimist", version); + let routed = [ + entry("minimist@socket-642d7f02+1.2.2", "1.2.2"), + entry("minimist@socket-a8b05a61+1.2.5", "1.2.5"), + entry("minimist@socket-8cccd65b+0.0.8", "0.0.8"), + ]; + let stale = [ + entry("minimist@1.2.2", "1.2.2"), + entry("minimist@1.2.5", "1.2.5"), + entry("minimist@0.0.8", "0.0.8"), + ]; + pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); + rel_link(".pnpm/mkdirp@0.5.1/node_modules/mkdirp", &nm.join("mkdirp")); + rel_link( + "../../minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &store.join("mkdirp@0.5.1/node_modules/minimist"), + ); + let hoist = store.join("node_modules"); + rel_link( + "../minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &hoist.join("minimist"), + ); + for member in ["a", "b"] { + write_pkg(&root.join("packages").join(member), member, "1.0.0"); + rel_link(&format!("../../../packages/{member}"), &hoist.join(member)); + } + rel_link( + "../../../node_modules/.pnpm/minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &root.join("packages/a/node_modules/minimist"), + ); + rel_link( + "../../../node_modules/.pnpm/minimist@socket-a8b05a61+1.2.5/node_modules/minimist", + &root.join("packages/b/node_modules/minimist"), + ); + rel_link("../../a", &root.join("packages/b/node_modules/a")); + (store, routed, stale) + } + + /// #2353: in a workspace an entry may be linked from one member alone. + /// The members are importers like the root (the current lockfile names + /// them), so the entry only member `b` links stays live, and the three + /// upstream entries nothing links are dropped. A member the current + /// lockfile does not name (an install that did not finish) is still + /// read when `pnpm-lock.yaml` names it. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_only_a_workspace_member_links_is_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (store, routed, stale) = pnpm_workspace_route_orphans(&root); + let all: Vec<&PathBuf> = routed.iter().chain(&stale).collect(); + + assert_eq!(live_copies(&all).await, routed.to_vec()); + + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + std::fs::write( + root.join("pnpm-lock.yaml"), + pnpm_lock_of(&["packages/a", "packages/b"]), + ) + .unwrap(); + assert_eq!(live_copies(&all).await, routed.to_vec()); + } + + /// #2353: pnpm quotes an importer key that YAML cannot take plain + /// (`'@apps/web':`). The member is read all the same, so the entry it + /// alone links stays live beside the one nothing links. The copies are + /// named by their store paths, so only the member's link vouches. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_member_of_a_quoted_key_links_is_a_live_copy() { + for key in ["'@apps/web'", "\"@apps/web\""] { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, store) = pnpm_install(&root, &[key]); + let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + rel_link( + ".pnpm/is-number@7.0.0/node_modules/is-number", + &nm.join("is-number"), + ); + let member_only = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + write_pkg(&root.join("@apps/web"), "web", "1.0.0"); + rel_link( + "../../../node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad", + &root.join("@apps/web/node_modules/left-pad"), + ); + let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); + + assert_eq!( + live_copies(&[&used, &member_only, &orphan]).await, + vec![used, member_only], + "{key}" + ); + } + } + + /// #2353: a copy the caller found through a link in some + /// `node_modules` keeps its entry live, even when no lockfile names + /// that directory as an importer: the link is there, and the runtime + /// resolves through it. The entry's own dependencies stay live with + /// it. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_copy_is_linked_into_is_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, store) = pnpm_install(&root, &[]); + let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + rel_link( + ".pnpm/is-number@7.0.0/node_modules/is-number", + &nm.join("is-number"), + ); + let odd = pnpm_entry(&store, "is-odd@3.0.1", "is-odd", "3.0.1"); + let number6 = pnpm_entry(&store, "is-number@6.0.0", "is-number", "6.0.0"); + rel_link( + "../../is-number@6.0.0/node_modules/is-number", + &store.join("is-odd@3.0.1/node_modules/is-number"), + ); + let orphan = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + // A directory no lockfile names links `is-odd`. + let stray = root.join("tools/x/node_modules/is-odd"); + rel_link( + "../../../node_modules/.pnpm/is-odd@3.0.1/node_modules/is-odd", + &stray, + ); + + // Listed by their store paths alone, the entries only the stray + // directory reaches are orphans. + assert_eq!( + live_copies(&[&used, &odd, &number6, &orphan]).await, + vec![used.clone()] + ); + assert_eq!( + live_copies(&[&used, &stray, &odd, &number6, &orphan]).await, + vec![used, stray, odd, number6] + ); + } + + /// #2353: a transitive dependency has no link but the one in its + /// dependent's entry. `minimist@socket-8cccd65b+0.0.8` is reached only + /// through `mkdirp@0.5.1/node_modules/minimist`, and stays live for as + /// long as that entry is; once nothing links `mkdirp`'s entry either, + /// both are orphans. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_only_a_live_entry_links_is_a_live_copy() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (store, routed, stale) = pnpm_workspace_route_orphans(&root); + let mkdirp = store.join("mkdirp@0.5.1/node_modules/mkdirp"); + let [_, _, transitive] = &routed; + let [_, _, stale_transitive] = &stale; + + assert_eq!( + live_copies(&[stale_transitive, transitive, &mkdirp]).await, + vec![transitive.clone(), mkdirp.clone()] + ); + + std::fs::remove_file(root.join("node_modules/mkdirp")).unwrap(); + assert_eq!( + live_copies(&[stale_transitive, transitive, &mkdirp]).await, + Vec::::new() + ); + } + + /// #2353: wherever the walk cannot be sure it read every link, nothing + /// is dropped. Each case changes one thing about the store of + /// [`pnpm_hosted_route_orphan`], whose orphan is dropped as it stands. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_the_walk_cannot_read_keeps_every_entry() { + use std::os::unix::fs::PermissionsExt; + + type Change = fn(&Path); + type Case = (&'static str, Box); + let record = |from: &'static str, to: &'static str| { + move |root: &Path| { + let path = root.join("node_modules/.modules.yaml"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains(from), "{from}"); + std::fs::write(path, text.replace(from, to)).unwrap(); + } + }; + let hoisted_linker = record(r#""nodeLinker":"isolated""#, r#""nodeLinker":"hoisted""#); + let shamefully_hoisted = record( + r#""publicHoistPattern":[]"#, + r#""publicHoistPattern":["*"]"#, + ); + let other_layout = record(r#""layoutVersion":5"#, r#""layoutVersion":4"#); + let relocated_store = record( + r#""virtualStoreDir":".pnpm""#, + r#""virtualStoreDir":"../.store""#, + ); + let cases: Vec = vec![ + ("no install record", { + let change: Change = + |root| std::fs::remove_file(root.join("node_modules/.modules.yaml")).unwrap(); + Box::new(change) + }), + ("an install record that does not parse", { + let change: Change = |root| { + std::fs::write(root.join("node_modules/.modules.yaml"), "{ not json").unwrap() + }; + Box::new(change) + }), + ("node-linker=hoisted", Box::new(hoisted_linker)), + ("shamefully-hoist", Box::new(shamefully_hoisted)), + ("another layout version", Box::new(other_layout)), + ( + "a record of another virtual store", + Box::new(relocated_store), + ), + ("no current lockfile", { + let change: Change = + |root| std::fs::remove_file(root.join("node_modules/.pnpm/lock.yaml")).unwrap(); + Box::new(change) + }), + ("a current lockfile that is no pnpm lock", { + let change: Change = |root| { + std::fs::write(root.join("node_modules/.pnpm/lock.yaml"), "not: a lock\n") + .unwrap() + }; + Box::new(change) + }), + ("a current lockfile naming a member that is no directory", { + let change: Change = |root| { + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + pnpm_lock_of(&["packages/gone"]), + ) + .unwrap() + }; + Box::new(change) + }), + ("a current lockfile laid out as pnpm does not write it", { + let change: Change = |root| { + let lock = pnpm_lock_of(&[]).replace("\n .:\n", "\n .:\n"); + assert!(lock.contains("\n .:\n")); + std::fs::write(root.join("node_modules/.pnpm/lock.yaml"), lock).unwrap() + }; + Box::new(change) + }), + ("a pnpm-lock.yaml that cannot be read", { + let change: Change = + |root| std::fs::create_dir(root.join("pnpm-lock.yaml")).unwrap(); + Box::new(change) + }), + ("a pnpm-lock.yaml naming a member that is no directory", { + let change: Change = |root| { + std::fs::write( + root.join("pnpm-lock.yaml"), + pnpm_lock_of(&["packages/gone"]), + ) + .unwrap() + }; + Box::new(change) + }), + ("no link into the store", { + let change: Change = + |root| std::fs::remove_file(root.join("node_modules/minimist")).unwrap(); + Box::new(change) + }), + ("a package as a real dir of the importer", { + let change: Change = + |root| write_pkg(&root.join("node_modules/left-pad"), "left-pad", "1.3.0"); + Box::new(change) + }), + ("a package as a real dir of an importer's scope", { + let change: Change = + |root| write_pkg(&root.join("node_modules/@s/lp"), "@s/lp", "1.0.0"); + Box::new(change) + }), + ("a package as a real dir of the hoist dir", { + let change: Change = |root| { + write_pkg( + &root.join("node_modules/.pnpm/node_modules/left-pad"), + "left-pad", + "1.3.0", + ) + }; + Box::new(change) + }), + ("a live entry whose node_modules is a link", { + let change: Change = |root| { + let entry = root.join("node_modules/.pnpm/minimist@socket-642d7f02+1.2.2"); + std::fs::rename(entry.join("node_modules"), entry.join("moved")).unwrap(); + std::os::unix::fs::symlink("moved", entry.join("node_modules")).unwrap(); + }; + Box::new(change) + }), + ("a link that loops", { + let change: Change = |root| { + std::os::unix::fs::symlink("loop", root.join("node_modules/loop")).unwrap() + }; + Box::new(change) + }), + ]; + for (case, change) in cases { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + let copies = [&nm.join("minimist"), &stale, &routed]; + assert_eq!(live_copies(&copies[1..]).await, vec![routed.clone()]); + change(&root); + let kept: Vec = copies + .iter() + .filter(|copy| copy.exists()) + .map(|copy| (*copy).clone()) + .collect(); + assert_eq!( + live_copies(&kept.iter().collect::>()).await, + kept, + "{case}" + ); + } + + // A dir the walk may not read: an unreadable `node_modules` of the + // linked entry (not as root, which reads it all the same). + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (_, stale, routed) = pnpm_hosted_route_orphan(&root); + let unreadable = routed.parent().unwrap(); + std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o000)).unwrap(); + let readable = std::fs::read_dir(unreadable).is_ok(); + let kept = live_copies(&[&stale]).await; + std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o755)).unwrap(); + if !readable { + assert_eq!(kept, vec![stale], "an unreadable node_modules"); + } + } + + /// #2353: pnpm links directories with junctions on Windows, which the + /// walk does not follow, so nothing is dropped there. + #[cfg(windows)] + #[tokio::test] + async fn test_pnpm_store_orphans_are_kept_on_windows() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + assert_eq!( + live_copies(&[&nm.join("minimist"), &stale, &routed]).await, + vec![nm.join("minimist"), stale, routed] + ); + } + /// #599: Bun never prunes `.bun`. After an in-place `bun install` that /// rewires packages to hosted tarballs (or bumps a version), the old /// `@` entries stay on disk with nothing linking to diff --git a/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs b/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs index 8047cefc0d..8baa1a4065 100644 --- a/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs +++ b/crates/socket-patch-core/src/formats/pnpm/modules_yaml.rs @@ -17,10 +17,150 @@ pub(crate) fn field(text: &str, key: &str) -> Option { super::workspace::top_level_scalar(text, key) } +/// The fields of a `.modules.yaml` that say how the install is laid out +/// on disk. +#[derive(Debug, Default, serde::Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub(crate) struct Layout { + layout_version: Option, + node_linker: Option, + /// pnpm <= 4's spelling of a `publicHoistPattern` of `*`. + shamefully_hoist: Option, + public_hoist_pattern: Option>, + /// The virtual store, relative to `node_modules` (absolute on old + /// pnpm). + pub(crate) virtual_store_dir: Option, +} + +/// The `layoutVersion` pnpm 6 to 12 record: a flat virtual store of +/// `/node_modules/` dirs. +const FLAT_STORE_LAYOUT_VERSION: u64 = 5; + +impl Layout { + /// Read a record, JSON or YAML; `None` when it parses as neither, or + /// a field holds a value that is not of its type. + pub(crate) fn parse(text: &str) -> Option { + let text = strip_bom(text); + serde_json::from_str(text) + .ok() + .or_else(|| serde_saphyr::from_str(text).ok()) + } + + /// Whether the install is one of pnpm's isolated linker over a flat + /// virtual store, without `shamefully-hoist`: every package is then a + /// dir of a store entry, reached through links alone. A record of + /// another linker (`hoisted`, `pnp`), of another store layout or of a + /// `publicHoistPattern` of `*` is not. + pub(crate) fn is_isolated(&self) -> bool { + self.layout_version == Some(FLAT_STORE_LAYOUT_VERSION) + && self + .node_linker + .as_deref() + .is_none_or(|linker| linker == "isolated") + && self.shamefully_hoist != Some(true) + && !self + .public_hoist_pattern + .iter() + .flatten() + .any(|pattern| pattern == "*") + } +} + #[cfg(test)] mod tests { use super::*; + /// The records pnpm 12.25.1 (JSON) and pnpm 9.15.9 (YAML) write for a + /// default install, the paths shortened. + const PNPM_12_RECORD: &str = r#"{ + "hoistedDependencies": {}, + "hoistPattern": [ + "*" + ], + "included": { + "dependencies": true, + "devDependencies": true, + "optionalDependencies": true + }, + "layoutVersion": 5, + "nodeLinker": "isolated", + "packageManager": "pnpm@12.25.1", + "pendingBuilds": [], + "prunedAt": "Tue, 01 Dec 2026 14:46:07 GMT", + "publicHoistPattern": [], + "skipped": [], + "storeDir": "/home/dev/.local/share/pnpm/store/v11", + "virtualStoreDir": ".pnpm", + "virtualStoreDirMaxLength": 120, + "allowBuilds": {} +}"#; + const PNPM_9_RECORD: &str = "hoistPattern:\n - '*'\nhoistedDependencies: {}\nincluded:\n \ + dependencies: true\n devDependencies: true\n optionalDependencies: true\n\ + injectedDeps: {}\nlayoutVersion: 5\nnodeLinker: isolated\npackageManager: pnpm@9.15.9\n\ + pendingBuilds: []\nprunedAt: Tue, 01 Dec 2026 14:59:43 GMT\npublicHoistPattern:\n \ + - '*eslint*'\n - '*prettier*'\nregistries:\n default: https://registry.npmjs.org/\n\ + skipped: []\nstoreDir: /home/dev/.local/share/pnpm/store/v3\nvirtualStoreDir: .pnpm\n\ + virtualStoreDirMaxLength: 120\n"; + + #[test] + fn layout_reads_the_isolated_linker_of_json_and_yaml_records() { + for record in [PNPM_12_RECORD, PNPM_9_RECORD] { + let layout = Layout::parse(record).unwrap(); + assert!(layout.is_isolated(), "{record}"); + assert_eq!(layout.virtual_store_dir.as_deref(), Some(".pnpm")); + } + // pnpm 6 records no linker: it has the isolated one alone. + let pnpm_6 = PNPM_9_RECORD.replace("nodeLinker: isolated\n", ""); + assert!(Layout::parse(&pnpm_6).unwrap().is_isolated()); + } + + #[test] + fn layout_is_not_isolated_for_another_linker_layout_or_public_hoist() { + for (from, to) in [ + ("nodeLinker: isolated", "nodeLinker: hoisted"), + ("nodeLinker: isolated", "nodeLinker: pnp"), + ("layoutVersion: 5", "layoutVersion: 4"), + ("layoutVersion: 5\n", ""), + (" - '*eslint*'\n", " - '*'\n"), + ( + "layoutVersion: 5", + "layoutVersion: 5\nshamefullyHoist: true", + ), + ] { + let record = PNPM_9_RECORD.replace(from, to); + assert_ne!(record, PNPM_9_RECORD, "{from}"); + assert!(!Layout::parse(&record).unwrap().is_isolated(), "{record}"); + } + for (from, to) in [ + (r#""nodeLinker": "isolated""#, r#""nodeLinker": "hoisted""#), + ( + r#""publicHoistPattern": []"#, + r#""publicHoistPattern": ["*"]"#, + ), + ] { + let record = PNPM_12_RECORD.replace(from, to); + assert_ne!(record, PNPM_12_RECORD, "{from}"); + assert!(!Layout::parse(&record).unwrap().is_isolated(), "{record}"); + } + } + + #[test] + fn layout_of_an_unreadable_record_is_never_isolated() { + for record in [ + "", + "{ not json", + "- a\n- list\n", + r#"{"layoutVersion": [5], "nodeLinker": "isolated"}"#, + "layoutVersion: five\nnodeLinker: isolated\n", + "publicHoistPattern: '*'\nlayoutVersion: 5\n", + ] { + assert!( + !Layout::parse(record).is_some_and(|layout| layout.is_isolated()), + "{record:?}" + ); + } + } + #[test] fn reads_json_and_yaml_records_alike() { for text in [ diff --git a/crates/socket-patch-core/src/formats/pnpm/workspace.rs b/crates/socket-patch-core/src/formats/pnpm/workspace.rs index cfd43e4485..86de11b010 100644 --- a/crates/socket-patch-core/src/formats/pnpm/workspace.rs +++ b/crates/socket-patch-core/src/formats/pnpm/workspace.rs @@ -246,6 +246,63 @@ pub(crate) fn lock_text_member_importers(text: &str) -> Vec { members } +/// The importers besides the root `.` that a pnpm lock names, for a caller +/// that must not miss one: `None` when an `importers` section is not laid +/// out the way pnpm writes it, so that a key may be misread. pnpm writes +/// the section as a block, its keys at two spaces, plain or in quotes +/// (`'@apps/web':`); a key that holds an escape, a flow mapping and any +/// other indentation are not read. Every document counts (the env +/// document of pnpm 11 and later names the root alone), and a lock +/// without the section, which pnpm 6 to 8 write for a project that is no +/// workspace, names no member. +pub(crate) fn lock_text_member_importers_exact(text: &str) -> Option> { + let mut members = Vec::new(); + for (span, _) in super::grammar::documents(text) { + // Inside an `importers` section, and whether its first key is + // still to come. + let (mut in_importers, mut first) = (false, false); + for line in strip_bom(&text[span]).split('\n') { + let line = line.strip_suffix('\r').unwrap_or(line); + let content = line.trim_start_matches(' '); + if content.is_empty() || content.starts_with('#') { + continue; + } + let indent = line.len() - content.len(); + if content.starts_with('\t') { + if in_importers { + return None; + } + } else if indent == 0 { + in_importers = false; + if let Some((key, value)) = top_level_key(line) { + if key == "importers" { + match value { + "" => (in_importers, first) = (true, true), + "{}" => {} + _ => return None, + } + } + } + } else if in_importers { + if indent < 2 || (first && indent != 2) { + return None; + } + first = false; + if indent == 2 { + let (key, written, _) = super::lines::parse_key_line(line, 2)?; + if written.starts_with('"') && key.contains('\\') { + return None; + } + if key != "." { + members.push(key.to_string()); + } + } + } + } + } + Some(members) +} + /// Insert `block` at line `at` of `lines` (a file split at `\n`), ending /// its lines as the file ends its own (`eol`, the file's /// [`terminator`](crate::utils::line_endings::terminator)): in a CRLF file @@ -741,6 +798,68 @@ mod tests { ); } + /// The exact reader names every member pnpm writes, quoted keys + /// included, and answers `None` for a section it may misread. + #[test] + fn exact_member_importers_refuse_a_section_they_may_misread() { + let lock = |importers: &str| { + format!( + "lockfileVersion: '9.0'\n\nimporters:\n{importers}\npackages:\n\n \ + a@1.0.0:\n resolution: {{}}\n" + ) + }; + let exact = |importers: &str| lock_text_member_importers_exact(&lock(importers)); + let named = |members: &[&str]| Some(members.iter().map(|m| m.to_string()).collect()); + assert_eq!( + exact( + "\n .:\n dependencies:\n a:\n specifier: 1.0.0\n\n \ + apps/web: {}\n\n '@apps/web':\n dependencies: {}\n\n \ + \"@apps/api\": {}\n # apps/old: {}\n# kept\n ../shared: {}\n" + ), + named(&["apps/web", "@apps/web", "@apps/api", "../shared"]) + ); + // CRLF, the env document of pnpm 11 and later, and no section. + assert_eq!( + lock_text_member_importers_exact( + "---\nlockfileVersion: '9.0'\r\nimporters:\r\n .:\r\n \ + configDependencies: {}\r\n---\nlockfileVersion: '9.0'\r\nimporters:\r\n \ + '.': {}\r\n 'packages/a': {}\r\n" + ), + named(&["packages/a"]) + ); + assert_eq!( + lock_text_member_importers_exact("lockfileVersion: '6.0'\n\ndependencies: {}\n"), + named(&[]) + ); + assert_eq!( + lock_text_member_importers_exact("lockfileVersion: '9.0'\nimporters: {}\n"), + named(&[]) + ); + for misread in [ + // An escape in a quoted key. + "\n 'it''s': {}\n", + "\n \"a\\\\b\": {}\n", + "\n \"a\\\"b\": {}\n", + // Keys at another indentation. + "\n .: {}\n packages/a: {}\n", + "\n .: {}\n", + "\n .: {}\n packages/a: {}\n", + "\n\t.: {}\n", + // A line that is no key. + "\n .: {}\n ? complex\n", + "\n - .\n", + ] { + assert_eq!(exact(misread), None, "{misread:?}"); + } + // A flow mapping. + assert_eq!( + lock_text_member_importers_exact( + "lockfileVersion: '9.0'\nimporters: {.: {}, packages/a: {}}\n" + ), + None + ); + } + /// #1952: a commented-out importer is not a member, a column-0 comment /// does not end `importers:`, and the env document's importers never /// count; the line and text forms agree. From fe6afe1f4dcc3068c5f1a3d31d17a17240cec8ce Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 12:02:07 -0500 Subject: [PATCH 02/22] Test vex, apply --check and rollback over an unlinked pnpm store entry Hand-built pnpm stores in the shapes real pnpm leaves (#2353): - `vex` over a hosted patch routed through its registry attests from the entry the importer links, and refuses the patch while that copy is pristine, whichever entry it is in and whatever an unlinked entry holds; - `vex` over a vendored patch does not warn `vendored_tree_out_of_sync` for the upstream entry nothing links, and still warns for an unpatched linked copy; - `apply --check` is in sync when the linked copy is patched and drift when it is not; - `rollback` still restores a patched entry that nothing links. Co-Authored-By: Claude Fable 5.2 --- .../apply/check_verifies_installed_tree.rs | 65 ++++++++++ .../tests/e2e_vex_redirect.rs | 106 +++++++++++++++ .../socket-patch-cli/tests/e2e_vex_vendor.rs | 122 ++++++++++++++++++ .../tests/rollback/rollback_failure_paths.rs | 86 ++++++++++++ 4 files changed, 379 insertions(+) diff --git a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs index 348299f831..79a4375c80 100644 --- a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs +++ b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs @@ -513,3 +513,68 @@ fn check_remedy_keeps_global_prefix_and_heals_the_checked_tree() { assert_eq!(code, 0, "the remedy healed the checked tree: {stderr}"); assert_eq!(std::fs::read(&index).unwrap(), PATCHED); } + +/// #2353: pnpm keeps a store entry it no longer uses (pnpm 7 to 11 for up +/// to 7 days, pnpm 12 until `pnpm prune`), with nothing linking to it. Such +/// an entry is no installed copy for `--check`, as for `vex`: the copy the +/// importer links decides. A patched linked copy is in sync beside an +/// unlinked entry of another peer set that holds the original bytes, and +/// an unpatched linked copy is drift beside a patched unlinked one. +#[cfg(unix)] +#[test] +fn check_judges_the_pnpm_store_entry_the_install_links() { + for (linked_bytes, unlinked_bytes, in_sync) in + [(PATCHED, ORIGINAL, true), (ORIGINAL, PATCHED, false)] + { + let tmp = project(None); + let nm = tmp.path().join("node_modules"); + let store = nm.join(".pnpm"); + let linked = "check-target@1.0.0_peer@2.0.0"; + for (entry, bytes) in [ + (linked, linked_bytes), + ("check-target@1.0.0_peer@1.0.0", unlinked_bytes), + ] { + let pkg = store.join(entry).join("node_modules/check-target"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{ "name": "check-target", "version": "1.0.0" }"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n \ + check-target:\n specifier: 1.0.0\n version: 1.0.0(peer@2.0.0)\n\n\ + packages:\n\n check-target@1.0.0:\n resolution: {integrity: sha512-x}\n\n\ + snapshots:\n\n check-target@1.0.0(peer@2.0.0): {}\n", + ) + .unwrap(); + std::os::unix::fs::symlink( + format!(".pnpm/{linked}/node_modules/check-target"), + nm.join("check-target"), + ) + .unwrap(); + + let (code, stdout, stderr) = run_check(tmp.path(), &["--json"]); + let env = parse_json_envelope(stdout.trim()); + if in_sync { + assert_eq!(code, 0, "the linked copy is patched: {env}\n{stderr}"); + } else { + assert_eq!(code, 1, "the linked copy is unpatched: {env}\n{stderr}"); + assert!( + events(&env).iter().any(|e| e["action"] == "failed" + && e["purl"] == PURL + && e["errorCode"] == "not_applied"), + "{env}" + ); + } + } +} diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index f981d445c1..e4e51c526a 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2475,6 +2475,112 @@ fn bun_hosted_ref_ignores_orphaned_registry_store_entry() { } } +/// #2353: on pnpm 11.20 and later a hosted scan routes the patched release +/// through the registry of its patch, so the in-place `pnpm install` +/// writes the entry `left-pad@socket-+1.3.0`, links the importer to it +/// and leaves the upstream `left-pad@1.3.0` entry in the store with +/// nothing linking to it (real pnpm 12.25.1 / 11.29.0 layout; pnpm 12 +/// keeps it until `pnpm prune`). Nothing can load the orphan, so it is no +/// installed copy: the patched linked copy attests, where vex refused the +/// patch as `not_applied` and the reinstall it asked for changed nothing. +/// +/// The link decides, never the entry's name or its bytes. While the copy +/// the importer links is pristine, the patch is refused, whichever entry +/// that copy is in, and a patched entry nothing links does not vouch for +/// it. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_judged_by_the_store_entry_the_install_links() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let url = hosted_npm_url("left-pad", "1.3.0", UUID); + let alias = format!("socket-{}", &UUID[..8]); + let registry = url.strip_suffix("left-pad-1.3.0.tgz").unwrap(); + let lock = format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n left-pad@1.3.0: {alias}:1.3.0\n\n\ + importers:\n\n .:\n dependencies:\n left-pad:\n \ + specifier: {alias}:1.3.0\n version: {alias}:1.3.0\n\npackages:\n\n \ + left-pad@{alias}:1.3.0:\n resolution: {{integrity: {SRI}, tarball: {url}}}\n\n\ + snapshots:\n\n left-pad@{alias}:1.3.0: {{}}\n" + ); + let upstream_entry = "left-pad@1.3.0"; + let routed_entry = format!("left-pad@{alias}+1.3.0"); + // (the entry the importer links, its bytes, the other entry's bytes, + // whether the patch attests) + for (linked, linked_bytes, other_bytes, attests) in [ + (routed_entry.as_str(), patched, pristine, true), + (routed_entry.as_str(), pristine, patched, false), + (upstream_entry, pristine, patched, false), + ] { + let label = format!("the importer links {linked}, attests {attests}"); + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + put( + cwd, + "package.json", + br#"{ "name": "app", "version": "1.0.0", "dependencies": { "left-pad": "1.3.0" } }"#, + ); + put( + cwd, + "pnpm-workspace.yaml", + format!( + "packages:\n - '.'\nnamedRegistries:\n {alias}: {registry}\noverrides:\n \ + 'left-pad@1.3.0': '{alias}:1.3.0'\n" + ) + .as_bytes(), + ); + put(cwd, "pnpm-lock.yaml", lock.as_bytes()); + // What the install records beside the packages (pnpm 12.25.1). + put( + cwd, + "node_modules/.modules.yaml", + br#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ); + put(cwd, "node_modules/.pnpm/lock.yaml", lock.as_bytes()); + for entry in [upstream_entry, routed_entry.as_str()] { + let dir = format!("node_modules/.pnpm/{entry}/node_modules/left-pad"); + put( + cwd, + &format!("{dir}/package.json"), + br#"{ "name": "left-pad", "version": "1.3.0" }"#, + ); + let bytes = if entry == linked { + linked_bytes + } else { + other_bytes + }; + put(cwd, &format!("{dir}/index.js"), bytes); + } + std::os::unix::fs::symlink( + format!(".pnpm/{linked}/node_modules/left-pad"), + cwd.join("node_modules/left-pad"), + ) + .unwrap(); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + if attests { + assert_attested(cwd, code, &env, UUID, &label); + } else { + assert_eq!(code, Some(1), "{label}: {env}"); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{label}: {env}"); + } + for entry in [upstream_entry, routed_entry.as_str()] { + assert!( + cwd.join("node_modules/.pnpm").join(entry).is_dir(), + "{label}: vex leaves both entries in the store" + ); + } + } +} + /// The patch view for `name@version` (the [`left_pad_view`] shape). fn npm_view(name: &str, version: &str, after_hash: &str) -> Value { let mut view = left_pad_view(after_hash); diff --git a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs index 0efc064f9d..588126ef05 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_vendor.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_vendor.rs @@ -1445,6 +1445,128 @@ fn vendored_bun_orphaned_store_entry_is_not_out_of_sync() { } } +/// REGRESSION (#2353): pnpm keeps a store entry it no longer uses (pnpm +/// 7 to 11 for up to 7 days, pnpm 12 until `pnpm prune`). After the +/// in-place `pnpm install` that consumes a vendored tarball, the +/// pre-vendor `lodash@4.17.21` registry entry stays in +/// `node_modules/.pnpm`, pristine, while the importer links the tarball's +/// entry (`lodash@file+.socket+vendor+npm++lodash-4.17.21.tgz`, the +/// name real pnpm 10.34.9 and 12.25.1 give it). Nothing can load the +/// orphan, so it is no installed copy: no `vendored_tree_out_of_sync` +/// warning, which re-running the install could never clear. The control's +/// linked copy is unpatched beside a patched entry nothing links, and +/// must still warn. +#[cfg(unix)] +#[test] +fn vendored_pnpm_store_entry_nothing_links_is_not_out_of_sync() { + let purl = "pkg:npm/lodash@4.17.21"; + let uuid = "0a0a0a0a-1111-4111-8111-0a0a0a0a0a0a"; + let patched = b"patched npm bytes\n"; + let pristine = b"original unpatched bytes\n"; + for live_patched in [true, false] { + let label = format!("linked copy patched {live_patched}"); + let tmp = tempfile::tempdir().expect("create tempdir"); + let cwd = &tmp.path().join("app"); + std::fs::create_dir_all(cwd).unwrap(); + + let after_hash = compute_git_sha256_from_bytes(patched); + let rel = format!(".socket/vendor/npm/{uuid}/lodash-4.17.21.tgz"); + let sha256 = sha256_hex(&write_member_tgz( + &cwd.join(&rel), + "package/index.js", + patched, + )); + let record = make_record( + uuid, + "package/index.js", + &after_hash, + "GHSA-sync-aaaa", + &["CVE-2026-10"], + ); + let wiring = write_matrix_wiring(cwd, "npm", uuid, &rel); + let mut state = VendorState::new(); + state.entries.insert( + purl.to_string(), + detached_matrix_entry("npm", purl, uuid, &rel, sha256, record, wiring), + ); + std::fs::write( + cwd.join(".socket/vendor/state.json"), + serde_json::to_string_pretty(&state).expect("serialize vendor state"), + ) + .expect("write vendor state.json"); + + // What a pnpm install records beside the packages (pnpm 12.25.1). + let nm = cwd.join("node_modules"); + let store = nm.join(".pnpm"); + std::fs::create_dir_all(&store).unwrap(); + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + format!( + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n lodash:\n \ + specifier: file:{rel}\n version: file:{rel}\n\npackages:\n\n \ + lodash@file:{rel}:\n resolution: {{integrity: sha512-cGF0Y2hlZA==, \ + tarball: file:{rel}}}\n version: 4.17.21\n\nsnapshots:\n\n \ + lodash@file:{rel}: {{}}\n" + ), + ) + .unwrap(); + let live_entry = format!("lodash@file+.socket+vendor+npm+{uuid}+lodash-4.17.21.tgz"); + let (live_bytes, orphan_bytes) = if live_patched { + (&patched[..], &pristine[..]) + } else { + (&pristine[..], &patched[..]) + }; + for (entry, bytes) in [ + ("lodash@4.17.21", orphan_bytes), + (live_entry.as_str(), live_bytes), + ] { + let pkg = store.join(entry).join("node_modules/lodash"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{"name":"lodash","version":"4.17.21"}"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + std::os::unix::fs::symlink( + format!(".pnpm/{live_entry}/node_modules/lodash"), + nm.join("lodash"), + ) + .unwrap(); + + let vex_path = cwd.join("out.vex.json"); + let out = cli() + .args([ + "vex", + "--cwd", + cwd.to_str().unwrap(), + "--json", + "--output", + vex_path.to_str().unwrap(), + "--product", + "pkg:npm/app@1.0.0", + ]) + .output() + .expect("invoke vex"); + let env: Value = serde_json::from_slice(&out.stdout).expect("envelope JSON on stdout"); + assert!(out.status.success(), "{label}: {env}"); + assert_eq!(env["status"], "success", "{label}: {env}"); + let out_of_sync = env["warnings"].as_array().is_some_and(|ws| { + ws.iter().any(|w| { + w["code"] == "vendored_tree_out_of_sync" + && w["detail"].as_str().is_some_and(|d| d.contains(purl)) + }) + }); + assert_eq!(out_of_sync, !live_patched, "{label}: {env}"); + } +} + /// REGRESSION (#325): the lock rewires the hoisted `lodash@4.17.21` to the /// vendored tarball, but a parent package also BUNDLES `lodash@4.17.21` /// (`inBundle: true`). npm unpacks that copy from the parent's tarball, so diff --git a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs index 5b1cc1c405..c74c901d1d 100644 --- a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs +++ b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs @@ -482,6 +482,92 @@ fn bun_orphaned_store_entry_is_still_rolled_back() { ); } +/// #2353: pnpm keeps a store entry it no longer uses (pnpm 12 until +/// `pnpm prune`). A patched `is-number@6.0.0` entry the project has since +/// moved off (an in-place `pnpm install` of 7.0.0 re-linked the importer +/// to the new entry) is an orphan nothing loads now, but a later install +/// that resolves back to 6.0.0 re-links it as it is. Rollback must still +/// restore it: the orphan filter that keeps `vex` from judging the install +/// by such an entry is for checks of the live install only. +#[cfg(unix)] +#[test] +fn pnpm_store_entry_nothing_links_is_still_rolled_back() { + let before: &[u8] = b"module.exports = 'original'\n"; + let after: &[u8] = b"module.exports = 'original' // PATCHED-2353\n"; + let (before_hash, after_hash) = (git_sha256(before), git_sha256(after)); + let purl = "pkg:npm/is-number@6.0.0"; + + let tmp = tempfile::tempdir().expect("tempdir"); + let root = tmp.path(); + std::fs::write( + root.join("package.json"), + r#"{ "name": "app", "version": "0.0.0", "dependencies": { "is-number": "7.0.0" } }"#, + ) + .expect("write root package.json"); + let orphan = install_npm_pkg( + root, + "node_modules/.pnpm/is-number@6.0.0/node_modules", + "is-number", + "6.0.0", + after, + ); + install_npm_pkg( + root, + "node_modules/.pnpm/is-number@7.0.0/node_modules", + "is-number", + "7.0.0", + b"module.exports = 7\n", + ); + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + root.join("node_modules/.modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .expect("install record"); + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n is-number:\n \ + specifier: 7.0.0\n version: 7.0.0\n\npackages:\n\n is-number@7.0.0:\n \ + resolution: {integrity: sha512-x}\n\nsnapshots:\n\n is-number@7.0.0: {}\n", + ) + .expect("current lockfile"); + std::os::unix::fs::symlink( + ".pnpm/is-number@7.0.0/node_modules/is-number", + root.join("node_modules/is-number"), + ) + .expect("importer link"); + let socket = write_socket_manifest( + root, + &[manifest_entry( + purl, + "dddddddd-dddd-4ddd-8ddd-dddddddddddd", + &before_hash, + &after_hash, + )], + ); + common::write_blob(&socket, &before_hash, before); + common::write_blob(&socket, &after_hash, after); + + let (code, stdout, stderr) = run(root, &["rollback", "--json", "--offline", "--yes"]); + assert_eq!(code, 0, "stdout=\n{stdout}\nstderr=\n{stderr}"); + let v = parse_json_envelope(&stdout); + assert_eq!( + rollback_json::not_installed(&v), + json!([]), + "the orphaned entry must be found; stdout=\n{stdout}" + ); + assert_eq!( + rollback_json::agent_rolled_back(&v), + json!([purl]), + "stdout=\n{stdout}" + ); + assert_eq!( + std::fs::read(orphan.join("index.js")).expect("read orphan index.js"), + before, + "the orphaned entry must be restored; stdout=\n{stdout}\nstderr=\n{stderr}" + ); +} + /// A ledger entry whose ecosystem has no vendor backend in this build /// fails the vendored leg: exit 1, the purl + error in `vendoredFailed` /// with `vendor_revert_failed`, and the manifest entry retained From 8ce3e683056fc0fcef57f701126846a6e33a327c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 12:02:07 -0500 Subject: [PATCH 03/22] Run the in-place pnpm install and vex in the real-pnpm suites The registry-route legs (pnpm 11 and 12) and the vendored capstone (each pnpm of its matrix from 9 up) now also run the install a scan asks for over a `node_modules` that holds the upstream packages, in a second checkout so the project under test stays as it was. Each leg checks that pnpm kept the upstream entry in the store and linked the patched one, that `vex` attests from the linked copy (hosted) or does not warn (vendored), and that a linked copy put back on the upstream bytes is refused or warned about again (#2353). The capstone's first `vex`, which runs before any reinstall, now also expects the `vendored_tree_out_of_sync` warning: the project still links the upstream package there. The scan's files are written anew in the second checkout: pnpm 10.0 takes files no newer than its last install for unchanged and skips the install. The legs do not run on Windows, where the check keeps judging every store entry. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_redirect_pnpm_build.rs | 155 ++++++++++++---- .../tests/e2e_vendor_pnpm_build.rs | 172 ++++++++++++++++++ 2 files changed, 296 insertions(+), 31 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index c1bcc90de8..d591c76726 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -1867,42 +1867,135 @@ async fn registry_route_survives_resolution_and_cleans_up(pm: &str, tag: &str) { patch.name ); } - let (code, stdout, stderr) = run_socket( - &fresh, - &[ - "vex", - "--product", - "pkg:npm/app@1.0.0", - "--api-url", - &server.uri(), - "--org", - ORG, - "--api-token", - "fake", - "--patch-server-url", - &server.uri(), - ], - ); - assert_eq!(code, 0, "{tag}: verified VEX failed: {stdout}\n{stderr}"); - let vex: serde_json::Value = serde_json::from_str(&stdout).unwrap(); - let attested: Vec<(&str, &str)> = vex["statements"] - .as_array() - .into_iter() - .flatten() - .filter_map(|statement| { - Some(( - statement["vulnerability"]["name"].as_str()?, - statement["status"].as_str()?, - )) - }) - .collect(); + // The advisories `vex` attests in `dir`, each with its status. + let vex_statements = |dir: &Path, when: &str| -> Vec<(String, String)> { + let (code, stdout, stderr) = run_socket( + dir, + &[ + "vex", + "--product", + "pkg:npm/app@1.0.0", + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &server.uri(), + ], + ); + assert_eq!( + code, 0, + "{tag} {when}: verified VEX failed: {stdout}\n{stderr}" + ); + let vex: serde_json::Value = serde_json::from_str(&stdout).unwrap(); + vex["statements"] + .as_array() + .into_iter() + .flatten() + .filter_map(|statement| { + Some(( + statement["vulnerability"]["name"].as_str()?.to_string(), + statement["status"].as_str()?.to_string(), + )) + }) + .collect() + }; + let not_affected = |patch: &RoutePatch| (patch.advisory(), "not_affected".to_string()); + let attested = vex_statements(&fresh, "a fresh checkout"); for patch in &ROUTE_PATCHES { assert!( - attested.contains(&(patch.advisory().as_str(), "not_affected")), - "{tag}: {} must be attested from the routed lock: {vex}", + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested from the routed lock: {attested:?}", patch.name ); } + + // ── the install the scan asks for, over an installed tree ── + // A second checkout that holds the upstream packages (a developer's + // `node_modules`, a CI job that restores it from a cache), then the + // scan's two files and a plain `pnpm install`. pnpm links the project + // to the entries of the patches' registries and keeps the upstream + // entries in the store with nothing linking to them. `vex` judges the + // copies the install links: both patches attest, and a linked copy + // put back on the upstream bytes is refused again. + // + // pnpm links directories with junctions on Windows, which vex's check + // of the store's links does not follow: it judges every entry there. + if !cfg!(windows) { + let warm = tmp.path().join("warm"); + std::fs::create_dir_all(&warm).unwrap(); + for file in ["package.json", ".npmrc"] { + std::fs::copy(proj.join(file), warm.join(file)).unwrap(); + } + std::fs::write(warm.join("pnpm-lock.yaml"), &lock_before).unwrap(); + let install = |flags: &[&str], what: &str| { + let flag = store("store-warm"); + let mut args = vec!["install"]; + args.extend_from_slice(flags); + args.push(&flag); + let out = route_pnpm(&cache, &warm, pm, &args); + assert!(out.status.success(), "{tag} {what}:\n{}", chatter(&out)); + }; + install(&["--frozen-lockfile"], "the upstream install"); + // Written anew, as a scan would: a copy that kept the files' + // modification times could read as unchanged to pnpm. + for file in ["pnpm-lock.yaml", "pnpm-workspace.yaml"] { + std::fs::write(warm.join(file), std::fs::read(proj.join(file)).unwrap()).unwrap(); + } + install(&[], "the in-place install"); + assert_eq!( + read(&warm.join("pnpm-lock.yaml")), + read(&lock_path), + "{tag}: the in-place install keeps the scan's lock" + ); + // Both entries of the leaf are in the store, or this leg would + // prove nothing; the project is linked to the patched ones. + let entries = warm.join("node_modules/.pnpm"); + for entry in [ + "leaf@1.0.0".to_string(), + format!("leaf@{}+1.0.0", leaf.alias()), + ] { + assert!( + entries.join(&entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + for (through, name) in [("peer-user", "peer-user"), ("mid", "leaf")] { + assert!( + installed_index(&warm, through, name).starts_with(MARKER), + "{tag}: the in-place install links the patched {name}" + ); + } + let attested = vex_statements(&warm, "the in-place install"); + for patch in &ROUTE_PATCHES { + assert!( + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested after the in-place install: {attested:?}", + patch.name + ); + } + + // The leaf the install links, back on the upstream bytes (a new + // file: pnpm's are hard links into its store). + let linked_leaf = warm + .join("node_modules/mid") + .canonicalize() + .unwrap() + .parent() + .unwrap() + .join("leaf/index.js"); + std::fs::remove_file(&linked_leaf).unwrap(); + std::fs::write(&linked_leaf, route_index("leaf", false)).unwrap(); + let attested = vex_statements(&warm, "an unpatched linked leaf"); + assert!( + !attested.iter().any(|(name, _)| *name == leaf.advisory()) + && attested.contains(¬_affected(peer_user)), + "{tag}: an unpatched copy the install links must not be attested: {attested:?}" + ); + } + for (step, args) in [ ("add", vec!["add", "extra@1.0.0"]), ("update", vec!["update"]), diff --git a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs index 3d7f72b66b..603b98e6b9 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs @@ -586,6 +586,12 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { code, 0, "vex failed ({pm}).\nstdout:\n{stdout}\nstderr:\n{stderr}" ); + // No install has run since vendoring: the copy the project links is + // still the upstream one, and vex says so. + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: the installed tree still holds the upstream package:\n{stderr}" + ); let vex_doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&vex_path).unwrap()).unwrap(); let vex_stmts = vex_doc["statements"].as_array().unwrap(); @@ -669,6 +675,15 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { } eprintln!("VENDOR OK ({pm}, {driver:?})"); + assert_in_place_install_verifies( + tmp.path(), + &proj, + pm, + &store, + (pkg_before.as_slice(), lock_before.as_slice()), + (orig.as_slice(), patched.as_slice()), + ); + // 4. FRESH-CHECKOUT PROOF: committable files only, EMPTY store, // spike-proven `--frozen-lockfile --offline`. let fresh = tmp.path().join("fresh"); @@ -835,6 +850,163 @@ async fn run_pnpm_capstone(pm: &str, driver: VendorDriver) { eprintln!("REVERT OK ({pm})"); } +// ── the in-place install ─────────────────────────────────────────────── + +/// What `vex` says of a vendored package whose installed copy does not +/// hold the artifact's bytes (`vendored_tree_out_of_sync`). +const TREE_OUT_OF_SYNC: &str = "the installed tree does not match its vendored artifact"; + +/// The install `vendor` asks for, run over a `node_modules` that already +/// holds the upstream package (a developer's checkout, a CI job that +/// restores `node_modules` from a cache). pnpm links the project to the +/// entry of the vendored tarball and keeps the upstream entry in the +/// store with nothing linking to it. `vex` judges the copy the install +/// links: no `vendored_tree_out_of_sync` warning while that copy is +/// patched, and the warning again once it holds the upstream bytes. +/// +/// Runs in `tmp/warm`, a second checkout installed from `before` (the +/// pre-vendor `package.json` and `pnpm-lock.yaml`) and the fixture's +/// `store`, with `proj`'s vendored files copied over it, so `proj` stays +/// as vendoring left it. `bytes` are the upstream and the patched +/// `index.js`. +fn assert_in_place_install_verifies( + tmp: &Path, + proj: &Path, + pm: &str, + store: &Path, + before: (&[u8], &[u8]), + bytes: (&[u8], &[u8]), +) { + // pnpm links directories with junctions on Windows, which vex's check + // of the store's links does not follow: it judges every entry there. + if cfg!(windows) { + return; + } + let (pkg_before, lock_before) = before; + let (orig, patched) = bytes; + let warm = tmp.join("warm"); + std::fs::create_dir_all(&warm).unwrap(); + std::fs::write(warm.join("package.json"), pkg_before).unwrap(); + std::fs::write(warm.join("pnpm-lock.yaml"), lock_before).unwrap(); + let install = |flag: Option<&str>, what: &str| { + let mut args = vec![ + "install", + "--offline", + "--store-dir", + store.to_str().unwrap(), + ]; + args.extend(flag); + let out = corepack(&warm, pm, &args); + assert!( + out.status.success(), + "{what} failed ({pm}).\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr), + ); + }; + install(Some("--frozen-lockfile"), "the upstream install"); + let installed = warm.join("node_modules").join(DEP); + assert_eq!( + std::fs::read(installed.join("index.js")).unwrap(), + orig, + "{pm}: the first install holds the upstream package" + ); + + // Written anew, not copied with their modification times: pnpm 10.0 + // takes files no newer than its last install for unchanged and skips + // the install ("Already up to date"). + for file in ["package.json", "pnpm-lock.yaml", "pnpm-workspace.yaml"] { + if let Ok(bytes) = std::fs::read(proj.join(file)) { + std::fs::write(warm.join(file), bytes).unwrap(); + } + } + common::fs_tree::copy_tree(&proj.join(".socket"), &warm.join(".socket")); + // pnpm 9.0.0-9.0.4 refuse the vendored lock frozen (see the fresh + // checkout below), which is how pnpm installs where `CI` is set. + install( + absolutizes_file_overrides(pm).then_some("--no-frozen-lockfile"), + "the in-place install", + ); + + // The project links another entry now, and the upstream one is still + // in the store: without it this leg would prove nothing. + let entries = std::fs::canonicalize(warm.join("node_modules/.pnpm")).unwrap(); + let linked = std::fs::canonicalize(&installed).unwrap(); + let linked_entry = linked + .strip_prefix(&entries) + .unwrap_or_else(|_| panic!("{pm}: {linked:?} is outside the virtual store")) + .components() + .next() + .unwrap() + .as_os_str() + .to_string_lossy() + .into_owned(); + let upstream_entry = format!("{DEP}@{DEP_VERSION}"); + assert_ne!( + linked_entry, upstream_entry, + "{pm}: the in-place install links the vendored tarball's entry" + ); + let stale = entries + .join(&upstream_entry) + .join("node_modules") + .join(DEP) + .join("index.js"); + assert_eq!( + std::fs::read(&stale).ok().as_deref(), + Some(orig), + "{pm}: pnpm keeps the upstream entry it no longer links" + ); + assert_eq!( + std::fs::read(linked.join("index.js")).unwrap(), + patched, + "{pm}: the linked copy is the vendored one" + ); + + let vex_warnings = |what: &str| { + let vex_path = warm.join("out.vex.json"); + let (code, stdout, stderr) = run_socket( + &warm, + &[ + "vex", + "--cwd", + warm.to_str().unwrap(), + "--output", + vex_path.to_str().unwrap(), + "--product", + "pkg:npm/app@1.0.0", + ], + ); + assert_eq!( + code, 0, + "vex failed, {what} ({pm}).\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let doc: serde_json::Value = + serde_json::from_slice(&std::fs::read(&vex_path).unwrap()).unwrap(); + assert_eq!( + doc["statements"].as_array().map(Vec::len), + Some(1), + "{what} ({pm}): {doc}" + ); + stderr + }; + let stderr = vex_warnings("after the in-place install"); + assert!( + !stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: the linked copy is patched, and nothing links the upstream entry:\n{stderr}" + ); + + // The linked copy back on the upstream bytes (a new file: pnpm's are + // hard links into its store). + std::fs::remove_file(linked.join("index.js")).unwrap(); + std::fs::write(linked.join("index.js"), orig).unwrap(); + let stderr = vex_warnings("with an unpatched linked copy"); + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: an unpatched copy the install links must still warn:\n{stderr}" + ); + eprintln!("IN-PLACE INSTALL OK ({pm})"); +} + // ── manifest-less VEX (lockfile discovery) ───────────────────────────── /// The vulnerability set every vendored fixture's record carries. From c297208a0f3db9b5709e0b14b3e0799879ceb359 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 12:02:07 -0500 Subject: [PATCH 04/22] Document which pnpm store entries vex and apply --check judge `docs/ecosystems.md` says which links make a pnpm store entry an installed copy and where every entry is still judged; the CLI contract says the same for the verification basis of `vex` and `apply --check`; the pnpm compatibility notes record what the in-place install leaves in the store on each measured pnpm and which tests cover it (#2353). Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 ++ docs/ecosystems.md | 47 ++++++++++++++++++++++++- docs/testing/pnpm-compatibility.md | 35 ++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 147fed6cc7..43f7fe3ae3 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -817,6 +817,8 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link reaches is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. A copy that a link reaches is always hashed, whatever its entry is named. For pnpm the links are those of each importer's `node_modules` (the project root and the workspace members its lockfiles name), of the store's hoist directory `node_modules/.pnpm/node_modules`, of each reached entry's own `node_modules`, and the link through which the crawl found a copy. Where pnpm's links cannot all be read (Windows, `node-linker=hoisted`, `shamefully-hoist`, a moved virtual store, an unreadable directory; `docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list), every entry is hashed. `rollback` and `remove` restore unlinked entries too. + **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: * A **vendor ledger entry** attests only while some lockfile or config still wires its artifact. Otherwise it is omitted as `vendor_unwired`. The exception is a hosted takeover: the same package with a live redirect record falls through to that hosted claim. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 843aa0cc33..307f9d3441 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -786,7 +786,52 @@ while after `pnpm remove` or an upgrade (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). Scans skip such an entry when the current lockfile pnpm writes in the store (`node_modules/.pnpm/lock.yaml`) no longer lists its package, so a vendored scan does not fail on a package -the install dropped. `rollback` still reaches it. A recorded virtual store outside the project is not +the install dropped. `rollback` still reaches it. + +pnpm keeps an entry the same way when an install takes a package from +another source under the same name and version. The `pnpm install` that a +scan asks for, run over an existing `node_modules`, links the project to a +new entry: `node_modules/.pnpm/@socket-+` after a +hosted scan that routes the release through the registry of its patch +(pnpm 11.20 and later), `@file+…` after a vendored scan (`file+…` +on pnpm 8 and earlier). The upstream `@` entry stays in the +store with nothing linking to it. `vex` and `apply --check` judge the +copies the install loads, so they skip a pnpm store entry that no link +reaches, as they skip one in Bun's store, which Bun never prunes. A link +reaches an entry from: + +- the `node_modules` of an importer: the project root, and every + workspace member named by the lockfile pnpm writes in the store or by + `pnpm-lock.yaml`; +- the store's hoist directory, `node_modules/.pnpm/node_modules`; +- the `node_modules` of an entry that is itself reached (a transitive + dependency has no other link); +- any other `node_modules` in which the crawl found a copy of the package + being checked. + +A copy that a link reaches is always judged, whatever its entry is named: +an unpatched one still omits the patch (`not_applied`) or warns +(`vendored_tree_out_of_sync`). Where the links cannot all be read, every +entry is judged, as before: + +- on Windows, where pnpm links directories with junctions; +- under `node-linker=hoisted` or `shamefully-hoist` (a `publicHoistPattern` + of `*`), or a store layout other than the one pnpm 6 to 12 write; +- when `virtualStoreDir` moved the virtual store, or the install record + (`node_modules/.modules.yaml`) or the lockfile in the store is missing + or unreadable; +- when the store, a `node_modules`, a `@scope` directory, a link or + `pnpm-lock.yaml` cannot be read; +- when one of the two lockfiles names a workspace member that is not a + directory, or lists its importers in a layout pnpm does not write; +- when an importer's `node_modules` or the hoist directory holds a + package as a real directory, which the isolated linker never writes; +- when no link reaches the store at all. + +`rollback` and `remove` restore an unlinked entry too: a later install +that resolves back to it links it as it is. + +A recorded virtual store outside the project is not listed: other projects on the machine load the same files, so patching it in place would patch them as well. For pnpm's global virtual store (`enableGlobalVirtualStore`, `/v/links` under the pnpm store diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index 6a38ba4aaf..85810aede4 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -221,6 +221,11 @@ project with a peer-dependent package and a transitive leaf, both patched, each leg checks that `pnpm install --lockfile-only` leaves the scan's lock byte for byte; that a fresh checkout frozen-installs the patched bytes from an empty store with no flags, asking each patch's own registry for its package; +that the `pnpm install` the scan asks for, run over a `node_modules` that +holds the upstream packages, links the patched entries and keeps the upstream +ones in the store, where `vex` attests both patches from the linked copies and +refuses a linked copy that is put back on the upstream bytes (see "The install +over an existing `node_modules`" below; not on Windows); that `pnpm add`, `pnpm update`, `pnpm dedupe` and `pnpm install --fix-lockfile` keep both packages routed and patched; and that after each cleanup (a @@ -305,6 +310,36 @@ neither mode creates the file when every pnpm pin of the project (the setting from it. With no pin, or any pin that may be a later pnpm, the file is created as before. +### The install over an existing `node_modules` + +On the registry route, and in vendored mode on every pnpm, the patched +release has another lock key than the upstream one, so pnpm installs it as +another entry of its virtual store. Measured with pnpm 12.25.1 and 11.29.0 +(both modes) and 10.34.9, 9.15.9 and 8.15.9 (vendored): `pnpm install` over a +`node_modules` that holds the upstream package links the project (the +importer, the hoist directory, each dependent's entry) to +`node_modules/.pnpm/@socket-+` or `@file+…` (`file+…` +on pnpm 8), and leaves `node_modules/.pnpm/@` in the store with the upstream +bytes and nothing linking to it. pnpm 7–11 remove such an entry after 7 days, +pnpm 12 on `pnpm prune`. With `trustLockfile` the lock key stays, and pnpm +keeps the one entry. + +`vex` and `apply --check` judge the copies the install links, and skip an +entry that no link reaches (see "npm: which `node_modules` trees are crawled" +in [ecosystems](../ecosystems.md) for the links that are read and for the +layouts where every entry is still judged, Windows among them). There the +upstream entry reads as an unpatched copy until it is gone: `vex` omits a +hosted patch as `not_applied`, or warns `vendored_tree_out_of_sync` for a +vendored one. A clean `node_modules` has no such entry. + +The registry-route legs above and the vendored capstone +(`e2e_vendor_pnpm_build`, on each pnpm of its matrix from 9 up) run that +install in a second checkout and end in `vex`, with the linked copy patched +and then put back on the upstream bytes. Hand-built stores of the same +shapes cover the rule offline: `crawlers::npm_crawler` (`test_pnpm_store_*`), +`e2e_vex_redirect`, `e2e_vex_vendor` and the `rollback` suite, which restores +an unlinked entry. + ## Run locally ```sh From e4c56c74ee697707024f3bddc0e5d7c4894b640f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:06:23 -0500 Subject: [PATCH 05/22] Refuse a pnpm importers section that a line at column 0 cuts short `lock_text_member_importers_exact` promises `None` for a lock whose importers it may misread, but a line at column 0 that is no top-level key (the markers of a merge conflict) ended the `importers` section and the members after it were left out without a word. The walk that judges which pnpm store entries are live reads its seeds from that list, so a member it does not hear of is a `node_modules` it does not read. Inside the section, only a plain top-level key ends it now; any other line at column 0 gives `None` (#2353). Co-Authored-By: Claude Fable 5.2 --- .../src/formats/pnpm/workspace.rs | 35 +++++++++++++++---- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-core/src/formats/pnpm/workspace.rs b/crates/socket-patch-core/src/formats/pnpm/workspace.rs index 86de11b010..2ebfe889d1 100644 --- a/crates/socket-patch-core/src/formats/pnpm/workspace.rs +++ b/crates/socket-patch-core/src/formats/pnpm/workspace.rs @@ -250,11 +250,13 @@ pub(crate) fn lock_text_member_importers(text: &str) -> Vec { /// that must not miss one: `None` when an `importers` section is not laid /// out the way pnpm writes it, so that a key may be misread. pnpm writes /// the section as a block, its keys at two spaces, plain or in quotes -/// (`'@apps/web':`); a key that holds an escape, a flow mapping and any -/// other indentation are not read. Every document counts (the env -/// document of pnpm 11 and later names the root alone), and a lock -/// without the section, which pnpm 6 to 8 write for a project that is no -/// workspace, names no member. +/// (`'@apps/web':`), up to the next top-level key; a key that holds an +/// escape, a flow mapping, any other indentation and a section that a +/// line at column 0 which is no such key cuts short (a merge conflict +/// marker) are not read. Every document counts (the env document of pnpm +/// 11 and later names the root alone), and a lock without the section, +/// which pnpm 6 to 8 write for a project that is no workspace, names no +/// member. pub(crate) fn lock_text_member_importers_exact(text: &str) -> Option> { let mut members = Vec::new(); for (span, _) in super::grammar::documents(text) { @@ -273,8 +275,15 @@ pub(crate) fn lock_text_member_importers_exact(text: &str) -> Option return None; } } else if indent == 0 { + // pnpm's top-level keys are plain words; anything else at + // column 0 is no end of the section pnpm wrote. + let key = top_level_key(line) + .filter(|(key, _)| key.bytes().all(|b| b.is_ascii_alphanumeric())); + if in_importers && key.is_none() { + return None; + } in_importers = false; - if let Some((key, value)) = top_level_key(line) { + if let Some((key, value)) = key { if key == "importers" { match value { "" => (in_importers, first) = (true, true), @@ -848,9 +857,23 @@ mod tests { // A line that is no key. "\n .: {}\n ? complex\n", "\n - .\n", + // A line at column 0 that is no top-level key: the markers + // of a merge conflict, which would cut the section short. + "\n .: {}\n<<<<<<< HEAD\n packages/a: {}\n=======\n packages/b: {}\n>>>>>>> theirs\n", + "\n .: {}\n=======\n packages/b: {}\n", + "\n .: {}\n>>>>>>> theirs: with a colon\n packages/b: {}\n", + "\n .: {}\n...\n", ] { assert_eq!(exact(misread), None, "{misread:?}"); } + // Outside the section such a line cuts nothing short. + assert_eq!( + lock_text_member_importers_exact( + "<<<<<<< HEAD\nlockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n\n \ + packages/a: {}\n\npackages:\n\n a@1.0.0:\n resolution: {}\n" + ), + named(&["packages/a"]) + ); // A flow mapping. assert_eq!( lock_text_member_importers_exact( From 2a14437449ef280fc36009e66416635c5ce76165 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:06:23 -0500 Subject: [PATCH 06/22] Keep a pnpm store entry that any searched node_modules still reaches The walk that tells `vex` and `apply --check` which pnpm store entries are live read the links of the project's `node_modules`, the hoist directory and the members the lockfiles name. Two installs it judged wrong, each time dropping an unpatched copy that node still loads (#2353): - A `node_modules` that no lockfile names. A directory that left the workspace keeps the links of its last install: with real pnpm 11.27.0, `packages/b/node_modules/mkdirp` still links `mkdirp@0.5.1`, whose `minimist` link still points at the upstream `minimist@0.0.8` entry after member `a` moved to the patched one. Hosted `vex` attested `not_affected`, vendored `vex` lost its `vendored_tree_out_of_sync` warning and `apply --check` read in sync. - A `node_modules` the crawl reaches through a link (a git worktree that shares the main checkout's install). The members were read below the link's target, not below the crawled project, so an entry only the project's own member links was dropped and a hosted patch was attested from the lock's pin with nothing hashed. The walk now takes the `node_modules` roots the crawl searched and reads the links of every one of them, so an entry is live when any reaches it, through other entries too. It keeps every entry unless the store's own `node_modules` is among those roots as the real directory of its project. Each store is judged once per run (`LiveStoreEntries`), by the same links for `vex`'s record check and its hosted one: the second lookup used to judge the store again from the hosted copies alone. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/src/commands/vex.rs | 7 +- .../src/commands/vex_consumed.rs | 12 +- .../src/ecosystem_dispatch.rs | 52 +- .../src/crawlers/npm_crawler.rs | 558 +++++++++++------- 4 files changed, 400 insertions(+), 229 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex.rs b/crates/socket-patch-cli/src/commands/vex.rs index 031ab34aaf..4702cdf6d6 100644 --- a/crates/socket-patch-cli/src/commands/vex.rs +++ b/crates/socket-patch-cli/src/commands/vex.rs @@ -36,7 +36,7 @@ use crate::commands::vex_sources::{ self, Plan, RunApiClient, Sources, GO_WORKSPACE_OVERRIDE, RECORD_MISMATCH, RECORD_UNAVAILABLE, REDIRECT_UNWIRED, VENDOR_UNWIRED, WIRING_CONFLICT, }; -use crate::ecosystem_dispatch::{find_manifest_package_copies_reusing, JvmScope}; +use crate::ecosystem_dispatch::{find_manifest_package_copies_judged, JvmScope}; use crate::json_envelope::{Command, Envelope, EnvelopeError, PatchAction, PatchEvent, RunWarning}; use crate::ui::plural; @@ -997,8 +997,8 @@ async fn generate_vex( if quiet { verifying.set("Finding installed packages"); } - let copies = - find_manifest_package_copies_reusing(&purls, common, quiet, params.npm_prior.as_ref()) + let (copies, mut live_stores) = + find_manifest_package_copies_judged(&purls, common, quiet, params.npm_prior.as_ref()) .await; verifying.set("Verifying installed patches"); // The record check: every copy of each purl; for Maven, every copy @@ -1017,6 +1017,7 @@ async fn generate_vex( &plan.hosted, &copies, params.npm_prior.as_ref(), + &mut live_stores, ) .await; let vendor = VendorContext { diff --git a/crates/socket-patch-cli/src/commands/vex_consumed.rs b/crates/socket-patch-cli/src/commands/vex_consumed.rs index 8f66a589c3..78a06f65ca 100644 --- a/crates/socket-patch-cli/src/commands/vex_consumed.rs +++ b/crates/socket-patch-cli/src/commands/vex_consumed.rs @@ -42,6 +42,7 @@ use std::path::{Path, PathBuf}; #[cfg(not(test))] use socket_patch_core::crawlers::npm_crawler::with_store_peer_variant_copies; +use socket_patch_core::crawlers::npm_crawler::LiveStoreEntries; use socket_patch_core::crawlers::{ CargoCrawler, CrawlerOptions, Ecosystem, GoCrawler, MavenCrawler, }; @@ -65,7 +66,9 @@ use crate::ecosystem_dispatch::{ /// the installed-tree lookup. `installed` is that lookup's every-copy /// result ([`crate::ecosystem_dispatch::find_manifest_package_copies_reusing`] over /// the record view, which holds every hosted purl), including npm store -/// variants. The shared-location ecosystems read it instead of crawling +/// variants, and `live` the judgement of the npm stores' live entries that +/// lookup made, which this one shares: it drops no copy that lookup kept. +/// The shared-location ecosystems read it instead of crawling /// the tree a second time. `prior` /// (embedded hosted `scan --vex` only) is scan's npm crawl of the same /// tree: the identity fallback takes its packages instead of crawling the @@ -75,6 +78,7 @@ pub(crate) async fn hosted_consumed_copies( hosted: &BTreeMap, installed: &HashMap>, prior: Option<&NpmCrawlSnapshot>, + live: &mut LiveStoreEntries, ) -> HashMap { let mut out = HashMap::new(); if hosted.is_empty() { @@ -118,7 +122,7 @@ pub(crate) async fn hosted_consumed_copies( // An orphaned Bun or pnpm store entry is no consumed copy; the // installed lookup dropped its own, this drops the ones the alias // and identity fallbacks' variant expansion added. - socket_patch_core::crawlers::npm_crawler::retain_live_store_copies( + live.retain_live_copies( out.iter_mut() .filter(|(purl, _)| npm.contains(purl)) .map(|(_, copies)| &mut copies.paths), @@ -464,7 +468,9 @@ mod tests { )]); VARIANT_INPUTS .scope(std::cell::RefCell::new(Vec::new()), async { - let mut found = hosted_consumed_copies(common, &hosted, installed, None).await; + let mut live = LiveStoreEntries::default(); + let mut found = + hosted_consumed_copies(common, &hosted, installed, None, &mut live).await; let paths = found.remove(&purl).unwrap().paths; let calls = VARIANT_INPUTS.with(|inputs| inputs.borrow().clone()); (paths, calls) diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index 07c4533358..bcd8efcd6c 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -9,7 +9,7 @@ use std::path::{Path, PathBuf}; use crate::args::GlobalArgs; use socket_patch_core::crawlers::npm_crawler::{ - build_npm_purl, parse_package_name, retain_live_store_copies, with_store_peer_variant_copies, + build_npm_purl, parse_package_name, with_store_peer_variant_copies, LiveStoreEntries, }; use socket_patch_core::crawlers::walk_pool; use socket_patch_core::crawlers::CargoCrawler; @@ -990,6 +990,22 @@ async fn dispatch_find_with_npm_links( prior: Option<&NpmCrawlSnapshot>, links: NpmLinks, ) -> HashMap> { + dispatch_find_with_npm_roots(partitioned, options, silent, variant_merge, prior, links) + .await + .0 +} + +/// [`dispatch_find_with_npm_links`], with the npm `node_modules` roots it +/// searched: `None` when no npm purl was asked for, or the roots could +/// not be found. +async fn dispatch_find_with_npm_roots( + partitioned: &HashMap>, + options: &CrawlerOptions, + silent: bool, + variant_merge: MergeFn, + prior: Option<&NpmCrawlSnapshot>, + links: NpmLinks, +) -> (HashMap>, Option>) { let mut wanted: HashMap> = HashMap::new(); for purl in partitioned.get(&Ecosystem::Npm).into_iter().flatten() { wanted @@ -1014,7 +1030,7 @@ async fn dispatch_find_with_npm_links( ) .await; let Some(roots) = npm_roots else { - return found; + return (found, None); }; if links == NpmLinks::ForUnresolved { let resolved = |purl: &String| found.get(purl).is_some_and(|paths| !paths.is_empty()); @@ -1023,11 +1039,12 @@ async fn dispatch_find_with_npm_links( !purls.is_empty() }); if wanted.is_empty() { - return found; + return (found, Some(roots)); } } // A failed enumeration only loses the extra links; the copies stand. - let links = tokio::task::spawn_blocking(move || npm_links_to(&wanted, &roots)) + let link_roots = roots.clone(); + let links = tokio::task::spawn_blocking(move || npm_links_to(&wanted, &link_roots)) .await .unwrap_or_default(); for (purl, link) in links { @@ -1036,7 +1053,7 @@ async fn dispatch_find_with_npm_links( paths.push(link); } } - found + (found, Some(roots)) } /// Every package link directly in one of `roots` (scoped ones one level @@ -1338,9 +1355,24 @@ pub async fn find_manifest_package_copies_reusing( quiet: bool, prior: Option<&NpmCrawlSnapshot>, ) -> HashMap> { + find_manifest_package_copies_judged(purls, common, quiet, prior) + .await + .0 +} + +/// [`find_manifest_package_copies_reusing`], with the judgement of the npm +/// stores' live entries that its copies went through. A caller that +/// resolves more copies of the same tree (`vex`'s hosted lookup) filters +/// them by it, so the two lookups agree on every store entry. +pub(crate) async fn find_manifest_package_copies_judged( + purls: &[String], + common: &GlobalArgs, + quiet: bool, + prior: Option<&NpmCrawlSnapshot>, +) -> (HashMap>, LiveStoreEntries) { let partitioned = partition_purls(purls, common.ecosystems.as_deref()); let crawler_options = common.crawler_options(); - let mut copies = dispatch_find_with_npm_links( + let (mut copies, npm_roots) = dispatch_find_with_npm_roots( &partitioned, &crawler_options, quiet, @@ -1363,9 +1395,11 @@ pub async fn find_manifest_package_copies_reusing( } // A Bun or pnpm store entry nothing links any more (Bun never prunes // `.bun`; pnpm keeps the entry an in-place install replaced) is no - // copy the install loads, so the check skips it (#599, #2353). + // copy the install loads, so the check skips it (#599, #2353). A pnpm + // entry is judged by the links of every `node_modules` searched above. // Rollback and remove, which resolve without this, still restore it. - retain_live_store_copies( + let mut live = LiveStoreEntries::new(npm_roots); + live.retain_live_copies( copies .iter_mut() .filter(|(purl, _)| purl.starts_with("pkg:npm/")) @@ -1423,7 +1457,7 @@ pub async fn find_manifest_package_copies_reusing( .await; } copies.retain(|_, paths| !paths.is_empty()); - copies + (copies, live) } // ── JVM copies ────────────────────────────────────────────────────────── diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 21a5dc8373..e9b4785f00 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -888,24 +888,34 @@ fn orphaned_pnpm_store_entry_sync( /// [`live_bun_store_entries_sync`]); rollback and remove still restore /// the orphan. /// -/// An entry is live when a link reaches it from an importer's -/// `node_modules`, from pnpm's hoist dir `.pnpm/node_modules` (every -/// store package resolves through it), or from a live entry's -/// `node_modules`. The importers are the root and the members the -/// current lockfile names (`.pnpm/lock.yaml`, which every install -/// rewrites with the importers it has linked so far), and, when those -/// leave some entry unreached, the members of the project's -/// `pnpm-lock.yaml` too: it names every member of the workspace, so also -/// one whose links the current lockfile does not record (an install that -/// did not finish). The entries in `linked` are live as well: the caller -/// found a copy in each through a link outside the store, in a -/// `node_modules` no lockfile may name. A stale link pnpm left behind -/// still counts: the runtime resolves through it. +/// An entry is live when a link reaches it from a `node_modules` whose +/// packages node can load, from pnpm's hoist dir `.pnpm/node_modules` +/// (every store package resolves through it), or from a live entry's +/// `node_modules`. Those `node_modules` are: +/// +/// - `roots`, every one the crawl searched: the project's own, each +/// workspace member's, and any other below the project. A directory +/// that left the workspace keeps the links of its last install, and +/// node run from there still loads what they reach, whatever the +/// lockfiles say; +/// - the members the current lockfile names (`.pnpm/lock.yaml`, which +/// every install rewrites with the importers it has linked so far), +/// and, when those leave some entry unreached, the members of the +/// project's `pnpm-lock.yaml`: a member can sit where the crawl does +/// not look. +/// +/// A stale link pnpm left behind still counts: the runtime resolves +/// through it. /// /// A link the walk misses would hide a copy the install loads, so the /// walk keeps every entry wherever it cannot be sure it read them all: /// /// - on Windows, where pnpm links directories with junctions; +/// - when the store's own `node_modules` is not among `roots` as the real +/// directory of its project: it was not searched (a run from inside a +/// member), or the crawl reached it through a link (a git worktree that +/// shares another checkout's install), and then the lockfiles beside +/// the store describe a project that is not the crawled one; /// - when the store is not the one `node_modules/.modules.yaml` records, /// or the record is not of the isolated linker over a flat store (see /// [`Layout::is_isolated`](crate::formats::pnpm::modules_yaml::Layout::is_isolated): @@ -915,13 +925,11 @@ fn orphaned_pnpm_store_entry_sync( /// a member that is no directory; /// - when the store, a `node_modules` dir, a scope dir or a link cannot be /// read; -/// - when an importer's `node_modules` or the hoist dir holds a package -/// as a real dir, which the isolated linker never writes there; +/// - when the `node_modules` of the project or of a member a lockfile +/// names, or the hoist dir, holds a package as a real dir, which the +/// isolated linker never writes there; /// - when no link reaches any entry. -fn live_pnpm_store_entries_sync( - store_path: &Path, - linked: &HashSet, -) -> Option> { +fn live_pnpm_store_entries_sync(store_path: &Path, roots: &[PathBuf]) -> Option> { use crate::constants::npm_family::PNPM_LOCK; use crate::formats::pnpm::grammar::is_pnpm_lock_text; use crate::formats::pnpm::modules_yaml::Layout; @@ -934,6 +942,34 @@ fn live_pnpm_store_entries_sync( let store = std::fs::canonicalize(store_path).ok()?; let nm = store.parent()?; let root = nm.parent()?; + // The crawl's roots by their real paths. The store's `node_modules` + // must be one of them, and each spelling of it the real directory + // right under its project: `root` is then the project the crawl + // searched, whose members the lockfiles name. + let mut searched: Vec = Vec::new(); + let mut is_root = false; + for dir in roots { + let real = match std::fs::canonicalize(dir) { + Ok(real) => real, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, + Err(_) => return None, + }; + if real != nm { + searched.push(real); + continue; + } + let project = match dir.parent() { + Some(project) if !project.as_os_str().is_empty() => project, + _ => Path::new("."), + }; + if std::fs::canonicalize(project).ok()?.join(dir.file_name()?) != nm { + return None; + } + is_root = true; + } + if !is_root { + return None; + } let record = read_regular_to_string_sync(&nm.join(PNPM_MODULES_YAML)).ok()?; let layout = Layout::parse(&record).filter(Layout::is_isolated)?; if std::fs::canonicalize(nm.join(layout.virtual_store_dir?)).ok()? != store { @@ -942,29 +978,19 @@ fn live_pnpm_store_entries_sync( let current = read_regular_to_string_sync(&store.join("lock.yaml")) .ok() .filter(|text| is_pnpm_lock_text(text))?; - let listing = list_dir_sync(&store); - if !listing.complete { - return None; - } - let entries: HashSet = listing - .entries - .into_iter() - .filter(|entry| { - !(entry.name_str.starts_with('.') || entry.name_str == "node_modules") - && entry.file_type.is_some_and(|ft| ft.is_dir()) - }) - .map(|entry| entry.name) - .collect(); + let entries = pnpm_store_entry_names(list_dir_sync(&store))?; // The `node_modules` of each member a lock names. A member that is no // directory may be a key read wrong, whose links would go unread. - let members = |lock: &str| -> Option> { - lock_text_member_importers_exact(lock)? - .into_iter() - .map(|member| { - let member = root.join(member); - is_dir_sync(&member).then(|| member.join("node_modules")) - }) - .collect() + let members = |lock: &str| -> Option> { + let mut dirs = Vec::new(); + for member in lock_text_member_importers_exact(lock)? { + let member = root.join(member); + if !is_dir_sync(&member) { + return None; + } + dirs.push((member.join("node_modules"), LinkDir::Importer)); + } + Some(dirs) }; let mut walk = PnpmStoreWalk { @@ -972,12 +998,16 @@ fn live_pnpm_store_entries_sync( entries: &entries, live: HashSet::new(), }; - let mut seeds = vec![store.join("node_modules"), nm.to_path_buf()]; + let mut seeds = vec![ + (store.join("node_modules"), LinkDir::Importer), + (nm.to_path_buf(), LinkDir::Importer), + ]; seeds.extend(members(¤t)?); - walk.reach(seeds, linked)?; + seeds.extend(searched.into_iter().map(|dir| (dir, LinkDir::Searched))); + walk.reach(seeds)?; if walk.live.len() < entries.len() { match read_regular_to_string_sync(&root.join(PNPM_LOCK)) { - Ok(wanted) => walk.reach(members(&wanted)?, &HashSet::new())?, + Ok(wanted) => walk.reach(members(&wanted)?)?, Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return None, } @@ -985,6 +1015,40 @@ fn live_pnpm_store_entries_sync( (!walk.live.is_empty()).then_some(walk.live) } +/// The names of the entry dirs of a pnpm store, from its listing: every +/// real dir but the hidden metadata and the `node_modules` hoist dir. +/// `None` when the listing is cut short: an entry left out would read as +/// one nothing links. +fn pnpm_store_entry_names(listing: Listing) -> Option> { + if !listing.complete { + return None; + } + let mut entries = HashSet::new(); + for child in listing.entries { + if child.name_str.starts_with('.') || child.name_str == "node_modules" { + continue; + } + if child.file_type.is_some_and(|ft| ft.is_dir()) { + entries.insert(child.name); + } + } + Some(entries) +} + +/// A dir whose package links [`PnpmStoreWalk`] reads. +#[derive(Clone, Copy, PartialEq, Eq)] +enum LinkDir { + /// A `node_modules` pnpm itself links: the project's, a member's that + /// a lockfile names, the hoist dir. It holds links alone. + Importer, + /// Another `node_modules` the crawl searched, which may hold packages + /// of its own beside links into the store. + Searched, + /// The `node_modules` of a store entry: the entry's own package and + /// links to its dependencies. + Entry, +} + /// The walk of [`live_pnpm_store_entries_sync`] over one store. struct PnpmStoreWalk<'a> { /// The store's real path. @@ -996,54 +1060,44 @@ struct PnpmStoreWalk<'a> { } impl PnpmStoreWalk<'_> { - /// Add to `live` the entries of `linked` and every entry reachable - /// through links from the `seeds` dirs (importers' `node_modules`, the - /// hoist dir), following each reached entry's own `node_modules` - /// links, one frontier at a time and each frontier's dirs in - /// parallel. A seed that does not exist links nothing. `None` when a - /// dir or a link cannot be read. - fn reach(&mut self, seeds: Vec, linked: &HashSet) -> Option<()> { - let mut frontier: Vec<(PathBuf, bool)> = Vec::new(); - for seed in seeds { + /// Add to `live` every entry reachable through links from the `seeds` + /// dirs, following each reached entry's own `node_modules` links, one + /// frontier at a time and each frontier's dirs in parallel. A seed + /// that does not exist links nothing. `None` when a dir or a link + /// cannot be read. + fn reach(&mut self, seeds: Vec<(PathBuf, LinkDir)>) -> Option<()> { + let mut frontier: Vec<(PathBuf, LinkDir)> = Vec::new(); + for (seed, kind) in seeds { match std::fs::canonicalize(seed) { - Ok(nm) => frontier.push((nm, true)), + Ok(nm) => frontier.push((nm, kind)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return None, } } - let mut reached: Vec = linked - .iter() - .filter(|entry| self.entries.contains(*entry)) - .cloned() - .collect(); - loop { - for entry in reached { - if !self.live.contains(&entry) { - frontier.push((self.store.join(&entry).join("node_modules"), false)); - self.live.insert(entry); - } - } - if frontier.is_empty() { - return Some(()); - } - let reads = par_map(frontier, |(nm, seed)| self.link_targets(&nm, seed)); + while !frontier.is_empty() { + let reads = par_map(frontier, |(nm, kind)| self.link_targets(&nm, kind)); frontier = Vec::new(); - reached = Vec::new(); for targets in reads { - reached.extend(targets?); + for entry in targets? { + if !self.live.contains(&entry) { + let nm = self.store.join(&entry).join("node_modules"); + frontier.push((nm, LinkDir::Entry)); + self.live.insert(entry); + } + } } } + Some(()) } /// The entries the package links of the `node_modules` dir `nm` point - /// into (scoped ones under `@scope/`). `nm` is real: a `seed` was + /// into (scoped ones under `@scope/`). `nm` is real: a seed was /// canonicalized, and an entry's own `node_modules` must be a real - /// dir of the store. A dir that does not exist links nothing. `None` - /// when the dir, a scope dir or a link cannot be read, or when a - /// `seed` holds a package as a real dir (an entry's `node_modules` - /// holds the entry's own package that way). - fn link_targets(&self, nm: &Path, seed: bool) -> Option> { - if !seed { + /// dir of the store. An entry's dir that does not exist links nothing. + /// `None` when the dir, a scope dir or a link cannot be read, or when + /// a [`LinkDir::Importer`] holds a package as a real dir. + fn link_targets(&self, nm: &Path, kind: LinkDir) -> Option> { + if kind == LinkDir::Entry { match std::fs::symlink_metadata(nm) { Ok(metadata) if metadata.is_dir() => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(Vec::new()), @@ -1065,7 +1119,7 @@ impl PnpmStoreWalk<'_> { } else if file_type.is_dir() { if !scope && name.as_encoded_bytes().starts_with(b"@") { dirs.push((dir.join(name), true)); - } else if seed { + } else if kind == LinkDir::Importer { return None; } } @@ -1309,19 +1363,73 @@ fn expand_workspace_pattern_sync(root: &Path, pattern: &str) -> Option HashSet { - // Each copy that lies in such a store, with its store and entry. - let copies: Vec<(&PathBuf, StoreLayout, PathBuf, OsString)> = paths - .iter() - .filter_map(|path| { - let real = std::fs::canonicalize(path).ok()?; - let (layout, store, entry) = unpruned_store_entry_of(&real).or_else(|| { +/// Which entries of the Bun and pnpm stores of a crawled tree the install +/// can still load (#599, #2353): an entry no link reaches is one nothing +/// can load (see [`live_bun_store_entries_sync`] and +/// [`live_pnpm_store_entries_sync`]), so a check of the live install +/// (`vex`, `apply --check`) drops the copies in it. Never for an +/// operation that restores copies. Each store is judged once, by the +/// same links whichever copies are asked about, so a later lookup over +/// the same tree keeps every copy an earlier one kept. +#[derive(Default)] +pub struct LiveStoreEntries { + /// The `node_modules` dirs the crawl searched: a link in any of them + /// keeps a pnpm entry live. `None` when they are not known, and no + /// pnpm entry is dropped. + roots: Option>, + /// The stores judged so far, by real path: the names of their live + /// entries, or `None` where the walk could not tell. + stores: HashMap>>, +} + +impl LiveStoreEntries { + /// For the tree a crawl searched through `roots` (what + /// [`NpmCrawler::get_node_modules_paths`] returned for it). + pub fn new(roots: Option>) -> Self { + Self { + roots, + stores: HashMap::new(), + } + } + + /// Drop from each list every copy that sits in an orphaned store + /// entry. Each store is walked once, however many lists and calls + /// name it. + pub async fn retain_live_copies<'a>( + &mut self, + lists: impl IntoIterator>, + ) { + let lists: Vec<&mut Vec> = lists.into_iter().collect(); + let paths: Vec = lists.iter().flat_map(|list| list.iter().cloned()).collect(); + if paths.is_empty() { + return; + } + let mut judged = std::mem::take(self); + let (orphans, judged) = run_walk(move || { + let orphans = judged.orphaned_copies_sync(&paths); + (orphans, judged) + }) + .await; + *self = judged; + if orphans.is_empty() { + return; + } + for list in lists { + list.retain(|path| !orphans.contains(path)); + } + } + + /// Paths among `paths` that are copies inside an orphaned `.bun` or + /// `.pnpm` store entry, judged by where each canonicalizes, or, when + /// that is out of every store (a Bun global store entry's shared dir, + /// #635), by the `.bun` entry the path itself names. + fn orphaned_copies_sync(&mut self, paths: &[PathBuf]) -> HashSet { + let mut orphans = HashSet::new(); + for path in paths { + let Ok(real) = std::fs::canonicalize(path) else { + continue; + }; + let Some((layout, store, entry)) = unpruned_store_entry_of(&real).or_else(|| { let (layout, store, entry) = unpruned_store_entry_of( &crate::utils::relpath::normalize_lexically_keeping_escapes(path), )?; @@ -1329,64 +1437,24 @@ fn orphaned_store_copies_sync(paths: &[PathBuf]) -> HashSet { return None; } Some((layout, std::fs::canonicalize(store).ok()?, entry)) - })?; - Some((path, layout, store, entry)) - }) - .collect(); - // The pnpm entries a copy's own path links into from outside the - // store: live whatever the walk of the store finds. - let mut linked: HashMap<&Path, HashSet> = HashMap::new(); - for (path, layout, store, entry) in &copies { - if *layout == StoreLayout::Pnpm && enters_store_through_link_sync(path, store) { - linked - .entry(store.as_path()) - .or_default() - .insert(entry.clone()); - } - } - let mut stores: HashMap<&Path, Option>> = HashMap::new(); - let mut orphans = HashSet::new(); - for (path, layout, store, entry) in &copies { - let live = stores.entry(store.as_path()).or_insert_with_key(|store| { - if *layout == StoreLayout::Pnpm { - let linked = linked.remove(store).unwrap_or_default(); - return live_pnpm_store_entries_sync(store, &linked); + }) else { + continue; + }; + let roots = self.roots.as_deref(); + let live = self.stores.entry(store).or_insert_with_key(|store| { + if layout == StoreLayout::Pnpm { + return live_pnpm_store_entries_sync(store, roots?); + } + let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); + live_bun_store_entries_sync(store, &candidates) + .map(|live| live.into_names(&candidates)) + }); + if live.as_ref().is_some_and(|live| !live.contains(&entry)) { + orphans.insert(path.clone()); } - let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); - live_bun_store_entries_sync(store, &candidates).map(|live| live.into_names(&candidates)) - }); - if live.as_ref().is_some_and(|live| !live.contains(entry)) { - orphans.insert((*path).clone()); - } - } - orphans -} - -/// Whether `path`, which resolves into the real dir `store`, gets there -/// through a link that sits outside the store: the copy was found in some -/// `node_modules` whose link points into a store entry, never by listing -/// the store itself. -fn enters_store_through_link_sync(path: &Path, store: &Path) -> bool { - for link in path.ancestors() { - let Some(parent) = link.parent() else { - return false; - }; - let parent = if parent.as_os_str().is_empty() { - Path::new(".") - } else { - parent - }; - let Ok(real_parent) = std::fs::canonicalize(parent) else { - return false; - }; - if !real_parent.starts_with(store) { - // The first component on the way up that sits outside the - // store: a link into an entry, or the store dir itself. - return std::fs::canonicalize(link) - .is_ok_and(|real| real != store && real.starts_with(store)); } + orphans } - false } /// The `node_modules/.bun` or `node_modules/.pnpm` store a real path lies @@ -1410,26 +1478,6 @@ fn unpruned_store_entry_of(real: &Path) -> Option<(StoreLayout, PathBuf, OsStrin None } -/// Drop from each list every copy that sits in an orphaned Bun or pnpm -/// store entry (#599, #2353): one no link from the install reaches, which -/// nothing can load. For a check of the live install (`vex`), never for -/// an operation that restores copies. Each store is walked once across -/// all the lists. -pub async fn retain_live_store_copies<'a>(lists: impl IntoIterator>) { - let lists: Vec<&mut Vec> = lists.into_iter().collect(); - let paths: Vec = lists.iter().flat_map(|list| list.iter().cloned()).collect(); - if paths.is_empty() { - return; - } - let orphans = run_walk(move || orphaned_store_copies_sync(&paths)).await; - if orphans.is_empty() { - return; - } - for list in lists { - list.retain(|path| !orphans.contains(path)); - } -} - /// The quick walk's guesses: a link named for a package only one `.bun` /// entry holds points at that entry, and a `@scope` dir none of whose /// packages has a second entry links (at most) that scope's entries, so @@ -7947,7 +7995,9 @@ mod tests { pad12.clone(), odd.clone(), ]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![number6, number7, pad12, odd]); } @@ -8119,10 +8169,22 @@ mod tests { dir } - /// The copies of `copies` that `vex`'s live-copy filter keeps. - async fn live_copies(copies: &[&PathBuf]) -> Vec { + /// The copies of `copies` that `vex`'s live-copy filter keeps, for a + /// crawl of the project at `root`. + async fn live_copies(root: &Path, copies: &[&PathBuf]) -> Vec { + let options = CrawlerOptions { + cwd: root.to_path_buf(), + global: false, + global_prefix: None, + }; + let roots = NpmCrawler::new() + .get_node_modules_paths(&options) + .await + .unwrap(); let mut copies: Vec = copies.iter().map(|path| (*path).clone()).collect(); - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(Some(roots)) + .retain_live_copies([&mut copies]) + .await; copies } @@ -8162,12 +8224,12 @@ mod tests { let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); assert_eq!( - live_copies(&[&nm.join("minimist"), &stale, &routed]).await, + live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, vec![nm.join("minimist"), routed.clone()] ); // The orphan alone is dropped too: the walk needs no live copy in // the list to find the importer's link. - assert_eq!(live_copies(&[&stale]).await, Vec::::new()); + assert_eq!(live_copies(&root, &[&stale]).await, Vec::::new()); let purls = vec!["pkg:npm/minimist@1.2.2".to_string()]; let found = NpmCrawler::new().find_by_purls(&nm, &purls).await.unwrap(); @@ -8211,7 +8273,7 @@ mod tests { ); assert_eq!( - live_copies(&[&stale, &vendored, &nm.join("minimist")]).await, + live_copies(&root, &[&stale, &vendored, &nm.join("minimist")]).await, vec![vendored, nm.join("minimist")] ); } @@ -8257,7 +8319,11 @@ mod tests { ); assert_eq!( - live_copies(&[&removed, &number, &old, &scoped, &old_vendored, &hoisted]).await, + live_copies( + &root, + &[&removed, &number, &old, &scoped, &old_vendored, &hoisted] + ) + .await, vec![number, scoped, hoisted] ); } @@ -8286,7 +8352,7 @@ mod tests { ); assert_eq!( - live_copies(&[&nm.join("minimist"), &upstream, &routed]).await, + live_copies(&root, &[&nm.join("minimist"), &upstream, &routed]).await, vec![nm.join("minimist"), upstream] ); } @@ -8354,7 +8420,7 @@ mod tests { let (store, routed, stale) = pnpm_workspace_route_orphans(&root); let all: Vec<&PathBuf> = routed.iter().chain(&stale).collect(); - assert_eq!(live_copies(&all).await, routed.to_vec()); + assert_eq!(live_copies(&root, &all).await, routed.to_vec()); std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); std::fs::write( @@ -8362,7 +8428,7 @@ mod tests { pnpm_lock_of(&["packages/a", "packages/b"]), ) .unwrap(); - assert_eq!(live_copies(&all).await, routed.to_vec()); + assert_eq!(live_copies(&root, &all).await, routed.to_vec()); } /// #2353: pnpm quotes an importer key that YAML cannot take plain @@ -8390,52 +8456,108 @@ mod tests { let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); assert_eq!( - live_copies(&[&used, &member_only, &orphan]).await, + live_copies(&root, &[&used, &member_only, &orphan]).await, vec![used, member_only], "{key}" ); } } - /// #2353: a copy the caller found through a link in some - /// `node_modules` keeps its entry live, even when no lockfile names - /// that directory as an importer: the link is there, and the runtime - /// resolves through it. The entry's own dependencies stay live with - /// it. + /// #2353: a `node_modules` that no lockfile names still loads what it + /// links. Member `b` (on `mkdirp@0.5.1`) left the workspace, and member + /// `a`'s `minimist@0.0.8` was installed again from the registry of its + /// patch (real pnpm 11.27.0): `a` and the hoist dir link the routed + /// entry, and neither lockfile names `packages/b`. Yet + /// `packages/b/node_modules/mkdirp` still links `mkdirp@0.5.1`, whose + /// `minimist` link still points at the upstream entry, and node run + /// from `packages/b` loads that copy. It stays live for as long as the + /// crawl finds that `node_modules`, however the copies are named; + /// without it, the upstream entry and `mkdirp`'s are orphans. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_copy_is_linked_into_is_a_live_copy() { + async fn test_pnpm_store_entry_a_node_modules_no_lockfile_names_reaches_is_a_live_copy() { let tmp = tempfile::tempdir().unwrap(); let root: PathBuf = tmp.path().components().collect(); - let (nm, store) = pnpm_install(&root, &[]); - let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + let (_, store) = pnpm_install(&root, &["packages/a"]); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + let upstream = pnpm_entry(&store, "minimist@0.0.8", "minimist", "0.0.8"); + let routed = pnpm_entry( + &store, + "minimist@socket-8cccd65b+0.0.8", + "minimist", + "0.0.8", + ); + let mkdirp = pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); rel_link( - ".pnpm/is-number@7.0.0/node_modules/is-number", - &nm.join("is-number"), + "../../minimist@0.0.8/node_modules/minimist", + &store.join("mkdirp@0.5.1/node_modules/minimist"), + ); + rel_link( + "../minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &store.join("node_modules/minimist"), ); - let odd = pnpm_entry(&store, "is-odd@3.0.1", "is-odd", "3.0.1"); - let number6 = pnpm_entry(&store, "is-number@6.0.0", "is-number", "6.0.0"); + for member in ["a", "b"] { + write_pkg(&root.join("packages").join(member), member, "1.0.0"); + } rel_link( - "../../is-number@6.0.0/node_modules/is-number", - &store.join("is-odd@3.0.1/node_modules/is-number"), + "../../../node_modules/.pnpm/minimist@socket-8cccd65b+0.0.8/node_modules/minimist", + &root.join("packages/a/node_modules/minimist"), ); - let orphan = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); - // A directory no lockfile names links `is-odd`. - let stray = root.join("tools/x/node_modules/is-odd"); rel_link( - "../../../node_modules/.pnpm/is-odd@3.0.1/node_modules/is-odd", - &stray, + "../../../node_modules/.pnpm/mkdirp@0.5.1/node_modules/mkdirp", + &root.join("packages/b/node_modules/mkdirp"), ); - // Listed by their store paths alone, the entries only the stray - // directory reaches are orphans. + // Named by their store paths: no copy's own path leads to an entry. + let copies = [&upstream, &routed, &mkdirp]; assert_eq!( - live_copies(&[&used, &odd, &number6, &orphan]).await, - vec![used.clone()] + live_copies(&root, &copies).await, + vec![upstream.clone(), routed.clone(), mkdirp.clone()] ); + + std::fs::remove_dir_all(root.join("packages/b/node_modules")).unwrap(); + assert_eq!(live_copies(&root, &copies).await, vec![routed]); + } + + /// #2353: a `node_modules` the crawl reaches through a link (a git + /// worktree that shares the main checkout's install) belongs to a + /// project elsewhere, and the members the lockfile in its store names + /// are that project's, not the crawled one's. Every entry is kept, so + /// the one only the crawled project's member links stays a copy. So + /// is every entry of a store whose own `node_modules` the crawl did + /// not search (a run from inside a member). From the main checkout, + /// which the worktree is no part of, the member's entry is an orphan. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_the_crawl_reaches_through_a_link_keeps_every_entry() { + let tmp = tempfile::tempdir().unwrap(); + let base: PathBuf = tmp.path().components().collect(); + let main = base.join("main"); + let (main_nm, store) = pnpm_install(&main, &["packages/a"]); + let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + rel_link( + ".pnpm/is-number@7.0.0/node_modules/is-number", + &main_nm.join("is-number"), + ); + let member_only = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); + write_pkg(&main.join("packages/a"), "a", "1.0.0"); + // The worktree: the main checkout's install, its own member links. + let worktree = base.join("worktree"); + write_pkg(&worktree.join("packages/a"), "a", "1.0.0"); + rel_link("../main/node_modules", &worktree.join("node_modules")); + rel_link( + "../../../node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad", + &worktree.join("packages/a/node_modules/left-pad"), + ); + let copies = [&used, &member_only, &orphan]; + let all = vec![used.clone(), member_only.clone(), orphan.clone()]; + + assert_eq!(live_copies(&main, &copies).await, vec![used.clone()]); + assert_eq!(live_copies(&worktree, &copies).await, all); assert_eq!( - live_copies(&[&used, &stray, &odd, &number6, &orphan]).await, - vec![used, stray, odd, number6] + live_copies(&worktree.join("packages/a"), &copies).await, + all ); } @@ -8455,13 +8577,13 @@ mod tests { let [_, _, stale_transitive] = &stale; assert_eq!( - live_copies(&[stale_transitive, transitive, &mkdirp]).await, + live_copies(&root, &[stale_transitive, transitive, &mkdirp]).await, vec![transitive.clone(), mkdirp.clone()] ); std::fs::remove_file(root.join("node_modules/mkdirp")).unwrap(); assert_eq!( - live_copies(&[stale_transitive, transitive, &mkdirp]).await, + live_copies(&root, &[stale_transitive, transitive, &mkdirp]).await, Vec::::new() ); } @@ -8603,7 +8725,7 @@ mod tests { let root: PathBuf = tmp.path().components().collect(); let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); let copies = [&nm.join("minimist"), &stale, &routed]; - assert_eq!(live_copies(&copies[1..]).await, vec![routed.clone()]); + assert_eq!(live_copies(&root, &copies[1..]).await, vec![routed.clone()]); change(&root); let kept: Vec = copies .iter() @@ -8611,7 +8733,7 @@ mod tests { .map(|copy| (*copy).clone()) .collect(); assert_eq!( - live_copies(&kept.iter().collect::>()).await, + live_copies(&root, &kept.iter().collect::>()).await, kept, "{case}" ); @@ -8625,7 +8747,7 @@ mod tests { let unreadable = routed.parent().unwrap(); std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o000)).unwrap(); let readable = std::fs::read_dir(unreadable).is_ok(); - let kept = live_copies(&[&stale]).await; + let kept = live_copies(&root, &[&stale]).await; std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o755)).unwrap(); if !readable { assert_eq!(kept, vec![stale], "an unreadable node_modules"); @@ -8641,7 +8763,7 @@ mod tests { let root: PathBuf = tmp.path().components().collect(); let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); assert_eq!( - live_copies(&[&nm.join("minimist"), &stale, &routed]).await, + live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, vec![nm.join("minimist"), stale, routed] ); } @@ -8778,7 +8900,9 @@ mod tests { stale_odd.join("is-odd"), ]; let mut other = vec![pad.clone(), churned.clone()]; - retain_live_store_copies([&mut copies, &mut other]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies, &mut other]) + .await; assert_eq!( copies, vec![ @@ -8818,7 +8942,9 @@ mod tests { "{scanned:?}" ); let mut copies = vec![pad.clone(), member_pad.clone()]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad, member_pad]); } @@ -8853,7 +8979,9 @@ mod tests { link_dir(&member_pad, &member_nm.join("left-pad")); let mut copies = vec![pad.clone(), member_pad.clone(), churned]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad, member_pad]); } @@ -8888,7 +9016,9 @@ mod tests { "{scanned:?}" ); let mut copies = vec![pad.clone(), lp]; - retain_live_store_copies([&mut copies]).await; + LiveStoreEntries::new(None) + .retain_live_copies([&mut copies]) + .await; assert_eq!(copies, vec![pad]); } From 3ff92e9431d28c228a349ba49a33251bd9d91583 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:06:58 -0500 Subject: [PATCH 07/22] Judge a pnpm store in a checkout of part of its workspace Two smaller points of the walk over a pnpm store's links (#2353): - A member the lockfiles name that is not on disk made the walk keep every entry, so `vex` kept refusing a hosted patch over the entry an in-place install left behind wherever part of a workspace is checked out (a container image that copies some members; real pnpm 11.27.0 installs that frozen, and both lockfiles still name the rest). A path that is not there links nothing, so the walk goes on; one that is there and is no directory still keeps every entry. - A child of the store whose type could not be read was left out of the entries, so a copy in it read as one nothing links. The walk keeps every entry now when the type of a child that is not hidden cannot be read. Co-Authored-By: Claude Fable 5.2 --- .../src/crawlers/npm_crawler.rs | 106 ++++++++++++++---- 1 file changed, 85 insertions(+), 21 deletions(-) diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index e9b4785f00..06eec75c4c 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -902,7 +902,8 @@ fn orphaned_pnpm_store_entry_sync( /// every install rewrites with the importers it has linked so far), /// and, when those leave some entry unreached, the members of the /// project's `pnpm-lock.yaml`: a member can sit where the crawl does -/// not look. +/// not look. One that is not there (a checkout of part of the +/// workspace) links nothing. /// /// A stale link pnpm left behind still counts: the runtime resolves /// through it. @@ -922,9 +923,9 @@ fn orphaned_pnpm_store_entry_sync( /// `node-linker=hoisted`, `shamefully-hoist`, another layout version); /// - without a current lockfile, or when it or `pnpm-lock.yaml` cannot be /// read, lays its importers out in a way pnpm does not write, or names -/// a member that is no directory; -/// - when the store, a `node_modules` dir, a scope dir or a link cannot be -/// read; +/// a member that is there and is no directory; +/// - when the store, a `node_modules` dir, a scope dir, a link or the type +/// of a child of the store cannot be read; /// - when the `node_modules` of the project or of a member a lockfile /// names, or the hoist dir, holds a package as a real dir, which the /// isolated linker never writes there; @@ -979,16 +980,18 @@ fn live_pnpm_store_entries_sync(store_path: &Path, roots: &[PathBuf]) -> Option< .ok() .filter(|text| is_pnpm_lock_text(text))?; let entries = pnpm_store_entry_names(list_dir_sync(&store))?; - // The `node_modules` of each member a lock names. A member that is no - // directory may be a key read wrong, whose links would go unread. + // The `node_modules` of each member a lock names. let members = |lock: &str| -> Option> { let mut dirs = Vec::new(); for member in lock_text_member_importers_exact(lock)? { let member = root.join(member); - if !is_dir_sync(&member) { - return None; + match std::fs::metadata(&member) { + Ok(metadata) if metadata.is_dir() => { + dirs.push((member.join("node_modules"), LinkDir::Importer)); + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + _ => return None, } - dirs.push((member.join("node_modules"), LinkDir::Importer)); } Some(dirs) }; @@ -1017,18 +1020,19 @@ fn live_pnpm_store_entries_sync(store_path: &Path, roots: &[PathBuf]) -> Option< /// The names of the entry dirs of a pnpm store, from its listing: every /// real dir but the hidden metadata and the `node_modules` hoist dir. -/// `None` when the listing is cut short: an entry left out would read as -/// one nothing links. +/// `None` when the listing is cut short or the type of a child that is +/// not hidden cannot be read: an entry left out would read as one nothing +/// links. fn pnpm_store_entry_names(listing: Listing) -> Option> { if !listing.complete { return None; } let mut entries = HashSet::new(); for child in listing.entries { - if child.name_str.starts_with('.') || child.name_str == "node_modules" { + if child.name_str.starts_with('.') { continue; } - if child.file_type.is_some_and(|ft| ft.is_dir()) { + if child.file_type?.is_dir() && child.name_str != "node_modules" { entries.insert(child.name); } } @@ -8588,6 +8592,68 @@ mod tests { ); } + /// #2353: a member the lockfiles name that is not there links nothing. + /// A checkout of part of a workspace (a container image that copies + /// some members) installs frozen with both lockfiles still naming the + /// rest, and the entry nothing links is an orphan there all the same. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_a_member_that_is_not_there_links_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let root: PathBuf = tmp.path().components().collect(); + let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + let lock = pnpm_lock_of(&["packages/gone", "apps/gone/too"]); + std::fs::write(nm.join(".pnpm/lock.yaml"), &lock).unwrap(); + std::fs::write(root.join("pnpm-lock.yaml"), &lock).unwrap(); + + assert_eq!( + live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, + vec![nm.join("minimist"), routed] + ); + } + + /// #2353: the entries of a store are its real dirs, read from a whole + /// listing with the type of every child that is not hidden. A child + /// whose type cannot be read may be an entry, and a listing cut short + /// may lack one: neither names the entries. + #[test] + fn test_pnpm_store_entry_names_need_the_type_of_every_child() { + let tmp = tempfile::tempdir().unwrap(); + std::fs::write(tmp.path().join("file"), "").unwrap(); + let type_of = |path: &Path| std::fs::symlink_metadata(path).unwrap().file_type(); + let (dir, file) = (type_of(tmp.path()), type_of(&tmp.path().join("file"))); + let names = |children: &[(&str, Option)], complete: bool| { + pnpm_store_entry_names(Listing { + entries: children + .iter() + .map(|(name, file_type)| ListedEntry { + name: OsString::from(name), + name_str: name.to_string(), + file_type: *file_type, + }) + .collect(), + complete, + }) + }; + let store = [ + ("a@1.0.0", Some(dir)), + ("lock.yaml", Some(file)), + ("node_modules", Some(dir)), + (".hidden", None), + ]; + assert_eq!( + names(&store, true), + Some(HashSet::from([OsString::from("a@1.0.0")])) + ); + assert_eq!(names(&store, false), None); + for unread in ["b@1.0.0", "node_modules"] { + let mut store = store.to_vec(); + store.retain(|(name, _)| *name != unread); + store.push((unread, None)); + assert_eq!(names(&store, true), None, "{unread}"); + } + } + /// #2353: wherever the walk cannot be sure it read every link, nothing /// is dropped. Each case changes one thing about the store of /// [`pnpm_hosted_route_orphan`], whose orphan is dropped as it stands. @@ -8647,11 +8713,12 @@ mod tests { }; Box::new(change) }), - ("a current lockfile naming a member that is no directory", { + ("a current lockfile naming a member that is a file", { let change: Change = |root| { + std::fs::write(root.join("member"), "").unwrap(); std::fs::write( root.join("node_modules/.pnpm/lock.yaml"), - pnpm_lock_of(&["packages/gone"]), + pnpm_lock_of(&["member"]), ) .unwrap() }; @@ -8670,13 +8737,10 @@ mod tests { |root| std::fs::create_dir(root.join("pnpm-lock.yaml")).unwrap(); Box::new(change) }), - ("a pnpm-lock.yaml naming a member that is no directory", { + ("a pnpm-lock.yaml naming a member that is a file", { let change: Change = |root| { - std::fs::write( - root.join("pnpm-lock.yaml"), - pnpm_lock_of(&["packages/gone"]), - ) - .unwrap() + std::fs::write(root.join("member"), "").unwrap(); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["member"])).unwrap() }; Box::new(change) }), From 08a9155b3dde0487b2b39ac127af10d45cab7e40 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:09:11 -0500 Subject: [PATCH 08/22] Test vex and apply --check over a node_modules no lockfile names Hand-built pnpm trees where the check passed while node still loads the pristine copy (#2353): - a directory that left the workspace still links a package whose dependency link points at the upstream entry: `vex` refuses the hosted patch while that `node_modules` is there and attests once it is gone, and `apply --check` reads drift, then in sync; - a worktree whose `node_modules` is a link to the main checkout's, and whose own member reaches the pristine entry: the copy is hashed and the patch refused, where it was attested from the lock's pin. Co-Authored-By: Claude Fable 5.2 --- .../apply/check_verifies_installed_tree.rs | 61 ++++- .../tests/e2e_vex_redirect.rs | 212 ++++++++++++++++++ 2 files changed, 261 insertions(+), 12 deletions(-) diff --git a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs index 79a4375c80..7509bd9b94 100644 --- a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs +++ b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs @@ -520,6 +520,12 @@ fn check_remedy_keeps_global_prefix_and_heals_the_checked_tree() { /// importer links decides. A patched linked copy is in sync beside an /// unlinked entry of another peer set that holds the original bytes, and /// an unpatched linked copy is drift beside a patched unlinked one. +/// +/// A link in any `node_modules` of the project counts, also one that no +/// lockfile names and that reaches the entry through another package: a +/// directory that left the workspace still loads what its links reach, +/// so the original bytes there are drift until that `node_modules` is +/// gone. #[cfg(unix)] #[test] fn check_judges_the_pnpm_store_entry_the_install_links() { @@ -563,18 +569,49 @@ fn check_judges_the_pnpm_store_entry_the_install_links() { ) .unwrap(); - let (code, stdout, stderr) = run_check(tmp.path(), &["--json"]); - let env = parse_json_envelope(stdout.trim()); - if in_sync { - assert_eq!(code, 0, "the linked copy is patched: {env}\n{stderr}"); - } else { - assert_eq!(code, 1, "the linked copy is unpatched: {env}\n{stderr}"); - assert!( - events(&env).iter().any(|e| e["action"] == "failed" - && e["purl"] == PURL - && e["errorCode"] == "not_applied"), - "{env}" - ); + let check = |in_sync: bool, what: &str| { + let (code, stdout, stderr) = run_check(tmp.path(), &["--json"]); + let env = parse_json_envelope(stdout.trim()); + if in_sync { + assert_eq!(code, 0, "{what}: {env}\n{stderr}"); + } else { + assert_eq!(code, 1, "{what}: {env}\n{stderr}"); + assert!( + events(&env).iter().any(|e| e["action"] == "failed" + && e["purl"] == PURL + && e["errorCode"] == "not_applied"), + "{what}: {env}" + ); + } + }; + check(in_sync, "the copy the importer links decides"); + if !in_sync { + continue; } + + // `tools/x` is no importer of the lockfile, and its `dep` reaches + // the entry that holds the original bytes. + let dep = store.join("dep@1.0.0/node_modules"); + std::fs::create_dir_all(dep.join("dep")).unwrap(); + std::fs::write( + dep.join("dep/package.json"), + r#"{ "name": "dep", "version": "1.0.0" }"#, + ) + .unwrap(); + std::os::unix::fs::symlink( + "../../check-target@1.0.0_peer@1.0.0/node_modules/check-target", + dep.join("check-target"), + ) + .unwrap(); + let stray = tmp.path().join("tools/x/node_modules"); + std::fs::create_dir_all(&stray).unwrap(); + std::os::unix::fs::symlink( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + stray.join("dep"), + ) + .unwrap(); + check(false, "tools/x loads the original copy through dep"); + std::fs::remove_dir_all(&stray).unwrap(); + check(true, "nothing reaches the original copy any more"); } } diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index e4e51c526a..a877632557 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2581,6 +2581,218 @@ fn pnpm_hosted_ref_is_judged_by_the_store_entry_the_install_links() { } } +/// The committed files of a pnpm workspace at `cwd` whose member +/// `packages/a` takes `left-pad@1.3.0` from the registry of its patch +/// (the route a hosted scan writes on pnpm 11.20 and later). +#[cfg(unix)] +fn write_pnpm_member_routing_left_pad(cwd: &Path) { + let url = hosted_npm_url("left-pad", "1.3.0", UUID); + let alias = format!("socket-{}", &UUID[..8]); + let registry = url.strip_suffix("left-pad-1.3.0.tgz").unwrap(); + put( + cwd, + "package.json", + br#"{ "name": "app", "version": "1.0.0", "private": true }"#, + ); + put( + cwd, + "packages/a/package.json", + br#"{ "name": "a", "version": "1.0.0", "dependencies": { "left-pad": "1.3.0" } }"#, + ); + put( + cwd, + "pnpm-workspace.yaml", + format!( + "packages:\n - packages/a\nnamedRegistries:\n {alias}: {registry}\noverrides:\n \ + 'left-pad@1.3.0': '{alias}:1.3.0'\n" + ) + .as_bytes(), + ); + put( + cwd, + "pnpm-lock.yaml", + format!( + "lockfileVersion: '9.0'\n\nsettings:\n autoInstallPeers: true\n \ + excludeLinksFromLockfile: false\n\noverrides:\n left-pad@1.3.0: {alias}:1.3.0\n\n\ + importers:\n\n .: {{}}\n\n packages/a:\n dependencies:\n left-pad:\n \ + specifier: {alias}:1.3.0\n version: {alias}:1.3.0\n\npackages:\n\n \ + left-pad@{alias}:1.3.0:\n resolution: {{integrity: {SRI}, tarball: {url}}}\n\n\ + snapshots:\n\n left-pad@{alias}:1.3.0: {{}}\n" + ) + .as_bytes(), + ); +} + +/// What a pnpm install (12.25.1) records in `nm` beside the packages: the +/// install record, and `lock` as the lockfile in the store. +#[cfg(unix)] +fn write_pnpm_install_record(nm: &Path, lock: &[u8]) { + put( + nm, + ".modules.yaml", + br#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ); + put(nm, ".pnpm/lock.yaml", lock); +} + +/// `name@version`, its `index.js` holding `index`, in the entry `entry` of +/// the store under `nm`. +#[cfg(unix)] +fn put_pnpm_entry(nm: &Path, entry: &str, name: &str, version: &str, index: &[u8]) { + let dir = format!(".pnpm/{entry}/node_modules/{name}"); + put( + nm, + &format!("{dir}/package.json"), + format!(r#"{{ "name": "{name}", "version": "{version}" }}"#).as_bytes(), + ); + put(nm, &format!("{dir}/index.js"), index); +} + +/// A link at `at` to `target`, as pnpm writes its package links. +#[cfg(unix)] +fn pnpm_link(target: &str, at: &Path) { + std::fs::create_dir_all(at.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(target, at).unwrap(); +} + +/// #2353: a `node_modules` that no lockfile names still loads what it +/// links. Member `b` (on `dep@1.0.0`, which depends on `left-pad`) left +/// the workspace, and member `a`'s `left-pad@1.3.0` was installed again +/// from the registry of its patch (real pnpm 11.27.0 layout): `a` and the +/// hoist dir link the routed entry, and neither lockfile names +/// `packages/b`. But `packages/b/node_modules/dep` still links `dep@1.0.0`, +/// whose `left-pad` link still points at the upstream entry, and node run +/// from `packages/b` loads that pristine copy. The patch is refused for as +/// long as that `node_modules` is there, and attested once it is gone. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_refused_while_a_node_modules_no_lockfile_names_loads_the_upstream_copy() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + write_pnpm_member_routing_left_pad(cwd); + let nm = cwd.join("node_modules"); + write_pnpm_install_record(&nm, &std::fs::read(cwd.join("pnpm-lock.yaml")).unwrap()); + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); + put_pnpm_entry(&nm, "dep@1.0.0", "dep", "1.0.0", b"require('left-pad')\n"); + pnpm_link( + "../../left-pad@1.3.0/node_modules/left-pad", + &nm.join(".pnpm/dep@1.0.0/node_modules/left-pad"), + ); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + pnpm_link( + &format!("../../../node_modules/.pnpm/{routed}/node_modules/left-pad"), + &cwd.join("packages/a/node_modules/left-pad"), + ); + put( + cwd, + "packages/b/package.json", + br#"{ "name": "b", "version": "1.0.0", "dependencies": { "dep": "1.0.0" } }"#, + ); + pnpm_link( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + &cwd.join("packages/b/node_modules/dep"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + let args = ["--proxy-url", &server.uri()]; + + let (code, env) = vex_json(cwd, &args); + assert_eq!(code, Some(1), "packages/b loads the pristine copy: {env}"); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{env}"); + + std::fs::remove_dir_all(cwd.join("packages/b/node_modules")).unwrap(); + let (code, env) = vex_json(cwd, &args); + assert_attested( + cwd, + code, + &env, + UUID, + "nothing reaches the upstream entry any more", + ); +} + +/// #2353: a `node_modules` reached through a link belongs to a project +/// elsewhere. In a git worktree that shares the main checkout's install +/// (`worktree/node_modules -> ../main/node_modules`), the worktree's +/// member `a` links `dep@1.0.0`, whose `left-pad` link points at the +/// pristine `left-pad@1.3.0` entry; no member of the main checkout links +/// either. The store's lockfile names the main checkout's members, so its +/// entries are not judged from the worktree: every copy is hashed, and +/// the pristine one refuses the hosted patch, where it was dropped and +/// the patch attested from the lock's pin with nothing hashed. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let tmp = tempfile::tempdir().unwrap(); + // The main checkout holds the install, made before the scan. + let main = tmp.path().join("main"); + put( + &main, + "packages/a/package.json", + br#"{ "name": "a", "version": "1.0.0", "dependencies": { "dep": "1.0.0" } }"#, + ); + let nm = main.join("node_modules"); + write_pnpm_install_record( + &nm, + b"lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n is-number:\n \ + specifier: 7.0.0\n version: 7.0.0\n\n packages/a:\n dependencies:\n dep:\n \ + specifier: 1.0.0\n version: 1.0.0\n\npackages:\n\n dep@1.0.0:\n \ + resolution: {integrity: sha512-x}\n\n is-number@7.0.0:\n \ + resolution: {integrity: sha512-y}\n\n left-pad@1.3.0:\n \ + resolution: {integrity: sha512-z}\n\nsnapshots:\n\n dep@1.0.0:\n dependencies:\n \ + left-pad: 1.3.0\n\n is-number@7.0.0: {}\n\n left-pad@1.3.0: {}\n", + ); + put_pnpm_entry(&nm, "is-number@7.0.0", "is-number", "7.0.0", b"7\n"); + pnpm_link( + ".pnpm/is-number@7.0.0/node_modules/is-number", + &nm.join("is-number"), + ); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, "dep@1.0.0", "dep", "1.0.0", b"require('left-pad')\n"); + pnpm_link( + "../../left-pad@1.3.0/node_modules/left-pad", + &nm.join(".pnpm/dep@1.0.0/node_modules/left-pad"), + ); + // The worktree: the scan's files, the main checkout's install, and + // its own member's link. + let cwd = &tmp.path().join("worktree"); + write_pnpm_member_routing_left_pad(cwd); + pnpm_link("../main/node_modules", &cwd.join("node_modules")); + pnpm_link( + "../../../node_modules/.pnpm/dep@1.0.0/node_modules/dep", + &cwd.join("packages/a/node_modules/dep"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + assert_eq!( + code, + Some(1), + "the worktree's member loads the pristine copy: {env}" + ); + assert_eq!(skipped_reason(&env, purl), "not_applied", "{env}"); +} + /// The patch view for `name@version` (the [`left_pad_view`] shape). fn npm_view(name: &str, version: &str, after_hash: &str) -> Value { let mut view = left_pad_view(after_hash); From 2d4c713fd9171ca9baeec4f0c3ae4c9a1186190e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:09:11 -0500 Subject: [PATCH 09/22] Correct the docs on which links keep a pnpm store entry The contract said a copy that a link reaches is always hashed, which was not true of a link in a `node_modules` that no lockfile names. It and `docs/ecosystems.md` now say which links are read: those of every `node_modules` the crawl searches, of the members the lockfiles name, of the hoist directory and of each reached entry. They also say that a link in a `node_modules` the crawl does not search is not read, that a store reached through a linked `node_modules` or from inside a member is not judged, and that a member that is not on disk links nothing (#2353). Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- docs/ecosystems.md | 44 ++++++++++++++++--------- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 43f7fe3ae3..8cd9bd78af 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -817,7 +817,7 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | -**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link reaches is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. A copy that a link reaches is always hashed, whatever its entry is named. For pnpm the links are those of each importer's `node_modules` (the project root and the workspace members its lockfiles name), of the store's hoist directory `node_modules/.pnpm/node_modules`, of each reached entry's own `node_modules`, and the link through which the crawl found a copy. Where pnpm's links cannot all be read (Windows, `node-linker=hoisted`, `shamefully-hoist`, a moved virtual store, an unreadable directory; `docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list), every entry is hashed. `rollback` and `remove` restore unlinked entries too. +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link reaches is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm the links read are those of every `node_modules` the crawl searches (the project root's and each one below it, so also the one a directory keeps after it leaves the workspace), of each workspace member the lockfile in the store or `pnpm-lock.yaml` names, of the store's hoist directory `node_modules/.pnpm/node_modules`, and of each reached entry's own `node_modules`; every store is judged once per run, by the same links for the record check and the hosted one. A copy in an entry that such a link reaches is always hashed, whatever the entry is named. A link in a `node_modules` that the crawl does not search and no lockfile names is not read, as a package installed there is not found. Where pnpm's links cannot all be read (Windows, a store whose own `node_modules` the crawl does not search or reaches through a link, `node-linker=hoisted`, `shamefully-hoist`, a moved virtual store, an unreadable directory; `docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list), every entry is hashed. `rollback` and `remove` restore unlinked entries too. **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 307f9d3441..2cc216acee 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -800,32 +800,44 @@ copies the install loads, so they skip a pnpm store entry that no link reaches, as they skip one in Bun's store, which Bun never prunes. A link reaches an entry from: -- the `node_modules` of an importer: the project root, and every - workspace member named by the lockfile pnpm writes in the store or by - `pnpm-lock.yaml`; +- any `node_modules` the crawl searches (see the top of this section): the + project root's, each workspace member's, and the one a directory keeps + after it leaves the workspace, since node run from there still loads + what its links reach; +- the `node_modules` of a workspace member named by the lockfile pnpm + writes in the store or by `pnpm-lock.yaml`, wherever it sits (a member + that is not on disk links nothing); - the store's hoist directory, `node_modules/.pnpm/node_modules`; - the `node_modules` of an entry that is itself reached (a transitive - dependency has no other link); -- any other `node_modules` in which the crawl found a copy of the package - being checked. + dependency has no other link). -A copy that a link reaches is always judged, whatever its entry is named: -an unpatched one still omits the patch (`not_applied`) or warns -(`vendored_tree_out_of_sync`). Where the links cannot all be read, every -entry is judged, as before: +A copy in an entry that such a link reaches is always judged, whatever the +entry is named: an unpatched one still omits the patch (`not_applied`) or +warns (`vendored_tree_out_of_sync`). A link in a `node_modules` that the +crawl does not search and no lockfile names (below `dist/` or a hidden +directory, or outside the project) is not read, as a package installed +there is not found. + +Where the links cannot all be read, every entry is judged, as before: - on Windows, where pnpm links directories with junctions; +- when the crawl does not search the store's own `node_modules` as a real + directory of its project: a run from inside a workspace member, or a + `node_modules` that is a link to another checkout's (a git worktree + that shares an install), whose lockfiles describe that other project; - under `node-linker=hoisted` or `shamefully-hoist` (a `publicHoistPattern` of `*`), or a store layout other than the one pnpm 6 to 12 write; - when `virtualStoreDir` moved the virtual store, or the install record (`node_modules/.modules.yaml`) or the lockfile in the store is missing or unreadable; -- when the store, a `node_modules`, a `@scope` directory, a link or - `pnpm-lock.yaml` cannot be read; -- when one of the two lockfiles names a workspace member that is not a - directory, or lists its importers in a layout pnpm does not write; -- when an importer's `node_modules` or the hoist directory holds a - package as a real directory, which the isolated linker never writes; +- when the store, the type of one of its entries, a `node_modules`, a + `@scope` directory, a link or `pnpm-lock.yaml` cannot be read; +- when one of the two lockfiles names a workspace member that is on disk + and is not a directory, or does not list its importers the way pnpm + writes them (a merge conflict left in the file, for one); +- when the `node_modules` of the project or of a member that a lockfile + names, or the hoist directory, holds a package as a real directory, + which the isolated linker never writes; - when no link reaches the store at all. `rollback` and `remove` restore an unlinked entry too: a later install From c77a1fa25dbb430e222d4e7b87a807503baf128c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 13:30:21 -0500 Subject: [PATCH 10/22] Test that a lockfile's member is read where the crawl does not look With every searched `node_modules` read, the members in the unit fixtures were reached without the lockfiles, so nothing held the lockfile's members in place. A member below `vendor/`, which the crawl skips, has no other word of it: the entry it alone links stays live when the lockfile in the store names it, when only `pnpm-lock.yaml` does and under a quoted key, and is an orphan when neither names it (#2353). Co-Authored-By: Claude Fable 5.2 --- .../src/crawlers/npm_crawler.rs | 60 +++++++++++++++---- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 06eec75c4c..ce3944c4d1 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -8435,14 +8435,23 @@ mod tests { assert_eq!(live_copies(&root, &all).await, routed.to_vec()); } - /// #2353: pnpm quotes an importer key that YAML cannot take plain - /// (`'@apps/web':`). The member is read all the same, so the entry it - /// alone links stays live beside the one nothing links. The copies are - /// named by their store paths, so only the member's link vouches. + /// #2353: a member's `node_modules` is read because a lockfile names + /// the member, wherever it sits: below `vendor/` the crawl does not + /// search, so the lockfile is the only word of it. The entry such a + /// member alone links stays live when the lockfile in the store names + /// the member, and when only `pnpm-lock.yaml` does; pnpm quotes a key + /// that YAML cannot take plain (`'@apps/vendor/web':`), and it is read + /// all the same. A `node_modules` that is neither searched nor named + /// is not read, and its entry is an orphan. The copies are named by + /// their store paths, so only the member's link vouches for one. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_member_of_a_quoted_key_links_is_a_live_copy() { - for key in ["'@apps/web'", "\"@apps/web\""] { + async fn test_pnpm_store_entry_a_member_only_a_lockfile_names_links_is_a_live_copy() { + for (key, member) in [ + ("vendor/b", "vendor/b"), + ("'@apps/vendor/web'", "@apps/vendor/web"), + ("\"@apps/vendor/web\"", "@apps/vendor/web"), + ] { let tmp = tempfile::tempdir().unwrap(); let root: PathBuf = tmp.path().components().collect(); let (nm, store) = pnpm_install(&root, &[key]); @@ -8452,17 +8461,42 @@ mod tests { &nm.join("is-number"), ); let member_only = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); - write_pkg(&root.join("@apps/web"), "web", "1.0.0"); + let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); + write_pkg(&root.join(member), "member", "1.0.0"); + let member_nm = root.join(member).join("node_modules"); + let up = "../".repeat(member.split('/').count() + 1); rel_link( - "../../../node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad", - &root.join("@apps/web/node_modules/left-pad"), + &format!("{up}node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad"), + &member_nm.join("left-pad"), + ); + let options = CrawlerOptions { + cwd: root.clone(), + global: false, + global_prefix: None, + }; + let searched = NpmCrawler::new() + .get_node_modules_paths(&options) + .await + .unwrap(); + assert_eq!(searched, vec![nm.clone()], "{key}"); + let copies = [&used, &member_only, &orphan]; + let live = vec![used.clone(), member_only.clone()]; + + assert_eq!(live_copies(&root, &copies).await, live, "{key}"); + + std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&[])).unwrap(); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&[key])).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + live, + "{key}: pnpm-lock.yaml" ); - let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); + std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&[])).unwrap(); assert_eq!( - live_copies(&root, &[&used, &member_only, &orphan]).await, - vec![used, member_only], - "{key}" + live_copies(&root, &copies).await, + vec![used], + "{key}: no lockfile" ); } } From e644e58243ad9879aace2c3843e653548e15db36 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 15:43:02 -0500 Subject: [PATCH 11/22] Judge a pnpm store entry by every link below the scanned project After the in-place `pnpm install` that a hosted or vendored scan asks for, the upstream `@` entry stays in `node_modules/.pnpm` with nothing linking to it, and `vex` and `apply --check` refused the patch for it (#2353). The first rule on this branch proved such an entry dead by walking the links pnpm should have written: the crawl's roots, the lockfiles' members, the hoist dir. Two reviews each found a layout it did not read, where a copy that still loads was left out: a link under a directory the crawl skips by name, a link in a real package's own `node_modules`, a `modulesDir` of more than one level. The rule now reads the links there are. For a package version whose copies sit in two or more entries of one store, every symbolic link below the outer of the scanned directory and the store's project is listed, in every directory whatever its name, and resolved, never followed. An entry is kept when a link outside the store's entries resolves into it, or a link inside a kept entry does. The closure is needed: on pnpm 11.29.0 and 12.25.1 a hosted scan gives a package that names the patched one as a peer a new entry too, and its old entry keeps its link to the old one. A version that sits in one entry is not judged, and the project is not read for it, so a removed package and an upgraded-away version are hashed as on main. Every entry is kept where a link may have gone unread: on Windows, when the two directories are unrelated, when the install record is not the isolated linker's over this store, when a lockfile is missing or not laid out as pnpm writes it, when a lockfile names an importer that is not a directory inside the store's project, when a directory or a link cannot be read, past 1,000,000 directories, and when no link resolves into any entry. Five more cases keep entries that the sweep alone would leave out. The first four were reproduced with real node against a store that pnpm 12.25.1 left: - A copy that sits in the store but in none of its entries (a real directory of the hoist dir, which every store package resolves through) was dropped whenever its version sat in two entries. Only a copy in an entry dir is judged now. - A link whose target is spelled another way than the store's path was not matched to its entry. macOS reaches every volume under `/System/Volumes/Data` as well, and `canonicalize` keeps that spelling. A link that leaves the trees read is now checked against the store by file identity, and every entry is kept when it lies in the store. - Node looks a package up in the `node_modules` of every directory above the one it starts in. Each `node_modules` above the swept directory is swept as well. - A link to a directory outside the trees read (a `link:` dependency on another checkout) leads to a `node_modules` that is not read, which may link back into the store. Every entry is kept then. - A link that resolves to a child of the store which could be an entry and is not one of those listed cannot be matched to an entry: a file system that folds case need not give an entry's listed spelling back (macOS does). Every entry is kept then. This one was not reproduced: no such file system was at hand. The unit tests are rewritten for the rule: the hosted and the vendored leftover, the peer pair, a link from each kind of place, the gate, and one case for every condition that keeps all entries. Each of the first four cases above has a test that was seen to fail without its change. The CLI hands the filter the scanned directory in place of the crawl's `node_modules` roots. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/vex_consumed.rs | 4 +- .../src/ecosystem_dispatch.rs | 31 +- .../src/crawlers/npm_crawler.rs | 1949 +++++++++++------ 3 files changed, 1303 insertions(+), 681 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vex_consumed.rs b/crates/socket-patch-cli/src/commands/vex_consumed.rs index 78a06f65ca..de1cb3c302 100644 --- a/crates/socket-patch-cli/src/commands/vex_consumed.rs +++ b/crates/socket-patch-cli/src/commands/vex_consumed.rs @@ -468,7 +468,9 @@ mod tests { )]); VARIANT_INPUTS .scope(std::cell::RefCell::new(Vec::new()), async { - let mut live = LiveStoreEntries::default(); + // The judgement `vex` hands over: the installed lookup's, + // made for the scanned directory. + let mut live = LiveStoreEntries::new(Some(common.cwd.clone())); let mut found = hosted_consumed_copies(common, &hosted, installed, None, &mut live).await; let paths = found.remove(&purl).unwrap().paths; diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index bcd8efcd6c..65afd35a72 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -990,22 +990,6 @@ async fn dispatch_find_with_npm_links( prior: Option<&NpmCrawlSnapshot>, links: NpmLinks, ) -> HashMap> { - dispatch_find_with_npm_roots(partitioned, options, silent, variant_merge, prior, links) - .await - .0 -} - -/// [`dispatch_find_with_npm_links`], with the npm `node_modules` roots it -/// searched: `None` when no npm purl was asked for, or the roots could -/// not be found. -async fn dispatch_find_with_npm_roots( - partitioned: &HashMap>, - options: &CrawlerOptions, - silent: bool, - variant_merge: MergeFn, - prior: Option<&NpmCrawlSnapshot>, - links: NpmLinks, -) -> (HashMap>, Option>) { let mut wanted: HashMap> = HashMap::new(); for purl in partitioned.get(&Ecosystem::Npm).into_iter().flatten() { wanted @@ -1030,7 +1014,7 @@ async fn dispatch_find_with_npm_roots( ) .await; let Some(roots) = npm_roots else { - return (found, None); + return found; }; if links == NpmLinks::ForUnresolved { let resolved = |purl: &String| found.get(purl).is_some_and(|paths| !paths.is_empty()); @@ -1039,12 +1023,11 @@ async fn dispatch_find_with_npm_roots( !purls.is_empty() }); if wanted.is_empty() { - return (found, Some(roots)); + return found; } } // A failed enumeration only loses the extra links; the copies stand. - let link_roots = roots.clone(); - let links = tokio::task::spawn_blocking(move || npm_links_to(&wanted, &link_roots)) + let links = tokio::task::spawn_blocking(move || npm_links_to(&wanted, &roots)) .await .unwrap_or_default(); for (purl, link) in links { @@ -1053,7 +1036,7 @@ async fn dispatch_find_with_npm_roots( paths.push(link); } } - (found, Some(roots)) + found } /// Every package link directly in one of `roots` (scoped ones one level @@ -1372,7 +1355,7 @@ pub(crate) async fn find_manifest_package_copies_judged( ) -> (HashMap>, LiveStoreEntries) { let partitioned = partition_purls(purls, common.ecosystems.as_deref()); let crawler_options = common.crawler_options(); - let (mut copies, npm_roots) = dispatch_find_with_npm_roots( + let mut copies = dispatch_find_with_npm_links( &partitioned, &crawler_options, quiet, @@ -1396,9 +1379,9 @@ pub(crate) async fn find_manifest_package_copies_judged( // A Bun or pnpm store entry nothing links any more (Bun never prunes // `.bun`; pnpm keeps the entry an in-place install replaced) is no // copy the install loads, so the check skips it (#599, #2353). A pnpm - // entry is judged by the links of every `node_modules` searched above. + // entry is judged by every link below the scanned project. // Rollback and remove, which resolve without this, still restore it. - let mut live = LiveStoreEntries::new(npm_roots); + let mut live = LiveStoreEntries::new((!common.is_global()).then(|| common.cwd.clone())); live.retain_live_copies( copies .iter_mut() diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index ce3944c4d1..3dbaf20f55 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -2,6 +2,7 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::ffi::{OsStr, OsString}; use std::fs::FileType; use std::path::{Path, PathBuf}; +use std::sync::Arc; use serde::Deserialize; @@ -876,101 +877,95 @@ fn orphaned_pnpm_store_entry_sync( } /// The `.pnpm` store entries an install can still load, by name (#2353); -/// `None` when the walk cannot tell, and every entry must be kept. pnpm +/// `None` when that cannot be told, and every entry must be kept. pnpm /// keeps an entry it no longer uses (see /// [`orphaned_pnpm_store_entry_sync`]), and an in-place `pnpm install` /// that takes a package from another source under the same name and /// version (a hosted patch routed through its own registry, a vendored -/// `file:` tarball) writes a new entry, re-links every dependent to it -/// and leaves the old `@` dir behind. The current lockfile +/// `file:` tarball) writes a new entry, links the project to it and +/// leaves the old `@` dir behind. The current lockfile /// still lists that name and version, so a check of each installed copy /// (`vex`) judges an entry by the links instead, as for Bun (see /// [`live_bun_store_entries_sync`]); rollback and remove still restore /// the orphan. /// -/// An entry is live when a link reaches it from a `node_modules` whose -/// packages node can load, from pnpm's hoist dir `.pnpm/node_modules` -/// (every store package resolves through it), or from a live entry's -/// `node_modules`. Those `node_modules` are: +/// The links read are all the links there are, not the ones pnpm should +/// have written: every symbolic link below `tree`, whatever its directory +/// is named (see [`links_below_sync`]; `sweeps` holds the trees read so +/// far). An entry is live when a link that sits outside the store's +/// entries resolves into it, or a link inside a live entry does. So an +/// entry left out is one that only other left-out entries link, and no +/// path that starts outside them leads into it. Such chains are what a +/// hosted scan leaves: a dependent that names the patched package as a +/// peer gets a new entry of its own +/// (`_@socket-+`), and its old entry keeps +/// its link to the old one (measured on pnpm 11.29.0 and 12.25.1). /// -/// - `roots`, every one the crawl searched: the project's own, each -/// workspace member's, and any other below the project. A directory -/// that left the workspace keeps the links of its last install, and -/// node run from there still loads what they reach, whatever the -/// lockfiles say; -/// - the members the current lockfile names (`.pnpm/lock.yaml`, which -/// every install rewrites with the importers it has linked so far), -/// and, when those leave some entry unreached, the members of the -/// project's `pnpm-lock.yaml`: a member can sit where the crawl does -/// not look. One that is not there (a checkout of part of the -/// workspace) links nothing. -/// -/// A stale link pnpm left behind still counts: the runtime resolves -/// through it. -/// -/// A link the walk misses would hide a copy the install loads, so the -/// walk keeps every entry wherever it cannot be sure it read them all: +/// `tree` is the outer of the directory `scanned` and the directory that +/// holds the store's `node_modules`. Node looks a package up in the +/// `node_modules` of every directory above the one it starts in, so each +/// `node_modules` of a directory above `tree` is read the same way. A +/// link anywhere else is not read, so every entry is kept wherever pnpm +/// may have written one there, or the links cannot all be read or +/// followed: /// /// - on Windows, where pnpm links directories with junctions; -/// - when the store's own `node_modules` is not among `roots` as the real -/// directory of its project: it was not searched (a run from inside a -/// member), or the crawl reached it through a link (a git worktree that -/// shares another checkout's install), and then the lockfiles beside -/// the store describe a project that is not the crawled one; +/// - when neither of the two directories holds the other (a +/// `node_modules` that is a link to another checkout's, a global +/// install); /// - when the store is not the one `node_modules/.modules.yaml` records, /// or the record is not of the isolated linker over a flat store (see /// [`Layout::is_isolated`](crate::formats::pnpm::modules_yaml::Layout::is_isolated): -/// `node-linker=hoisted`, `shamefully-hoist`, another layout version); -/// - without a current lockfile, or when it or `pnpm-lock.yaml` cannot be -/// read, lays its importers out in a way pnpm does not write, or names -/// a member that is there and is no directory; -/// - when the store, a `node_modules` dir, a scope dir, a link or the type -/// of a child of the store cannot be read; -/// - when the `node_modules` of the project or of a member a lockfile -/// names, or the hoist dir, holds a package as a real dir, which the -/// isolated linker never writes there; -/// - when no link reaches any entry. -fn live_pnpm_store_entries_sync(store_path: &Path, roots: &[PathBuf]) -> Option> { +/// `node-linker=hoisted` and `pnp`, whose loaders name store paths +/// without a link, `shamefully-hoist`, another layout version); +/// - without the lockfile pnpm writes in the store, or when it or +/// `pnpm-lock.yaml` cannot be read or lays its importers out in a way +/// pnpm does not write; +/// - when a workspace member one of the two lockfiles names is not a +/// directory inside the directory that holds the store's +/// `node_modules`. pnpm links each member's dependencies below the +/// member, so a member outside has links the sweep does not read, and +/// members that are not found there show that this directory is not +/// the workspace's root (a `modulesDir` of more than one level puts the +/// store below it); +/// - when a directory that is read, the type of one of its children or +/// the target of a link cannot be read, or one of the trees holds more +/// than [`LINK_SWEEP_DIR_BUDGET`] directories; +/// - when a link resolves to a directory outside the trees read (a +/// `link:` dependency on another checkout): what its `node_modules` +/// links is not read; +/// - when a link resolves into the store by a path that is spelled +/// another way than the store's (macOS reaches a volume under +/// `/System/Volumes/Data` as well), or to a child of the store that +/// could be an entry and is not one of those listed, so that its entry +/// cannot be named; +/// - when no link reaches any entry (`symlink=false`). +fn live_pnpm_store_entries_sync( + store_path: &Path, + scanned: &Path, + sweeps: &mut HashMap>>>, +) -> Option> { use crate::constants::npm_family::PNPM_LOCK; use crate::formats::pnpm::grammar::is_pnpm_lock_text; use crate::formats::pnpm::modules_yaml::Layout; use crate::formats::pnpm::workspace::lock_text_member_importers_exact; use crate::utils::fs::read_regular_to_string_sync; + use crate::utils::relpath::normalize_lexically; if cfg!(windows) { return None; } let store = std::fs::canonicalize(store_path).ok()?; let nm = store.parent()?; - let root = nm.parent()?; - // The crawl's roots by their real paths. The store's `node_modules` - // must be one of them, and each spelling of it the real directory - // right under its project: `root` is then the project the crawl - // searched, whose members the lockfiles name. - let mut searched: Vec = Vec::new(); - let mut is_root = false; - for dir in roots { - let real = match std::fs::canonicalize(dir) { - Ok(real) => real, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, - Err(_) => return None, - }; - if real != nm { - searched.push(real); - continue; - } - let project = match dir.parent() { - Some(project) if !project.as_os_str().is_empty() => project, - _ => Path::new("."), - }; - if std::fs::canonicalize(project).ok()?.join(dir.file_name()?) != nm { - return None; - } - is_root = true; - } - if !is_root { + let project = nm.parent()?; + let scanned = std::fs::canonicalize(scanned).ok()?; + let tree = if project.starts_with(&scanned) { + scanned.as_path() + } else if scanned.starts_with(project) { + project + } else { return None; - } + }; let record = read_regular_to_string_sync(&nm.join(PNPM_MODULES_YAML)).ok()?; let layout = Layout::parse(&record).filter(Layout::is_isolated)?; if std::fs::canonicalize(nm.join(layout.virtual_store_dir?)).ok()? != store { @@ -979,43 +974,122 @@ fn live_pnpm_store_entries_sync(store_path: &Path, roots: &[PathBuf]) -> Option< let current = read_regular_to_string_sync(&store.join("lock.yaml")) .ok() .filter(|text| is_pnpm_lock_text(text))?; - let entries = pnpm_store_entry_names(list_dir_sync(&store))?; - // The `node_modules` of each member a lock names. - let members = |lock: &str| -> Option> { - let mut dirs = Vec::new(); + let wanted = match read_regular_to_string_sync(&project.join(PNPM_LOCK)) { + Ok(wanted) => Some(wanted), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => None, + Err(_) => return None, + }; + for lock in [Some(¤t), wanted.as_ref()].into_iter().flatten() { for member in lock_text_member_importers_exact(lock)? { - let member = root.join(member); - match std::fs::metadata(&member) { - Ok(metadata) if metadata.is_dir() => { - dirs.push((member.join("node_modules"), LinkDir::Importer)); - } - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - _ => return None, + let member = Path::new(&member); + if member.is_absolute() { + return None; + } + // A member that climbs out of `project` does not normalize. + let member = std::fs::canonicalize(project.join(normalize_lexically(member)?)).ok()?; + if !member.starts_with(project) || !std::fs::metadata(&member).ok()?.is_dir() { + return None; } } - Some(dirs) - }; - - let mut walk = PnpmStoreWalk { - store: &store, - entries: &entries, - live: HashSet::new(), - }; - let mut seeds = vec![ - (store.join("node_modules"), LinkDir::Importer), - (nm.to_path_buf(), LinkDir::Importer), - ]; - seeds.extend(members(¤t)?); - seeds.extend(searched.into_iter().map(|dir| (dir, LinkDir::Searched))); - walk.reach(seeds)?; - if walk.live.len() < entries.len() { - match read_regular_to_string_sync(&root.join(PNPM_LOCK)) { - Ok(wanted) => walk.reach(members(&wanted)?)?, + } + let entries = pnpm_store_entry_names(list_dir_sync(&store))?; + // Node climbs past `tree`: the `node_modules` above it are read too. + let mut trees = vec![tree.to_path_buf()]; + for above in tree.ancestors().skip(1) { + match std::fs::canonicalize(above.join("node_modules")) { + Ok(nm) if nm.is_dir() => trees.push(nm), + Ok(_) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(_) => return None, } } - (!walk.live.is_empty()).then_some(walk.live) + let mut swept = Vec::with_capacity(trees.len()); + for tree in &trees { + let links = sweeps + .entry(tree.clone()) + .or_insert_with(|| links_below_sync(tree).map(Arc::new)); + swept.push(links.clone()?); + } + let links = || swept.iter().flat_map(|links| links.iter()); + + // A link that leads out of the trees read: a directory behind it is + // not read, and a path spelled another way than `store` may still lie + // in it. The directories found to be no part of the store are checked + // once. + let store_id = same_file::Handle::from_path(&store).ok()?; + let mut elsewhere: HashSet<&Path> = HashSet::new(); + for link in links() { + if trees.iter().any(|tree| link.target.starts_with(tree)) { + continue; + } + if link.target.is_dir() { + return None; + } + for dir in link.target.ancestors() { + if !elsewhere.insert(dir) { + break; + } + if same_file::Handle::from_path(dir).is_ok_and(|id| id == store_id) { + return None; + } + } + } + + // The entry of this store that a real path lies in. + let entry_of = |path: &Path| -> Option<&OsStr> { + match path.strip_prefix(&store).ok()?.components().next()? { + std::path::Component::Normal(name) => entries.get(name).map(OsString::as_os_str), + _ => None, + } + }; + // Whether a real path lies in a child of this store that could be an + // entry and is not one of the listed ones: a file, or an entry spelled + // another way than it is listed (not every file system that folds + // case gives the one spelling back). + let in_unlisted_child = |path: &Path| { + let child = path.strip_prefix(&store).ok(); + match child.and_then(|rest| rest.components().next()) { + Some(std::path::Component::Normal(name)) => { + is_pnpm_store_entry_name(name) && !entries.contains(name) + } + _ => false, + } + }; + let mut live: HashSet<&OsStr> = HashSet::new(); + let mut frontier: Vec<&OsStr> = Vec::new(); + // The entries each entry's own links resolve into. + let mut linked: HashMap<&OsStr, Vec<&OsStr>> = HashMap::new(); + for link in links() { + let Some(target) = entry_of(&link.target) else { + if in_unlisted_child(&link.target) { + return None; + } + continue; + }; + match entry_of(&link.path) { + Some(source) if source == target => {} + Some(source) => linked.entry(source).or_default().push(target), + None => { + if live.insert(target) { + frontier.push(target); + } + } + } + } + while let Some(entry) = frontier.pop() { + for target in linked.remove(entry).into_iter().flatten() { + if live.insert(target) { + frontier.push(target); + } + } + } + (!live.is_empty()).then(|| live.into_iter().map(OsStr::to_os_string).collect()) +} + +/// Whether a child of a pnpm store named `name` can be an entry dir: not +/// the hidden metadata, and not the `node_modules` hoist dir. +fn is_pnpm_store_entry_name(name: &OsStr) -> bool { + !name.as_encoded_bytes().starts_with(b".") && name != "node_modules" } /// The names of the entry dirs of a pnpm store, from its listing: every @@ -1032,141 +1106,76 @@ fn pnpm_store_entry_names(listing: Listing) -> Option> { if child.name_str.starts_with('.') { continue; } - if child.file_type?.is_dir() && child.name_str != "node_modules" { + if child.file_type?.is_dir() && is_pnpm_store_entry_name(&child.name) { entries.insert(child.name); } } Some(entries) } -/// A dir whose package links [`PnpmStoreWalk`] reads. -#[derive(Clone, Copy, PartialEq, Eq)] -enum LinkDir { - /// A `node_modules` pnpm itself links: the project's, a member's that - /// a lockfile names, the hoist dir. It holds links alone. - Importer, - /// Another `node_modules` the crawl searched, which may hold packages - /// of its own beside links into the store. - Searched, - /// The `node_modules` of a store entry: the entry's own package and - /// links to its dependencies. - Entry, -} - -/// The walk of [`live_pnpm_store_entries_sync`] over one store. -struct PnpmStoreWalk<'a> { - /// The store's real path. - store: &'a Path, - /// The names of the store's entry dirs. - entries: &'a HashSet, - /// The entries reached so far. - live: HashSet, -} - -impl PnpmStoreWalk<'_> { - /// Add to `live` every entry reachable through links from the `seeds` - /// dirs, following each reached entry's own `node_modules` links, one - /// frontier at a time and each frontier's dirs in parallel. A seed - /// that does not exist links nothing. `None` when a dir or a link - /// cannot be read. - fn reach(&mut self, seeds: Vec<(PathBuf, LinkDir)>) -> Option<()> { - let mut frontier: Vec<(PathBuf, LinkDir)> = Vec::new(); - for (seed, kind) in seeds { - match std::fs::canonicalize(seed) { - Ok(nm) => frontier.push((nm, kind)), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(_) => return None, - } - } - while !frontier.is_empty() { - let reads = par_map(frontier, |(nm, kind)| self.link_targets(&nm, kind)); - frontier = Vec::new(); - for targets in reads { - for entry in targets? { - if !self.live.contains(&entry) { - let nm = self.store.join(&entry).join("node_modules"); - frontier.push((nm, LinkDir::Entry)); - self.live.insert(entry); - } - } - } - } - Some(()) - } - - /// The entries the package links of the `node_modules` dir `nm` point - /// into (scoped ones under `@scope/`). `nm` is real: a seed was - /// canonicalized, and an entry's own `node_modules` must be a real - /// dir of the store. An entry's dir that does not exist links nothing. - /// `None` when the dir, a scope dir or a link cannot be read, or when - /// a [`LinkDir::Importer`] holds a package as a real dir. - fn link_targets(&self, nm: &Path, kind: LinkDir) -> Option> { - if kind == LinkDir::Entry { - match std::fs::symlink_metadata(nm) { - Ok(metadata) if metadata.is_dir() => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Some(Vec::new()), - _ => return None, - } - } - let mut targets = Vec::new(); - let mut dirs = vec![(nm.to_path_buf(), false)]; - while let Some((dir, scope)) = dirs.pop() { +/// A symbolic link [`links_below_sync`] found. +struct SweptLink { + /// Where the link is: a path below the swept tree, through real + /// directories alone. + path: PathBuf, + /// The real path it resolves to. + target: PathBuf, +} + +/// How many directories [`links_below_sync`] reads before it gives up: a +/// tree this large is no single project (a home directory, a disk), and +/// the caller keeps every store entry instead of waiting on it. +const LINK_SWEEP_DIR_BUDGET: usize = 1_000_000; + +/// [`links_below_within_sync`] under [`LINK_SWEEP_DIR_BUDGET`]. +fn links_below_sync(tree: &Path) -> Option> { + links_below_within_sync(tree, LINK_SWEEP_DIR_BUDGET) +} + +/// Every symbolic link below the real directory `tree` that resolves, +/// with the real path it resolves to. No directory is skipped by name +/// (hidden ones, `vendor`, `dist`, a package's own `node_modules`: a +/// loader can start in any of them), and a link is listed, never +/// followed: what lies behind it is either in the tree, and read there, +/// or outside it. A link whose target does not exist leads nowhere and is +/// left out. +/// +/// `None` when the answer would not be complete: a directory, the type of +/// a child or the target of a link cannot be read, or the tree holds more +/// than `budget` directories, itself included. Each level of the tree is +/// read in parallel. +fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option> { + let mut links = Vec::new(); + let mut frontier = vec![tree.to_path_buf()]; + while !frontier.is_empty() { + budget = budget.checked_sub(frontier.len())?; + let reads = par_map(frontier, |dir| { + let mut links = Vec::new(); + let mut dirs = Vec::new(); for child in std::fs::read_dir(&dir).ok()? { let child = child.ok()?; - let name = child.file_name(); let file_type = child.file_type().ok()?; - if name.as_encoded_bytes().starts_with(b".") { - continue; - } - if file_type.is_symlink() { - targets.extend(self.link_target(&dir.join(name))?); - } else if file_type.is_dir() { - if !scope && name.as_encoded_bytes().starts_with(b"@") { - dirs.push((dir.join(name), true)); - } else if kind == LinkDir::Importer { - return None; + if file_type.is_dir() { + dirs.push(child.path()); + } else if file_type.is_symlink() { + let path = child.path(); + match std::fs::canonicalize(&path) { + Ok(target) => links.push(SweptLink { path, target }), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, } } } - } - Some(targets) - } - - /// The entry the link at `link` points into: `Some(None)` for a link - /// to anywhere else (a workspace member, a dir that is gone), `None` - /// when it cannot be resolved. The link's own target is read first - /// and resolved lexically (pnpm writes relative targets, and `link` - /// sits in a real dir, so each `..` climbs a real dir); one that does - /// not land in an entry dir that way (an absolute target, a link to a - /// link) is canonicalized instead. - fn link_target(&self, link: &Path) -> Option> { - let lexical = std::fs::read_link(link) - .ok() - .and_then(|target| { - Some(crate::utils::relpath::normalize_lexically_keeping_escapes( - &link.parent()?.join(target), - )) - }) - .and_then(|path| self.entry_of(&path)); - if lexical.is_some() { - return Some(lexical); - } - match std::fs::canonicalize(link) { - Ok(real) => Some(self.entry_of(&real)), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some(None), - Err(_) => None, - } - } - - /// The entry dir of the store that `path` lies in. - fn entry_of(&self, path: &Path) -> Option { - match path.strip_prefix(self.store).ok()?.components().next()? { - std::path::Component::Normal(name) => { - self.entries.contains(name).then(|| name.to_os_string()) - } - _ => None, + Some((links, dirs)) + }); + frontier = Vec::new(); + for read in reads { + let (found, dirs) = read?; + links.extend(found); + frontier.extend(dirs); } } + Some(links) } /// What [`live_bun_store_entries_sync`] found, by index into the @@ -1373,88 +1382,124 @@ const WORKSPACE_GLOB_DIR_BUDGET: usize = 20_000; /// [`live_pnpm_store_entries_sync`]), so a check of the live install /// (`vex`, `apply --check`) drops the copies in it. Never for an /// operation that restores copies. Each store is judged once, by the -/// same links whichever copies are asked about, so a later lookup over -/// the same tree keeps every copy an earlier one kept. +/// same links whichever copies are asked about. +/// +/// A pnpm store is judged only for a package version whose copies sit in +/// two or more of its entries, which is what an in-place install that +/// changed the package's source leaves. Any other copy is kept as it is, +/// and the project is not read for it. #[derive(Default)] pub struct LiveStoreEntries { - /// The `node_modules` dirs the crawl searched: a link in any of them - /// keeps a pnpm entry live. `None` when they are not known, and no - /// pnpm entry is dropped. - roots: Option>, + /// The directory the crawl scanned: the links below it decide which + /// pnpm entries are live. `None` when there is none (a global + /// install), and no pnpm entry is dropped. + scanned: Option, /// The stores judged so far, by real path: the names of their live - /// entries, or `None` where the walk could not tell. + /// entries, or `None` where that could not be told. stores: HashMap>>, + /// The trees whose links were read so far (see [`links_below_sync`]), + /// so that several pnpm stores below one scanned directory share one + /// read of it. + sweeps: HashMap>>>, } impl LiveStoreEntries { - /// For the tree a crawl searched through `roots` (what - /// [`NpmCrawler::get_node_modules_paths`] returned for it). - pub fn new(roots: Option>) -> Self { + /// For a crawl of the project at `scanned` (the crawl's `cwd`); `None` + /// for one that scans no project directory. + pub fn new(scanned: Option) -> Self { Self { - roots, - stores: HashMap::new(), + scanned, + ..Self::default() } } - /// Drop from each list every copy that sits in an orphaned store - /// entry. Each store is walked once, however many lists and calls - /// name it. + /// Drop from each list, the copies of one package version, every copy + /// that sits in an orphaned store entry. Each store is judged once, + /// however many lists and calls name it. pub async fn retain_live_copies<'a>( &mut self, lists: impl IntoIterator>, ) { let lists: Vec<&mut Vec> = lists.into_iter().collect(); - let paths: Vec = lists.iter().flat_map(|list| list.iter().cloned()).collect(); - if paths.is_empty() { + let copies: Vec> = lists.iter().map(|list| list.to_vec()).collect(); + if copies.iter().all(Vec::is_empty) { return; } let mut judged = std::mem::take(self); let (orphans, judged) = run_walk(move || { - let orphans = judged.orphaned_copies_sync(&paths); + let orphans: Vec> = copies + .iter() + .map(|copies| judged.orphaned_copies_sync(copies)) + .collect(); (orphans, judged) }) .await; *self = judged; - if orphans.is_empty() { - return; - } - for list in lists { - list.retain(|path| !orphans.contains(path)); + for (list, orphans) in lists.into_iter().zip(orphans) { + if !orphans.is_empty() { + list.retain(|path| !orphans.contains(path)); + } } } - /// Paths among `paths` that are copies inside an orphaned `.bun` or - /// `.pnpm` store entry, judged by where each canonicalizes, or, when - /// that is out of every store (a Bun global store entry's shared dir, - /// #635), by the `.bun` entry the path itself names. + /// Paths among `paths`, the copies of one package version, that are + /// copies inside an orphaned `.bun` or `.pnpm` store entry, judged by + /// where each canonicalizes, or, when that is out of every store (a + /// Bun global store entry's shared dir, #635), by the `.bun` entry the + /// path itself names. fn orphaned_copies_sync(&mut self, paths: &[PathBuf]) -> HashSet { + let located: Vec<(&PathBuf, StoreLayout, PathBuf, OsString)> = paths + .iter() + .filter_map(|path| { + let real = std::fs::canonicalize(path).ok()?; + let (layout, store, entry) = unpruned_store_entry_of(&real).or_else(|| { + let (layout, store, entry) = unpruned_store_entry_of( + &crate::utils::relpath::normalize_lexically_keeping_escapes(path), + )?; + if layout != StoreLayout::Bun { + return None; + } + Some((layout, std::fs::canonicalize(store).ok()?, entry)) + })?; + Some((path, layout, store, entry)) + }) + .collect(); + // The pnpm stores that hold these copies in more than one entry. + let mut first: HashMap<&Path, &OsStr> = HashMap::new(); + let mut split: HashSet<&Path> = HashSet::new(); + for (_, layout, store, entry) in &located { + if *layout == StoreLayout::Pnpm + && *first.entry(store.as_path()).or_insert(entry.as_os_str()) != entry.as_os_str() + { + split.insert(store.as_path()); + } + } let mut orphans = HashSet::new(); - for path in paths { - let Ok(real) = std::fs::canonicalize(path) else { + for (path, layout, store, entry) in &located { + // Only an entry dir is judged: a copy that the hoist dir or a + // hidden child of the store holds is in no entry. + if *layout == StoreLayout::Pnpm + && !(split.contains(store.as_path()) && is_pnpm_store_entry_name(entry)) + { continue; - }; - let Some((layout, store, entry)) = unpruned_store_entry_of(&real).or_else(|| { - let (layout, store, entry) = unpruned_store_entry_of( - &crate::utils::relpath::normalize_lexically_keeping_escapes(path), - )?; - if layout != StoreLayout::Bun { - return None; + } + let live = match self.stores.get(store) { + Some(live) => live, + None => { + let live = if *layout == StoreLayout::Pnpm { + self.scanned.as_deref().and_then(|scanned| { + live_pnpm_store_entries_sync(store, scanned, &mut self.sweeps) + }) + } else { + let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); + live_bun_store_entries_sync(store, &candidates) + .map(|live| live.into_names(&candidates)) + }; + self.stores.entry(store.clone()).or_insert(live) } - Some((layout, std::fs::canonicalize(store).ok()?, entry)) - }) else { - continue; }; - let roots = self.roots.as_deref(); - let live = self.stores.entry(store).or_insert_with_key(|store| { - if layout == StoreLayout::Pnpm { - return live_pnpm_store_entries_sync(store, roots?); - } - let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); - live_bun_store_entries_sync(store, &candidates) - .map(|live| live.into_names(&candidates)) - }); - if live.as_ref().is_some_and(|live| !live.contains(&entry)) { - orphans.insert(path.clone()); + if live.as_ref().is_some_and(|live| !live.contains(entry)) { + orphans.insert((*path).clone()); } } orphans @@ -8173,41 +8218,78 @@ mod tests { dir } - /// The copies of `copies` that `vex`'s live-copy filter keeps, for a - /// crawl of the project at `root`. - async fn live_copies(root: &Path, copies: &[&PathBuf]) -> Vec { - let options = CrawlerOptions { - cwd: root.to_path_buf(), - global: false, - global_prefix: None, - }; - let roots = NpmCrawler::new() - .get_node_modules_paths(&options) - .await - .unwrap(); - let mut copies: Vec = copies.iter().map(|path| (*path).clone()).collect(); - LiveStoreEntries::new(Some(roots)) - .retain_live_copies([&mut copies]) - .await; - copies + /// A fresh temp dir, its path, and a project directory two levels + /// below it (`ws/app`), so that a test owns the directories above the + /// project. + fn pnpm_project_dir() -> (tempfile::TempDir, PathBuf, PathBuf) { + let tmp = tempfile::tempdir().unwrap(); + let base: PathBuf = tmp.path().components().collect(); + let root = base.join("ws/app"); + std::fs::create_dir_all(&root).unwrap(); + (tmp, base, root) + } + + /// A link at `link` to the absolute path `target`, in a directory made + /// for it. Returns `link`. + #[cfg(unix)] + fn abs_link(target: &Path, link: &Path) -> PathBuf { + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(target, link).unwrap(); + link.to_path_buf() + } + + /// What `vex`'s live-copy filter keeps of each list of `lists` (the + /// copies of one package version each) for a crawl of the directory + /// `scanned`, and the judgement it made. + async fn judge_lists( + scanned: &Path, + lists: &[&[&PathBuf]], + ) -> (Vec>, LiveStoreEntries) { + let mut lists: Vec> = lists + .iter() + .map(|copies| copies.iter().map(|path| (*path).clone()).collect()) + .collect(); + let mut live = LiveStoreEntries::new(Some(scanned.to_path_buf())); + live.retain_live_copies(lists.iter_mut()).await; + (lists, live) + } + + /// [`judge_lists`] for the copies of one package version. + async fn live_copies(scanned: &Path, copies: &[&PathBuf]) -> Vec { + judge_lists(scanned, &[copies]).await.0.remove(0) } + /// The trees `live` read the links of that lie below `base`, sorted. + #[cfg(unix)] + fn swept_below(live: &LiveStoreEntries, base: &Path) -> Vec { + let base = std::fs::canonicalize(base).unwrap(); + let mut trees: Vec = live + .sweeps + .keys() + .filter(|tree| tree.starts_with(&base)) + .cloned() + .collect(); + trees.sort(); + trees + } + + /// The upstream copy a hosted scan leaves behind, below the project. + const LEFTOVER: &str = "node_modules/.pnpm/minimist@1.2.2/node_modules/minimist"; + /// The entry of the registry of the patch of `minimist@1.2.2`. + const ROUTED_ENTRY: &str = "minimist@socket-642d7f02+1.2.2"; + /// The store a hosted scan and the in-place `pnpm install` it asks for /// leave (real pnpm 12.25.1 and 11.29.0): the importer links the entry /// of the patch's registry, and the upstream `minimist@1.2.2` entry /// stays behind with nothing linking to it. Returns `node_modules`, - /// the orphaned copy and the linked one. - fn pnpm_hosted_route_orphan(root: &Path) -> (PathBuf, PathBuf, PathBuf) { + /// the leftover copy and the linked one. + fn pnpm_hosted_route_leftover(root: &Path) -> (PathBuf, PathBuf, PathBuf) { let (nm, store) = pnpm_install(root, &[]); let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); - let routed = pnpm_entry( - &store, - "minimist@socket-642d7f02+1.2.2", - "minimist", - "1.2.2", - ); + assert_eq!(stale, root.join(LEFTOVER)); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); rel_link( - ".pnpm/minimist@socket-642d7f02+1.2.2/node_modules/minimist", + &format!(".pnpm/{ROUTED_ENTRY}/node_modules/minimist"), &nm.join("minimist"), ); (nm, stale, routed) @@ -8217,23 +8299,24 @@ mod tests { /// release through the registry of its patch, so the in-place install /// writes `minimist@socket-+1.2.2`, links the importer to it and /// leaves the upstream `minimist@1.2.2` entry behind (a one-package - /// project has no hoist dir). The orphan is no installed copy for - /// `vex`, whatever it holds; the resolver still finds it, so rollback - /// restores it, and the scan still lists the package once. + /// project has no hoist dir). The leftover is no installed copy for + /// `vex`, whatever it holds, and the entry the importer links stays + /// one; the resolver still finds the leftover, so rollback restores + /// it, and the scan still lists the package once. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_hosted_route_orphans_is_not_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + async fn test_pnpm_store_entry_a_hosted_route_leaves_behind_is_not_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); assert_eq!( live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, vec![nm.join("minimist"), routed.clone()] ); - // The orphan alone is dropped too: the walk needs no live copy in - // the list to find the importer's link. - assert_eq!(live_copies(&root, &[&stale]).await, Vec::::new()); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()] + ); let purls = vec!["pkg:npm/minimist@1.2.2".to_string()]; let found = NpmCrawler::new().find_by_purls(&nm, &purls).await.unwrap(); @@ -8263,9 +8346,8 @@ mod tests { /// leaves the upstream entry behind the same way. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_vendored_tarball_orphans_is_not_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); + async fn test_pnpm_store_entry_a_vendored_tarball_leaves_behind_is_not_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); let (nm, store) = pnpm_install(&root, &[]); let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); let entry = @@ -8282,74 +8364,18 @@ mod tests { ); } - /// #2353 over the store of #1197: a removed package, an upgraded-away - /// version and the vendored entry of an old version stay in the store - /// with nothing linking to them, beside the entries the importer links - /// (a scoped one through its `@scope` dir) and one the hoist dir - /// links. The filter drops exactly the unlinked ones. - #[cfg(unix)] - #[tokio::test] - async fn test_pnpm_store_entries_an_upgrade_orphans_are_not_live_copies() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, store) = pnpm_install(&root, &[]); - let number = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); - rel_link( - ".pnpm/is-number@7.0.0/node_modules/is-number", - &nm.join("is-number"), - ); - let scoped = pnpm_entry( - &store, - "@s+lp@file+.socket+vendor+npm+u+s-lp-1.0.0.tgz", - "@s/lp", - "1.0.0", - ); - rel_link( - "../.pnpm/@s+lp@file+.socket+vendor+npm+u+s-lp-1.0.0.tgz/node_modules/@s/lp", - &nm.join("@s/lp"), - ); - let hoisted = pnpm_entry(&store, "ms@2.1.2", "ms", "2.1.2"); - rel_link( - "../ms@2.1.2/node_modules/ms", - &store.join("node_modules/ms"), - ); - let removed = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); - let old = pnpm_entry(&store, "@s+lp@0.9.0", "@s/lp", "0.9.0"); - let old_vendored = pnpm_entry( - &store, - "ms@file+.socket+vendor+npm+v+ms-2.1.3.tgz", - "ms", - "2.1.3", - ); - - assert_eq!( - live_copies( - &root, - &[&removed, &number, &old, &scoped, &old_vendored, &hoisted] - ) - .await, - vec![number, scoped, hoisted] - ); - } - /// #2353: a linked entry is an installed copy whatever its name. Before /// the in-place install the importer still links the upstream /// `minimist@1.2.2` entry, so that copy is the one `vex` must judge, /// and an entry of the patch's registry that nothing links (a later - /// rollback's leftover) is the orphan. + /// rollback's leftover) is the one left out. #[cfg(unix)] #[tokio::test] async fn test_pnpm_store_entry_the_importer_links_stays_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); + let (_tmp, _, root) = pnpm_project_dir(); let (nm, store) = pnpm_install(&root, &[]); let upstream = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); - let routed = pnpm_entry( - &store, - "minimist@socket-642d7f02+1.2.2", - "minimist", - "1.2.2", - ); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); rel_link( ".pnpm/minimist@1.2.2/node_modules/minimist", &nm.join("minimist"), @@ -8367,10 +8393,10 @@ mod tests { /// Each routed `minimist` entry is linked from one place only: 1.2.2 /// from member `a` (and the hoist dir), 1.2.5 from member `b` alone, /// 0.0.8 from `mkdirp`'s entry alone. The three upstream entries are - /// left behind. Returns the root's store, and the routed and the stale - /// copy of each version in that order. + /// left behind. Returns the root's store, and the routed and the + /// leftover copy of each version in that order. #[cfg(unix)] - fn pnpm_workspace_route_orphans(root: &Path) -> (PathBuf, [PathBuf; 3], [PathBuf; 3]) { + fn pnpm_workspace_route_leftovers(root: &Path) -> (PathBuf, [PathBuf; 3], [PathBuf; 3]) { let (nm, store) = pnpm_install(root, &["packages/a", "packages/b"]); let entry = |entry: &str, version: &str| pnpm_entry(&store, entry, "minimist", version); let routed = [ @@ -8410,21 +8436,33 @@ mod tests { (store, routed, stale) } - /// #2353: in a workspace an entry may be linked from one member alone. - /// The members are importers like the root (the current lockfile names - /// them), so the entry only member `b` links stays live, and the three - /// upstream entries nothing links are dropped. A member the current - /// lockfile does not name (an install that did not finish) is still - /// read when `pnpm-lock.yaml` names it. + /// What the filter keeps of the leftover and the routed copy of each + /// version of [`pnpm_workspace_route_leftovers`], one list a version. + #[cfg(unix)] + async fn live_route_pairs( + scanned: &Path, + routed: &[PathBuf; 3], + stale: &[PathBuf; 3], + ) -> Vec> { + let pairs: Vec<[&PathBuf; 2]> = stale.iter().zip(routed).map(|(s, r)| [s, r]).collect(); + let lists: Vec<&[&PathBuf]> = pairs.iter().map(|pair| pair.as_slice()).collect(); + judge_lists(scanned, &lists).await.0 + } + + /// #2353: in a workspace an entry may be linked from one member alone, + /// or from another entry alone. Every link below the project is read, + /// so the entry only member `b` links and the one only `mkdirp`'s + /// entry links stay live, and the three upstream entries nothing links + /// are left out. It makes no difference which of the two lockfiles + /// names a member. #[cfg(unix)] #[tokio::test] async fn test_pnpm_store_entry_only_a_workspace_member_links_is_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (store, routed, stale) = pnpm_workspace_route_orphans(&root); - let all: Vec<&PathBuf> = routed.iter().chain(&stale).collect(); + let (_tmp, _, root) = pnpm_project_dir(); + let (store, routed, stale) = pnpm_workspace_route_leftovers(&root); + let kept: Vec> = routed.iter().map(|copy| vec![copy.clone()]).collect(); - assert_eq!(live_copies(&root, &all).await, routed.to_vec()); + assert_eq!(live_route_pairs(&root, &routed, &stale).await, kept); std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); std::fs::write( @@ -8432,73 +8470,32 @@ mod tests { pnpm_lock_of(&["packages/a", "packages/b"]), ) .unwrap(); - assert_eq!(live_copies(&root, &all).await, routed.to_vec()); - } - - /// #2353: a member's `node_modules` is read because a lockfile names - /// the member, wherever it sits: below `vendor/` the crawl does not - /// search, so the lockfile is the only word of it. The entry such a - /// member alone links stays live when the lockfile in the store names - /// the member, and when only `pnpm-lock.yaml` does; pnpm quotes a key - /// that YAML cannot take plain (`'@apps/vendor/web':`), and it is read - /// all the same. A `node_modules` that is neither searched nor named - /// is not read, and its entry is an orphan. The copies are named by - /// their store paths, so only the member's link vouches for one. + assert_eq!(live_route_pairs(&root, &routed, &stale).await, kept); + } + + /// #2353: a transitive dependency has no link but the one in its + /// dependent's entry. `minimist@socket-8cccd65b+0.0.8` is reached only + /// through `mkdirp@0.5.1/node_modules/minimist`, and stays live for as + /// long as that entry is; once nothing links `mkdirp`'s entry either, + /// neither copy of `minimist@0.0.8` is one the install loads. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_member_only_a_lockfile_names_links_is_a_live_copy() { - for (key, member) in [ - ("vendor/b", "vendor/b"), - ("'@apps/vendor/web'", "@apps/vendor/web"), - ("\"@apps/vendor/web\"", "@apps/vendor/web"), - ] { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, store) = pnpm_install(&root, &[key]); - let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); - rel_link( - ".pnpm/is-number@7.0.0/node_modules/is-number", - &nm.join("is-number"), - ); - let member_only = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); - let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); - write_pkg(&root.join(member), "member", "1.0.0"); - let member_nm = root.join(member).join("node_modules"); - let up = "../".repeat(member.split('/').count() + 1); - rel_link( - &format!("{up}node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad"), - &member_nm.join("left-pad"), - ); - let options = CrawlerOptions { - cwd: root.clone(), - global: false, - global_prefix: None, - }; - let searched = NpmCrawler::new() - .get_node_modules_paths(&options) - .await - .unwrap(); - assert_eq!(searched, vec![nm.clone()], "{key}"); - let copies = [&used, &member_only, &orphan]; - let live = vec![used.clone(), member_only.clone()]; - - assert_eq!(live_copies(&root, &copies).await, live, "{key}"); + async fn test_pnpm_store_entry_only_a_live_entry_links_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, routed, stale) = pnpm_workspace_route_leftovers(&root); + let [_, _, transitive] = &routed; + let [_, _, stale_transitive] = &stale; - std::fs::write(store.join("lock.yaml"), pnpm_lock_of(&[])).unwrap(); - std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&[key])).unwrap(); - assert_eq!( - live_copies(&root, &copies).await, - live, - "{key}: pnpm-lock.yaml" - ); + assert_eq!( + live_copies(&root, &[stale_transitive, transitive]).await, + vec![transitive.clone()] + ); - std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&[])).unwrap(); - assert_eq!( - live_copies(&root, &copies).await, - vec![used], - "{key}: no lockfile" - ); - } + std::fs::remove_file(root.join("node_modules/mkdirp")).unwrap(); + assert_eq!( + live_copies(&root, &[stale_transitive, transitive]).await, + Vec::::new() + ); } /// #2353: a `node_modules` that no lockfile names still loads what it @@ -8508,14 +8505,12 @@ mod tests { /// entry, and neither lockfile names `packages/b`. Yet /// `packages/b/node_modules/mkdirp` still links `mkdirp@0.5.1`, whose /// `minimist` link still points at the upstream entry, and node run - /// from `packages/b` loads that copy. It stays live for as long as the - /// crawl finds that `node_modules`, however the copies are named; - /// without it, the upstream entry and `mkdirp`'s are orphans. + /// from `packages/b` loads that copy. It stays live for as long as + /// that link is there; without it, the upstream entry is left out. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_a_node_modules_no_lockfile_names_reaches_is_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); + async fn test_pnpm_store_entry_a_former_member_reaches_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); let (_, store) = pnpm_install(&root, &["packages/a"]); std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); let upstream = pnpm_entry(&store, "minimist@0.0.8", "minimist", "0.0.8"); @@ -8525,7 +8520,7 @@ mod tests { "minimist", "0.0.8", ); - let mkdirp = pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); + pnpm_entry(&store, "mkdirp@0.5.1", "mkdirp", "0.5.1"); rel_link( "../../minimist@0.0.8/node_modules/minimist", &store.join("mkdirp@0.5.1/node_modules/minimist"), @@ -8547,103 +8542,587 @@ mod tests { ); // Named by their store paths: no copy's own path leads to an entry. - let copies = [&upstream, &routed, &mkdirp]; assert_eq!( - live_copies(&root, &copies).await, - vec![upstream.clone(), routed.clone(), mkdirp.clone()] + live_copies(&root, &[&upstream, &routed]).await, + vec![upstream.clone(), routed.clone()] ); std::fs::remove_dir_all(root.join("packages/b/node_modules")).unwrap(); - assert_eq!(live_copies(&root, &copies).await, vec![routed]); + assert_eq!( + live_copies(&root, &[&upstream, &routed]).await, + vec![routed] + ); } - /// #2353: a `node_modules` the crawl reaches through a link (a git - /// worktree that shares the main checkout's install) belongs to a - /// project elsewhere, and the members the lockfile in its store names - /// are that project's, not the crawled one's. Every entry is kept, so - /// the one only the crawled project's member links stays a copy. So - /// is every entry of a store whose own `node_modules` the crawl did - /// not search (a run from inside a member). From the main checkout, - /// which the worktree is no part of, the member's entry is an orphan. + /// #2353: when the patched package is a peer dependency of another + /// package, a hosted scan gives the dependent a new entry as well, and + /// the dependent's old entry keeps its link to the old `minimist` entry + /// (real pnpm 12.25.1 and 11.29.0). Neither old entry is linked from + /// outside the store's entries, so both are left out: a link inside an + /// entry nothing reaches keeps nothing. One link to the old dependent + /// from outside brings both back. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_the_crawl_reaches_through_a_link_keeps_every_entry() { - let tmp = tempfile::tempdir().unwrap(); - let base: PathBuf = tmp.path().components().collect(); - let main = base.join("main"); - let (main_nm, store) = pnpm_install(&main, &["packages/a"]); - let used = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + async fn test_pnpm_store_entries_only_each_other_links_are_not_live_copies() { + const OLD: &str = "needs-minimist@file+needs-minimist-1.0.0.tgz_minimist@1.2.2"; + const NEW: &str = + "needs-minimist@file+needs-minimist-1.0.0.tgz_minimist@socket-642d7f02+1.2.2"; + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let dependent = |entry: &str, peer_entry: &str| { + let dir = pnpm_entry(&store, entry, "needs-minimist", "1.0.0"); + rel_link( + &format!("../../{peer_entry}/node_modules/minimist"), + &store.join(entry).join("node_modules/minimist"), + ); + dir + }; + let old_dependent = dependent(OLD, "minimist@1.2.2"); + let new_dependent = dependent(NEW, ROUTED_ENTRY); rel_link( - ".pnpm/is-number@7.0.0/node_modules/is-number", - &main_nm.join("is-number"), + &format!(".pnpm/{NEW}/node_modules/needs-minimist"), + &nm.join("needs-minimist"), ); - let member_only = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); - let orphan = pnpm_entry(&store, "left-pad@1.2.0", "left-pad", "1.2.0"); - write_pkg(&main.join("packages/a"), "a", "1.0.0"); - // The worktree: the main checkout's install, its own member links. - let worktree = base.join("worktree"); - write_pkg(&worktree.join("packages/a"), "a", "1.0.0"); - rel_link("../main/node_modules", &worktree.join("node_modules")); - rel_link( - "../../../node_modules/.pnpm/left-pad@1.3.0/node_modules/left-pad", - &worktree.join("packages/a/node_modules/left-pad"), + let lists: [&[&PathBuf]; 2] = [&[&stale, &routed], &[&old_dependent, &new_dependent]]; + + assert_eq!( + judge_lists(&root, &lists).await.0, + vec![vec![routed.clone()], vec![new_dependent.clone()]] ); - let copies = [&used, &member_only, &orphan]; - let all = vec![used.clone(), member_only.clone(), orphan.clone()]; - assert_eq!(live_copies(&main, &copies).await, vec![used.clone()]); - assert_eq!(live_copies(&worktree, &copies).await, all); + abs_link( + &old_dependent, + &root.join("tools/node_modules/needs-minimist"), + ); assert_eq!( - live_copies(&worktree.join("packages/a"), &copies).await, - all + judge_lists(&root, &lists).await.0, + vec![vec![stale, routed], vec![old_dependent, new_dependent]] ); } - /// #2353: a transitive dependency has no link but the one in its - /// dependent's entry. `minimist@socket-8cccd65b+0.0.8` is reached only - /// through `mkdirp@0.5.1/node_modules/minimist`, and stays live for as - /// long as that entry is; once nothing links `mkdirp`'s entry either, - /// both are orphans. + /// #2353: every link there is counts, wherever it sits and whatever it + /// points at inside the entry: node, or any other loader, started from + /// that path loads the leftover copy. Each case adds one link to the + /// store of [`pnpm_hosted_route_leftover`], whose leftover is left out + /// as it stands, and the leftover is a live copy for as long as that + /// link is there. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_entry_only_a_live_entry_links_is_a_live_copy() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (store, routed, stale) = pnpm_workspace_route_orphans(&root); - let mkdirp = store.join("mkdirp@0.5.1/node_modules/mkdirp"); - let [_, _, transitive] = &routed; - let [_, _, stale_transitive] = &stale; - + async fn test_pnpm_store_entry_any_link_reaches_is_a_live_copy() { + // Adds the link; returns the path that takes it away again. + type AddLink = Box PathBuf>; + let to_the_package = |at: &'static str| -> AddLink { + Box::new(move |root: &Path| abs_link(&root.join(LEFTOVER), &root.join(at))) + }; + let cases: Vec<(&str, AddLink)> = vec![ + ("vendor/", to_the_package("vendor/x")), + ("dist/", to_the_package("dist/x")), + ("build/", to_the_package("build/x")), + ("a hidden directory", to_the_package(".cache/tool/x")), + ( + "a former member's node_modules", + to_the_package("packages/gone/node_modules/minimist"), + ), + ( + "the hoist directory", + to_the_package("node_modules/.pnpm/node_modules/minimist"), + ), + ("a scoped link", to_the_package("node_modules/@s/pkg")), + ( + "a real package's node_modules in a live entry", + Box::new(|root: &Path| { + let nested = format!( + "node_modules/.pnpm/{ROUTED_ENTRY}/node_modules/minimist/node_modules/old" + ); + abs_link(&root.join(LEFTOVER), &root.join(nested)) + }), + ), + ( + "a real package's node_modules in a member", + Box::new(|root: &Path| { + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + pnpm_lock_of(&["packages/a"]), + ) + .unwrap(); + let real = root.join("packages/a/node_modules/real"); + write_pkg(&real, "real", "1.0.0"); + abs_link(&root.join(LEFTOVER), &real.join("node_modules/minimist")) + }), + ), + ( + "a nested project's node_modules", + Box::new(|root: &Path| { + let (nm, _) = pnpm_install(&root.join("apps/web"), &[]); + abs_link(&root.join(LEFTOVER), &nm.join("minimist")) + }), + ), + ( + "the node_modules of the directory above the project", + Box::new(|root: &Path| { + let above = root.parent().unwrap().join("node_modules/@up/minimist"); + abs_link(&root.join(LEFTOVER), &above) + }), + ), + ( + "a real package's node_modules two directories above the project", + Box::new(|root: &Path| { + let real = root.ancestors().nth(2).unwrap().join("node_modules/real"); + write_pkg(&real, "real", "1.0.0"); + abs_link(&root.join(LEFTOVER), &real.join("node_modules/minimist")) + }), + ), + ( + "a link that is a child of the store", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + abs_link(&store.join("minimist@1.2.2"), &store.join("alias")) + }), + ), + ( + "a link to the entry's node_modules", + Box::new(|root: &Path| { + abs_link( + root.join(LEFTOVER).parent().unwrap(), + &root.join("vendor/modules"), + ) + }), + ), + ( + "a link to a file of the package", + Box::new(|root: &Path| { + abs_link( + &root.join(LEFTOVER).join("package.json"), + &root.join("vendor/minimist.json"), + ) + }), + ), + ( + "a chain of two links, the second outside the project", + Box::new(|root: &Path| { + let hop = root.ancestors().nth(2).unwrap().join("hop"); + abs_link(&root.join(LEFTOVER), &hop); + abs_link(&hop, &root.join("tools/x")) + }), + ), + ( + "a chain through the link of an entry nothing reaches", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + pnpm_entry(&store, "dep@0.9.0", "dep", "0.9.0"); + let inner = store.join("dep@0.9.0/node_modules/minimist"); + rel_link("../../minimist@1.2.2/node_modules/minimist", &inner); + abs_link(&inner, &root.join("vendor/x")) + }), + ), + ]; + for (case, add_link) in cases { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let copies = [&stale, &routed]; + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{case}: before the link" + ); + let link = add_link(&root); + assert_eq!( + live_copies(&root, &copies).await, + vec![stale.clone(), routed.clone()], + "{case}" + ); + // The link kept it, not a store that could no longer be judged. + std::fs::remove_file(&link).unwrap(); + assert_eq!( + live_copies(&root, &copies).await, + vec![routed.clone()], + "{case}: without the link" + ); + } + } + + /// #2353: a link may spell an entry in another case than the store + /// lists it. On a file system that folds case the link resolves, and + /// the entry is a live copy (`canonicalize` gives the listed spelling + /// back on macOS; where it does not, the entry cannot be named and + /// every entry is kept). Where case is kept, the link leads nowhere. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_a_link_in_another_case_reaches_is_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let link = root.join("vendor/x"); + rel_link( + "../node_modules/.PNPM/Minimist@1.2.2/node_modules/minimist", + &link, + ); + let kept = live_copies(&root, &[&stale, &routed]).await; + if link.join("package.json").is_file() { + assert_eq!(kept, vec![stale, routed], "the file system folds case"); + } else { + assert_eq!(kept, vec![routed], "the link leads nowhere"); + } + } + + /// #2353: what does not reach the leftover entry does not keep it, and + /// does not stop the store from being judged. Each case changes one + /// thing about the store of [`pnpm_hosted_route_leftover`], and the + /// leftover is left out all the same. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_entry_no_link_reaches_from_outside_is_not_a_live_copy() { + type Change = Box; + let member = |key: &'static str, dir: &'static str, wanted: bool| -> Change { + Box::new(move |root: &Path| { + write_pkg(&root.join(dir), "member", "1.0.0"); + let lock = if wanted { + root.join("pnpm-lock.yaml") + } else { + root.join("node_modules/.pnpm/lock.yaml") + }; + std::fs::write(lock, pnpm_lock_of(&[key])).unwrap(); + }) + }; + let real_dir = |at: &'static str, name: &'static str| -> Change { + Box::new(move |root: &Path| write_pkg(&root.join(at), name, "1.3.0")) + }; + let cases: Vec<(&str, Change)> = vec![ + ( + "a link inside an entry nothing reaches", + Box::new(|root: &Path| { + let store = root.join("node_modules/.pnpm"); + pnpm_entry(&store, "dep@0.9.0", "dep", "0.9.0"); + rel_link( + "../../minimist@1.2.2/node_modules/minimist", + &store.join("dep@0.9.0/node_modules/minimist"), + ); + }), + ), + ( + "links inside the leftover entry to itself", + Box::new(|root: &Path| { + let package = root.join(LEFTOVER); + rel_link(".", &package.join("self")); + rel_link( + "../minimist/package.json", + &package.join("../.bin/minimist"), + ); + rel_link("../..", &package.join("node_modules/up")); + }), + ), + ( + "a link whose target is not there", + Box::new(|root: &Path| { + abs_link(&root.join(LEFTOVER).join("gone"), &root.join("vendor/x")); + rel_link("nowhere", &root.join("dist/x")); + }), + ), + ( + "a link to a file outside the project", + Box::new(|root: &Path| { + let file = root.ancestors().nth(2).unwrap().join("file"); + std::fs::write(&file, "").unwrap(); + abs_link(&file, &root.join("tools/file")); + }), + ), + ( + "a link to a directory inside the project", + Box::new(|root: &Path| { + abs_link(root, &root.join("packages/a/node_modules/root")); + abs_link(&root.join("node_modules"), &root.join("vendor/modules")); + }), + ), + ( + "a package as a real directory of the importer", + real_dir("node_modules/left-pad", "left-pad"), + ), + ( + "a package as a real directory of an importer's scope", + real_dir("node_modules/@s/lp", "@s/lp"), + ), + ( + "a linked entry whose node_modules is a link", + Box::new(|root: &Path| { + let entry = root.join("node_modules/.pnpm").join(ROUTED_ENTRY); + std::fs::rename(entry.join("node_modules"), entry.join("moved")).unwrap(); + rel_link("moved", &entry.join("node_modules")); + }), + ), + ( + "a member the lockfile in the store names", + member("packages/a", "packages/a", false), + ), + ( + "a member pnpm-lock.yaml names", + member("packages/a", "packages/a", true), + ), + ( + "a member under a key in single quotes", + member("'@apps/vendor/web'", "@apps/vendor/web", false), + ), + ( + "a member under a key in double quotes", + member("\"@apps/vendor/web\"", "@apps/vendor/web", true), + ), + ( + "a member that is a link to a directory inside the project", + Box::new(|root: &Path| { + write_pkg(&root.join("real/member"), "member", "1.0.0"); + abs_link(&root.join("real/member"), &root.join("packages/linked")); + std::fs::write( + root.join("node_modules/.pnpm/lock.yaml"), + pnpm_lock_of(&["packages/linked"]), + ) + .unwrap(); + }), + ), + ( + "an empty node_modules above the project", + Box::new(|root: &Path| { + std::fs::create_dir_all(root.parent().unwrap().join("node_modules/.bin")) + .unwrap(); + std::fs::write(root.ancestors().nth(2).unwrap().join("node_modules"), "") + .unwrap(); + }), + ), + ]; + for (case, change) in cases { + let (_tmp, _, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + change(&root); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed], + "{case}" + ); + } + } + + /// #2353: a pnpm store is judged for a package version only when its + /// copies sit in two or more entries of the store, which is what an + /// in-place install that changed the package's source leaves. A + /// removed package and an upgraded-away version (#1197) hold their + /// version in one entry: each is kept though nothing links it, and + /// the project is not read for them. Where one version does sit in + /// two entries, the others are still kept as they are. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_is_judged_only_for_a_version_in_two_of_its_entries() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, store) = pnpm_install(&root, &[]); + let linked = pnpm_entry(&store, "is-number@7.0.0", "is-number", "7.0.0"); + let link = nm.join("is-number"); + rel_link(".pnpm/is-number@7.0.0/node_modules/is-number", &link); + let removed = pnpm_entry(&store, "left-pad@1.3.0", "left-pad", "1.3.0"); + let upgraded = pnpm_entry(&store, "is-number@6.0.0", "is-number", "6.0.0"); + + let lists: [&[&PathBuf]; 3] = [&[&removed], &[&upgraded], &[&linked, &link]]; + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!( + kept, + vec![ + vec![removed.clone()], + vec![upgraded.clone()], + vec![linked.clone(), link.clone()] + ] + ); + assert!( + live.stores.is_empty() && live.sweeps.is_empty(), + "no store is judged and no tree is read" + ); + + // Two peer variants of one version, both linked, are both kept; + // they are judged, so the project is read for them. + let peers = [ + pnpm_entry(&store, "dep@1.0.0_peer@1.0.0", "dep", "1.0.0"), + pnpm_entry(&store, "dep@1.0.0_peer@2.0.0", "dep", "1.0.0"), + ]; + rel_link( + ".pnpm/dep@1.0.0_peer@1.0.0/node_modules/dep", + &nm.join("dep"), + ); + rel_link( + "../dep@1.0.0_peer@2.0.0/node_modules/dep", + &store.join("node_modules/dep"), + ); + let (kept, live) = judge_lists(&root, &[&[&peers[0], &peers[1]], &[&removed]]).await; + assert_eq!(kept, vec![peers.to_vec(), vec![removed.clone()]]); assert_eq!( - live_copies(&root, &[stale_transitive, transitive, &mkdirp]).await, - vec![transitive.clone(), mkdirp.clone()] + swept_below(&live, &root), + vec![std::fs::canonicalize(&root).unwrap()] ); - std::fs::remove_file(root.join("node_modules/mkdirp")).unwrap(); + // The leftover of an in-place install is left out, and the store's + // judgement is not turned on the versions that sit in one entry. + let stale = pnpm_entry(&store, "minimist@1.2.2", "minimist", "1.2.2"); + let routed = pnpm_entry(&store, ROUTED_ENTRY, "minimist", "1.2.2"); + rel_link( + &format!(".pnpm/{ROUTED_ENTRY}/node_modules/minimist"), + &nm.join("minimist"), + ); + let lists: [&[&PathBuf]; 3] = [&[&removed], &[&stale, &routed], &[&upgraded]]; + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!(kept, vec![vec![removed], vec![routed], vec![upgraded]]); + assert_eq!(live.stores.len(), 1); + } + + /// #2353: a copy that sits in the store but in none of its entry dirs + /// is never left out. Every package of the store resolves through the + /// hoist dir `.pnpm/node_modules`, so a package that is a real + /// directory there loads without any link, and a hidden child of the + /// store is not judged at all. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_copy_in_none_of_its_entries_is_always_a_live_copy() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + let hoisted = nm.join(".pnpm/node_modules/minimist"); + write_pkg(&hoisted, "minimist", "1.2.2"); + let hidden = nm.join(".pnpm/.staging/node_modules/minimist"); + write_pkg(&hidden, "minimist", "1.2.2"); + let through = abs_link(&hoisted, &root.join("vendor/hoisted")); + assert_eq!( - live_copies(&root, &[stale_transitive, transitive, &mkdirp]).await, - Vec::::new() + live_copies(&root, &[&stale, &hoisted, &hidden, &through, &routed]).await, + vec![hoisted.clone(), hidden.clone(), through, routed] + ); + // Also when no entry but the leftover's holds a copy of the list. + assert_eq!( + live_copies(&root, &[&stale, &hoisted, &hidden]).await, + vec![hoisted, hidden] ); } - /// #2353: a member the lockfiles name that is not there links nothing. - /// A checkout of part of a workspace (a container image that copies - /// some members) installs frozen with both lockfiles still naming the - /// rest, and the entry nothing links is an orphan there all the same. + /// #2353: the links are read below the outer of the scanned directory + /// and the project that holds the store. A run from inside a workspace + /// member reads the whole project, and a run from a directory above + /// the project reads everything below that directory, so a link in + /// another checkout there counts. The same link is out of reach of a + /// scan of the project alone. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_a_member_that_is_not_there_links_nothing() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); - let lock = pnpm_lock_of(&["packages/gone", "apps/gone/too"]); - std::fs::write(nm.join(".pnpm/lock.yaml"), &lock).unwrap(); - std::fs::write(root.join("pnpm-lock.yaml"), &lock).unwrap(); + async fn test_pnpm_store_is_judged_by_the_links_below_the_outer_directory() { + let (_tmp, base, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + std::fs::write(nm.join(".pnpm/lock.yaml"), pnpm_lock_of(&["packages/a"])).unwrap(); + let member = root.join("packages/a"); + write_pkg(&member, "a", "1.0.0"); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + let (kept, live) = judge_lists(&member, &[&copies]).await; + assert_eq!(kept, vec![vec![routed.clone()]]); assert_eq!( - live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, - vec![nm.join("minimist"), routed] + swept_below(&live, &base), + vec![std::fs::canonicalize(&root).unwrap()] + ); + let link = abs_link(&stale, &root.join("vendor/x")); + assert_eq!(live_copies(&member, &copies).await, both); + std::fs::remove_file(link).unwrap(); + + let (kept, live) = judge_lists(&base, &[&copies]).await; + assert_eq!(kept, vec![vec![routed.clone()]]); + assert_eq!( + swept_below(&live, &base), + vec![std::fs::canonicalize(&base).unwrap()] ); + abs_link(&stale, &base.join("other/checkout/dist/x")); + assert_eq!(live_copies(&base, &copies).await, both); + assert_eq!(live_copies(&root, &copies).await, vec![routed.clone()]); + assert_eq!(live_copies(&member, &copies).await, vec![routed]); + } + + /// #2353: several pnpm stores below one scanned directory are judged + /// from one read of its links, and a link in one project's + /// `node_modules` keeps an entry of the other's store. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_stores_below_one_scanned_directory_share_one_sweep() { + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let nested = root.join("apps/web"); + let (nested_nm, nested_stale, nested_routed) = pnpm_hosted_route_leftover(&nested); + let lists: [&[&PathBuf]; 2] = [&[&stale, &routed], &[&nested_stale, &nested_routed]]; + + let (kept, live) = judge_lists(&root, &lists).await; + assert_eq!( + kept, + vec![vec![routed.clone()], vec![nested_routed.clone()]] + ); + assert_eq!(live.stores.len(), 2); + assert_eq!( + swept_below(&live, &base), + vec![std::fs::canonicalize(&root).unwrap()] + ); + + abs_link(&stale, &nested_nm.join("old-minimist")); + assert_eq!( + judge_lists(&root, &lists).await.0, + vec![vec![stale, routed], vec![nested_routed]] + ); + } + + /// #2353: the sweep lists every link below a tree, in whatever + /// directory, with the real path it resolves to, and follows none: a + /// link behind a link to a directory outside the tree is not read. A + /// link whose target is not there is left out. One directory more than + /// the budget, and there is no answer. + #[cfg(unix)] + #[test] + fn test_links_below_lists_every_link_and_follows_none() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let (tree, outside) = (base.join("tree"), base.join("outside")); + std::fs::create_dir_all(outside.join("deep")).unwrap(); + std::fs::write(outside.join("file"), "").unwrap(); + abs_link(&outside.join("file"), &outside.join("deep/unread")); + // Ten directories, the tree itself among them. + for dir in [ + "vendor", + "dist/a/b", + ".hidden", + "node_modules/pkg/node_modules/@s", + ] { + std::fs::create_dir_all(tree.join(dir)).unwrap(); + } + std::fs::write(tree.join("file"), "").unwrap(); + let mut expected = vec![ + (tree.join(".hidden/up"), tree.clone()), + (tree.join("chain"), outside.clone()), + (tree.join("dist/a/b/file"), tree.join("file")), + ( + tree.join("node_modules/pkg/node_modules/@s/x"), + tree.join("vendor"), + ), + (tree.join("vendor/dir"), outside.clone()), + ]; + abs_link(&tree, &tree.join(".hidden/up")); + abs_link(&tree.join("vendor/dir"), &tree.join("chain")); + abs_link(&tree.join("file"), &tree.join("dist/a/b/file")); + abs_link( + &tree.join("vendor"), + &tree.join("node_modules/pkg/node_modules/@s/x"), + ); + abs_link(&outside, &tree.join("vendor/dir")); + rel_link("nowhere", &tree.join("dangling")); + + let found = |budget: usize| { + let mut links: Vec<(PathBuf, PathBuf)> = links_below_within_sync(&tree, budget)? + .into_iter() + .map(|link| (link.path, link.target)) + .collect(); + links.sort(); + Some(links) + }; + expected.sort(); + assert_eq!(found(10), Some(expected.clone())); + assert_eq!(found(9), None); + assert_eq!( + links_below_sync(&tree).map(|links| links.len()), + Some(expected.len()) + ); + assert!(links_below_sync(&tree.join("missing")).is_none()); } /// #2353: the entries of a store are its real dirs, read from a whole @@ -8688,143 +9167,227 @@ mod tests { } } - /// #2353: wherever the walk cannot be sure it read every link, nothing - /// is dropped. Each case changes one thing about the store of - /// [`pnpm_hosted_route_orphan`], whose orphan is dropped as it stands. + /// #2353: wherever a link that reaches an entry may have gone unread, + /// nothing is left out. Each case changes one thing about the store of + /// [`pnpm_hosted_route_leftover`], whose leftover is left out as it + /// stands. #[cfg(unix)] #[tokio::test] - async fn test_pnpm_store_the_walk_cannot_read_keeps_every_entry() { + async fn test_pnpm_store_that_cannot_be_judged_keeps_every_entry() { use std::os::unix::fs::PermissionsExt; - type Change = fn(&Path); - type Case = (&'static str, Box); - let record = |from: &'static str, to: &'static str| { - move |root: &Path| { + type Change = Box; + let record = |from: &'static str, to: &'static str| -> Change { + Box::new(move |root: &Path| { let path = root.join("node_modules/.modules.yaml"); let text = std::fs::read_to_string(&path).unwrap(); assert!(text.contains(from), "{from}"); std::fs::write(path, text.replace(from, to)).unwrap(); - } + }) }; - let hoisted_linker = record(r#""nodeLinker":"isolated""#, r#""nodeLinker":"hoisted""#); - let shamefully_hoisted = record( - r#""publicHoistPattern":[]"#, - r#""publicHoistPattern":["*"]"#, - ); - let other_layout = record(r#""layoutVersion":5"#, r#""layoutVersion":4"#); - let relocated_store = record( - r#""virtualStoreDir":".pnpm""#, - r#""virtualStoreDir":"../.store""#, - ); - let cases: Vec = vec![ - ("no install record", { - let change: Change = - |root| std::fs::remove_file(root.join("node_modules/.modules.yaml")).unwrap(); - Box::new(change) - }), - ("an install record that does not parse", { - let change: Change = |root| { + // `lock` in place of the lockfile in the store, or of + // `pnpm-lock.yaml`. + fn write_lock(root: &Path, wanted: bool, lock: &str) { + let path = if wanted { + root.join("pnpm-lock.yaml") + } else { + root.join("node_modules/.pnpm/lock.yaml") + }; + std::fs::write(path, lock).unwrap(); + } + // The directory `ws/x`, beside the project. + fn beside(root: &Path) -> PathBuf { + let dir = root.parent().unwrap().join("x"); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + let misplaced_importers = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + let lock = pnpm_lock_of(&[]).replace("\n .:\n", "\n .:\n"); + assert!(lock.contains("\n .:\n")); + write_lock(root, wanted, &lock); + }) + }; + let member_missing = |wanted: bool| -> Change { + Box::new(move |root: &Path| write_lock(root, wanted, &pnpm_lock_of(&["packages/gone"]))) + }; + let member_a_file = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + std::fs::write(root.join("member"), "").unwrap(); + write_lock(root, wanted, &pnpm_lock_of(&["member"])); + }) + }; + let member_climbing_out = |wanted: bool| -> Change { + Box::new(move |root: &Path| { + beside(root); + write_lock(root, wanted, &pnpm_lock_of(&["../x"])); + }) + }; + let mut cases: Vec<(&str, Change)> = vec![ + ( + "no install record", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/.modules.yaml")).unwrap() + }), + ), + ( + "an install record that does not parse", + Box::new(|root: &Path| { std::fs::write(root.join("node_modules/.modules.yaml"), "{ not json").unwrap() - }; - Box::new(change) - }), - ("node-linker=hoisted", Box::new(hoisted_linker)), - ("shamefully-hoist", Box::new(shamefully_hoisted)), - ("another layout version", Box::new(other_layout)), + }), + ), + ( + "node-linker=hoisted", + record(r#""nodeLinker":"isolated""#, r#""nodeLinker":"hoisted""#), + ), + ( + "shamefully-hoist", + record( + r#""publicHoistPattern":[]"#, + r#""publicHoistPattern":["*"]"#, + ), + ), + ( + "another layout version", + record(r#""layoutVersion":5"#, r#""layoutVersion":4"#), + ), ( "a record of another virtual store", - Box::new(relocated_store), + record( + r#""virtualStoreDir":".pnpm""#, + r#""virtualStoreDir":"../.store""#, + ), + ), + ( + "no lockfile in the store", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/.pnpm/lock.yaml")).unwrap() + }), + ), + ( + "a lockfile in the store that is no pnpm lock", + Box::new(|root: &Path| write_lock(root, false, "not: a lock\n")), + ), + ( + "a lockfile in the store laid out as pnpm does not write it", + misplaced_importers(false), + ), + ( + "a pnpm-lock.yaml laid out as pnpm does not write it", + misplaced_importers(true), + ), + ( + "a pnpm-lock.yaml that cannot be read", + Box::new(|root: &Path| std::fs::create_dir(root.join("pnpm-lock.yaml")).unwrap()), + ), + ( + "a member of the lockfile in the store that climbs out", + member_climbing_out(false), + ), + ( + "a member of pnpm-lock.yaml that climbs out", + member_climbing_out(true), + ), + ( + "a member named by an absolute path", + Box::new(|root: &Path| { + let member = beside(root); + let member = member.to_str().unwrap(); + let lock = pnpm_lock_of(&[member]); + assert_eq!( + crate::formats::pnpm::workspace::lock_text_member_importers_exact(&lock), + Some(vec![member.to_string()]) + ); + write_lock(root, false, &lock); + }), + ), + ( + "a member of the lockfile in the store that is not on disk", + member_missing(false), + ), + ( + "a member of pnpm-lock.yaml that is not on disk", + member_missing(true), + ), + ( + "a member of the lockfile in the store that is a file", + member_a_file(false), + ), + ( + "a member of pnpm-lock.yaml that is a file", + member_a_file(true), + ), + ( + "a member that is a link to a directory outside the project", + Box::new(|root: &Path| { + abs_link(&beside(root), &root.join("packages/out")); + write_lock(root, false, &pnpm_lock_of(&["packages/out"])); + }), + ), + ( + "a link to a directory outside the trees read", + Box::new(|root: &Path| { + abs_link(&beside(root), &root.join("node_modules/linked")); + }), + ), + ( + "a link in a node_modules above the project to a directory beside it", + Box::new(|root: &Path| { + let above = root.parent().unwrap().join("node_modules/linked"); + abs_link(&beside(root), &above); + }), + ), + ( + "a link that loops", + Box::new(|root: &Path| rel_link("loop", &root.join("vendor/loop"))), + ), + ( + "a link through a file", + Box::new(|root: &Path| { + std::fs::write(root.join("file"), "").unwrap(); + rel_link("../file/child", &root.join("vendor/x")); + }), + ), + ( + "a link into the store that names none of its entries", + Box::new(|root: &Path| { + abs_link( + &root.join("node_modules/.pnpm/lock.yaml"), + &root.join("vendor/lock.yaml"), + ); + }), + ), + ( + "no link into the store", + Box::new(|root: &Path| { + std::fs::remove_file(root.join("node_modules/minimist")).unwrap() + }), ), - ("no current lockfile", { - let change: Change = - |root| std::fs::remove_file(root.join("node_modules/.pnpm/lock.yaml")).unwrap(); - Box::new(change) - }), - ("a current lockfile that is no pnpm lock", { - let change: Change = |root| { - std::fs::write(root.join("node_modules/.pnpm/lock.yaml"), "not: a lock\n") - .unwrap() - }; - Box::new(change) - }), - ("a current lockfile naming a member that is a file", { - let change: Change = |root| { - std::fs::write(root.join("member"), "").unwrap(); - std::fs::write( - root.join("node_modules/.pnpm/lock.yaml"), - pnpm_lock_of(&["member"]), - ) - .unwrap() - }; - Box::new(change) - }), - ("a current lockfile laid out as pnpm does not write it", { - let change: Change = |root| { - let lock = pnpm_lock_of(&[]).replace("\n .:\n", "\n .:\n"); - assert!(lock.contains("\n .:\n")); - std::fs::write(root.join("node_modules/.pnpm/lock.yaml"), lock).unwrap() - }; - Box::new(change) - }), - ("a pnpm-lock.yaml that cannot be read", { - let change: Change = - |root| std::fs::create_dir(root.join("pnpm-lock.yaml")).unwrap(); - Box::new(change) - }), - ("a pnpm-lock.yaml naming a member that is a file", { - let change: Change = |root| { - std::fs::write(root.join("member"), "").unwrap(); - std::fs::write(root.join("pnpm-lock.yaml"), pnpm_lock_of(&["member"])).unwrap() - }; - Box::new(change) - }), - ("no link into the store", { - let change: Change = - |root| std::fs::remove_file(root.join("node_modules/minimist")).unwrap(); - Box::new(change) - }), - ("a package as a real dir of the importer", { - let change: Change = - |root| write_pkg(&root.join("node_modules/left-pad"), "left-pad", "1.3.0"); - Box::new(change) - }), - ("a package as a real dir of an importer's scope", { - let change: Change = - |root| write_pkg(&root.join("node_modules/@s/lp"), "@s/lp", "1.0.0"); - Box::new(change) - }), - ("a package as a real dir of the hoist dir", { - let change: Change = |root| { - write_pkg( - &root.join("node_modules/.pnpm/node_modules/left-pad"), - "left-pad", - "1.3.0", - ) - }; - Box::new(change) - }), - ("a live entry whose node_modules is a link", { - let change: Change = |root| { - let entry = root.join("node_modules/.pnpm/minimist@socket-642d7f02+1.2.2"); - std::fs::rename(entry.join("node_modules"), entry.join("moved")).unwrap(); - std::os::unix::fs::symlink("moved", entry.join("node_modules")).unwrap(); - }; - Box::new(change) - }), - ("a link that loops", { - let change: Change = |root| { - std::os::unix::fs::symlink("loop", root.join("node_modules/loop")).unwrap() - }; - Box::new(change) - }), ]; + // macOS reaches every volume under `/System/Volumes/Data` as well, + // and `canonicalize` keeps that spelling. + #[cfg(target_os = "macos")] + cases.push(( + "a link into the leftover entry spelled through /System/Volumes/Data", + Box::new(|root: &Path| { + let real = std::fs::canonicalize(root.join(LEFTOVER)).unwrap(); + let spelled = Path::new("/System/Volumes/Data") + .join(real.strip_prefix("/").unwrap()) + .join("package.json"); + assert!(spelled.is_file(), "{spelled:?}"); + abs_link(&spelled, &root.join("vendor/minimist.json")); + }), + )); for (case, change) in cases { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); - let copies = [&nm.join("minimist"), &stale, &routed]; - assert_eq!(live_copies(&root, &copies[1..]).await, vec![routed.clone()]); + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()], + "{case}: before the change" + ); change(&root); + let copies = [&stale, &routed, &nm.join("minimist")]; let kept: Vec = copies .iter() .filter(|copy| copy.exists()) @@ -8837,29 +9400,103 @@ mod tests { ); } - // A dir the walk may not read: an unreadable `node_modules` of the - // linked entry (not as root, which reads it all the same). - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (_, stale, routed) = pnpm_hosted_route_orphan(&root); - let unreadable = routed.parent().unwrap(); - std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o000)).unwrap(); - let readable = std::fs::read_dir(unreadable).is_ok(); - let kept = live_copies(&root, &[&stale]).await; - std::fs::set_permissions(unreadable, std::fs::Permissions::from_mode(0o755)).unwrap(); - if !readable { - assert_eq!(kept, vec![stale], "an unreadable node_modules"); + // A scanned directory that neither holds the project nor lies in + // it, and a crawl that scans no project directory (`--global`). + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + let other = base.join("ws/other"); + std::fs::create_dir_all(&other).unwrap(); + assert_eq!(live_copies(&other, &copies).await, both); + assert_eq!(live_copies(&base.join("missing"), &copies).await, both); + let mut global = both.clone(); + LiveStoreEntries::new(None) + .retain_live_copies([&mut global]) + .await; + assert_eq!(global, both); + + // Directories that cannot be read (not as root, which reads them + // all the same): one below the project, one in a `node_modules` + // above it, and one that the target of a link lies behind. + for (case, locked, link) in [ + ( + "an unreadable directory below the project", + "ws/app/dist/private", + None, + ), + ( + "an unreadable directory in a node_modules above the project", + "ws/node_modules/private", + None, + ), + ( + "a link whose target lies behind an unreadable directory", + "locked", + Some("ws/app/vendor/x"), + ), + ] { + let (_tmp, base, root) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&root); + let locked = base.join(locked); + std::fs::create_dir_all(&locked).unwrap(); + std::fs::write(locked.join("file"), "").unwrap(); + if let Some(link) = link { + abs_link(&locked.join("file"), &base.join(link)); + } + assert_eq!( + live_copies(&root, &[&stale, &routed]).await, + vec![routed.clone()], + "{case}: while it can be read" + ); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let unreadable = std::fs::read_dir(&locked).is_err(); + let kept = live_copies(&root, &[&stale, &routed]).await; + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + if unreadable { + assert_eq!(kept, vec![stale, routed], "{case}"); + } } } + /// #2353: a `node_modules` that is a link to another checkout's (a git + /// worktree that shares the main checkout's install) belongs to a + /// project elsewhere. Its store is in neither the scanned worktree nor + /// a directory that holds it, so every entry is kept there, and the + /// leftover that only the worktree's member links stays a copy. From + /// the main checkout, which the worktree is no part of, nothing links + /// the leftover. + #[cfg(unix)] + #[tokio::test] + async fn test_pnpm_store_of_another_checkout_keeps_every_entry() { + let (_tmp, base, main) = pnpm_project_dir(); + let (_, stale, routed) = pnpm_hosted_route_leftover(&main); + // The worktree: the main checkout's install, its own member links. + let worktree = base.join("ws/worktree"); + write_pkg(&worktree.join("packages/a"), "a", "1.0.0"); + rel_link("../app/node_modules", &worktree.join("node_modules")); + rel_link( + "../../../node_modules/.pnpm/minimist@1.2.2/node_modules/minimist", + &worktree.join("packages/a/node_modules/minimist"), + ); + let copies: [&PathBuf; 2] = [&stale, &routed]; + let both = vec![stale.clone(), routed.clone()]; + + assert_eq!(live_copies(&main, &copies).await, vec![routed.clone()]); + assert_eq!(live_copies(&worktree, &copies).await, both); + assert_eq!( + live_copies(&worktree.join("packages/a"), &copies).await, + both + ); + } + /// #2353: pnpm links directories with junctions on Windows, which the - /// walk does not follow, so nothing is dropped there. + /// sweep does not read, so nothing is left out there. #[cfg(windows)] #[tokio::test] - async fn test_pnpm_store_orphans_are_kept_on_windows() { - let tmp = tempfile::tempdir().unwrap(); - let root: PathBuf = tmp.path().components().collect(); - let (nm, stale, routed) = pnpm_hosted_route_orphan(&root); + async fn test_pnpm_store_leftovers_are_kept_on_windows() { + let (_tmp, _, root) = pnpm_project_dir(); + let (nm, stale, routed) = pnpm_hosted_route_leftover(&root); assert_eq!( live_copies(&root, &[&nm.join("minimist"), &stale, &routed]).await, vec![nm.join("minimist"), stale, routed] From c12ac25fe2ac2fccd81158cf005a5d89de9c6e0a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:28:49 -0500 Subject: [PATCH 12/22] Test vex over the in-place pnpm install in a workspace, link by link The real-pnpm suites ran the in-place install in a one-importer project. Two more legs per pnpm (11 and 12, on the registry route) run it in a workspace where the patched package is hoisted and is also the peer dependency of a tarball package. That is the layout in which the old entry of the dependent keeps its link to the old entry of the patched package (#2353): - `vex` attests both patches after the install. - A link to the upstream entry from `vendor/`, `dist/`, a hidden directory or a real package's own `node_modules` makes `vex` refuse the patch as `not_applied` until the link is gone. - Under `modulesDir: sub/node_modules` the store sits in `sub/node_modules/.pnpm` and each member's links in `/sub/node_modules` (measured on pnpm 10.12.1, 10.34.9, 11.29.0 and 12.25.1; 9.15.9 and 10.11.1 keep the store in `node_modules/.pnpm`). Every entry is hashed there, so both patches stay refused. A run from a member finds no patch to attest: the scan's files are the workspace root's. `tests/common/pnpm_links.rs` reads the links a second time, with its own walk and none of the crates' code. Where `vex` attests, no path from outside the store's entries may lead into an entry that holds the upstream bytes; where a link was added, it must find that link. The registry-route leg and the vendored capstone that already ran the install use it too, and the capstone links the upstream entry from `vendor/` to see the warning come back. Offline, the hosted suite builds the nested `modulesDir` store by hand. The store of another checkout now holds both entries of the package, so that the test shows unrelated directories keeping them, and not a version that sits in one entry. `apply --check` is run from inside a workspace member: it is in sync while nothing links the entry that holds the original bytes, and a link to that entry from `vendor/` at the workspace root is drift, which shows that the whole project is read. Ran with `SOCKET_PATCH_PNPM_E2E_REQUIRED=1` on pnpm 12.23.0 and 11.29.0 (the route legs), 10.34.9, 9.15.9 and 11.29.0 (the vendored capstone) and 12.25.1 (its pinned matrix leg). Co-Authored-By: Claude Fable 5.2 --- .../apply/check_verifies_installed_tree.rs | 119 ++++- crates/socket-patch-cli/tests/common/mod.rs | 4 + .../tests/common/pnpm_links.rs | 96 ++++ .../tests/e2e_redirect_pnpm_build.rs | 434 +++++++++++++++++- .../tests/e2e_vendor_pnpm_build.rs | 43 +- .../tests/e2e_vex_redirect.rs | 128 ++++-- .../tests/rollback/rollback_failure_paths.rs | 5 +- 7 files changed, 785 insertions(+), 44 deletions(-) create mode 100644 crates/socket-patch-cli/tests/common/pnpm_links.rs diff --git a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs index 7509bd9b94..e895ff6bed 100644 --- a/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs +++ b/crates/socket-patch-cli/tests/apply/check_verifies_installed_tree.rs @@ -521,11 +521,11 @@ fn check_remedy_keeps_global_prefix_and_heals_the_checked_tree() { /// unlinked entry of another peer set that holds the original bytes, and /// an unpatched linked copy is drift beside a patched unlinked one. /// -/// A link in any `node_modules` of the project counts, also one that no -/// lockfile names and that reaches the entry through another package: a -/// directory that left the workspace still loads what its links reach, -/// so the original bytes there are drift until that `node_modules` is -/// gone. +/// Every link below the project counts, also one in a `node_modules` +/// that no lockfile names and that leads to the entry through another +/// package: a directory that left the workspace still loads what its +/// links lead to, so the original bytes there are drift until that +/// `node_modules` is gone. #[cfg(unix)] #[test] fn check_judges_the_pnpm_store_entry_the_install_links() { @@ -615,3 +615,112 @@ fn check_judges_the_pnpm_store_entry_the_install_links() { check(true, "nothing reaches the original copy any more"); } } + +/// #2353: a run from inside a workspace member reads the links of the +/// whole project that holds the store, not of the member alone. The +/// member's manifest patches `check-target`, and the member links the +/// patched entry; the entry of another peer set holds the original bytes +/// with nothing linking to it, so the member is in sync. A link to that +/// entry from `vendor/` at the workspace root, outside the member, is a +/// way to load it, and is drift until it is gone. +#[cfg(unix)] +#[test] +fn check_from_a_workspace_member_reads_the_links_of_the_whole_project() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_root_package_json(root); + let member = root.join("packages/a"); + std::fs::create_dir_all(&member).unwrap(); + std::fs::write( + member.join("package.json"), + r#"{ "name": "a", "version": "1.0.0", "dependencies": { "check-target": "1.0.0" } }"#, + ) + .unwrap(); + write_manifest( + &member, + json!({ PURL: patch_record( + "28282828-2828-4282-8282-282828282828", + one_file("index.js", ORIGINAL, PATCHED), + )}), + ); + let nm = root.join("node_modules"); + let store = nm.join(".pnpm"); + let (linked, unlinked) = ( + "check-target@1.0.0_peer@2.0.0", + "check-target@1.0.0_peer@1.0.0", + ); + for (entry, bytes) in [(linked, PATCHED), (unlinked, ORIGINAL)] { + let pkg = store.join(entry).join("node_modules/check-target"); + std::fs::create_dir_all(&pkg).unwrap(); + std::fs::write( + pkg.join("package.json"), + r#"{ "name": "check-target", "version": "1.0.0" }"#, + ) + .unwrap(); + std::fs::write(pkg.join("index.js"), bytes).unwrap(); + } + // What the install records beside the packages (pnpm 12.25.1). + std::fs::write( + nm.join(".modules.yaml"), + r#"{"hoistedDependencies":{},"hoistPattern":["*"],"layoutVersion":5,"nodeLinker":"isolated","packageManager":"pnpm@12.25.1","publicHoistPattern":[],"virtualStoreDir":".pnpm"}"#, + ) + .unwrap(); + std::fs::write( + store.join("lock.yaml"), + "lockfileVersion: '9.0'\n\nimporters:\n\n .: {}\n\n packages/a:\n dependencies:\n \ + check-target:\n specifier: 1.0.0\n version: 1.0.0(peer@2.0.0)\n\n\ + packages:\n\n check-target@1.0.0:\n resolution: {integrity: sha512-x}\n\n\ + snapshots:\n\n check-target@1.0.0(peer@2.0.0): {}\n", + ) + .unwrap(); + std::fs::create_dir_all(member.join("node_modules")).unwrap(); + std::os::unix::fs::symlink( + format!("../../../node_modules/.pnpm/{linked}/node_modules/check-target"), + member.join("node_modules/check-target"), + ) + .unwrap(); + + let check = |in_sync: bool, what: &str| { + let (code, stdout, stderr) = run_check(&member, &["--json"]); + let env = parse_json_envelope(stdout.trim()); + if in_sync { + assert_eq!(code, 0, "{what}: {env}\n{stderr}"); + } else { + assert_eq!(code, 1, "{what}: {env}\n{stderr}"); + assert!( + events(&env).iter().any(|e| e["action"] == "failed" + && e["purl"] == PURL + && e["errorCode"] == "not_applied"), + "{what}: {env}" + ); + } + }; + check( + true, + "nothing links the entry that holds the original bytes", + ); + + let stray = root.join("vendor/check-target"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink( + format!("../node_modules/.pnpm/{unlinked}/node_modules/check-target"), + &stray, + ) + .unwrap(); + check( + false, + "vendor/ at the workspace root loads the original copy", + ); + std::fs::remove_file(&stray).unwrap(); + check(true, "the link is gone"); + + // The member's own link decides as before. + std::fs::write( + store + .join(linked) + .join("node_modules/check-target/index.js"), + ORIGINAL, + ) + .unwrap(); + check(false, "the copy the member links holds the original bytes"); +} diff --git a/crates/socket-patch-cli/tests/common/mod.rs b/crates/socket-patch-cli/tests/common/mod.rs index b561772c2d..9bd2974d34 100644 --- a/crates/socket-patch-cli/tests/common/mod.rs +++ b/crates/socket-patch-cli/tests/common/mod.rs @@ -57,6 +57,10 @@ pub mod fs_tree; /// The mock public proxy the hermetic `scan` suites answer with. pub mod scan_proxy; +/// An independent reading of the links into a pnpm virtual store, for the +/// real-pnpm suites to hold `vex` against. +pub mod pnpm_links; + // ── Binary discovery + invocation ───────────────────────────────────── /// Quick check whether `cmd` is on PATH. Used to soft-skip diff --git a/crates/socket-patch-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs new file mode 100644 index 0000000000..79021aad56 --- /dev/null +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -0,0 +1,96 @@ +//! An independent reading of which entries of a pnpm virtual store an +//! install can load (#2353), for the real-pnpm suites to hold `vex` +//! against. It shares no code with the crates under test: its own walk of +//! the tree and its own reading of every link. Reached as +//! `common::pnpm_links`, or on its own with +//! `#[path = "common/pnpm_links.rs"] mod pnpm_links;`. + +#![allow(dead_code)] + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; + +/// The entry of `store` that the real path `path` lies in: the name of +/// the store's child directory that holds it, unless that child is hidden +/// or the hoist directory `node_modules`. +fn entry_of(store: &Path, path: &Path) -> Option { + let name = path.strip_prefix(store).ok()?.components().next()?; + let name = name.as_os_str().to_str()?; + let is_entry = !name.starts_with('.') + && name != "node_modules" + && std::fs::symlink_metadata(store.join(name)).is_ok_and(|meta| meta.is_dir()); + is_entry.then(|| name.to_string()) +} + +/// Every symbolic link below `tree` with the real path it resolves to, +/// found by listing every real directory, whatever its name. A link whose +/// target is not there is left out. +fn links_below(tree: &Path) -> Vec<(PathBuf, PathBuf)> { + let mut links = Vec::new(); + let mut dirs = vec![tree.to_path_buf()]; + while let Some(dir) = dirs.pop() { + for child in std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{dir:?}: {e}")) { + let child = child.unwrap(); + let kind = child.file_type().unwrap(); + if kind.is_dir() { + dirs.push(child.path()); + } else if kind.is_symlink() { + if let Ok(target) = std::fs::canonicalize(child.path()) { + links.push((child.path(), target)); + } + } + } + } + links +} + +/// The entries of the virtual store `store` that a path which starts +/// below `tree` and outside the store's entries leads into: each entry +/// that a link outside the entries resolves into, each entry that a link +/// inside one of those resolves into, and so on. +pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { + let tree = std::fs::canonicalize(tree).unwrap(); + let store = std::fs::canonicalize(store).unwrap(); + let links = links_below(&tree); + let mut reachable = BTreeSet::new(); + loop { + let before = reachable.len(); + for (link, target) in &links { + let Some(to) = entry_of(&store, target) else { + continue; + }; + let from_reachable = + entry_of(&store, link).is_none_or(|from| reachable.contains(&from)); + if from_reachable { + reachable.insert(to); + } + } + if reachable.len() == before { + return reachable; + } + } +} + +/// The entries of the virtual store `store` that hold the package `name` +/// as a real directory whose `file` satisfies `holds`. +pub fn store_entries_holding( + store: &Path, + name: &str, + file: &str, + holds: impl Fn(&[u8]) -> bool, +) -> BTreeSet { + let store = std::fs::canonicalize(store).unwrap(); + let mut entries = BTreeSet::new(); + for child in std::fs::read_dir(&store).unwrap() { + let child = child.unwrap(); + let Some(entry) = entry_of(&store, &child.path()) else { + continue; + }; + let package = child.path().join("node_modules").join(name); + let real = std::fs::symlink_metadata(&package).is_ok_and(|meta| meta.is_dir()); + if real && std::fs::read(package.join(file)).is_ok_and(|bytes| holds(&bytes)) { + entries.insert(entry); + } + } + entries +} diff --git a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs index d591c76726..0a90ec3cab 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -91,6 +91,8 @@ mod fs_tree; mod cache_env; #[path = "common/hermetic.rs"] mod hermetic; +#[path = "common/pnpm_links.rs"] +mod pnpm_links; #[path = "vex_e2e_common/mod.rs"] mod vex_e2e_common; use vex_e2e_common::{ @@ -1921,8 +1923,8 @@ async fn registry_route_survives_resolution_and_cleans_up(pm: &str, tag: &str) { // copies the install links: both patches attest, and a linked copy // put back on the upstream bytes is refused again. // - // pnpm links directories with junctions on Windows, which vex's check - // of the store's links does not follow: it judges every entry there. + // pnpm links directories with junctions on Windows, which vex does not + // read as links: it judges every entry there. if !cfg!(windows) { let warm = tmp.path().join("warm"); std::fs::create_dir_all(&warm).unwrap(); @@ -1976,6 +1978,17 @@ async fn registry_route_survives_resolution_and_cleans_up(pm: &str, tag: &str) { patch.name ); } + // An independent reading of every link below the checkout agrees: + // no path from outside the store's entries leads into an entry + // that holds the upstream leaf. + let unpatched = pnpm_links::store_entries_holding(&entries, "leaf", "index.js", |bytes| { + !bytes.starts_with(MARKER.as_bytes()) + }); + let reachable = pnpm_links::reachable_store_entries(&warm, &entries); + assert!( + unpatched.contains("leaf@1.0.0") && unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream leaf, and a link leads into one: {reachable:?}" + ); // The leaf the install links, back on the upstream bytes (a new // file: pnpm's are hard links into its store). @@ -3319,6 +3332,423 @@ async fn pnpm11_registry_route_is_left_for_a_bazel_hub_added_later() { registry_route_is_left_for_a_bazel_hub_added_later(PNPM_TERTIARY, "pnpm11-bazel-hub").await; } +// ── the in-place install in a workspace (#2353) ───────────────────────── + +/// A workspace of the registry-route packages in `proj` that takes `leaf` +/// every way a patched package can be taken: member `a` through `mid` (so +/// pnpm hoists it), member `b` directly and as the peer dependency of the +/// local tarball `needs-leaf`, and the root through `peer-user`, itself +/// patched. `modules_dir` is the workspace's `modulesDir` setting, when it +/// has one; the root then pins pnpm in `engines`, since the scan takes the +/// pnpm that installed the project from `node_modules/.modules.yaml`, and +/// that record is written below the `modulesDir`. +#[cfg(unix)] +fn write_route_workspace(proj: &Path, registry: &MockServer, modules_dir: Option<&str>) { + let put = |path: &str, bytes: &[u8]| { + let path = proj.join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + }; + let engines = match modules_dir { + Some(_) => r#","engines":{"pnpm":">=11.20.0"}"#, + None => "", + }; + put( + "package.json", + format!( + r#"{{"name":"app","version":"1.0.0","private":true,"dependencies":{{"host":"1.0.0","peer-user":"1.0.0"}}{engines}}}"# + ) + .as_bytes(), + ); + put( + "packages/a/package.json", + br#"{"name":"a","version":"1.0.0","private":true,"dependencies":{"mid":"1.0.0"}}"#, + ); + put( + "packages/b/package.json", + br#"{"name":"b","version":"1.0.0","private":true,"dependencies":{"leaf":"1.0.0","needs-leaf":"file:../../needs-leaf-1.0.0.tgz"}}"#, + ); + let needs_leaf = RoutePackage { + name: "needs-leaf", + fields: serde_json::json!({"peerDependencies": {"leaf": "*"}}), + }; + put("needs-leaf-1.0.0.tgz", &route_tgz(&needs_leaf, false)); + let modules_dir = modules_dir.map_or(String::new(), |dir| format!("modulesDir: {dir}\n")); + put( + "pnpm-workspace.yaml", + format!("packages:\n - packages/*\n{modules_dir}").as_bytes(), + ); + put( + ".npmrc", + format!("registry={}/\n", registry.uri()).as_bytes(), + ); +} + +/// What `vex` says of the project at `dir`: its exit code, the advisories +/// it attests with their status, and its stderr. +#[cfg(unix)] +fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, String) { + let (code, stdout, stderr) = run_socket( + dir, + &[ + "vex", + "--product", + "pkg:npm/app@1.0.0", + "--api-url", + &server.uri(), + "--org", + ORG, + "--api-token", + "fake", + "--patch-server-url", + &server.uri(), + ], + ); + let statements = serde_json::from_str::(&stdout) + .ok() + .and_then(|vex| vex["statements"].as_array().cloned()) + .into_iter() + .flatten() + .filter_map(|statement| { + Some(( + statement["vulnerability"]["name"].as_str()?.to_string(), + statement["status"].as_str()?.to_string(), + )) + }) + .collect(); + (code, statements, stderr) +} + +/// The workspace of [`write_route_workspace`] in `proj`, installed from +/// the default registry, scanned, and installed again over the same +/// `node_modules`, as a scan asks. `None` when the fixture install fails +/// where the toolchain is not required. +#[cfg(unix)] +fn route_workspace_installed_in_place( + tmp: &Path, + proj: &Path, + pm: &str, + tag: &str, + server: &MockServer, +) -> Option<()> { + let cache = tmp.join("pnpm-cache"); + let store = format!("--store-dir={}", tmp.join("store").display()); + let chatter = |out: &Output| { + format!( + "stdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }; + let install = route_pnpm(&cache, proj, pm, &["install", &store]); + if !install.status.success() { + assert!( + !pnpm_required(), + "fixture install failed:\n{}", + chatter(&install) + ); + println!("SKIP {tag}: fixture install failed:\n{}", chatter(&install)); + return None; + } + let (code, stdout, stderr) = run_hosted(HostedDriver::Scan, proj, &server.uri(), &[]); + assert_eq!( + code, 0, + "{tag}: scan failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + let workspace = std::fs::read_to_string(proj.join("pnpm-workspace.yaml")).unwrap(); + for patch in &ROUTE_PATCHES { + assert!( + workspace.contains(&patch.override_line()), + "{tag}: the scan routes {}:\n{workspace}", + patch.name + ); + } + let install = route_pnpm(&cache, proj, pm, &["install", &store]); + assert!( + install.status.success(), + "{tag}: the in-place install:\n{}", + chatter(&install) + ); + Some(()) +} + +/// THE IN-PLACE INSTALL IN A WORKSPACE against a real pnpm (#2353), with +/// the patched `leaf` hoisted and also the peer dependency of a tarball +/// package. +/// +/// pnpm links every importer, the hoist directory and each dependent to +/// the entries of the patches' registries, and keeps the upstream entries +/// in the store. `needs-leaf`, which names `leaf` as a peer, gets a new +/// entry as well, and its old entry keeps its link to the upstream `leaf`: +/// the two old entries link each other and nothing else links either. +/// +/// * `vex` attests both patches. An independent reading of every link +/// below the project (`common/pnpm_links.rs`) agrees: no path that +/// starts outside the store's entries leads into an entry that holds +/// the upstream bytes. +/// * A link to the upstream `leaf` from `vendor/`, `dist/`, a hidden +/// directory or a real package's own `node_modules` is a path node can +/// load it by. The independent reading finds it, and `vex` refuses the +/// patch as `not_applied` until the link is gone. +#[cfg(unix)] +async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: &str) { + if !has_corepack_pm(pm) { + println!("SKIP {tag}: `corepack {pm}` unavailable"); + return; + } + let registry = MockServer::start().await; + mount_route_registry(®istry).await; + let server = MockServer::start().await; + mount_route_patch_server(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + write_route_workspace(&proj, ®istry, None); + if route_workspace_installed_in_place(tmp.path(), &proj, pm, tag, &server).is_none() { + return; + } + let [leaf, peer_user] = &ROUTE_PATCHES; + let not_affected = |patch: &RoutePatch| (patch.advisory(), "not_affected".to_string()); + let upstream = |bytes: &[u8]| !bytes.starts_with(MARKER.as_bytes()); + + // What pnpm left: both entries of each patched package, and the old + // entry of the peer-dependent tarball, still linked to the old leaf. + let store = proj.join("node_modules/.pnpm"); + let old_leaf = store.join("leaf@1.0.0/node_modules/leaf"); + for entry in [ + "leaf@1.0.0".to_string(), + format!("leaf@{}+1.0.0", leaf.alias()), + ] { + assert!( + store.join(&entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + let old_dependents: Vec = std::fs::read_dir(&store) + .unwrap() + .filter_map(|child| child.unwrap().file_name().into_string().ok()) + .filter(|entry| entry.starts_with("needs-leaf@")) + .filter(|entry| { + std::fs::canonicalize(store.join(entry).join("node_modules/leaf")) + .is_ok_and(|real| real == std::fs::canonicalize(&old_leaf).unwrap()) + }) + .collect(); + assert_eq!( + old_dependents.len(), + 1, + "{tag}: the old entry of the peer-dependent package keeps its link to the old leaf" + ); + for (through, name) in [ + ("node_modules/peer-user", "peer-user"), + ("packages/b/node_modules/leaf", "leaf"), + ("packages/b/node_modules/needs-leaf/../leaf", "leaf"), + ("packages/a/node_modules/mid/../leaf", "leaf"), + ("node_modules/.pnpm/node_modules/leaf", "leaf"), + ] { + let index = std::fs::read_to_string(proj.join(through).join("index.js")) + .unwrap_or_else(|e| panic!("{tag}: {name} through {through}: {e}")); + assert!( + index.starts_with(MARKER), + "{tag}: {through} loads the patched {name}:\n{index}" + ); + } + + // The independent reading: entries hold the upstream bytes, and no + // path from outside the entries leads into one. + let unpatched = + |name: &str| pnpm_links::store_entries_holding(&store, name, "index.js", upstream); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + for patch in &ROUTE_PATCHES { + let unpatched = unpatched(patch.name); + assert!( + !unpatched.is_empty(), + "{tag}: an entry must still hold the upstream {}", + patch.name + ); + assert!( + unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream {}, and a link leads into one: {reachable:?}", + patch.name + ); + } + assert!( + !reachable.contains(&old_dependents[0]), + "{tag}: nothing links the old entry of the peer-dependent package: {reachable:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex after the in-place install:\n{stderr}"); + for patch in &ROUTE_PATCHES { + assert!( + attested.contains(¬_affected(patch)), + "{tag}: {} must be attested after the in-place install: {attested:?}\n{stderr}", + patch.name + ); + } + + // A link to the upstream leaf, wherever it sits, is a way to load it. + let host = std::fs::canonicalize(proj.join("node_modules/host")).unwrap(); + for (from, link) in [ + ("vendor/", proj.join("vendor/leaf")), + ("dist/", proj.join("dist/leaf")), + ("a hidden directory", proj.join(".cache/tool/leaf")), + ( + "a real package's own node_modules", + host.join("node_modules/leaf"), + ), + ] { + std::fs::create_dir_all(link.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(&old_leaf, &link).unwrap(); + assert_eq!( + std::fs::read_to_string(link.join("index.js")).unwrap(), + route_index("leaf", false), + "{tag}: a link from {from} loads the upstream leaf" + ); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must find the link from {from}: {reachable:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex with a link from {from}:\n{stderr}"); + assert!( + !attested.contains(¬_affected(leaf)) && attested.contains(¬_affected(peer_user)), + "{tag}: a link from {from} to the upstream leaf must refuse its patch alone: \ + {attested:?}\n{stderr}" + ); + assert!( + stderr.contains("leaf@1.0.0") && stderr.contains("not_applied"), + "{tag}: a link from {from}: the refusal says why:\n{stderr}" + ); + std::fs::remove_file(&link).unwrap(); + } + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex without the links:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without the links leaf is attested again: {attested:?}\n{stderr}" + ); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm12_registry_route_in_place_install_is_judged_by_every_link() { + registry_route_in_place_install_is_judged_by_every_link(PNPM_NAMED_REGISTRY, "pnpm12-in-place") + .await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm11_registry_route_in_place_install_is_judged_by_every_link() { + registry_route_in_place_install_is_judged_by_every_link(PNPM_TERTIARY, "pnpm11-in-place").await; +} + +/// THE IN-PLACE INSTALL UNDER A NESTED `modulesDir` against a real pnpm +/// (#2353). With `modulesDir: sub/node_modules`, pnpm 10.12 and later put +/// the virtual store in `sub/node_modules/.pnpm` and link each member's +/// dependencies in `/sub/node_modules` (measured on 10.12.1, +/// 10.34.9, 11.29.0 and 12.25.1; earlier ones keep the store in +/// `node_modules/.pnpm`). The lockfile in the store still names the +/// members by their paths from the workspace root, and none of them is a +/// directory below `sub/`, the directory that holds the store's +/// `node_modules`. `vex` cannot tell which directory the members' links +/// are below, so it keeps every entry: the upstream entries the in-place +/// install left behind refuse both patches as `not_applied`, as before +/// #2353, although nothing links them. A run from a member finds no patch +/// to attest: the scan's files are the workspace root's. +#[cfg(unix)] +async fn registry_route_in_place_install_under_a_nested_modules_dir(pm: &str, tag: &str) { + if !has_corepack_pm(pm) { + println!("SKIP {tag}: `corepack {pm}` unavailable"); + return; + } + let registry = MockServer::start().await; + mount_route_registry(®istry).await; + let server = MockServer::start().await; + mount_route_patch_server(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let proj = tmp.path().join("proj"); + write_route_workspace(&proj, ®istry, Some("sub/node_modules")); + if route_workspace_installed_in_place(tmp.path(), &proj, pm, tag, &server).is_none() { + return; + } + let [leaf, _] = &ROUTE_PATCHES; + + // Where pnpm put the store and the members' links. + let store = proj.join("sub/node_modules/.pnpm"); + assert!( + store.is_dir() && !proj.join("node_modules/.pnpm").exists(), + "{tag}: the virtual store follows modulesDir" + ); + let routed = format!("leaf@{}+1.0.0", leaf.alias()); + for entry in ["leaf@1.0.0", routed.as_str()] { + assert!( + store.join(entry).is_dir(), + "{tag}: {entry} must be in the store after the in-place install" + ); + } + assert_eq!( + std::fs::canonicalize(proj.join("packages/b/sub/node_modules/leaf")).unwrap(), + std::fs::canonicalize(store.join(&routed).join("node_modules/leaf")).unwrap(), + "{tag}: a member's links sit in its own modulesDir" + ); + let current = std::fs::read_to_string(store.join("lock.yaml")).unwrap(); + assert!( + current.contains("\n packages/b:\n") && !proj.join("sub/packages").exists(), + "{tag}: the lockfile in the store names the members from the workspace root:\n{current}" + ); + // Nothing links the upstream entries here either. + let upstream = |bytes: &[u8]| !bytes.starts_with(MARKER.as_bytes()); + let unpatched = pnpm_links::store_entries_holding(&store, "leaf", "index.js", upstream); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + unpatched.contains("leaf@1.0.0") && unpatched.is_disjoint(&reachable), + "{tag}: {unpatched:?} hold the upstream leaf, unlinked: {reachable:?}" + ); + + let (code, attested, stderr) = route_vex(&proj, &server); + assert_ne!(code, 0, "{tag}: vex from the root: {attested:?}\n{stderr}"); + assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); + for patch in &ROUTE_PATCHES { + // Named as `@`, in a purl when it is the only one. + let release = format!("{}@{ROUTE_VERSION}", patch.name); + assert!( + stderr.contains(&release) && stderr.contains("not_applied"), + "{tag}: every entry is judged, so {} is refused:\n{stderr}", + patch.name + ); + } + let (code, attested, stderr) = route_vex(&proj.join("packages/b"), &server); + assert_ne!(code, 0, "{tag}: vex from a member: {attested:?}\n{stderr}"); + assert!(attested.is_empty(), "{tag}: {attested:?}\n{stderr}"); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm12_registry_route_in_place_install_under_a_nested_modules_dir() { + registry_route_in_place_install_under_a_nested_modules_dir( + PNPM_NAMED_REGISTRY, + "pnpm12-nested-modules-dir", + ) + .await; +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +#[serial_test::serial] +#[ignore = "wall-bound real-pnpm installs (~1min); runs on Linux and macOS as an e2e CI matrix leg"] +async fn pnpm11_registry_route_in_place_install_under_a_nested_modules_dir() { + registry_route_in_place_install_under_a_nested_modules_dir( + PNPM_TERTIARY, + "pnpm11-nested-modules-dir", + ) + .await; +} + /// #1074: with pnpm's `lockfile` setting off, pnpm neither reads nor /// writes `pnpm-lock.yaml` and installs the upstream package from the /// registry, so a hosted pin in the committed lock patches nothing. Over a diff --git a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs index 603b98e6b9..b3299aeb98 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_pnpm_build.rs @@ -862,7 +862,10 @@ const TREE_OUT_OF_SYNC: &str = "the installed tree does not match its vendored a /// entry of the vendored tarball and keeps the upstream entry in the /// store with nothing linking to it. `vex` judges the copy the install /// links: no `vendored_tree_out_of_sync` warning while that copy is -/// patched, and the warning again once it holds the upstream bytes. +/// patched, and the warning again once it holds the upstream bytes. An +/// independent reading of every link below the checkout +/// (`common/pnpm_links.rs`) agrees that nothing leads into the upstream +/// entry, and a link to it from `vendor/` brings the warning back. /// /// Runs in `tmp/warm`, a second checkout installed from `before` (the /// pre-vendor `package.json` and `pnpm-lock.yaml`) and the fixture's @@ -877,8 +880,8 @@ fn assert_in_place_install_verifies( before: (&[u8], &[u8]), bytes: (&[u8], &[u8]), ) { - // pnpm links directories with junctions on Windows, which vex's check - // of the store's links does not follow: it judges every entry there. + // pnpm links directories with junctions on Windows, which vex does not + // read as links: it judges every entry there. if cfg!(windows) { return; } @@ -994,6 +997,40 @@ fn assert_in_place_install_verifies( !stderr.contains(TREE_OUT_OF_SYNC), "{pm}: the linked copy is patched, and nothing links the upstream entry:\n{stderr}" ); + // An independent reading of every link below the checkout agrees: the + // upstream entry holds the upstream bytes, and no path from outside + // the store's entries leads into it. + let reachable = || common::pnpm_links::reachable_store_entries(&warm, &entries); + let unpatched = + common::pnpm_links::store_entries_holding(&entries, DEP, "index.js", |bytes| bytes == orig); + assert!( + unpatched.contains(&upstream_entry) && unpatched.is_disjoint(&reachable()), + "{pm}: {unpatched:?} hold the upstream package, and a link leads into one: {:?}", + reachable() + ); + + // A link to the upstream entry is a way to load it, in whatever + // directory it sits: the warning is back until the link is gone. + let stray = warm.join("vendor/old"); + std::fs::create_dir_all(stray.parent().unwrap()).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(stale.parent().unwrap(), &stray).unwrap(); + assert!( + reachable().contains(&upstream_entry), + "{pm}: the independent reading must find the link: {:?}", + reachable() + ); + let stderr = vex_warnings("with a link to the upstream entry"); + assert!( + stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: a link in vendor/ loads the upstream entry, so it must warn:\n{stderr}" + ); + std::fs::remove_file(&stray).unwrap(); + let stderr = vex_warnings("without the link to the upstream entry"); + assert!( + !stderr.contains(TREE_OUT_OF_SYNC), + "{pm}: nothing links the upstream entry any more:\n{stderr}" + ); // The linked copy back on the upstream bytes (a new file: pnpm's are // hard links into its store). diff --git a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs index a877632557..91e3082482 100644 --- a/crates/socket-patch-cli/tests/e2e_vex_redirect.rs +++ b/crates/socket-patch-cli/tests/e2e_vex_redirect.rs @@ -2723,15 +2723,17 @@ fn pnpm_hosted_ref_is_refused_while_a_node_modules_no_lockfile_names_loads_the_u ); } -/// #2353: a `node_modules` reached through a link belongs to a project -/// elsewhere. In a git worktree that shares the main checkout's install -/// (`worktree/node_modules -> ../main/node_modules`), the worktree's -/// member `a` links `dep@1.0.0`, whose `left-pad` link points at the -/// pristine `left-pad@1.3.0` entry; no member of the main checkout links -/// either. The store's lockfile names the main checkout's members, so its -/// entries are not judged from the worktree: every copy is hashed, and -/// the pristine one refuses the hosted patch, where it was dropped and -/// the patch attested from the lock's pin with nothing hashed. +/// #2353: a `node_modules` that is a link to another checkout's belongs +/// to a project elsewhere. A git worktree shares the main checkout's +/// install (`worktree/node_modules -> ../main/node_modules`), which holds +/// both `left-pad` entries after the in-place install. The worktree's +/// member `a` still links `dep@1.0.0`, whose `left-pad` link points at the +/// pristine `left-pad@1.3.0` entry; nothing in the main checkout links +/// either. The store is in neither the scanned worktree nor a directory +/// that holds it, so its entries are not judged from there: every copy is +/// hashed, and the pristine one refuses the hosted patch. From the main +/// checkout, which the worktree is no part of, nothing links the pristine +/// entry, and the patch attests. #[cfg(unix)] #[test] fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() { @@ -2741,35 +2743,27 @@ fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() ); let purl = "pkg:npm/left-pad@1.3.0"; let tmp = tempfile::tempdir().unwrap(); - // The main checkout holds the install, made before the scan. - let main = tmp.path().join("main"); - put( - &main, - "packages/a/package.json", - br#"{ "name": "a", "version": "1.0.0", "dependencies": { "dep": "1.0.0" } }"#, - ); + // The main checkout holds the install. + let main = &tmp.path().join("main"); + write_pnpm_member_routing_left_pad(main); let nm = main.join("node_modules"); - write_pnpm_install_record( - &nm, - b"lockfileVersion: '9.0'\n\nimporters:\n\n .:\n dependencies:\n is-number:\n \ - specifier: 7.0.0\n version: 7.0.0\n\n packages/a:\n dependencies:\n dep:\n \ - specifier: 1.0.0\n version: 1.0.0\n\npackages:\n\n dep@1.0.0:\n \ - resolution: {integrity: sha512-x}\n\n is-number@7.0.0:\n \ - resolution: {integrity: sha512-y}\n\n left-pad@1.3.0:\n \ - resolution: {integrity: sha512-z}\n\nsnapshots:\n\n dep@1.0.0:\n dependencies:\n \ - left-pad: 1.3.0\n\n is-number@7.0.0: {}\n\n left-pad@1.3.0: {}\n", - ); - put_pnpm_entry(&nm, "is-number@7.0.0", "is-number", "7.0.0", b"7\n"); - pnpm_link( - ".pnpm/is-number@7.0.0/node_modules/is-number", - &nm.join("is-number"), - ); + write_pnpm_install_record(&nm, &std::fs::read(main.join("pnpm-lock.yaml")).unwrap()); + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); put_pnpm_entry(&nm, "dep@1.0.0", "dep", "1.0.0", b"require('left-pad')\n"); pnpm_link( "../../left-pad@1.3.0/node_modules/left-pad", &nm.join(".pnpm/dep@1.0.0/node_modules/left-pad"), ); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + pnpm_link( + &format!("../../../node_modules/.pnpm/{routed}/node_modules/left-pad"), + &main.join("packages/a/node_modules/left-pad"), + ); // The worktree: the scan's files, the main checkout's install, and // its own member's link. let cwd = &tmp.path().join("worktree"); @@ -2783,14 +2777,84 @@ fn pnpm_hosted_ref_is_hashed_in_a_store_reached_through_a_linked_node_modules() UUID.to_string(), one_file_view(UUID, purl, "package/index.js", pristine, patched), )]); + let args = ["--proxy-url", &server.uri()]; - let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + let (code, env) = vex_json(cwd, &args); assert_eq!( code, Some(1), "the worktree's member loads the pristine copy: {env}" ); assert_eq!(skipped_reason(&env, purl), "not_applied", "{env}"); + + let (code, env) = vex_json(main, &args); + assert_attested( + main, + code, + &env, + UUID, + "nothing in the main checkout reaches the pristine entry", + ); +} + +/// #2353: with a `modulesDir` of more than one level, pnpm 10.12 and +/// later put the virtual store in `/.pnpm` and link each +/// member's dependencies in `/` (real pnpm 12.25.1 +/// layout). The lockfile in the store names the members from the +/// workspace root, and none of them is a directory below `sub/`, which +/// holds the store's `node_modules`. The store's entries are not judged +/// then: the pristine upstream entry is hashed and refuses the patch, +/// although nothing links it. The same workspace without the setting is +/// judged, and attests. +#[cfg(unix)] +#[test] +fn pnpm_hosted_ref_is_hashed_in_a_store_under_a_nested_modules_dir() { + let (pristine, patched) = ( + &b"module.exports = 'pristine'\n"[..], + &b"module.exports = 'patched'\n"[..], + ); + let purl = "pkg:npm/left-pad@1.3.0"; + let routed = format!("left-pad@socket-{}+1.3.0", &UUID[..8]); + for (modules_dir, attests) in [("node_modules", true), ("sub/node_modules", false)] { + let tmp = tempfile::tempdir().unwrap(); + let cwd = &tmp.path().join("app"); + write_pnpm_member_routing_left_pad(cwd); + if modules_dir != "node_modules" { + let workspace = cwd.join("pnpm-workspace.yaml"); + let text = std::fs::read_to_string(&workspace).unwrap(); + std::fs::write(workspace, format!("{text}modulesDir: {modules_dir}\n")).unwrap(); + } + let nm = cwd.join(modules_dir); + write_pnpm_install_record(&nm, &std::fs::read(cwd.join("pnpm-lock.yaml")).unwrap()); + put_pnpm_entry(&nm, "left-pad@1.3.0", "left-pad", "1.3.0", pristine); + put_pnpm_entry(&nm, &routed, "left-pad", "1.3.0", patched); + pnpm_link( + &format!("../{routed}/node_modules/left-pad"), + &nm.join(".pnpm/node_modules/left-pad"), + ); + // From `packages/a/` up to the workspace root. + let up = "../".repeat(2 + modules_dir.split('/').count()); + pnpm_link( + &format!("{up}{modules_dir}/.pnpm/{routed}/node_modules/left-pad"), + &cwd.join("packages/a").join(modules_dir).join("left-pad"), + ); + let (_rt, server) = serve_patch_views(vec![( + UUID.to_string(), + one_file_view(UUID, purl, "package/index.js", pristine, patched), + )]); + + let (code, env) = vex_json(cwd, &["--proxy-url", &server.uri()]); + if attests { + assert_attested(cwd, code, &env, UUID, modules_dir); + } else { + assert_eq!(code, Some(1), "{modules_dir}: {env}"); + assert_eq!( + skipped_reason(&env, purl), + "not_applied", + "{modules_dir}: {env}" + ); + } + } } /// The patch view for `name@version` (the [`left_pad_view`] shape). diff --git a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs index c74c901d1d..e0b118075f 100644 --- a/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs +++ b/crates/socket-patch-cli/tests/rollback/rollback_failure_paths.rs @@ -487,8 +487,9 @@ fn bun_orphaned_store_entry_is_still_rolled_back() { /// moved off (an in-place `pnpm install` of 7.0.0 re-linked the importer /// to the new entry) is an orphan nothing loads now, but a later install /// that resolves back to 6.0.0 re-links it as it is. Rollback must still -/// restore it: the orphan filter that keeps `vex` from judging the install -/// by such an entry is for checks of the live install only. +/// restore it, as it restores the entry an in-place install leaves behind +/// when a package changes its source: leaving an unlinked entry out is +/// for the checks of the live install (`vex`, `apply --check`) only. #[cfg(unix)] #[test] fn pnpm_store_entry_nothing_links_is_still_rolled_back() { From c86a2fd37e8aa5bb8f2ee1a1ee6ff1a27faec3a0 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 16:28:49 -0500 Subject: [PATCH 13/22] Document which pnpm store entries vex judges under the link sweep `CLI_CONTRACT.md`, `docs/ecosystems.md` and the pnpm compatibility notes described the first rule of this branch: the links of the `node_modules` the crawl searches, of the lockfiles' members and of the hoist directory. They now describe the rule in the code (#2353): - which entries are left out, and that only a package version that sits in two entries of one store is judged at all; - the tree whose links are read, and the `node_modules` above it; - every condition under which all entries are still hashed; - what was measured with real pnpm: the pair of old entries a hosted scan leaves when the patched package is a peer dependency, the `.bin` shims, and where a `modulesDir` of more than one level puts the store. What the sweep costs, for the record. Release builds, `vex --offline` on a pnpm 12.25.1 project of 1,222 store entries (7,377 directories, 4,111 links), 40 runs of each binary, interleaved, on a machine that was busy with other work (load average 21 to 34). The base is this branch's merge base, 1b3f422f9: state of the project merge base this branch one entry per patched version 50 / 75 ms 51 / 73 ms four versions in two entries each 44 / 98 ms 218 / 365 ms (minimum / median) Where no version sits in two entries nothing is read, and the run costs what it cost before. Where one does, the links are read once: 172 to 326 ms on that project, 0.8 to 1.8 s on a tree of 29,120 directories, and 5.6 to 7.6 s on one of 235,697, against 0.12 s and 4.8 s for `find -type l` on the first and the last. A project whose patched package has two peer variants pays for the sweep on every run, leftover or not. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- docs/ecosystems.md | 119 ++++++++++++++++-------- docs/testing/pnpm-compatibility.md | 55 ++++++++--- 3 files changed, 123 insertions(+), 53 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8cd9bd78af..8af6181c7b 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -817,7 +817,7 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | -**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link reaches is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm the links read are those of every `node_modules` the crawl searches (the project root's and each one below it, so also the one a directory keeps after it leaves the workspace), of each workspace member the lockfile in the store or `pnpm-lock.yaml` names, of the store's hoist directory `node_modules/.pnpm/node_modules`, and of each reached entry's own `node_modules`; every store is judged once per run, by the same links for the record check and the hosted one. A copy in an entry that such a link reaches is always hashed, whatever the entry is named. A link in a `node_modules` that the crawl does not search and no lockfile names is not read, as a package installed there is not found. Where pnpm's links cannot all be read (Windows, a store whose own `node_modules` the crawl does not search or reaches through a link, `node-linker=hoisted`, `shamefully-hoist`, a moved virtual store, an unreadable directory; `docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list), every entry is hashed. `rollback` and `remove` restore unlinked entries too. +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store; a version in one entry is hashed as before, linked or not. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it) and in each `node_modules` of a directory above it, in every directory whatever its name. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout); under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or a lockfile is missing, unreadable or not laid out as pnpm writes it; when a lockfile names an importer that is not a directory inside the store's project (also a `modulesDir` of more than one level); when a directory or a link cannot be read; when a link resolves to a directory outside what was read, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2cc216acee..17d78ac7cb 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -796,49 +796,86 @@ hosted scan that routes the release through the registry of its patch (pnpm 11.20 and later), `@file+…` after a vendored scan (`file+…` on pnpm 8 and earlier). The upstream `@` entry stays in the store with nothing linking to it. `vex` and `apply --check` judge the -copies the install loads, so they skip a pnpm store entry that no link -reaches, as they skip one in Bun's store, which Bun never prunes. A link -reaches an entry from: - -- any `node_modules` the crawl searches (see the top of this section): the - project root's, each workspace member's, and the one a directory keeps - after it leaves the workspace, since node run from there still loads - what its links reach; -- the `node_modules` of a workspace member named by the lockfile pnpm - writes in the store or by `pnpm-lock.yaml`, wherever it sits (a member - that is not on disk links nothing); -- the store's hoist directory, `node_modules/.pnpm/node_modules`; -- the `node_modules` of an entry that is itself reached (a transitive - dependency has no other link). - -A copy in an entry that such a link reaches is always judged, whatever the -entry is named: an unpatched one still omits the patch (`not_applied`) or -warns (`vendored_tree_out_of_sync`). A link in a `node_modules` that the -crawl does not search and no lockfile names (below `dist/` or a hidden -directory, or outside the project) is not read, as a package installed -there is not found. - -Where the links cannot all be read, every entry is judged, as before: +copies the install loads, so they leave that entry out, as they leave out +an unlinked entry of Bun's store, which Bun never prunes. + +For pnpm the rule is narrow: + +- It applies to a package version only when its copies sit in two or more + entries of one store, which is what such an install leaves. A version + that sits in one entry is judged as before, whether or not anything + links it (a removed package, an upgraded-away version), and the project + is not read for it. +- For a version in two entries, every symbolic link below one directory + is read: the scanned directory, or the project that holds the store's + `node_modules` when the scan started inside it (a run from a workspace + member reads the whole project). No directory is skipped by name, so a + link in `vendor/`, `dist/`, a hidden directory, a package's own + `node_modules` or a directory that left the workspace counts. Node also + looks a package up in the `node_modules` of every directory above the + one it starts in, so each `node_modules` above that directory is read + the same way. A link is resolved, never followed. +- An entry is judged when a link that sits outside the store's entries + resolves into it (into its package, a file of it, or the entry itself), + or when a link inside a judged entry does. The store's hoist directory, + `node_modules/.pnpm/node_modules`, is outside the entries. The entries + left out are those that only other left-out entries link. + +The last case is real. When the patched package is a peer dependency of +another package, a hosted scan gives the dependent a new entry as well +(`_@socket-+`), and the dependent's old +entry keeps its link to the old `@` entry (measured on pnpm +11.29.0 and 12.25.1). Nothing outside the two links either, so both are +left out. A vendored scan keeps the dependent's entry and points its link +at the new one. + +A copy in a judged entry is always hashed, whatever the entry is named: an +unpatched one still omits the patch (`not_applied`) or warns +(`vendored_tree_out_of_sync`). So is a copy that sits in the store but in +none of its entries (a package that is a real directory of the hoist +directory). Only links are read: a script or a setting that spells out +the path of a store entry is not. + +Wherever a link into an entry may have gone unread, every entry is +judged, as before: - on Windows, where pnpm links directories with junctions; -- when the crawl does not search the store's own `node_modules` as a real - directory of its project: a run from inside a workspace member, or a - `node_modules` that is a link to another checkout's (a git worktree - that shares an install), whose lockfiles describe that other project; -- under `node-linker=hoisted` or `shamefully-hoist` (a `publicHoistPattern` - of `*`), or a store layout other than the one pnpm 6 to 12 write; -- when `virtualStoreDir` moved the virtual store, or the install record - (`node_modules/.modules.yaml`) or the lockfile in the store is missing - or unreadable; -- when the store, the type of one of its entries, a `node_modules`, a - `@scope` directory, a link or `pnpm-lock.yaml` cannot be read; -- when one of the two lockfiles names a workspace member that is on disk - and is not a directory, or does not list its importers the way pnpm - writes them (a merge conflict left in the file, for one); -- when the `node_modules` of the project or of a member that a lockfile - names, or the hoist directory, holds a package as a real directory, - which the isolated linker never writes; -- when no link reaches the store at all. +- when the scanned directory neither holds the store's project nor lies + inside it: a `--global` run, or a `node_modules` that is a link to + another checkout's (a git worktree that shares an install); +- when the install record (`node_modules/.modules.yaml`) is missing or + unreadable, or records `node-linker=hoisted` or `pnp`, `shamefully-hoist` + (a `publicHoistPattern` of `*`), a store layout other than the one pnpm + 6 to 12 write, or another virtual store (`virtualStoreDir`); +- when the lockfile pnpm writes in the store + (`node_modules/.pnpm/lock.yaml`) is missing or unreadable, + `pnpm-lock.yaml` is unreadable, or either one does not list its + importers the way pnpm writes them (a merge conflict left in the file, + for one); +- when an importer that either lockfile names is not a directory inside + the project that holds the store: one outside it (`../shared`, an + absolute path, a link that leads out), one that is not on disk (a + checkout of part of a workspace), or a file. pnpm links each importer's + dependencies below the importer, so such links would not be read. A + `modulesDir` of more than one level falls under this too: pnpm 10.12 + and later put the store in `/.pnpm` and each member's links + in `/`, so no member is below the directory that + holds the store; +- when a directory that is read, the type of one of its children or the + target of a link cannot be read (a link whose target is not there is + left out), or one tree holds more than 1,000,000 directories; +- when a link resolves to a directory outside what was read: what the + `node_modules` of that directory links is not read. A `link:` + dependency on another checkout is such a link. So are a pnpm + workspace's links to its members, for a project that sits in that + workspace's checkout without being a member of it and is scanned from + its own directory; +- when a link resolves into the store by a path that names none of its + entries: the store's own path spelled another way (macOS reaches a + volume under `/System/Volumes/Data` as well), or a child of the store + that is not one of the entries it lists (a name in another case, on a + file system that folds case); +- when no link resolves into any entry at all. `rollback` and `remove` restore an unlinked entry too: a later install that resolves back to it links it as it is. diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index 85810aede4..6f70ac3d73 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -324,21 +324,54 @@ bytes and nothing linking to it. pnpm 7–11 remove such an entry after 7 days, pnpm 12 on `pnpm prune`. With `trustLockfile` the lock key stays, and pnpm keeps the one entry. -`vex` and `apply --check` judge the copies the install links, and skip an -entry that no link reaches (see "npm: which `node_modules` trees are crawled" -in [ecosystems](../ecosystems.md) for the links that are read and for the -layouts where every entry is still judged, Windows among them). There the -upstream entry reads as an unpatched copy until it is gone: `vex` omits a -hosted patch as `not_applied`, or warns `vendored_tree_out_of_sync` for a -vendored one. A clean `node_modules` has no such entry. +When the patched package is a peer dependency of another package, the +registry route gives the dependent a new entry as well +(`_@socket-+`), and the dependent's old entry +keeps its link to the old `@` entry (pnpm 11.29.0 and +12.25.1). Vendored mode keeps the dependent's entry and points its link at +the new one (pnpm 8.15.9, 9.15.9, 10.34.9 and 12.25.1). pnpm 12.25.1 writes +the path of the store entry into each `.bin` shim and rewrites the shim on +that install; pnpm 8.15.9, 9.15.9, 10.34.9 and 11.29.0 start a bin through +the package link beside the shim. + +`vex` and `apply --check` judge the copies the install links. For a package +version that sits in two entries of one store they read every link below +the scanned directory, and leave out an entry that no path from outside +the store's entries leads into (see "npm: which `node_modules` trees are +crawled" in [ecosystems](../ecosystems.md) for the rule and for the layouts +where every entry is still judged, Windows among them). There the upstream +entry reads as an unpatched copy until it is gone: `vex` omits a hosted +patch as `not_applied`, or warns `vendored_tree_out_of_sync` for a vendored +one. A clean `node_modules` has no such entry. + +One such layout is a workspace with a `modulesDir` of more than one level. +Measured with `modulesDir: sub/node_modules`: pnpm 10.12.1, 10.34.9, 11.29.0 +and 12.25.1 put the virtual store in `sub/node_modules/.pnpm` and each +member's links in `/sub/node_modules`; pnpm 9.15.9 and 10.11.1 put +the links and the install record there too, but keep the virtual store in +`node_modules/.pnpm`. Either way every entry is judged, so the upstream +entry refuses the patch until it is gone. The registry-route legs above and the vendored capstone (`e2e_vendor_pnpm_build`, on each pnpm of its matrix from 9 up) run that install in a second checkout and end in `vex`, with the linked copy patched -and then put back on the upstream bytes. Hand-built stores of the same -shapes cover the rule offline: `crawlers::npm_crawler` (`test_pnpm_store_*`), -`e2e_vex_redirect`, `e2e_vex_vendor` and the `rollback` suite, which restores -an unlinked entry. +and then put back on the upstream bytes; the capstone also links the +upstream entry from `vendor/`, which brings the warning back. Two more +registry-route legs run the install in a workspace whose patched package is +hoisted and is also the peer dependency of a tarball package +(`*_in_place_install_is_judged_by_every_link`, +`*_in_place_install_under_a_nested_modules_dir`; not on Windows): `vex` +attests both patches; a link to the upstream entry from `vendor/`, `dist/`, +a hidden directory or a package's own `node_modules` refuses the patch +until the link is gone; and under the nested `modulesDir` the patches stay +refused. Where `vex` attests, a second reading of the links +(`tests/common/pnpm_links.rs`, which shares no code with the CLI) checks +that no path from outside the store's entries leads into an entry that +holds the upstream bytes, and where a link was added it must find that +link. Hand-built stores of the same shapes cover the rule offline: +`crawlers::npm_crawler` (`test_pnpm_store_*`, `test_links_below_*`), +`e2e_vex_redirect`, `e2e_vex_vendor`, the `apply --check` suite and the +`rollback` suite, which restores an unlinked entry. ## Run locally From cf936642798725b3a61fef29094e48b61cd11272 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Tue, 1 Dec 2026 17:04:14 -0500 Subject: [PATCH 14/22] Read no links above the scanned project for a pnpm store The sweep that decides which entries of a pnpm store an install links (#2353) also read each node_modules of a directory above the scanned one. pnpm writes no link there into a store below it, so the read only guarded against a link placed by hand, and it had a cost: with the rule that keeps every entry when a link leads to a directory that is not read, a project that sits in another pnpm workspace's checkout was never judged (that workspace links its members from its own node_modules), every judged run read the outer install, and the outcome depended on directories nobody scanned. The links read are now those below the scanned directory, or below the project that holds the store when the scan started inside it. A link to a directory outside it still keeps every entry. The docs say what is not read: links above that directory, a path to an entry that a file spells out, and NODE_PATH. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/crawlers/npm_crawler.rs | 108 ++++++------------ docs/ecosystems.md | 34 +++--- 3 files changed, 54 insertions(+), 90 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8af6181c7b..bd80ee6e4f 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -817,7 +817,7 @@ Recognition rules that hold for every ecosystem: | Hosted: a discovered patch-host reference (or a live pre-v5 redirect-ledger record) | The installed copies the build **consumes** through the hosted wiring are hash-verified when any exist: the Go replacement module, never the pristine `M@v` in the module cache; the Socket-registry cargo source dir; maven's suffixed version. Installed evidence wins: `hash_mismatch` / `not_applied` are omitted. With **nothing installed**, a discovered reference whose lock pins the artifact (or whose format's rewriter never writes a pin) attests from that pin, which is the same evidence as in-run `scan --mode hosted --vex`. A pre-v5 ledger-only record, or a reference whose required pin is missing, stays `package_not_found`. So do purls that `--ecosystems` kept out of the crawl, because "not installed" has to mean the crawler looked. The same goes for npm purls when an installed pnpm tree records its virtual store outside the project (`enableGlobalVirtualStore`, or a `virtualStoreDir` that climbs out): transitive deps there are invisible to the crawler. A pnpm `modulesDir` inside the project is crawled. A Composer purl is omitted as `composer_install_unread` instead when `composer.json`'s `config.vendor-dir` puts the install outside the project (an absolute path, `~/…`, `$VAR/…`, or one that climbs out) and an install is there (its `composer/installed.json` exists, or the directory cannot be resolved): the crawler reads no tree outside the project that only a project file names, so that install was not checked and may predate the redirect (#686). While nothing is installed there the pin still attests, and with `COMPOSER_VENDOR_DIR` set to the directory the crawler reads it and the installed bytes decide. A yarn Plug'n'Play project (`.pnp.cjs` / `.pnp.js`) has no tree to crawl: an npm purl there attests from the lock's pin only when the PnP loader itself resolves it through the patch (berry names the hosted url, yarn 1 the resolved url's `#` in its cache folder). A loader written before the lock was rewired runs the registry copy, so the purl stays omitted until `yarn install` rewrites it (#519). | `(redirected)` | | Agent: a manifest record with no live hosted/vendored wiring | The installed tree, unchanged. **Every** installed copy the crawler finds for the purl (npm nests duplicates of one `name@version`; pnpm, vlt, Bun and Deno stores add peer-variant copies and copies bundled inside other packages) must hash to the patched bytes, as `apply` patches every copy (Maven: every copy a build consumes, Gradle hash dirs included — see [Gradle builds](#gradle-builds-v50)). One unpatched copy omits the purl with that copy's tag (`not_applied` / `hash_mismatch`). | none | -**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store; a version in one entry is hashed as before, linked or not. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it) and in each `node_modules` of a directory above it, in every directory whatever its name. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout); under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or a lockfile is missing, unreadable or not laid out as pnpm writes it; when a lockfile names an importer that is not a directory inside the store's project (also a `modulesDir` of more than one level); when a directory or a link cannot be read; when a link resolves to a directory outside what was read, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. +**Unlinked store entries.** In every row an installed copy is one the install can load. Bun never prunes `node_modules/.bun`, and pnpm keeps a `node_modules/.pnpm` entry it no longer uses (pnpm 7–11 for up to 7 days, pnpm 12 until `pnpm prune`). After the in-place install that a hosted or vendored scan asks for, the project links a new entry (on pnpm, `@socket-+` for a release routed through the registry of its patch and `@file+…` for a vendored tarball, `file+…` on pnpm 8 and earlier), and the upstream `@` entry stays in the store, pristine. An entry that no link leads into is not an installed copy: `vex` and `apply --check` do not hash it, so it neither omits a patch as `not_applied` nor warns `vendored_tree_out_of_sync`. For pnpm this applies to a package version only when its copies sit in two or more entries of one store; a version in one entry is hashed as before, linked or not. For a version in two entries, every symbolic link is read below the scanned directory (or below the project that holds the store, when the scan started inside it), in every directory whatever its name; nothing above that directory is read. An entry is hashed when a link outside the store's entries resolves into it, or a link inside a hashed entry does; the entries left out are those that only other left-out entries link (a hosted scan leaves such a pair when the patched package is a peer dependency: the dependent gets a new entry, and its old entry keeps its link to the old one). A copy in the store but in none of its entries is always hashed. Only links are read, not a path to an entry that a file spells out or `NODE_PATH` names. Every store is judged once per run, by the same links for the record check and the hosted one. Where a link may have gone unread, every entry is hashed: on Windows; when the scanned directory and the store's project are unrelated (`--global`, a `node_modules` linked from another checkout); under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or a lockfile is missing, unreadable or not laid out as pnpm writes it; when a lockfile names an importer that is not a directory inside the store's project (also a `modulesDir` of more than one level); when a directory or a link cannot be read; when a link resolves to a directory outside the directory that was read, or into the store by a path that names none of its entries (another spelling of the store's path or of an entry's name); and when no link resolves into any entry (`docs/ecosystems.md`, "npm: which `node_modules` trees are crawled", has the list). `rollback` and `remove` restore unlinked entries too. **Liveness gates.** These gates run before hashing, and `--no-verify` / `--vex-no-verify` skips only the hashing, never the gates: diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 3dbaf20f55..dc9f23a2af 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -902,10 +902,9 @@ fn orphaned_pnpm_store_entry_sync( /// its link to the old one (measured on pnpm 11.29.0 and 12.25.1). /// /// `tree` is the outer of the directory `scanned` and the directory that -/// holds the store's `node_modules`. Node looks a package up in the -/// `node_modules` of every directory above the one it starts in, so each -/// `node_modules` of a directory above `tree` is read the same way. A -/// link anywhere else is not read, so every entry is kept wherever pnpm +/// holds the store's `node_modules`. A link outside it is not read (one +/// in a `node_modules` above it, which pnpm does not write into this +/// store, or in another checkout), so every entry is kept wherever pnpm /// may have written one there, or the links cannot all be read or /// followed: /// @@ -928,12 +927,12 @@ fn orphaned_pnpm_store_entry_sync( /// members that are not found there show that this directory is not /// the workspace's root (a `modulesDir` of more than one level puts the /// store below it); -/// - when a directory that is read, the type of one of its children or -/// the target of a link cannot be read, or one of the trees holds more -/// than [`LINK_SWEEP_DIR_BUDGET`] directories; -/// - when a link resolves to a directory outside the trees read (a -/// `link:` dependency on another checkout): what its `node_modules` -/// links is not read; +/// - when a directory below `tree`, the type of one of its children or +/// the target of a link cannot be read, or `tree` holds more than +/// [`LINK_SWEEP_DIR_BUDGET`] directories; +/// - when a link resolves to a directory outside `tree` (a `link:` +/// dependency on another checkout, a former workspace member): what +/// its `node_modules` links is not read; /// - when a link resolves into the store by a path that is spelled /// another way than the store's (macOS reaches a volume under /// `/System/Volumes/Data` as well), or to a child of the store that @@ -993,33 +992,18 @@ fn live_pnpm_store_entries_sync( } } let entries = pnpm_store_entry_names(list_dir_sync(&store))?; - // Node climbs past `tree`: the `node_modules` above it are read too. - let mut trees = vec![tree.to_path_buf()]; - for above in tree.ancestors().skip(1) { - match std::fs::canonicalize(above.join("node_modules")) { - Ok(nm) if nm.is_dir() => trees.push(nm), - Ok(_) => {} - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(_) => return None, - } - } - let mut swept = Vec::with_capacity(trees.len()); - for tree in &trees { - let links = sweeps - .entry(tree.clone()) - .or_insert_with(|| links_below_sync(tree).map(Arc::new)); - swept.push(links.clone()?); - } - let links = || swept.iter().flat_map(|links| links.iter()); - - // A link that leads out of the trees read: a directory behind it is - // not read, and a path spelled another way than `store` may still lie - // in it. The directories found to be no part of the store are checked - // once. + let links = sweeps + .entry(tree.to_path_buf()) + .or_insert_with(|| links_below_sync(tree).map(Arc::new)) + .clone()?; + + // A link that leads out of `tree`: a directory behind it is not read, + // and a path spelled another way than `store` may still lie in it. + // The directories found to be no part of the store are checked once. let store_id = same_file::Handle::from_path(&store).ok()?; let mut elsewhere: HashSet<&Path> = HashSet::new(); - for link in links() { - if trees.iter().any(|tree| link.target.starts_with(tree)) { + for link in links.iter() { + if link.target.starts_with(tree) { continue; } if link.target.is_dir() { @@ -1059,7 +1043,7 @@ fn live_pnpm_store_entries_sync( let mut frontier: Vec<&OsStr> = Vec::new(); // The entries each entry's own links resolve into. let mut linked: HashMap<&OsStr, Vec<&OsStr>> = HashMap::new(); - for link in links() { + for link in links.iter() { let Some(target) = entry_of(&link.target) else { if in_unlisted_child(&link.target) { return None; @@ -1377,9 +1361,10 @@ fn expand_workspace_pattern_sync(root: &Path, pattern: &str) -> Option