From 60fcaa086f606609e1ca23e1f3339e76efa03e4f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 2 Dec 2026 01:23:54 -0500 Subject: [PATCH 1/3] Follow a link that leads out of the project instead of keeping every pnpm entry A link in the project to a directory outside it kept every pnpm store entry, because what that directory's `node_modules` link was not read (#2430). One such link switched the fix of #2353 off for the whole project, and every Bazel workspace has four of them (`bazel-bin`, `bazel-out`, `bazel-testlogs`, `bazel-`); a `link:` dependency on another checkout is one too. Such a link is now followed, since node loads what is behind it from where it really is. A directory behind it is read like the project. So is each `node_modules` in a directory above it, or above a file behind such a link, which is where node looks up the packages of what it loads from there: a member that left the workspace keeps the links pnpm wrote for it. The home directory and what lies above it are not looked at, as in git's own lookup. One budget of 500,000 directories and links holds for everything read, every link goes through the same checks as the ones in the project, and every entry is still kept when a directory cannot be read or the budget runs out. This also replaces the rule for a link to a file outside the project (every entry kept when a `node_modules` sits above the file): those `node_modules` are read, so one that links nothing changes nothing. Measured in a Bazel 9.3.2 workspace that links about 1,200 packages with aspect_rules_js 3.6.0: about 7,000 directories and 6,700 links behind the `bazel-*` links, and 9,200 directories of external repository contents behind those. After a vendored scan and the in-place install, vex attests without a warning; a link to the upstream entry in `bazel-bin`, in an external repository's contents or in a `node_modules` above the output tree's workspace directory brings the warning back. Following the links lists directories and resolves links outside the git checkout. No file is opened there. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/common/pnpm_links.rs | 41 +- .../tests/e2e_redirect_pnpm_build.rs | 42 ++ .../src/crawlers/npm_crawler.rs | 556 ++++++++++++------ docs/ecosystems.md | 37 +- docs/testing/pnpm-compatibility.md | 11 + 6 files changed, 477 insertions(+), 212 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8355704f7..dc92fc8d1 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -894,7 +894,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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or the directory holds more than 500,000 directories and links; when a link resolves to a directory outside the directory that was read, to a file outside it that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, 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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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. A link that leads out of it is followed: the directory behind it, and each `node_modules` in a directory above that directory or above a file behind such a link (up to the home directory, which is not looked at), are read the same way, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the store itself, 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-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs index 3c4b6c6e8..448c3081b 100644 --- a/crates/socket-patch-cli/tests/common/pnpm_links.rs +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -45,13 +45,46 @@ fn links_below(tree: &Path) -> Vec<(PathBuf, PathBuf)> { } /// 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. +/// below `tree`, or below what a link leads to outside it, 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); + // Node loads what a link leads to from where it really is: every + // directory a link leads to outside the trees read so far is read as + // well, and so is the `node_modules` of each directory above it. + let mut trees = vec![tree]; + let mut links = Vec::new(); + let mut next = 0; + while next < trees.len() { + let found = links_below(&trees[next]); + next += 1; + for (_, target) in &found { + let read = |path: &Path| trees.iter().any(|tree| path.starts_with(tree)); + if target.starts_with(&store) || read(target) { + continue; + } + let mut open: Vec = Vec::new(); + if target.is_dir() { + open.push(target.clone()); + } + for above in target.ancestors().skip(1) { + if let Ok(modules) = std::fs::canonicalize(above.join("node_modules")) { + if modules.is_dir() && !modules.starts_with(&store) { + open.push(modules); + } + } + } + for dir in open { + if !trees.iter().any(|tree| dir.starts_with(tree)) { + trees.push(dir); + } + } + } + links.extend(found); + } let mut reachable = BTreeSet::new(); loop { let before = reachable.len(); 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 8a046719a..13146952f 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -3911,6 +3911,48 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: attested.contains(¬_affected(leaf)), "{tag}: without the links leaf is attested again: {attested:?}\n{stderr}" ); + + // A link that leads out of the project is followed. A directory + // beside the project that links nothing of the store changes nothing; + // one whose `node_modules` links the upstream leaf, as a member that + // left the workspace keeps doing, refuses the patch. + let outside = tmp.path().join("shared"); + std::fs::create_dir_all(outside.join("lib")).unwrap(); + std::fs::create_dir_all(proj.join("tools")).unwrap(); + std::os::unix::fs::symlink(outside.join("lib"), proj.join("tools/lib")).unwrap(); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!( + code, 0, + "{tag}: vex with a link out of the project:\n{stderr}" + ); + assert!( + attested.contains(¬_affected(leaf)) && attested.contains(¬_affected(peer_user)), + "{tag}: a link to a directory that links nothing must change nothing: \ + {attested:?}\n{stderr}" + ); + std::fs::create_dir_all(outside.join("node_modules")).unwrap(); + std::os::unix::fs::symlink(&old_leaf, outside.join("node_modules/leaf")).unwrap(); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must follow the link out of the project: {reachable:?}" + ); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex with a stale member outside:\n{stderr}"); + assert!( + !attested.contains(¬_affected(leaf)) + && attested.contains(¬_affected(peer_user)) + && stderr.contains("not_applied"), + "{tag}: a directory outside that links the upstream leaf must refuse its patch: \ + {attested:?}\n{stderr}" + ); + std::fs::remove_file(outside.join("node_modules/leaf")).unwrap(); + let (code, attested, stderr) = route_vex(&proj, &server); + assert_eq!(code, 0, "{tag}: vex once the stale link is gone:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without the stale link leaf is attested again: {attested:?}\n{stderr}" + ); } #[cfg(unix)] diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 4ce9a4164..76f570666 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -891,8 +891,8 @@ fn orphaned_pnpm_store_entry_sync( /// /// 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 +/// is named (see [`sweep_tree_sync`]; `sweeps` holds the trees read so +/// far), and below what a link leads to outside it. 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 @@ -903,11 +903,22 @@ fn orphaned_pnpm_store_entry_sync( /// /// `tree` is the outer of the directory `scanned` and the workspace's /// root (the directory that holds the store's `node_modules`, or the one -/// a `modulesDir` setting points from). 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: +/// a `modulesDir` setting points from). Nothing above it is read: pnpm +/// writes no link there into a store below it. +/// +/// A link that leads out of the trees read is followed, since node loads +/// what is behind it from where it really is. A directory behind such a +/// link is read like `tree`. So is each `node_modules` in a directory +/// above it, or above a file behind such a link, which is where node +/// looks up the packages of what it loads from there: a member that left +/// the workspace keeps the links pnpm wrote for it, and Bazel's `bazel-*` +/// links lead into an output tree with links of its own. The home +/// directory and what lies above it are not looked at (git's own home +/// rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): +/// a stray `~/node_modules` says nothing of this project. One budget +/// holds for all the trees. +/// +/// Every entry is kept wherever a link may have gone unread: /// /// - on Windows, where pnpm links directories with junctions; /// - when neither of the two directories holds the other (a @@ -935,15 +946,9 @@ fn orphaned_pnpm_store_entry_sync( /// level, the nearest directory above it whose `modulesDir` setting /// names that `node_modules` (pnpm 10.12 and later put the store /// there); with members found at neither, the root is not known; -/// - 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_BUDGET`] directories and links; -/// - when a link resolves to a directory outside `tree` (a `link:` -/// dependency on another checkout, a former workspace member): what -/// the `node_modules` below it link is not read. Nor is what a file -/// outside `tree` loads, so a link to one counts the same way when a -/// directory above the file holds a `node_modules` (see -/// [`node_modules_above_sync`]); +/// - when a directory that is read, the type of one of its children or +/// the target of a link cannot be read, or the trees read hold more +/// than [`LINK_SWEEP_BUDGET`] directories and links between them; /// - when a link resolves to the store itself, into it by a path that is /// spelled another way than the store's (macOS reaches a volume under /// `/System/Volumes/Data` as well, and a file system that folds case @@ -954,7 +959,25 @@ fn orphaned_pnpm_store_entry_sync( fn live_pnpm_store_entries_sync( store_path: &Path, scanned: &Path, - sweeps: &mut HashMap>>>, + sweeps: &mut HashMap>>, +) -> Option> { + live_pnpm_store_entries_under_sync( + store_path, + scanned, + crate::utils::repo_root::home().as_deref(), + LINK_SWEEP_BUDGET, + sweeps, + ) +} + +/// [`live_pnpm_store_entries_sync`] with the home directory and the +/// budget of directories and links given. +fn live_pnpm_store_entries_under_sync( + store_path: &Path, + scanned: &Path, + home: Option<&Path>, + budget: usize, + sweeps: &mut HashMap>>, ) -> Option> { use crate::constants::npm_family::PNPM_LOCK; use crate::formats::pnpm::grammar::is_pnpm_lock_text; @@ -975,12 +998,11 @@ fn live_pnpm_store_entries_sync( // directory, or holds it and may be read from there: like any other // file a project run looks up above the scanned directory, not past // the checkout, and not at the home directory. - let home = crate::utils::repo_root::home(); let readable = |dir: &Path| { dir.starts_with(&scanned) || (scanned.starts_with(dir) && (dir == scanned - || (!crate::utils::repo_root::at_or_above_home(dir, home.as_deref()) + || (!crate::utils::repo_root::at_or_above_home(dir, home) && upward_readable(ReadScope::Workspace, &scanned, dir)))) }; // The workspace's root, which the lockfiles name their importers @@ -1080,46 +1102,115 @@ fn live_pnpm_store_entries_sync( return None; }; let entries = pnpm_store_entry_names(list_dir_sync(&store))?; - let links = sweeps - .entry(tree.to_path_buf()) - .or_insert_with(|| links_below_sync(tree).map(Arc::new)) - .clone()?; - - // A link whose target is not below `store` as the store is spelled. - // A directory outside `tree` behind it is not read. And wherever it - // leads, it may still lie in the store by another spelling of the - // store's path, so each directory above it is held against the store - // by identity, once (nothing is opened: a target may be a pipe). + // The trees whose links are read: `tree`, and what a link leads to + // outside the trees read so far. Node loads a file from where it + // really is, so a directory behind such a link is read like `tree`, + // and so is each `node_modules` above that directory, or above a file + // behind such a link, which is where node looks up the packages of + // what it loads from there (a member that left the workspace keeps + // the links pnpm wrote for it). The home directory and what lies + // above it are not looked at (git's own home rule): a stray + // `~/node_modules` says nothing of this project. One budget holds + // for all the trees. let store_id = file_id(&store)?; - let mut elsewhere: HashSet<&Path> = HashSet::new(); - // The directories above the files that links out of `tree` lead to. - let mut above_files: HashSet<&Path> = HashSet::new(); - for link in links.iter() { - if link.target.starts_with(&store) { - // The store itself: a path through the link names any entry. - if link.target == store { - return None; + let mut trees = vec![tree.to_path_buf()]; + let mut roots: HashSet = trees.iter().cloned().collect(); + let mut swept: Vec> = Vec::new(); + // The `node_modules` that are links themselves, above what was read. + let mut beside: Vec = Vec::new(); + let mut budget = budget; + // Directories held against the store by identity, and directories + // whose `node_modules` was looked for. + let mut elsewhere: HashSet = HashSet::new(); + let mut above: HashSet = HashSet::new(); + let mut next = 0; + while next < trees.len() { + let root = trees[next].clone(); + next += 1; + let sweep = match sweeps.get(&root) { + Some(read) => read.clone()?, + None => match sweep_tree_sync(&root, budget) { + Ok(sweep) => { + let sweep = Arc::new(sweep); + sweeps.insert(root, Some(sweep.clone())); + sweep + } + Err(NoSweep::Unreadable) => { + sweeps.insert(root, None); + return None; + } + Err(NoSweep::OverBudget) => return None, + }, + }; + budget = budget.checked_sub(sweep.cost)?; + for link in &sweep.links { + if link.target.starts_with(&store) { + // The store itself: a path through the link names any entry. + if link.target == store { + return None; + } + continue; } - continue; - } - // Out of `tree`: nothing behind a directory is read, and node - // loads a file from where it really is, with the packages of the - // `node_modules` above it. - if !link.target.starts_with(tree) - && (link.target.is_dir() - || node_modules_above_sync(&link.target, home.as_deref(), &mut above_files)?) - { - return None; - } - for dir in link.target.ancestors() { - if !elsewhere.insert(dir) { - break; + if !link.target.ancestors().any(|dir| roots.contains(dir)) { + let mut open = Vec::new(); + if link.target.is_dir() { + open.push(link.target.clone()); + } + for dir in link.target.ancestors().skip(1) { + if crate::utils::repo_root::at_or_above_home(dir, home) + || !above.insert(dir.to_path_buf()) + { + break; + } + let nm = dir.join("node_modules"); + match std::fs::canonicalize(&nm) { + Ok(real) if real.is_dir() => { + if real == store { + return None; + } + if real != nm { + beside.push(SweptLink { + path: nm, + target: real.clone(), + }); + } + if !real.starts_with(&store) { + open.push(real); + } + } + Ok(_) => {} + Err(e) if leads_nowhere(&e) => {} + Err(_) => return None, + } + } + for dir in open { + if !dir.ancestors().any(|above| roots.contains(above)) { + roots.insert(dir.clone()); + trees.push(dir); + } + } } - if file_id(dir).is_none_or(|id| id == store_id) { - return None; + // Wherever the link leads, it may lie in the store by another + // spelling of the store's path: each directory above it is + // held against the store by identity, once (nothing is + // opened: a target may be a pipe). + for dir in link.target.ancestors() { + if !elsewhere.insert(dir.to_path_buf()) { + break; + } + if file_id(dir).is_none_or(|id| id == store_id) { + return None; + } } } + swept.push(sweep); } + let links = || { + swept + .iter() + .flat_map(|sweep| sweep.links.iter()) + .chain(&beside) + }; // The entry of this store that a real path lies in. let entry_of = |path: &Path| -> Option<&OsStr> { @@ -1145,7 +1236,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.iter() { + for link in links() { let Some(target) = entry_of(&link.target) else { if in_unlisted_child(&link.target) { return None; @@ -1191,34 +1282,6 @@ fn leads_nowhere(error: &std::io::Error) -> bool { } } -/// Whether a directory above the file `file` holds a `node_modules` dir, -/// which is where node looks up the packages of a file it loads from -/// there. pnpm links a workspace member's dependencies in the member's -/// `node_modules`, and a member that left the workspace keeps them. The -/// home directory and what lies above it are not looked at (git's own -/// home rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): -/// a stray `~/node_modules` says nothing of this project. `seen` holds -/// the directories already found to have none. `None` when one cannot be -/// told. -fn node_modules_above_sync<'a>( - file: &'a Path, - home: Option<&Path>, - seen: &mut HashSet<&'a Path>, -) -> Option { - for dir in file.ancestors().skip(1) { - if crate::utils::repo_root::at_or_above_home(dir, home) || !seen.insert(dir) { - break; - } - match std::fs::metadata(dir.join("node_modules")) { - Ok(meta) if meta.is_dir() => return Some(true), - Ok(_) => {} - Err(e) if leads_nowhere(&e) => {} - Err(_) => return None, - } - } - Some(false) -} - /// The device and inode of the file at `path`, which name one file however /// its path is spelled. Read with `stat`, so nothing is opened. `None` /// when it cannot be read, and on a platform without the pair. @@ -1280,7 +1343,31 @@ struct SweptLink { /// memory as well. const LINK_SWEEP_BUDGET: usize = 500_000; +/// The links of one tree ([`sweep_tree_sync`]). +struct Sweep { + links: Vec, + /// The directories and links read for it, counted against the budget + /// again by each store that is judged by it. + cost: usize, +} + +/// Why a tree has no [`Sweep`]. +enum NoSweep { + /// A directory, the type of a child or the target of a link cannot be + /// read: so it is on every read. + Unreadable, + /// It holds more than the budget that was left. + OverBudget, +} + +/// [`sweep_tree_sync`]'s links, for a caller with one tree. +#[cfg(test)] +fn links_below_within_sync(tree: &Path, budget: usize) -> Option> { + sweep_tree_sync(tree, budget).ok().map(|sweep| sweep.links) +} + /// [`links_below_within_sync`] under [`LINK_SWEEP_BUDGET`]. +#[cfg(test)] fn links_below_sync(tree: &Path) -> Option> { links_below_within_sync(tree, LINK_SWEEP_BUDGET) } @@ -1293,15 +1380,18 @@ fn links_below_sync(tree: &Path) -> Option> { /// or outside it. A link that leads nowhere (see [`leads_nowhere`]) 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 +/// No answer when it 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) and links. Each level of /// the tree is read in parallel. -fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option> { +fn sweep_tree_sync(tree: &Path, budget: usize) -> Result { let mut links = Vec::new(); let mut frontier = vec![tree.to_path_buf()]; + let mut left = budget; while !frontier.is_empty() { - budget = budget.checked_sub(frontier.len())?; + left = left + .checked_sub(frontier.len()) + .ok_or(NoSweep::OverBudget)?; let reads = par_map(frontier, |dir| { let mut links = Vec::new(); let mut dirs = Vec::new(); @@ -1332,13 +1422,16 @@ fn links_below_within_sync(tree: &Path, mut budget: usize) -> Option>>>, + sweeps: HashMap>>, } impl LiveStoreEntries { @@ -8945,9 +9038,38 @@ mod tests { abs_link(&store.join("minimist@1.2.2"), &store.join("alias")) }), ), - // Node loads a linked file from where it is: beside the - // `node_modules` of a member that left the workspace, which is - // not read, so every entry is kept while the link is there. + // Node loads what a link leads to from where it really is: a + // directory outside the project is read like the project, and + // so is each `node_modules` above it, or above a file outside. + ( + "a link to a directory outside the project that links the leftover", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/minimist")); + abs_link(&shared, &root.join("tools/shared")) + }), + ), + ( + "a link to a directory below the node_modules of one outside the project", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + abs_link(&root.join(LEFTOVER), &shared.join("node_modules/@s/mini")); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + abs_link(&shared.join("lib/deep"), &root.join("tools/deep")) + }), + ), + ( + "a chain of two directories outside the project", + Box::new(|root: &Path| { + let (x, y) = ( + root.parent().unwrap().join("x"), + root.parent().unwrap().join("y"), + ); + abs_link(&root.join(LEFTOVER), &y.join("vendor/minimist")); + abs_link(&y, &x.join("deps/y")); + abs_link(&x, &root.join("tools/x")) + }), + ), ( "a link to a file of a former member outside the project", Box::new(|root: &Path| { @@ -9204,36 +9326,59 @@ mod tests { }), ), ]; - // A link to a file outside the project, with no `node_modules` in - // a directory above the file: a file named so, and a link named - // so whose target is not there, are none. Only on a machine with - // no `node_modules` above the temp dir itself. + // What a link leads to outside the project is read, and links + // nothing of the store: a file with a `node_modules` above it, a + // file below a file and a dangling link of that name, a pipe, and + // directories that link each other and the project. let mut cases = cases; - let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); - let home = crate::utils::repo_root::home(); - let above_temp = - node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); - if above_temp == Some(false) { - cases.push(( - "a link to a file outside the project", - Box::new(|root: &Path| { - let outside = root.ancestors().nth(2).unwrap().join("elsewhere"); - std::fs::create_dir_all(outside.join("deep")).unwrap(); - std::fs::write(outside.join("deep/file"), "").unwrap(); - abs_link(&outside.join("deep/file"), &root.join("tools/file")); - std::fs::write(outside.join("node_modules"), "").unwrap(); - rel_link("nowhere", &outside.join("deep/node_modules")); - }), - )); - cases.push(( - "a link to a named pipe outside the project", - Box::new(|root: &Path| { - let pipe = root.ancestors().nth(2).unwrap().join("pipe"); - mkfifo(&pipe); - abs_link(&pipe, &root.join("tools/ctl")); - }), - )); - } + cases.push(( + "a link to a file outside the project", + Box::new(|root: &Path| { + let outside = root.ancestors().nth(2).unwrap().join("elsewhere"); + std::fs::create_dir_all(outside.join("deep")).unwrap(); + std::fs::write(outside.join("deep/file"), "").unwrap(); + abs_link(&outside.join("deep/file"), &root.join("tools/file")); + std::fs::write(outside.join("node_modules"), "").unwrap(); + rel_link("nowhere", &outside.join("deep/node_modules")); + }), + )); + cases.push(( + "a link to a file outside the project below a node_modules", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + write_pkg(&shared.join("node_modules/real"), "real", "1.0.0"); + abs_link(root, &shared.join("node_modules/app")); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); + abs_link( + &shared.join("lib/deep/gen.js"), + &root.join("scripts/gen.js"), + ); + }), + )); + cases.push(( + "a link to a named pipe outside the project", + Box::new(|root: &Path| { + let pipe = root.ancestors().nth(2).unwrap().join("pipe"); + mkfifo(&pipe); + abs_link(&pipe, &root.join("tools/ctl")); + }), + )); + cases.push(( + "links to directories outside the project", + Box::new(|root: &Path| { + let (x, y) = ( + root.parent().unwrap().join("x"), + root.parent().unwrap().join("y"), + ); + write_pkg(&y.join("node_modules/real"), "real", "1.0.0"); + abs_link(&y, &x.join("deps/y")); + abs_link(&x, &y.join("deps/x")); + abs_link(root, &y.join("app")); + abs_link(&x, &root.join("node_modules/linked")); + abs_link(&x.join("deps"), &root.join("bazel-bin")); + }), + )); for (case, change) in cases { let (_tmp, _, root) = pnpm_project_dir(); let (_, stale, routed) = pnpm_hosted_route_leftover(&root); @@ -9256,51 +9401,89 @@ mod tests { assert!(made.success(), "mkfifo {path:?}"); } - /// #2353: node looks up the packages of a file in the `node_modules` - /// of each directory above it, up to the home directory, which is - /// not looked at, nor is anything above it. A file or a dangling link - /// named `node_modules` is none. + /// #2353: what a link leads to outside the project is read up to the + /// home directory, which is not looked at, nor is anything above it: a + /// `node_modules` there is no part of this project. And the trees + /// outside count against the same budget as the project. #[cfg(unix)] #[test] - fn test_node_modules_above_a_file_stops_at_the_home_directory() { + fn test_pnpm_store_links_outside_are_read_below_home_and_within_one_budget() { let tmp = tempfile::tempdir().unwrap(); let base = std::fs::canonicalize(tmp.path()).unwrap(); let home = base.join("home"); - let file = home.join("projects/shared/lib/gen.js"); - std::fs::create_dir_all(file.parent().unwrap()).unwrap(); - std::fs::write(&file, "").unwrap(); - let above = |home: &Path| node_modules_above_sync(&file, Some(home), &mut HashSet::new()); - - assert_eq!(above(&home), Some(false)); - std::fs::write(home.join("projects/shared/lib/node_modules"), "").unwrap(); - rel_link("nowhere", &home.join("projects/shared/node_modules")); - std::fs::create_dir_all(home.join("node_modules")).unwrap(); - std::fs::create_dir_all(base.join("node_modules")).unwrap(); - assert_eq!(above(&home), Some(false), "not in the home directory"); - assert_eq!( - above(&base.join("elsewhere")), - Some(true), - "with the home directory elsewhere" - ); - std::fs::create_dir_all(home.join("projects/node_modules")).unwrap(); - assert_eq!(above(&home), Some(true), "below the home directory"); + let root = home.join("projects/app"); + std::fs::create_dir_all(&root).unwrap(); + let (nm, _, _) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let outside = home.join("projects/shared/lib"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("gen.js"), "").unwrap(); + abs_link(&outside.join("gen.js"), &root.join("scripts/gen.js")); + let leftover = OsString::from("minimist@1.2.2"); + let live = |home: &Path, budget: usize| { + live_pnpm_store_entries_under_sync( + &store, + &root, + Some(home), + budget, + &mut HashMap::new(), + ) + }; + let reaches_leftover = |home: &Path| { + live(home, LINK_SWEEP_BUDGET) + .expect("the store is judged") + .contains(&leftover) + }; - // A directory found to have none is not asked again. - let mut seen = HashSet::new(); - let other = home.join("other/a/file"); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut seen), - Some(false) - ); - std::fs::create_dir_all(home.join("other/node_modules")).unwrap(); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut seen), - Some(false) + // In the home directory itself, and above it: not looked at. + abs_link(&root.join(LEFTOVER), &home.join("node_modules/minimist")); + abs_link(&root.join(LEFTOVER), &base.join("node_modules/minimist")); + assert!(!reaches_leftover(&home)); + assert!( + reaches_leftover(&base.join("elsewhere")), + "with another home" ); - assert_eq!( - node_modules_above_sync(&other, Some(&home), &mut HashSet::new()), - Some(true) + // Below the home directory: read. + abs_link( + &root.join(LEFTOVER), + &home.join("projects/node_modules/minimist"), ); + assert!(reaches_leftover(&home)); + + // The home rule holds above the scanned directory, not at it: a + // project whose root is the home directory is judged. + let at_home = home.join("app"); + std::fs::create_dir_all(&at_home).unwrap(); + std::fs::write( + at_home.join("pnpm-workspace.yaml"), + "packages:\n - packages/*\nmodulesDir: sub/node_modules\n", + ) + .unwrap(); + let nested = pnpm_install_into(&at_home.join("sub/node_modules"), &["packages/a"]); + let nested_stale = pnpm_entry(&nested, "minimist@1.2.2", "minimist", "1.2.2"); + let nested_routed = pnpm_entry(&nested, ROUTED_ENTRY, "minimist", "1.2.2"); + write_pkg(&at_home.join("packages/a"), "a", "1.0.0"); + abs_link( + &nested_routed, + &at_home.join("packages/a/sub/node_modules/minimist"), + ); + let judged = live_pnpm_store_entries_under_sync( + &nested, + &at_home, + Some(&at_home), + LINK_SWEEP_BUDGET, + &mut HashMap::new(), + ) + .expect("a root at the home directory is judged"); + assert!(!judged.contains(&leftover) && judged.len() == 1); + let _ = nested_stale; + + // One budget for the project and what its links lead to. + let cost = |tree: &Path| sweep_tree_sync(tree, LINK_SWEEP_BUDGET).ok().unwrap().cost; + let whole = cost(&root) + cost(&home.join("projects/node_modules")); + assert!(live(&home, whole).is_some()); + assert!(live(&home, whole - 1).is_none()); + assert!(live(&home, cost(&root)).is_none()); } /// #2353: a pnpm store is judged for a package version only when its @@ -9830,12 +10013,6 @@ mod tests { write_lock(root, false, &pnpm_lock_of(&["packages/out"])); }), ), - ( - "a link to a directory outside the project", - Box::new(|root: &Path| { - abs_link(&beside(root), &root.join("node_modules/linked")); - }), - ), ( "a link to the store itself", Box::new(|root: &Path| { @@ -9843,16 +10020,15 @@ mod tests { }), ), ( - "a link to a file outside the project below an empty node_modules", + "a link to a directory outside the project that is a link to the store", Box::new(|root: &Path| { let shared = beside(root); - std::fs::create_dir_all(shared.join("node_modules")).unwrap(); - std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); - std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); abs_link( - &shared.join("lib/deep/gen.js"), - &root.join("scripts/gen.js"), + &root.join("node_modules/.pnpm"), + &shared.join("node_modules"), ); + std::fs::create_dir_all(shared.join("lib")).unwrap(); + abs_link(&shared.join("lib"), &root.join("tools/lib")); }), ), ( @@ -9931,26 +10107,26 @@ mod tests { assert_eq!(global, both); // Directories that cannot be read (not as root, which reads them - // all the same): one below the project, and one that the target - // of a link lies behind. That target is a file outside the - // project, which keeps every entry by itself on a machine with a - // `node_modules` above the temp dir. - let mut locked_dirs = vec![( - "an unreadable directory below the project", - "ws/app/dist/private", - None, - )]; - let temp = std::fs::canonicalize(std::env::temp_dir()).unwrap(); - let home = crate::utils::repo_root::home(); - let above_temp = - node_modules_above_sync(&temp.join("x/file"), home.as_deref(), &mut HashSet::new()); - if above_temp == Some(false) { - locked_dirs.push(( + // all the same): one below the project, one that the target of a + // link lies behind, and one below a directory outside the project + // that a link leads to. + let locked_dirs = [ + ( + "an unreadable directory below the project", + "ws/app/dist/private", + None, + ), + ( "a link whose target lies behind an unreadable directory", "locked", Some(("locked/file", "ws/app/vendor/x")), - )); - } + ), + ( + "an unreadable directory below one outside the project", + "ws/out/private", + Some(("ws/out", "ws/app/tools/out")), + ), + ]; for (case, locked, link) in locked_dirs { let (_tmp, base, root) = pnpm_project_dir(); let (_, stale, routed) = pnpm_hosted_route_leftover(&root); @@ -9958,7 +10134,9 @@ mod tests { std::fs::create_dir_all(&locked).unwrap(); std::fs::write(locked.join("file"), "").unwrap(); if let Some((target, link)) = link { - std::fs::write(base.join(target), "").unwrap(); + if !base.join(target).is_dir() { + std::fs::write(base.join(target), "").unwrap(); + } abs_link(&base.join(target), &base.join(link)); } assert_eq!( diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 0fc3998d7..bb4778fc1 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -873,9 +873,19 @@ For pnpm the rule is narrow: `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. A link is - resolved, never followed. Nothing above that directory is read: pnpm - writes no link there into a store below it. + `node_modules` or a directory that left the workspace counts. Nothing + above that directory is read: pnpm writes no link there into a store + below it. +- A link that leads out of that directory is followed, since node loads + what is behind it from where it really is. A directory behind such a + link is read the same way, and so is each `node_modules` in a + directory above it, or above a file behind such a link. So a `link:` + dependency on another checkout, the `bazel-*` links into Bazel's + output tree, and a file of a member that left the workspace (which + keeps the links pnpm wrote for it) are all read. The home directory + and what lies above it are not looked at, so a link to an interpreter + under the home directory (a virtualenv's `python`) and a stray + `~/node_modules` change nothing. - 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, @@ -938,21 +948,12 @@ judged, as before: the store in `/.pnpm` and each member's links in `/`. Where the setting comes from somewhere the project's files do not show, the root is not known; -- when a directory below the one that is read, the type of one of its - children or the target of a link cannot be read, or it holds more than - 500,000 directories and links. A link that leads nowhere is left out: - its target is not there, it loops, or its path passes through a file; -- when a link resolves to a directory outside the one that is read: what - the `node_modules` of that directory links is not read. A `link:` - dependency on another checkout is such a link, and so is a - convenience link to a build tool's output elsewhere on the disk. A - link to a file outside counts the same way when a directory above the - file holds a `node_modules`: node loads the file from where it is, - with the packages it finds there, and a member that left the - workspace keeps the links pnpm wrote for it. The home directory and - what lies above it are not looked at for this, so a link to an - interpreter under the home directory (a virtualenv's `python`) and a - stray `~/node_modules` change nothing; +- when a directory that is read (below the scanned one, or behind a + link that leads out of it), the type of one of its children or the + target of a link cannot be read, or all that is read comes to more + than 500,000 directories and links. A link that leads nowhere is left + out: its target is not there, it loops, or its path passes through a + file; - when a link resolves to the store itself, or into it 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, and a file system that diff --git a/docs/testing/pnpm-compatibility.md b/docs/testing/pnpm-compatibility.md index 98659f7b6..dc7c3e93c 100644 --- a/docs/testing/pnpm-compatibility.md +++ b/docs/testing/pnpm-compatibility.md @@ -388,6 +388,17 @@ one. `pnpm prune` removes the entry at once (measured on 11.29.0 and 12.25.1, on the registry route), and a clean `node_modules` has no such entry. +A link that leads out of the scanned directory is followed. Measured in a +Bazel 9.3.2 workspace that links about 1,200 packages with aspect_rules_js +3.6.0: the `bazel-bin`, `bazel-out`, `bazel-testlogs` and `bazel-` +links lead into the output tree, which holds about 7,000 directories and +6,700 links, and from there into the contents of the external repositories +(about 9,200 directories). After a vendored scan and the `pnpm install` +over the existing `node_modules`, `vex` reads all of it and attests without +a warning; a link to the upstream entry in `bazel-bin`, in an external +repository's contents, or in a `node_modules` above the output tree's +workspace directory brings the warning back. + A workspace with a `modulesDir` of more than one level is judged from the workspace's root. 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 From d5a319d9470005cd40f31cdbb0250c42561f6846 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 2 Dec 2026 03:06:20 -0500 Subject: [PATCH 2/3] Read what a project's links lead to once, up to the home directory Following a link out of the project was done per store and per link, which left several gaps the review found: - A `node_modules` above a directory outside the project that is itself a link was not followed, so a link into the store behind it went unread. - A link to the home directory, or to one above it, was read like any other directory. It now keeps every entry, and no `node_modules` at the home directory or above it is looked at. - Bazel's `bazel-bin`, `bazel-out` and `bazel-` lead to directories inside each other. Each was read in full and charged against the budget again. A directory is now read once, around what was read already. - Each store of a project repeated the whole pass, and a pass that failed was repeated as well. The links reached from a tree are now kept for the run, failures included. - A link to a file outside the project is handled as before this branch: it keeps every entry when a `node_modules` sits in a directory above the file. It is judged after every directory is read, so a file inside a directory that a later link leads to is not held against a `node_modules` that was read. The unit tests take the home directory as a value, so nothing of the machine's own home or temp directory is read by them. Part of #2353. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/common/pnpm_links.rs | 12 +- .../src/crawlers/npm_crawler.rs | 499 +++++++++++------- docs/ecosystems.md | 25 +- 4 files changed, 338 insertions(+), 200 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index dc92fc8d1..4da651be0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -894,7 +894,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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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. A link that leads out of it is followed: the directory behind it, and each `node_modules` in a directory above that directory or above a file behind such a link (up to the home directory, which is not looked at), are read the same way, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the store itself, 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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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. A link to a directory outside it is followed: that directory, and each `node_modules` in a directory above it (up to the home directory, which is not read), are read the same way and once each, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the home directory or one above it, to a file outside what was read that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, 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-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs index 448c3081b..5c3ee5756 100644 --- a/crates/socket-patch-cli/tests/common/pnpm_links.rs +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -55,6 +55,7 @@ pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { // Node loads what a link leads to from where it really is: every // directory a link leads to outside the trees read so far is read as // well, and so is the `node_modules` of each directory above it. + let stop = std::fs::canonicalize(std::env::temp_dir()).unwrap(); let mut trees = vec![tree]; let mut links = Vec::new(); let mut next = 0; @@ -66,11 +67,16 @@ pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { if target.starts_with(&store) || read(target) { continue; } - let mut open: Vec = Vec::new(); - if target.is_dir() { - open.push(target.clone()); + // Only a directory is followed, and nothing at the temp dir + // or above it is read: the tests build below it. + if !target.is_dir() { + continue; } + let mut open: Vec = vec![target.clone()]; for above in target.ancestors().skip(1) { + if stop.starts_with(above) { + break; + } if let Ok(modules) = std::fs::canonicalize(above.join("node_modules")) { if modules.is_dir() && !modules.starts_with(&store) { open.push(modules); diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index 76f570666..da2d67af6 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -891,8 +891,9 @@ fn orphaned_pnpm_store_entry_sync( /// /// 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 [`sweep_tree_sync`]; `sweeps` holds the trees read so -/// far), and below what a link leads to outside it. An entry is live when a link that sits outside the store's +/// is named, and below what a link leads to outside it (see +/// [`links_reached_from_sync`]; `sweeps` holds what was 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 @@ -906,17 +907,9 @@ fn orphaned_pnpm_store_entry_sync( /// a `modulesDir` setting points from). Nothing above it is read: pnpm /// writes no link there into a store below it. /// -/// A link that leads out of the trees read is followed, since node loads -/// what is behind it from where it really is. A directory behind such a -/// link is read like `tree`. So is each `node_modules` in a directory -/// above it, or above a file behind such a link, which is where node -/// looks up the packages of what it loads from there: a member that left -/// the workspace keeps the links pnpm wrote for it, and Bazel's `bazel-*` -/// links lead into an output tree with links of its own. The home -/// directory and what lies above it are not looked at (git's own home -/// rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): -/// a stray `~/node_modules` says nothing of this project. One budget -/// holds for all the trees. +/// A link that leads out of `tree` is followed (see +/// [`links_reached_from_sync`]): the directory behind it is read, and +/// each `node_modules` above that directory, up to the home directory. /// /// Every entry is kept wherever a link may have gone unread: /// @@ -947,8 +940,12 @@ fn orphaned_pnpm_store_entry_sync( /// names that `node_modules` (pnpm 10.12 and later put the store /// there); with members found at neither, the root is not known; /// - when a directory that is read, the type of one of its children or -/// the target of a link cannot be read, or the trees read hold more -/// than [`LINK_SWEEP_BUDGET`] directories and links between them; +/// the target of a link cannot be read, or what is read comes to more +/// than [`LINK_SWEEP_BUDGET`] directories and links; +/// - when a link leads to the home directory or a directory above it, or +/// to a file outside what is read that has a `node_modules` in a +/// directory above it: what that file loads by paths of its own is not +/// read; /// - when a link resolves to the store itself, into it by a path that is /// spelled another way than the store's (macOS reaches a volume under /// `/System/Volumes/Data` as well, and a file system that folds case @@ -956,28 +953,12 @@ fn orphaned_pnpm_store_entry_sync( /// 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> { - live_pnpm_store_entries_under_sync( - store_path, - scanned, - crate::utils::repo_root::home().as_deref(), - LINK_SWEEP_BUDGET, - sweeps, - ) -} - -/// [`live_pnpm_store_entries_sync`] with the home directory and the -/// budget of directories and links given. fn live_pnpm_store_entries_under_sync( store_path: &Path, scanned: &Path, home: Option<&Path>, budget: usize, - sweeps: &mut HashMap>>, + sweeps: &mut HashMap>>>, ) -> Option> { use crate::constants::npm_family::PNPM_LOCK; use crate::formats::pnpm::grammar::is_pnpm_lock_text; @@ -1102,115 +1083,36 @@ fn live_pnpm_store_entries_under_sync( return None; }; let entries = pnpm_store_entry_names(list_dir_sync(&store))?; - // The trees whose links are read: `tree`, and what a link leads to - // outside the trees read so far. Node loads a file from where it - // really is, so a directory behind such a link is read like `tree`, - // and so is each `node_modules` above that directory, or above a file - // behind such a link, which is where node looks up the packages of - // what it loads from there (a member that left the workspace keeps - // the links pnpm wrote for it). The home directory and what lies - // above it are not looked at (git's own home rule): a stray - // `~/node_modules` says nothing of this project. One budget holds - // for all the trees. + // Every link below `tree` and below what its links lead to: the same + // for each store of the tree, so it is read once. + let links = sweeps + .entry(tree.to_path_buf()) + .or_insert_with(|| links_reached_from_sync(tree, home, budget).map(Arc::new)) + .clone()?; + + // Wherever a link leads, it may lie in the store by another spelling + // of the store's path: each directory above its target is held + // against the store by identity, once (nothing is opened: a target + // may be a pipe). let store_id = file_id(&store)?; - let mut trees = vec![tree.to_path_buf()]; - let mut roots: HashSet = trees.iter().cloned().collect(); - let mut swept: Vec> = Vec::new(); - // The `node_modules` that are links themselves, above what was read. - let mut beside: Vec = Vec::new(); - let mut budget = budget; - // Directories held against the store by identity, and directories - // whose `node_modules` was looked for. - let mut elsewhere: HashSet = HashSet::new(); - let mut above: HashSet = HashSet::new(); - let mut next = 0; - while next < trees.len() { - let root = trees[next].clone(); - next += 1; - let sweep = match sweeps.get(&root) { - Some(read) => read.clone()?, - None => match sweep_tree_sync(&root, budget) { - Ok(sweep) => { - let sweep = Arc::new(sweep); - sweeps.insert(root, Some(sweep.clone())); - sweep - } - Err(NoSweep::Unreadable) => { - sweeps.insert(root, None); - return None; - } - Err(NoSweep::OverBudget) => return None, - }, - }; - budget = budget.checked_sub(sweep.cost)?; - for link in &sweep.links { - if link.target.starts_with(&store) { - // The store itself: a path through the link names any entry. - if link.target == store { - return None; - } - continue; + let mut elsewhere: HashSet<&Path> = HashSet::new(); + for link in links.iter() { + if link.target.starts_with(&store) { + // The store itself: a path through the link names any entry. + if link.target == store { + return None; } - if !link.target.ancestors().any(|dir| roots.contains(dir)) { - let mut open = Vec::new(); - if link.target.is_dir() { - open.push(link.target.clone()); - } - for dir in link.target.ancestors().skip(1) { - if crate::utils::repo_root::at_or_above_home(dir, home) - || !above.insert(dir.to_path_buf()) - { - break; - } - let nm = dir.join("node_modules"); - match std::fs::canonicalize(&nm) { - Ok(real) if real.is_dir() => { - if real == store { - return None; - } - if real != nm { - beside.push(SweptLink { - path: nm, - target: real.clone(), - }); - } - if !real.starts_with(&store) { - open.push(real); - } - } - Ok(_) => {} - Err(e) if leads_nowhere(&e) => {} - Err(_) => return None, - } - } - for dir in open { - if !dir.ancestors().any(|above| roots.contains(above)) { - roots.insert(dir.clone()); - trees.push(dir); - } - } + continue; + } + for dir in link.target.ancestors() { + if !elsewhere.insert(dir) { + break; } - // Wherever the link leads, it may lie in the store by another - // spelling of the store's path: each directory above it is - // held against the store by identity, once (nothing is - // opened: a target may be a pipe). - for dir in link.target.ancestors() { - if !elsewhere.insert(dir.to_path_buf()) { - break; - } - if file_id(dir).is_none_or(|id| id == store_id) { - return None; - } + if file_id(dir).is_none_or(|id| id == store_id) { + return None; } } - swept.push(sweep); } - let links = || { - swept - .iter() - .flat_map(|sweep| sweep.links.iter()) - .chain(&beside) - }; // The entry of this store that a real path lies in. let entry_of = |path: &Path| -> Option<&OsStr> { @@ -1236,7 +1138,7 @@ fn live_pnpm_store_entries_under_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; @@ -1263,6 +1165,128 @@ fn live_pnpm_store_entries_under_sync( (!live.is_empty()).then(|| live.into_iter().map(OsStr::to_os_string).collect()) } +/// Every link below `tree` and below what a link leads to outside it, +/// with the real path each resolves to; `None` when they cannot all be +/// read. +/// +/// Node loads what a link leads to from where it really is. So a +/// directory behind a link that leads out of what was read is read like +/// `tree`, and so is each `node_modules` in a directory above it, which +/// is where node looks up the packages of what it loads from there (a +/// member that left the workspace keeps the links pnpm wrote for it, and +/// Bazel's `bazel-*` links lead into an output tree with links of its +/// own). A `node_modules` that is a link itself is one more link, and +/// what it leads to is read the same way. A directory is read once: one +/// that holds directories already read is read around them. +/// +/// The home directory and what lies above it are not read (git's own +/// home rule, see [`at_or_above_home`](crate::utils::repo_root::at_or_above_home)): +/// a `node_modules` there is not looked at, and a link to a directory +/// there leaves the answer unknown. So does a link to a file outside +/// with a `node_modules` in a directory above it: what that file loads +/// by paths of its own is not read. `budget` holds for all the +/// directories and links read. +fn links_reached_from_sync( + tree: &Path, + home: Option<&Path>, + budget: usize, +) -> Option> { + use crate::utils::repo_root::at_or_above_home; + + let mut links: Vec = Vec::new(); + // The directories read, and those still to read. + let mut roots: HashSet = HashSet::new(); + let mut queue: VecDeque = VecDeque::from([tree.to_path_buf()]); + let mut queued: HashSet = queue.iter().cloned().collect(); + // Directories whose `node_modules` was looked for. + let mut above: HashSet = HashSet::new(); + // The files that links lead to outside what was read at the time. + let mut files: Vec = Vec::new(); + let mut left = budget; + let inside = + |roots: &HashSet, path: &Path| path.ancestors().any(|dir| roots.contains(dir)); + while let Some(root) = queue.pop_front() { + if inside(&roots, &root) { + continue; + } + // Read around what was read already. + let read: HashSet = roots + .iter() + .filter(|done| done.starts_with(&root)) + .cloned() + .collect(); + let sweep = sweep_tree_sync(&root, left, &read).ok()?; + left -= sweep.cost; + roots.insert(root); + // What the links of this directory lead to outside what is read. + let mut targets: VecDeque = + sweep.links.iter().map(|link| link.target.clone()).collect(); + links.extend(sweep.links); + while let Some(target) = targets.pop_front() { + if inside(&roots, &target) || queued.contains(&target) { + continue; + } + if !target.is_dir() { + files.push(target); + continue; + } + if at_or_above_home(&target, home) { + return None; + } + for dir in target.ancestors().skip(1) { + if at_or_above_home(dir, home) || !above.insert(dir.to_path_buf()) { + break; + } + let nm = dir.join("node_modules"); + let real = match std::fs::canonicalize(&nm) { + Ok(real) if real.is_dir() => real, + Ok(_) => continue, + Err(e) if leads_nowhere(&e) => continue, + Err(_) => return None, + }; + if real == nm { + if queued.insert(real.clone()) { + queue.push_back(real); + } + } else { + // A link like any other: it may lead into a store, + // and what it leads to is read in its turn. + links.push(SweptLink { + path: nm, + target: real.clone(), + }); + targets.push_back(real); + } + } + if queued.insert(target.clone()) { + queue.push_back(target); + } + } + } + // A file outside everything that was read: what it loads by paths of + // its own is not read, so it must have no `node_modules` to load + // packages from. One inside what was read in the end is like any + // other file there. + let mut above_files: HashSet<&Path> = HashSet::new(); + for file in &files { + if inside(&roots, file) { + continue; + } + for dir in file.ancestors().skip(1) { + if at_or_above_home(dir, home) || !above_files.insert(dir) { + break; + } + match std::fs::metadata(dir.join("node_modules")) { + Ok(meta) if meta.is_dir() => return None, + Ok(_) => {} + Err(e) if leads_nowhere(&e) => {} + Err(_) => return None, + } + } + } + Some(links) +} + /// Whether a link failed to resolve because it leads nowhere: its target /// is not there, a level of its path is a file, or it loops. Nothing is /// loaded through such a link, so it is left out; any other failure (a @@ -1326,7 +1350,7 @@ fn pnpm_store_entry_names(listing: Listing) -> Option> { Some(entries) } -/// A symbolic link [`links_below_sync`] found. +/// A symbolic link [`sweep_tree_sync`] found. struct SweptLink { /// Where the link is: a path below the swept tree, through real /// directories alone. @@ -1335,19 +1359,20 @@ struct SweptLink { target: PathBuf, } -/// How many directories and links [`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. A monorepo with a store of 5,200 entries holds about 98,000 -/// directories and 20,000 links. The links are kept, so this bounds the -/// memory as well. +/// How many directories and links [`links_reached_from_sync`] reads +/// before it gives up, in the project and in what its links lead to: more +/// than this is no single project (a home directory, a disk), and the +/// caller keeps every store entry instead of waiting on it. A monorepo +/// with a store of 5,200 entries holds about 98,000 directories and +/// 20,000 links; the output tree of a Bazel workspace of 1,200 packages +/// adds about 16,000 directories and 7,000 links. The links are kept, so +/// this bounds the memory as well. const LINK_SWEEP_BUDGET: usize = 500_000; /// The links of one tree ([`sweep_tree_sync`]). struct Sweep { links: Vec, - /// The directories and links read for it, counted against the budget - /// again by each store that is judged by it. + /// The directories and links read for it. cost: usize, } @@ -1363,7 +1388,9 @@ enum NoSweep { /// [`sweep_tree_sync`]'s links, for a caller with one tree. #[cfg(test)] fn links_below_within_sync(tree: &Path, budget: usize) -> Option> { - sweep_tree_sync(tree, budget).ok().map(|sweep| sweep.links) + sweep_tree_sync(tree, budget, &HashSet::new()) + .ok() + .map(|sweep| sweep.links) } /// [`links_below_within_sync`] under [`LINK_SWEEP_BUDGET`]. @@ -1380,11 +1407,13 @@ fn links_below_sync(tree: &Path) -> Option> { /// or outside it. A link that leads nowhere (see [`leads_nowhere`]) is /// left out. /// +/// The directories in `read` are not entered: they were read already. +/// /// No answer when it 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) and links. Each level of /// the tree is read in parallel. -fn sweep_tree_sync(tree: &Path, budget: usize) -> Result { +fn sweep_tree_sync(tree: &Path, budget: usize, read: &HashSet) -> Result { let mut links = Vec::new(); let mut frontier = vec![tree.to_path_buf()]; let mut left = budget; @@ -1408,7 +1437,10 @@ fn sweep_tree_sync(tree: &Path, budget: usize) -> Result { let child = child.ok()?; let file_type = child.file_type().ok()?; if file_type.is_dir() { - dirs.push(child.path()); + let path = child.path(); + if !read.contains(&path) { + dirs.push(path); + } } else if file_type.is_symlink() { let path = child.path(); match std::fs::canonicalize(&path) { @@ -1728,10 +1760,13 @@ pub struct LiveStoreEntries { /// The stores judged so far, by real path: the names of their live /// 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>>, + /// The links reached from each tree read so far (see + /// [`links_reached_from_sync`]), so that several pnpm stores below one + /// scanned directory share one read of it. + sweeps: HashMap>>>, + /// The home directory, which is not read, nor is anything above it + /// (see [`links_reached_from_sync`]). + home: Option, } impl LiveStoreEntries { @@ -1740,6 +1775,7 @@ impl LiveStoreEntries { pub fn new(scanned: Option) -> Self { Self { scanned, + home: crate::utils::repo_root::home(), ..Self::default() } } @@ -1837,7 +1873,13 @@ impl LiveStoreEntries { None => { let live = if *layout == StoreLayout::Pnpm { self.scanned.as_deref().and_then(|scanned| { - live_pnpm_store_entries_sync(store, scanned, &mut self.sweeps) + live_pnpm_store_entries_under_sync( + store, + scanned, + self.home.as_deref(), + LINK_SWEEP_BUDGET, + &mut self.sweeps, + ) }) } else { let candidates = pnpm_shaped_store_candidates_sync(store, StoreLayout::Bun); @@ -8621,7 +8663,12 @@ mod tests { .iter() .map(|copies| copies.iter().map(|path| (*path).clone()).collect()) .collect(); - let mut live = LiveStoreEntries::new(Some(scanned.to_path_buf())); + // Nothing at the temp dir or above it is read, whatever the + // machine keeps there: it stands in for the home directory. + let mut live = LiveStoreEntries { + home: Some(std::fs::canonicalize(std::env::temp_dir()).unwrap()), + ..LiveStoreEntries::new(Some(scanned.to_path_buf())) + }; live.retain_live_copies(lists.iter_mut()).await; (lists, live) } @@ -9342,18 +9389,18 @@ mod tests { rel_link("nowhere", &outside.join("deep/node_modules")); }), )); + // A file that a link leads to is judged once every directory is + // read: this one lies in a directory another link leads to, which + // is found after it. cases.push(( - "a link to a file outside the project below a node_modules", + "a link to a file in a directory outside the project that is read", Box::new(|root: &Path| { - let shared = root.parent().unwrap().join("shared"); - write_pkg(&shared.join("node_modules/real"), "real", "1.0.0"); - abs_link(root, &shared.join("node_modules/app")); - std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); - std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); - abs_link( - &shared.join("lib/deep/gen.js"), - &root.join("scripts/gen.js"), - ); + let out = root.parent().unwrap().join("out"); + write_pkg(&out.join("node_modules/real"), "real", "1.0.0"); + std::fs::create_dir_all(out.join("lib")).unwrap(); + std::fs::write(out.join("lib/gen.js"), "").unwrap(); + abs_link(&out.join("lib/gen.js"), &root.join("a-file.js")); + abs_link(&out, &root.join("z-dir")); }), )); cases.push(( @@ -9402,12 +9449,13 @@ mod tests { } /// #2353: what a link leads to outside the project is read up to the - /// home directory, which is not looked at, nor is anything above it: a - /// `node_modules` there is no part of this project. And the trees - /// outside count against the same budget as the project. + /// home directory. A `node_modules` there or above it is not looked + /// at, and a link to the home directory, or to one above it, leaves the + /// answer unknown. A `node_modules` that is a link itself is followed + /// like any other link. #[cfg(unix)] #[test] - fn test_pnpm_store_links_outside_are_read_below_home_and_within_one_budget() { + fn test_pnpm_store_links_outside_are_read_below_the_home_directory() { let tmp = tempfile::tempdir().unwrap(); let base = std::fs::canonicalize(tmp.path()).unwrap(); let home = base.join("home"); @@ -9417,23 +9465,19 @@ mod tests { let store = nm.join(".pnpm"); let outside = home.join("projects/shared/lib"); std::fs::create_dir_all(&outside).unwrap(); - std::fs::write(outside.join("gen.js"), "").unwrap(); - abs_link(&outside.join("gen.js"), &root.join("scripts/gen.js")); + abs_link(&outside, &root.join("tools/lib")); let leftover = OsString::from("minimist@1.2.2"); - let live = |home: &Path, budget: usize| { + let live = |home: &Path| { live_pnpm_store_entries_under_sync( &store, &root, Some(home), - budget, + LINK_SWEEP_BUDGET, &mut HashMap::new(), ) }; - let reaches_leftover = |home: &Path| { - live(home, LINK_SWEEP_BUDGET) - .expect("the store is judged") - .contains(&leftover) - }; + let reaches_leftover = + |home: &Path| live(home).expect("the store is judged").contains(&leftover); // In the home directory itself, and above it: not looked at. abs_link(&root.join(LEFTOVER), &home.join("node_modules/minimist")); @@ -9444,11 +9488,36 @@ mod tests { "with another home" ); // Below the home directory: read. - abs_link( + let below = abs_link( &root.join(LEFTOVER), &home.join("projects/node_modules/minimist"), ); assert!(reaches_leftover(&home)); + std::fs::remove_file(below).unwrap(); + std::fs::remove_dir(home.join("projects/node_modules")).unwrap(); + assert!(!reaches_leftover(&home)); + + // A `node_modules` above the directory that is a link: what it + // leads to is read, and the `node_modules` above that as well. + let real = home.join("real/deps/nm"); + std::fs::create_dir_all(&real).unwrap(); + let linked = abs_link(&real, &home.join("projects/shared/node_modules")); + assert!(!reaches_leftover(&home)); + let behind = abs_link( + &root.join(LEFTOVER), + &home.join("real/node_modules/minimist"), + ); + assert!(reaches_leftover(&home)); + std::fs::remove_file(behind).unwrap(); + std::fs::remove_file(linked).unwrap(); + + // A link to the home directory, or to a directory above it. + for (name, target) in [("home", &home), ("above", &base)] { + let link = abs_link(target, &root.join("tools").join(name)); + assert!(live(&home).is_none(), "{name}"); + std::fs::remove_file(link).unwrap(); + } + assert!(!reaches_leftover(&home)); // The home rule holds above the scanned directory, not at it: a // project whose root is the home directory is judged. @@ -9460,7 +9529,7 @@ mod tests { ) .unwrap(); let nested = pnpm_install_into(&at_home.join("sub/node_modules"), &["packages/a"]); - let nested_stale = pnpm_entry(&nested, "minimist@1.2.2", "minimist", "1.2.2"); + pnpm_entry(&nested, "minimist@1.2.2", "minimist", "1.2.2"); let nested_routed = pnpm_entry(&nested, ROUTED_ENTRY, "minimist", "1.2.2"); write_pkg(&at_home.join("packages/a"), "a", "1.0.0"); abs_link( @@ -9476,14 +9545,59 @@ mod tests { ) .expect("a root at the home directory is judged"); assert!(!judged.contains(&leftover) && judged.len() == 1); - let _ = nested_stale; + } - // One budget for the project and what its links lead to. - let cost = |tree: &Path| sweep_tree_sync(tree, LINK_SWEEP_BUDGET).ok().unwrap().cost; - let whole = cost(&root) + cost(&home.join("projects/node_modules")); - assert!(live(&home, whole).is_some()); - assert!(live(&home, whole - 1).is_none()); - assert!(live(&home, cost(&root)).is_none()); + /// #2353: one budget holds for the project and what its links lead + /// to, and a directory is read once however many links lead into it + /// and in whatever order: the links of Bazel's `bazel-bin`, + /// `bazel-out` and `bazel-` lead to directories inside each + /// other, and a link may lead to a directory above the project. + #[cfg(unix)] + #[test] + fn test_pnpm_store_links_outside_are_read_once_within_one_budget() { + let tmp = tempfile::tempdir().unwrap(); + let base = std::fs::canonicalize(tmp.path()).unwrap(); + let root = base.join("ws/app"); + std::fs::create_dir_all(&root).unwrap(); + let (nm, _, _) = pnpm_hosted_route_leftover(&root); + let store = nm.join(".pnpm"); + let out = base.join("out/execroot"); + std::fs::create_dir_all(out.join("bazel-out/cfg/bin/pkg")).unwrap(); + std::fs::create_dir_all(out.join("bazel-out/cfg/testlogs")).unwrap(); + let live = |budget: usize| { + live_pnpm_store_entries_under_sync( + &store, + &root, + Some(&base), + budget, + &mut HashMap::new(), + ) + }; + let cost = |tree: &Path| { + sweep_tree_sync(tree, LINK_SWEEP_BUDGET, &HashSet::new()) + .ok() + .unwrap() + .cost + }; + let project = cost(&root); + assert!(live(project).is_some() && live(project - 1).is_none()); + + // The innermost directory first, then two that hold it: each is + // read once, so the whole comes to the project (with its three + // new links) and the output tree. + abs_link(&out.join("bazel-out/cfg/bin"), &root.join("bazel-bin")); + abs_link(&out.join("bazel-out"), &root.join("bazel-out")); + abs_link(&out, &root.join("bazel-ws")); + let whole = project + 3 + cost(&out); + assert!(live(whole).is_some()); + assert!(live(whole - 1).is_none()); + + // A link back to the project, and one to the directory above it, + // read nothing twice either: only `ws` itself is new. + abs_link(&root, &out.join("app")); + abs_link(root.parent().unwrap(), &root.join("up")); + assert!(live(whole + 2 + 1).is_some()); + assert!(live(whole + 2).is_none()); } /// #2353: a pnpm store is judged for a package version only when its @@ -10019,6 +10133,19 @@ mod tests { abs_link(&root.join("node_modules/.pnpm"), &root.join("vendor/store")); }), ), + ( + "a link to a file outside the project below a node_modules", + Box::new(|root: &Path| { + let shared = beside(root); + write_pkg(&shared.join("node_modules/real"), "real", "1.0.0"); + std::fs::create_dir_all(shared.join("lib/deep")).unwrap(); + std::fs::write(shared.join("lib/deep/gen.js"), "").unwrap(); + abs_link( + &shared.join("lib/deep/gen.js"), + &root.join("scripts/gen.js"), + ); + }), + ), ( "a link to a directory outside the project that is a link to the store", Box::new(|root: &Path| { diff --git a/docs/ecosystems.md b/docs/ecosystems.md index bb4778fc1..e8753ed4a 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -876,16 +876,14 @@ For pnpm the rule is narrow: `node_modules` or a directory that left the workspace counts. Nothing above that directory is read: pnpm writes no link there into a store below it. -- A link that leads out of that directory is followed, since node loads - what is behind it from where it really is. A directory behind such a - link is read the same way, and so is each `node_modules` in a - directory above it, or above a file behind such a link. So a `link:` - dependency on another checkout, the `bazel-*` links into Bazel's - output tree, and a file of a member that left the workspace (which - keeps the links pnpm wrote for it) are all read. The home directory - and what lies above it are not looked at, so a link to an interpreter - under the home directory (a virtualenv's `python`) and a stray - `~/node_modules` change nothing. +- A link to a directory outside that directory is followed, since node + loads what is behind it from where it really is. The directory is read + the same way, and so is each `node_modules` in a directory above it (a + member that left the workspace keeps the links pnpm wrote for it). So + a `link:` dependency on another checkout and the `bazel-*` links into + Bazel's output tree are read. A directory is read once, however many + links lead into it. The home directory and what lies above it are not + read. - 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, @@ -954,6 +952,13 @@ judged, as before: than 500,000 directories and links. A link that leads nowhere is left out: its target is not there, it loops, or its path passes through a file; +- when a link leads to the home directory or to a directory above it; +- when a link leads to a file outside what is read and a directory above + that file holds a `node_modules`: what the file loads by paths of its + own is not read. The home directory and what lies above it are not + looked at for this, so a link to an interpreter under the home + directory (a virtualenv's `python`) and a stray `~/node_modules` + change nothing; - when a link resolves to the store itself, or into it 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, and a file system that From dda483e959fa78e0f726ae14acb80617730184a3 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Wed, 2 Dec 2026 04:12:43 -0500 Subject: [PATCH 3/3] Bound the read outside a pnpm project by identity, order and budget Review findings on following a link out of the project: - The home directory was told by its path alone, so a link that spells it another way (macOS reaches it under /System/Volumes/Data as well) had the whole home directory read. It is told by identity now. - Each directory read was held against every directory read before it. With many separate directories outside that is quadratic. They are kept in order, and those below one are found by range. - A `node_modules` looked for above a directory outside was not charged to the budget. Each lookup counts now. - The real-pnpm steps read `node_modules` in every directory above the machine's temp directory. They run with the test's own directory as the home directory. - The independent reading in the tests did not record a `node_modules` that is a link, so it missed one that leads into the store. It records it and reads what lies above its target, and a leg now makes such a link. - The docs still said nothing above the scanned directory is read. A directory above it is read when a link leads to it or below it. - Two doc comments named a function that was renamed. Part of #2353. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/common/pnpm_links.rs | 37 ++++---- .../tests/e2e_redirect_pnpm_build.rs | 50 +++++++++- .../src/crawlers/npm_crawler.rs | 93 +++++++++++++++---- docs/ecosystems.md | 9 +- 5 files changed, 145 insertions(+), 46 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 4da651be0..eff9faa88 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -894,7 +894,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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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. A link to a directory outside it is followed: that directory, and each `node_modules` in a directory above it (up to the home directory, which is not read), are read the same way and once each, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the home directory or one above it, to a file outside what was read that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, 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 and do not hold the same bytes in each; a version in one entry is hashed as before, linked or not, and so are copies that hold the same bytes (the peer variants of a package), since leaving one out would change no verdict; copies of more than 64 MB or 50,000 files are not compared and count as holding other bytes. 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 for its own sake. A link to a directory outside it is followed: that directory, and each `node_modules` in a directory above it (up to the home directory, which is not read), are read the same way and once each, so a `link:` dependency on another checkout and Bazel's `bazel-*` links are read; a directory above the scanned one is read only this way. A link that leads nowhere (no target, a loop, a path through a file) is left out. 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, and only beside a hashed entry of the same version: when none of a version's entries is linked, all are hashed as before (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), or the store's project lies above the git checkout the run started in; under `node-linker=hoisted`, `shamefully-hoist` or a moved virtual store; when the install record or the lockfile in the store is missing or unreadable, `pnpm-lock.yaml` is unreadable, or either lists its importers in a way pnpm does not write; when a lockfile names an importer that is not a directory inside the workspace's root (under a `modulesDir` of more than one level, the directory whose `modulesDir` setting names the store's `node_modules`); when a directory or a link cannot be read, or all that is read comes to more than 500,000 directories and links; when a link resolves to the home directory or one above it, to a file outside what was read that has a `node_modules` in a directory above it (the home directory and above are not looked at), to the store itself, 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-cli/tests/common/pnpm_links.rs b/crates/socket-patch-cli/tests/common/pnpm_links.rs index 5c3ee5756..66a3ffe99 100644 --- a/crates/socket-patch-cli/tests/common/pnpm_links.rs +++ b/crates/socket-patch-cli/tests/common/pnpm_links.rs @@ -54,7 +54,10 @@ pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { let store = std::fs::canonicalize(store).unwrap(); // Node loads what a link leads to from where it really is: every // directory a link leads to outside the trees read so far is read as - // well, and so is the `node_modules` of each directory above it. + // well, and so is the `node_modules` of each directory above it. A + // `node_modules` that is a link is one more link, and what it leads + // to is read the same way. Nothing at the temp dir or above it is + // read: the tests build below it. let stop = std::fs::canonicalize(std::env::temp_dir()).unwrap(); let mut trees = vec![tree]; let mut links = Vec::new(); @@ -62,34 +65,28 @@ pub fn reachable_store_entries(tree: &Path, store: &Path) -> BTreeSet { while next < trees.len() { let found = links_below(&trees[next]); next += 1; - for (_, target) in &found { - let read = |path: &Path| trees.iter().any(|tree| path.starts_with(tree)); - if target.starts_with(&store) || read(target) { - continue; - } - // Only a directory is followed, and nothing at the temp dir - // or above it is read: the tests build below it. - if !target.is_dir() { + let mut targets: Vec = found.iter().map(|(_, to)| to.clone()).collect(); + links.extend(found); + while let Some(target) = targets.pop() { + let read = trees.iter().any(|tree| target.starts_with(tree)); + if read || target.starts_with(&store) || !target.is_dir() || stop.starts_with(&target) { continue; } - let mut open: Vec = vec![target.clone()]; for above in target.ancestors().skip(1) { if stop.starts_with(above) { break; } - if let Ok(modules) = std::fs::canonicalize(above.join("node_modules")) { - if modules.is_dir() && !modules.starts_with(&store) { - open.push(modules); - } - } - } - for dir in open { - if !trees.iter().any(|tree| dir.starts_with(tree)) { - trees.push(dir); + let modules = above.join("node_modules"); + let Ok(real) = std::fs::canonicalize(&modules) else { + continue; + }; + if real != modules { + links.push((modules, real.clone())); } + targets.push(real); } + trees.push(target); } - links.extend(found); } let mut reachable = BTreeSet::new(); loop { 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 13146952f..761614d5a 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_pnpm_build.rs @@ -3655,7 +3655,16 @@ fn write_route_workspace(proj: &Path, registry: &MockServer, modules_dir: Option /// 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( + route_vex_env(dir, server, &[]) +} + +/// [`route_vex`] with extra env. +fn route_vex_env( + dir: &Path, + server: &MockServer, + env: &[(String, String)], +) -> (i32, Vec<(String, String)>, String) { + let (code, stdout, stderr) = run_socket_env( dir, &[ "vex", @@ -3670,6 +3679,7 @@ fn route_vex(dir: &Path, server: &MockServer) -> (i32, Vec<(String, String)>, St "--patch-server-url", &server.uri(), ], + env, ); let statements = serde_json::from_str::(&stdout) .ok() @@ -3915,12 +3925,15 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: // A link that leads out of the project is followed. A directory // beside the project that links nothing of the store changes nothing; // one whose `node_modules` links the upstream leaf, as a member that - // left the workspace keeps doing, refuses the patch. + // left the workspace keeps doing, refuses the patch. The test's own + // directory stands in for the home directory, so no `node_modules` + // that the machine keeps above it is read. + let home = [("HOME".to_string(), tmp.path().to_str().unwrap().to_string())]; let outside = tmp.path().join("shared"); std::fs::create_dir_all(outside.join("lib")).unwrap(); std::fs::create_dir_all(proj.join("tools")).unwrap(); std::os::unix::fs::symlink(outside.join("lib"), proj.join("tools/lib")).unwrap(); - let (code, attested, stderr) = route_vex(&proj, &server); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); assert_eq!( code, 0, "{tag}: vex with a link out of the project:\n{stderr}" @@ -3937,7 +3950,7 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: reachable.contains("leaf@1.0.0"), "{tag}: the independent reading must follow the link out of the project: {reachable:?}" ); - let (code, attested, stderr) = route_vex(&proj, &server); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); assert_eq!(code, 0, "{tag}: vex with a stale member outside:\n{stderr}"); assert!( !attested.contains(¬_affected(leaf)) @@ -3947,12 +3960,39 @@ async fn registry_route_in_place_install_is_judged_by_every_link(pm: &str, tag: {attested:?}\n{stderr}" ); std::fs::remove_file(outside.join("node_modules/leaf")).unwrap(); - let (code, attested, stderr) = route_vex(&proj, &server); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); assert_eq!(code, 0, "{tag}: vex once the stale link is gone:\n{stderr}"); assert!( attested.contains(¬_affected(leaf)), "{tag}: without the stale link leaf is attested again: {attested:?}\n{stderr}" ); + + // A `node_modules` there that is a link itself is one more link: into + // the upstream entry's `node_modules`, it loads the upstream leaf. + std::fs::remove_dir(outside.join("node_modules")).unwrap(); + std::os::unix::fs::symlink(old_leaf.parent().unwrap(), outside.join("node_modules")).unwrap(); + let reachable = pnpm_links::reachable_store_entries(&proj, &store); + assert!( + reachable.contains("leaf@1.0.0"), + "{tag}: the independent reading must read a linked node_modules: {reachable:?}" + ); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!( + code, 0, + "{tag}: vex with a linked node_modules outside:\n{stderr}" + ); + assert!( + !attested.contains(¬_affected(leaf)) && stderr.contains("not_applied"), + "{tag}: a node_modules outside that is a link into the upstream entry must refuse \ + the patch: {attested:?}\n{stderr}" + ); + std::fs::remove_file(outside.join("node_modules")).unwrap(); + let (code, attested, stderr) = route_vex_env(&proj, &server, &home); + assert_eq!(code, 0, "{tag}: vex once that link is gone:\n{stderr}"); + assert!( + attested.contains(¬_affected(leaf)), + "{tag}: without that link leaf is attested again: {attested:?}\n{stderr}" + ); } #[cfg(unix)] diff --git a/crates/socket-patch-core/src/crawlers/npm_crawler.rs b/crates/socket-patch-core/src/crawlers/npm_crawler.rs index da2d67af6..63ef2ea9a 100644 --- a/crates/socket-patch-core/src/crawlers/npm_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/npm_crawler.rs @@ -1,4 +1,4 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use std::ffi::{OsStr, OsString}; use std::fs::FileType; use std::path::{Path, PathBuf}; @@ -843,7 +843,7 @@ fn pnpm_current_lockfile_sync( /// 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`]. +/// [`live_pnpm_store_entries_under_sync`]. fn orphaned_pnpm_store_entry_sync( store_path: &Path, entry_name: &str, @@ -904,12 +904,14 @@ fn orphaned_pnpm_store_entry_sync( /// /// `tree` is the outer of the directory `scanned` and the workspace's /// root (the directory that holds the store's `node_modules`, or the one -/// a `modulesDir` setting points from). Nothing above it is read: pnpm -/// writes no link there into a store below it. +/// a `modulesDir` setting points from). Nothing above it is read for its +/// own sake: pnpm writes no link there into a store below it. /// /// A link that leads out of `tree` is followed (see /// [`links_reached_from_sync`]): the directory behind it is read, and /// each `node_modules` above that directory, up to the home directory. +/// Only so is a directory above `tree` read: when a link leads to it, or +/// to a directory below it. /// /// Every entry is kept wherever a link may have gone unread: /// @@ -1184,18 +1186,35 @@ fn live_pnpm_store_entries_under_sync( /// a `node_modules` there is not looked at, and a link to a directory /// there leaves the answer unknown. So does a link to a file outside /// with a `node_modules` in a directory above it: what that file loads -/// by paths of its own is not read. `budget` holds for all the -/// directories and links read. +/// by paths of its own is not read. The home directory is told by what +/// names it however its path is spelled ([`file_id`]), not by its path +/// alone. `budget` holds for all the directories and links read, and for +/// each `node_modules` looked for. fn links_reached_from_sync( tree: &Path, home: Option<&Path>, budget: usize, ) -> Option> { use crate::utils::repo_root::at_or_above_home; + use std::ops::Bound; + + // The home directory and the ones above it, by path and by identity: + // a link may spell one another way (macOS reaches a volume under + // `/System/Volumes/Data` as well). + let home_ids: Vec<_> = home + .into_iter() + .flat_map(Path::ancestors) + .filter_map(file_id) + .collect(); + let not_read = |dir: &Path| { + at_or_above_home(dir, home) + || (!home_ids.is_empty() && file_id(dir).is_some_and(|id| home_ids.contains(&id))) + }; let mut links: Vec = Vec::new(); - // The directories read, and those still to read. - let mut roots: HashSet = HashSet::new(); + // The directories read (in order, so that those below one are found + // without going through them all), and those still to read. + let mut roots: BTreeSet = BTreeSet::new(); let mut queue: VecDeque = VecDeque::from([tree.to_path_buf()]); let mut queued: HashSet = queue.iter().cloned().collect(); // Directories whose `node_modules` was looked for. @@ -1204,15 +1223,16 @@ fn links_reached_from_sync( let mut files: Vec = Vec::new(); let mut left = budget; let inside = - |roots: &HashSet, path: &Path| path.ancestors().any(|dir| roots.contains(dir)); + |roots: &BTreeSet, path: &Path| path.ancestors().any(|dir| roots.contains(dir)); while let Some(root) = queue.pop_front() { if inside(&roots, &root) { continue; } - // Read around what was read already. + // Read around what was read already: the directories below + // `root` sort right after it. let read: HashSet = roots - .iter() - .filter(|done| done.starts_with(&root)) + .range::((Bound::Excluded(root.as_path()), Bound::Unbounded)) + .take_while(|done| done.starts_with(&root)) .cloned() .collect(); let sweep = sweep_tree_sync(&root, left, &read).ok()?; @@ -1230,13 +1250,15 @@ fn links_reached_from_sync( files.push(target); continue; } - if at_or_above_home(&target, home) { + if not_read(&target) { return None; } for dir in target.ancestors().skip(1) { - if at_or_above_home(dir, home) || !above.insert(dir.to_path_buf()) { + if above.contains(dir) || not_read(dir) { break; } + above.insert(dir.to_path_buf()); + left = left.checked_sub(1)?; let nm = dir.join("node_modules"); let real = match std::fs::canonicalize(&nm) { Ok(real) if real.is_dir() => real, @@ -1273,9 +1295,11 @@ fn links_reached_from_sync( continue; } for dir in file.ancestors().skip(1) { - if at_or_above_home(dir, home) || !above_files.insert(dir) { + if above_files.contains(dir) || not_read(dir) { break; } + above_files.insert(dir); + left = left.checked_sub(1)?; match std::fs::metadata(dir.join("node_modules")) { Ok(meta) if meta.is_dir() => return None, Ok(_) => {} @@ -1738,7 +1762,7 @@ const WORKSPACE_GLOB_DIR_BUDGET: usize = 20_000; /// Which entries of the Bun and pnpm stores of a crawled tree the install /// still links (#599, #2353): an entry no link leads to is no installed /// copy (see [`live_bun_store_entries_sync`] and -/// [`live_pnpm_store_entries_sync`]; a path to an entry that a file +/// [`live_pnpm_store_entries_under_sync`]; a path to an entry that a file /// spells out is not read), 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 @@ -9105,6 +9129,18 @@ mod tests { abs_link(&shared.join("lib/deep"), &root.join("tools/deep")) }), ), + ( + "a directory outside the project whose node_modules is a link into the leftover", + Box::new(|root: &Path| { + let shared = root.parent().unwrap().join("shared"); + std::fs::create_dir_all(shared.join("lib")).unwrap(); + abs_link( + root.join(LEFTOVER).parent().unwrap(), + &shared.join("node_modules"), + ); + abs_link(&shared.join("lib"), &root.join("tools/lib")) + }), + ), ( "a chain of two directories outside the project", Box::new(|root: &Path| { @@ -9519,6 +9555,27 @@ mod tests { } assert!(!reaches_leftover(&home)); + // The home directory by another spelling of its path is the home + // directory still: macOS reaches the data volume under + // `/System/Volumes/Data` as well, and `canonicalize` keeps that + // spelling. Only where the temp dir is on that volume. + #[cfg(target_os = "macos")] + { + let spelled = Path::new("/System/Volumes/Data").join(home.strip_prefix("/").unwrap()); + if spelled.is_dir() { + let link = abs_link(&spelled, &root.join("tools/home")); + assert!(live(&home).is_none(), "a link to the home directory"); + std::fs::remove_file(link).unwrap(); + // The `node_modules` in it still links the leftover. + let link = abs_link( + &spelled.join("projects/shared/lib"), + &root.join("tools/spelled"), + ); + assert!(!reaches_leftover(&home), "a directory below it"); + std::fs::remove_file(link).unwrap(); + } + } + // The home rule holds above the scanned directory, not at it: a // project whose root is the home directory is judged. let at_home = home.join("app"); @@ -9588,7 +9645,9 @@ mod tests { abs_link(&out.join("bazel-out/cfg/bin"), &root.join("bazel-bin")); abs_link(&out.join("bazel-out"), &root.join("bazel-out")); abs_link(&out, &root.join("bazel-ws")); - let whole = project + 3 + cost(&out); + // A `node_modules` is looked for in the four directories above + // them (`cfg`, `bazel-out`, `execroot`, `out`), once each. + let whole = project + 3 + cost(&out) + 4; assert!(live(whole).is_some()); assert!(live(whole - 1).is_none()); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index e8753ed4a..3d27e75c2 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -874,8 +874,8 @@ For pnpm the rule is narrow: 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. Nothing - above that directory is read: pnpm writes no link there into a store - below it. + above that directory is read for its own sake: pnpm writes no link + there into a store below it. - A link to a directory outside that directory is followed, since node loads what is behind it from where it really is. The directory is read the same way, and so is each `node_modules` in a directory above it (a @@ -883,7 +883,10 @@ For pnpm the rule is narrow: a `link:` dependency on another checkout and the `bazel-*` links into Bazel's output tree are read. A directory is read once, however many links lead into it. The home directory and what lies above it are not - read. + read. A directory above the project is read only this way: when a + link leads to it, or its `node_modules` sits above what a link leads + to. Only links are read there, as in the project: a path out of such + a directory that a file spells out (`require('../util')`) is not. - 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,