From 11f8bd5aaeeee6b3c064f4423b32387551ad1735 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 19 Nov 2026 15:40:10 -0500 Subject: [PATCH 1/5] Scan only a no-venv Python project's own packages A project with a Python marker (requirements.txt, pyproject.toml, ...) and no environment of its own fell back to the same site-packages list as `--global`: the interpreter on PATH, every other interpreter on the machine, and the environments tools keep for themselves (`uv tool install`, pipx apps, the Poetry installer, uv- and PDM-managed interpreters). Every package found there was offered as the project's. Hosted mode then warned `No requirements.txt entry for ` once per patch, vendored mode listed the same packages to vendor into the project, and agent mode listed them to patch in place. Two changes to the Python crawler: - The fallback reads one interpreter: the `python3` (else `python`, `py`) on PATH, asked from the project directory, and only the directories it reports. The well-known interpreter locations stand in when no interpreter answers. Other interpreters and tool environments are read only under `--global`. - That interpreter is shared, so discovery (`crawl_all`) keeps only the packages the project declares and the installed packages those require through `Requires-Dist`. Declarations read: `*requirements*.txt` / `.in` files, a `requirements/` directory, their `-r` includes, and the PEP 621 and PEP 735 tables of pyproject.toml. A declaration that is not read in full (setup.py, setup.cfg, another manager's lock, dynamic dependencies, a tool's own dependency table, a requirement on a local directory, a `${VAR}`, an unreadable include) leaves the crawl unscoped. Lookups by PURL are not scoped: a recorded patch names its package. The Hatch cells of the lockfile VEX suite wire a checkout with no lockfile and nothing installed. They passed only because the host's own Python packages made the scan query the mock API, which answers any query with the fixture's patch. The scan helper now activates a placeholder environment for those cells. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 25 + .../tests/in_process_python_envs.rs | 90 +++ .../tests/vex_pdm_hatch_common/mod.rs | 36 +- .../src/crawlers/python_crawler.rs | 129 +++- .../src/crawlers/python_crawler/scope.rs | 701 ++++++++++++++++++ .../tests/crawler_python_e2e.rs | 305 ++++++-- docs/ecosystems.md | 41 + 7 files changed, 1238 insertions(+), 89 deletions(-) create mode 100644 crates/socket-patch-core/src/crawlers/python_crawler/scope.rs diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 8f2665cba..97a7e6ffb 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1210,6 +1210,31 @@ the model is **not uniform** today: `composer.json`) is handled by invoking the tool **once per subproject** (`--cwd` each), as a per-directory CI step would. + *Python projects with no environment of their own (a refinement of "cwd-only"):* a project with a + Python marker (`pyproject.toml`, `setup.py`, `setup.cfg`, `requirements.txt` or a Python lock) and + none of the environments above installs into the interpreter on `PATH`, so that interpreter is the + one read: `python3` (else `python`, else `py`) is asked, from `--cwd`, for its + `site.getsitepackages()` and user site, and only those directories are read. The other + interpreters on the machine and the environments tools keep for themselves (`uv tool install`, + pipx apps, the Poetry installer, PDM's global project, uv- and PDM-managed interpreters) are read + only under `--global`. When no interpreter answers, the well-known interpreter locations (`/usr`, + `/usr/local`, `~/.local`, Homebrew, the python.org framework, pyenv, conda) stand in for it. That + interpreter is shared with everything else installed there, so `scan` discovery keeps only the + packages the project declares and the installed packages those require (their `Requires-Dist`, + transitively; markers and extras are not evaluated). The declarations read are the requirements + of every top-level `*requirements*.txt` / `*requirements*.in` file, of every `.txt` / `.in` file + in a top-level `requirements/` directory and of their `-r` includes, plus the PEP 621 `[project]` + `dependencies` / `optional-dependencies` and the PEP 735 `[dependency-groups]` of + `pyproject.toml`. A project that declares nothing, or whose declared packages are not installed, + has no packages there. Discovery is left unscoped (every package in that interpreter, as before) + when a declaration is not read in full: a `setup.py` or `setup.cfg`; a `poetry.lock`, `pdm.lock`, + `uv.lock` or PEP 751 / PEP 723 lock; `dynamic` dependencies; dependencies in a `[tool.poetry]`, + `[tool.pdm]`, `[tool.uv]` or `[tool.flit]` table; a requirement on a local directory or on a url + that names no package; a `${VAR}` in a requirements line; or an include that cannot be read. + `apply`, `rollback` and `vex` look a recorded patch's package up by PURL in the same interpreter + and are not scoped. A project whose environment only its manager creates (uv, Pipenv, Poetry with + its virtualenvs on) still has nothing installed until that environment exists. + *Gem install roots (a refinement of "cwd-only", not an exception to the one-project model):* the crawler probes the project's Bundler install roots in **bundler's own precedence order** — the app config file's `BUNDLE_PATH:` (`$BUNDLE_APP_CONFIG/config`, else `/.bundle/config` — what diff --git a/crates/socket-patch-cli/tests/in_process_python_envs.rs b/crates/socket-patch-cli/tests/in_process_python_envs.rs index b6219b8b3..72877af77 100644 --- a/crates/socket-patch-cli/tests/in_process_python_envs.rs +++ b/crates/socket-patch-cli/tests/in_process_python_envs.rs @@ -985,6 +985,96 @@ async fn uv_fresh_checkout_never_scans_the_system_python() { } } +/// A project whose only Python manifest is `requirements.txt`, with no +/// venv, installs into the interpreter on `PATH`, which other projects and +/// tools share. Only the packages it declares, and what those require, +/// reach the patch query, in every mode. A package that is merely installed +/// in that interpreter, or in another tool's own environment under HOME, is +/// not the project's: hosted mode has no line to pin it on, vendored mode +/// would add it to the project, and agent mode would patch a copy the +/// project never uses. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn requirements_project_without_a_venv_scans_only_what_it_declares() { + use socket_patch_cli::commands::scan::ScanMode; + use std::os::unix::fs::PermissionsExt; + + for (requirements, declared_is_found) in [ + // Nothing declared: nothing in the interpreter is the project's. + ("# only the standard library\n", false), + ("declared_pkg\n", true), + ] { + for mode in [ScanMode::Agent, ScanMode::Vendored, ScanMode::Hosted] { + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("proj"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), requirements).unwrap(); + // The interpreter on PATH, and what is installed in it. + let site = tmp.path().join("system/lib/python3.12/site-packages"); + std::fs::create_dir_all(&site).unwrap(); + write_dist_info(&site, "declared_pkg", "1.0.0"); + write_dist_info(&site, "system_decoy", "6.6.6"); + let bin = tmp.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let python = bin.join("python3"); + std::fs::write( + &python, + format!( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ + printf '%s\\n' '{}'\n", + site.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + // A pipx app's own environment under HOME. + let home = tmp.path().join("home"); + let tool = home.join(".local/pipx/venvs/hatch/lib/python3.12/site-packages"); + std::fs::create_dir_all(&tool).unwrap(); + write_dist_info(&tool, "tool_decoy", "6.6.6"); + + let server = MockServer::start().await; + mock_batch_empty(&server).await; + let saved: Vec<(&str, Option)> = + ["HOME", "PATH", "PIPX_HOME", "XDG_DATA_HOME"] + .into_iter() + .map(|key| (key, std::env::var_os(key))) + .collect(); + // The stub goes in front of the host's PATH, which the scan + // still needs for its other tools. + let mut path = vec![bin.clone()]; + path.extend(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + )); + std::env::set_var("PATH", std::env::join_paths(path).unwrap()); + std::env::set_var("HOME", &home); + std::env::remove_var("PIPX_HOME"); + std::env::remove_var("XDG_DATA_HOME"); + let mut args = default_args(&project, server.uri()); + args.mode = Some(mode); + let code = scan_scrubbed(args).await; + for (key, value) in saved { + match value { + Some(v) => std::env::set_var(key, v), + None => std::env::remove_var(key), + } + } + + let context = format!("{requirements:?} {mode:?}"); + assert_eq!(code, 0, "{context}"); + let bodies = batch_bodies(&server).await; + if declared_is_found { + assert_discovered(&bodies, "pkg:pypi/declared-pkg@1.0.0"); + } else { + assert_not_discovered(&bodies, "pkg:pypi/declared-pkg"); + } + assert_not_discovered(&bodies, "pkg:pypi/system-decoy"); + assert_not_discovered(&bodies, "pkg:pypi/tool-decoy"); + } + } +} + /// #525: uv syncs into `UV_PROJECT_ENVIRONMENT`, absolute or relative to the /// project, and ignores an activated `VIRTUAL_ENV` for project commands. #[tokio::test] diff --git a/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs b/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs index 3ca2682ac..b59f5d9fd 100644 --- a/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs +++ b/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs @@ -420,6 +420,31 @@ pub fn path_with_fake_hatch(scratch: &Path) -> std::ffi::OsString { std::env::join_paths(paths).unwrap() } +/// A virtualenv outside the project that holds one package unrelated to the +/// fixture, for a scan to find installed. Hatch has no lockfile, so `scan` +/// learns a Hatch project's packages only from what is installed, and the +/// hosted cells wire a checkout with nothing installed. [`ScanApi`] answers +/// any batch query with the fixture's patch, so one installed package of +/// any name is enough for the scan to ask. Without it the scan asks only +/// when the host's own Python holds a package the project declares. +fn placeholder_venv(scratch: &Path) -> PathBuf { + let venv = "placeholder-venv"; + put( + scratch, + &format!( + "{}/placeholder-0.0.0.dist-info/METADATA", + site_packages_rel(venv) + ), + b"Metadata-Version: 2.1\nName: placeholder\nVersion: 0.0.0\n", + ); + put( + scratch, + &format!("{venv}/pyvenv.cfg"), + b"include-system-site-packages = false\n", + ); + scratch.join(venv) +} + /// `scan --json` (hosted: `--mode hosted`; vendored: `--mode vendored --vendor-source /// build`) in `cwd` against `api`. pub fn run_scan( @@ -451,8 +476,15 @@ pub fn run_scan( } } args.extend(extra.iter().map(|s| s.to_string())); - let out = cli() - .env("PATH", path_with_fake_hatch(cwd.parent().unwrap())) + let scratch = cwd.parent().unwrap(); + let mut cmd = cli(); + cmd.env("PATH", path_with_fake_hatch(scratch)); + // A hosted scan of a project with no lock and no environment has + // nothing to ask the API about: see `placeholder_venv`. + if mode == Mode::Hosted && !cwd.join("pdm.lock").exists() && !cwd.join(".venv").exists() { + cmd.env("VIRTUAL_ENV", placeholder_venv(scratch)); + } + let out = cmd .args(&args) .current_dir(cwd) .output() diff --git a/crates/socket-patch-core/src/crawlers/python_crawler.rs b/crates/socket-patch-core/src/crawlers/python_crawler.rs index 52d3111c8..e3f1d7035 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler.rs @@ -14,6 +14,8 @@ mod oracle; #[cfg(target_os = "macos")] mod pdm_site; +mod scope; + // --------------------------------------------------------------------------- // Python command discovery // --------------------------------------------------------------------------- @@ -2798,14 +2800,37 @@ fn memoized_site_query(runner: &ProbeRunner) -> Option { /// project: under `--global` no project's `.python-version` picks the /// Python a pyenv shim runs. pub async fn get_global_python_site_packages() -> Vec { - system_python_site_packages(ProbeRunner::global()).await + system_python_site_packages(ProbeRunner::global(), SystemReach::Machine).await } -/// [`get_global_python_site_packages`] with the interpreter asked through -/// `runner`: a project that installs into the system Python asks from its -/// own directory (`--cwd`), so a version manager's shim follows that -/// project's `.python-version`. -async fn system_python_site_packages(runner: ProbeRunner) -> Vec { +/// The `site-packages` of the interpreter a project with no environment of +/// its own installs into: the Python on `PATH`, asked from the project's +/// directory (`--cwd`) so a version manager's shim follows that project's +/// `.python-version`. Only that interpreter's own answer counts. The other +/// interpreters on the machine, and the environments tools keep for +/// themselves, hold other projects' packages: `pip install -r +/// requirements.txt` never puts this project's there. +/// +/// When no interpreter answers (none on `PATH`, or a shim that fails), the +/// well-known interpreter locations stand in for it. +async fn project_interpreter_site_packages(cwd: &Path) -> Vec { + system_python_site_packages(ProbeRunner::project(cwd), SystemReach::Project).await +} + +/// How far a search of the system Python reaches. +#[derive(Clone, Copy, PartialEq, Eq)] +enum SystemReach { + /// `--global`: every interpreter on the machine, and the environments + /// tools keep for themselves. + Machine, + /// A project with no environment of its own: the one interpreter it + /// installs into (see [`project_interpreter_site_packages`]). + Project, +} + +/// The system Python `site-packages` within `reach`, the interpreter asked +/// through `runner`. +async fn system_python_site_packages(runner: ProbeRunner, reach: SystemReach) -> Vec { let mut results = Vec::new(); let mut seen = HashSet::new(); @@ -2828,6 +2853,11 @@ async fn system_python_site_packages(runner: ProbeRunner) -> Vec { } } + // A project installs into one interpreter, and it just answered. + if reach == SystemReach::Project && !results.is_empty() { + return results; + } + // 2. Well-known system paths let home_dir = crate::utils::fs::home_dir(); @@ -2989,6 +3019,14 @@ async fn system_python_site_packages(runner: ProbeRunner) -> Vec { scan_well_known(&miniconda, "site-packages", &mut seen, &mut results).await; } + // Everything below is an environment a tool keeps for itself (`uv tool + // install`, pipx, the Poetry installer, PDM's global project) or an + // interpreter a manager downloads. No project installs its + // requirements there. + if reach == SystemReach::Project { + return results; + } + // uv tool envs (`uv tool install`): one venv per tool under every // root uv may use (see `uv_dir_candidates`). for tools in uv_dir_candidates(home_dir.as_deref(), "UV_TOOL_DIR", "tools") { @@ -3427,37 +3465,49 @@ pub async fn is_python_project(cwd: &Path) -> bool { crate::utils::python_lock::python_lock_paths(cwd).is_ok_and(|paths| !paths.is_empty()) } -/// Local-mode discovery for [`PythonCrawler::get_site_packages_paths`] -/// over an explicit environment (tests pass a closure instead of mutating -/// the process environment). +/// The site dirs of [`local_sites_with`] alone. +#[cfg(test)] async fn local_site_packages_with( cwd: &Path, var: &impl Fn(&str) -> Option, ) -> Vec { + local_sites_with(cwd, var).await.0 +} + +/// Local-mode discovery for [`PythonCrawler::get_site_packages_paths`] +/// over an explicit environment (tests pass a closure instead of mutating +/// the process environment), plus whether the dirs are the shared +/// interpreter's ([`project_interpreter_site_packages`]) rather than an +/// environment of the project's own. What is installed in a shared +/// interpreter is not all this project's: see [`scope`]. +async fn local_sites_with( + cwd: &Path, + var: &impl Fn(&str) -> Option, +) -> (Vec, bool) { let venv_paths = find_local_venv_site_packages_with(cwd, var).await; if !venv_paths.is_empty() { - return venv_paths; + return (venv_paths, false); } // A Pipenv project's env is only ever the one Pipenv resolves for it // (see `pipenv_project_site_packages`). With none yet, nothing is // installed for the project, and its lock-only packages come from // `Pipfile.lock`; the OS Python is never its env (#504, #947). if is_pipenv_project(cwd) { - return Vec::new(); + return (Vec::new(), false); } // A uv project or script lock installs only into uv's own env. With // none synced yet nothing is installed for it, and its lock-only // packages come from the lock; the OS Python is never its env (#964). if uv_owns_project_env(cwd).await { - return Vec::new(); + return (Vec::new(), false); } if poetry_owns_project_env(cwd, var).await { - return Vec::new(); + return (Vec::new(), false); } if is_python_project(cwd).await { - return system_python_site_packages(ProbeRunner::project(cwd)).await; + return (project_interpreter_site_packages(cwd).await, true); } - Vec::new() + (Vec::new(), false) } // --------------------------------------------------------------------------- @@ -3519,10 +3569,11 @@ impl PythonCrawler { /// project (see `is_python_project`) whose env is not only ever /// Pipenv's own (`is_pipenv_project`), uv's own (see /// `uv_owns_project_env`) or Poetry's own (see - /// `poetry_owns_project_env`), fall through - /// to `get_global_python_site_packages`. This mirrors the - /// cargo / ruby / go pattern where a project marker - /// indicates "scan this ecosystem globally for this project". + /// `poetry_owns_project_env`), fall through to the interpreter + /// the project installs into + /// (`project_interpreter_site_packages`): the Python on `PATH`, + /// not every interpreter and tool environment on the machine, + /// which only `--global` reads. /// /// A fresh uv clone (`uv.lock`, no `.venv` yet) returns nothing: /// its lock-only packages come from `uv.lock` instead. @@ -3542,19 +3593,38 @@ impl PythonCrawler { options: &CrawlerOptions, var: &impl Fn(&str) -> Option, ) -> Result, std::io::Error> { + Ok(self.sites_with(options, var).await.0) + } + + /// [`Self::get_site_packages_paths_with`], plus whether the dirs are + /// the interpreter a project with no environment of its own shares + /// with everything else installed there (see [`local_sites_with`]). + async fn sites_with( + &self, + options: &CrawlerOptions, + var: &impl Fn(&str) -> Option, + ) -> (Vec, bool) { if options.global || options.global_prefix.is_some() { self.shadowed_lock().clear(); if let Some(ref custom) = options.global_prefix { - return Ok(vec![custom.clone()]); + return (vec![custom.clone()], false); } - return Ok(get_global_python_site_packages().await); + return (get_global_python_site_packages().await, false); } - let sites = local_site_packages_with(&options.cwd, var).await; + let (sites, shared) = local_sites_with(&options.cwd, var).await; self.set_search_order(&sites).await; - Ok(sites) + (sites, shared) } /// Crawl all discovered `site-packages` and return every package found. + /// + /// A project with no environment of its own is crawled in the + /// interpreter it shares with the rest of the machine, so only the + /// packages it declares, and the installed packages those require, are + /// returned ([`scope`]): another project's packages in that interpreter + /// are not this project's. A project whose declarations are not all + /// read (a `setup.py`, another manager's lock) is crawled unscoped. + /// Lookups by PURL are never scoped: a recorded patch names its package. pub async fn crawl_all(&self, options: &CrawlerOptions) -> Vec { let var = |name: &str| std::env::var(name).ok(); self.crawl_all_with(options, &var).await @@ -3569,14 +3639,19 @@ impl PythonCrawler { let mut packages = Vec::new(); let mut seen = HashSet::new(); - let sp_paths = self - .get_site_packages_paths_with(options, var) - .await - .unwrap_or_default(); + let (sp_paths, shared) = self.sites_with(options, var).await; + let scope = if shared { + scope::project_scope(&options.cwd, &sp_paths).await + } else { + None + }; for sp_path in &sp_paths { let listing = self.visible(sp_path, list_dist_info_packages(sp_path).await); for (name, version) in listing { + if scope.as_ref().is_some_and(|scope| !scope.contains(&name)) { + continue; + } let purl = format!("pkg:pypi/{name}@{version}"); if !seen.insert(purl.clone()) { continue; diff --git a/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs new file mode 100644 index 000000000..76065385b --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs @@ -0,0 +1,701 @@ +//! Which installed packages belong to a Python project that has no +//! environment of its own. +//! +//! A project with a `requirements.txt` or a `pyproject.toml` and no +//! virtualenv installs into the interpreter on `PATH`, and that interpreter +//! is shared: the distro's own packages, Homebrew's formulae and every +//! other project installed there sit in the same site-packages. A package +//! being installed there says nothing about whether this project uses it, +//! so the crawl keeps only the packages the project declares and the +//! installed packages those require. This is the Python counterpart of the +//! Maven local-repository scope ([`maven_scope`](super::super::maven_scope)). +//! +//! The scope applies only when every dependency declaration of the project +//! is one this module reads in full: pip requirements files, and the +//! PEP 621 / PEP 735 tables of `pyproject.toml`. Anything else (`setup.py`, +//! another manager's lock, a requirement on a local directory) leaves the +//! crawl unscoped, as it was before the scope existed. + +use std::collections::{BTreeSet, HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use toml_edit::{DocumentMut, Item}; + +use super::{canonicalize_pypi_name, read_egg_info_metadata_sync, read_python_metadata_sync}; +use crate::crawlers::listing::list_dir_sync; +use crate::utils::fs::{is_dir_sync, read_regular_to_string_sync, run_blocking}; +use crate::utils::requirements::{ + archive_filename_coords, editable_location, egg_name, has_env_reference, logical_lines, + names_before_at, parse_requirement, pip_reads_as_path, requirement_name, strip_comment, + strip_path_extras, +}; +use crate::vendor::lock_inventory::ProjectView; +use crate::vendor::pypi_requirements::{decode_requirements, requirements_includes}; + +/// The canonical names of the packages that belong to the project at `cwd` +/// among the distributions installed in `sites`: the ones it declares and, +/// transitively, the ones those require. `None` when the project declares +/// dependencies in a way this module does not read in full; the crawl then +/// stays unscoped. +pub(super) async fn project_scope(cwd: &Path, sites: &[PathBuf]) -> Option> { + let declared = declared_names(cwd).await?; + let sites = sites.to_vec(); + Some(run_blocking(move || required_closure(declared, &sites)).await) +} + +/// Files that decide a project's dependencies in a way this module does +/// not read: setuptools code and its legacy config, and the locks of the +/// managers whose projects can still install into the shared interpreter +/// (Poetry with `virtualenvs.create = false`, PDM without a venv). +const UNREAD_DECLARATIONS: &[&str] = &[ + "setup.py", + "setup.cfg", + "uv.lock", + "poetry.lock", + "pdm.lock", +]; + +/// `pyproject.toml` tables, under `[tool]`, where a manager keeps +/// dependencies in its own format instead of the PEP 621 `[project]` table. +const UNREAD_TOOL_TABLES: &[&[&str]] = &[ + &["poetry", "dependencies"], + &["poetry", "dev-dependencies"], + &["poetry", "group"], + &["pdm", "dev-dependencies"], + &["uv", "dev-dependencies"], + &["flit", "metadata"], +]; + +/// The canonical names the project at `cwd` declares as dependencies, over +/// all of its requirements files and its `pyproject.toml`. `None` when one +/// of its declarations is not read in full (see the module docs). +async fn declared_names(cwd: &Path) -> Option> { + let view = ProjectView::Disk(cwd); + for name in UNREAD_DECLARATIONS { + if view.exists_no_follow(name).await { + return None; + } + } + // A PEP 751 or PEP 723 lock lists a resolved set this module does not + // read either. + if crate::utils::python_lock::python_lock_paths(cwd).is_ok_and(|locks| !locks.is_empty()) { + return None; + } + let mut names = BTreeSet::new(); + match view.read_text("pyproject.toml").await { + Ok(text) => pyproject_declares(&text, &mut names)?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + let files = requirements_files(&view).await?; + requirements_declare(&view, files, &mut names).await?; + Some(names) +} + +/// The pip requirements files the project keeps: every top-level `*.txt` or +/// `*.in` file with `requirements` in its name (`requirements.txt`, +/// `requirements-dev.txt`, `dev-requirements.txt`, `requirements.in`) and +/// every `*.txt` or `*.in` file in a top-level `requirements/` directory, +/// whatever its name. A project installs from several of them, so a +/// package any of them names is one of its packages. `None` when the +/// project directory cannot be listed. +async fn requirements_files(view: &ProjectView<'_>) -> Option> { + let pip_reads = |name: &str| { + let lower = name.to_ascii_lowercase(); + lower.ends_with(".txt") || lower.ends_with(".in") + }; + let mut files = Vec::new(); + for entry in view.list_dir("").await.ok()? { + if entry.is_dir { + if entry.name == "requirements" { + for child in view.list_dir(&entry.name).await.ok()? { + if !child.is_dir && pip_reads(&child.name) { + files.push(format!("{}/{}", entry.name, child.name)); + } + } + } + } else if pip_reads(&entry.name) && entry.name.to_ascii_lowercase().contains("requirements") + { + files.push(entry.name); + } + } + Some(files) +} + +/// Adds to `names` every package `files` and their `-r` includes name. +/// `None` when a file cannot be read (a missing or out-of-root include, an +/// encoding pip's rules do not decode) or holds a line whose package cannot +/// be told ([`line_declares`]). +async fn requirements_declare( + view: &ProjectView<'_>, + files: Vec, + names: &mut BTreeSet, +) -> Option<()> { + let mut visited: HashSet = HashSet::new(); + let mut pending = files; + while let Some(rel) = pending.pop() { + if !visited.insert(rel.clone()) { + continue; + } + let content = view + .read_bytes(&rel) + .await + .and_then(decode_requirements) + .ok()?; + for line in logical_lines(&content) { + line_declares(strip_comment(&line.text), names)?; + } + pending.extend(requirements_includes(&rel, &content)); + } + Some(()) +} + +/// Adds to `names` the package one requirements line (comment stripped) +/// installs. `None` when the line installs something whose name cannot be +/// told from the file. +fn line_declares(code: &str, names: &mut BTreeSet) -> Option<()> { + let code = code.trim(); + if code.is_empty() { + return Some(()); + } + // pip expands `${NAME}` where it runs, so what the line installs is + // not knowable here. + if has_env_reference(code) { + return None; + } + if let Some(location) = editable_location(code) { + return location_declares(location, names); + } + // Every other option line installs nothing itself: the walk follows + // `-r`, `-c` only constrains, and the rest configure pip. + if code.starts_with('-') { + return Some(()); + } + let token = code.split_whitespace().next()?; + if !names_before_at(token) && (token.contains("://") || pip_reads_as_path(token)) { + return location_declares(token, names); + } + names.insert(canonicalize_pypi_name(parse_requirement(code)?.name)); + Some(()) +} + +/// Adds to `names` the package a path, archive or url requirement installs: +/// the one its `#egg=` fragment or its archive file name gives. The project +/// directory itself (`.`, `-e .`, `.[dev]`) adds nothing here, since its +/// dependencies are the ones `pyproject.toml` declares. `None` for any other +/// location, such as a sibling source directory, whose metadata this module +/// does not read. +fn location_declares(location: &str, names: &mut BTreeSet) -> Option<()> { + if let Some(name) = egg_name(location) { + names.insert(canonicalize_pypi_name(name)); + return Some(()); + } + let path = location.split(['#', '?', ';']).next().unwrap_or(location); + let path = strip_path_extras(path); + if path.trim_end_matches(['/', '\\']) == "." { + return Some(()); + } + let leaf = path.rsplit(['/', '\\']).next()?; + let (distribution, _) = archive_filename_coords(leaf)?; + names.insert(canonicalize_pypi_name(distribution)); + Some(()) +} + +/// Adds to `names` what a `pyproject.toml` declares: the PEP 621 `[project]` +/// name, `dependencies` and `optional-dependencies`, and the PEP 735 +/// `[dependency-groups]`. A file with none of those tables (linter and +/// formatter configuration only) declares nothing. `None` for a file that +/// does not parse, a dependency list the build backend fills in at build +/// time (`dynamic`), an entry that is not a PEP 508 requirement, and +/// dependencies kept in a tool's own table ([`UNREAD_TOOL_TABLES`]). +fn pyproject_declares(text: &str, names: &mut BTreeSet) -> Option<()> { + let document: DocumentMut = text.parse().ok()?; + let root = document.as_item(); + let unread = UNREAD_TOOL_TABLES + .iter() + .any(|path| lookup(root, &[&["tool"][..], *path].concat()).is_some()); + if unread { + return None; + } + if let Some(project) = root.get("project") { + let project = project.as_table_like()?; + if let Some(dynamic) = project.get("dynamic") { + for field in dynamic.as_array()? { + if matches!(field.as_str()?, "dependencies" | "optional-dependencies") { + return None; + } + } + } + if let Some(name) = project.get("name").and_then(Item::as_str) { + names.insert(canonicalize_pypi_name(name)); + } + if let Some(dependencies) = project.get("dependencies") { + array_declares(dependencies, names)?; + } + if let Some(optional) = project.get("optional-dependencies") { + for (_, extra) in optional.as_table_like()?.iter() { + array_declares(extra, names)?; + } + } + } + if let Some(groups) = root.get("dependency-groups") { + for (_, group) in groups.as_table_like()?.iter() { + array_declares(group, names)?; + } + } + Some(()) +} + +/// The item at `path` under `item`, each step through a table. +fn lookup<'a>(item: &'a Item, path: &[&str]) -> Option<&'a Item> { + path.iter() + .try_fold(item, |item, key| item.as_table_like()?.get(key)) +} + +/// Adds to `names` the PEP 508 requirements of a TOML array. A PEP 735 +/// `{include-group = "…"}` entry names another group of the same table, +/// which is read on its own. `None` when `item` is not an array or holds an +/// entry that is neither. +fn array_declares(item: &Item, names: &mut BTreeSet) -> Option<()> { + for entry in item.as_array()? { + if entry.is_inline_table() { + continue; + } + names.insert(canonicalize_pypi_name( + parse_requirement(entry.as_str()?)?.name, + )); + } + Some(()) +} + +/// `declared`, plus every package the distributions installed in `sites` +/// under those names require, transitively. Markers and extras are not +/// evaluated: a requirement that applies only on another platform, or only +/// with an extra nobody asked for, is followed too. That errs toward +/// keeping a package, which is what the crawl did before the scope existed. +fn required_closure(declared: BTreeSet, sites: &[PathBuf]) -> HashSet { + let mut requires: HashMap> = HashMap::new(); + for site in sites { + for entry in list_dir_sync(site) { + let file_name = entry.name.to_string_lossy(); + let path = site.join(&*file_name); + let installed = if file_name.ends_with(".dist-info") { + read_python_metadata_sync(&path).map(|(name, _)| (name, dist_info_requires(&path))) + } else if file_name.ends_with(".egg-info") { + read_egg_info_metadata_sync(&path).map(|(name, _)| (name, egg_info_requires(&path))) + } else { + None + }; + if let Some((name, required)) = installed { + requires + .entry(canonicalize_pypi_name(&name)) + .or_default() + .extend(required); + } + } + } + let mut scope = HashSet::new(); + let mut pending: Vec = declared.into_iter().collect(); + while let Some(name) = pending.pop() { + if !scope.insert(name.clone()) { + continue; + } + if let Some(required) = requires.get(&name) { + pending.extend(required.iter().cloned()); + } + } + scope +} + +/// The canonical names a `.dist-info` directory's `METADATA` requires. +fn dist_info_requires(dist_info: &Path) -> Vec { + read_regular_to_string_sync(&dist_info.join("METADATA")) + .map(|content| metadata_requires(&content)) + .unwrap_or_default() +} + +/// The canonical names a legacy `.egg-info` entry requires: the +/// `Requires-Dist` headers of its `PKG-INFO` (the entry itself when it is a +/// bare file) and, for a directory, every line of its `requires.txt`, whose +/// `[extra]` and `[:marker]` section headers name no package. +fn egg_info_requires(egg_info: &Path) -> Vec { + let requires_of = |path: &Path| { + read_regular_to_string_sync(path) + .map(|content| metadata_requires(&content)) + .unwrap_or_default() + }; + if !is_dir_sync(egg_info) { + return requires_of(egg_info); + } + let mut required = requires_of(&egg_info.join("PKG-INFO")); + if let Ok(content) = read_regular_to_string_sync(&egg_info.join("requires.txt")) { + required.extend( + content + .lines() + .filter_map(requirement_name) + .map(canonicalize_pypi_name), + ); + } + required +} + +/// The canonical names in the `Requires-Dist` headers of a core-metadata +/// file. The header block ends at the first empty line, as an email parser +/// reads it: a whitespace-only line continues the header before it (a +/// multi-line `License`), so it does not hide the requirements after it. +fn metadata_requires(content: &str) -> Vec { + content + .lines() + .take_while(|line| !line.is_empty()) + .filter_map(|line| line.strip_prefix("Requires-Dist:")) + .filter_map(requirement_name) + .map(canonicalize_pypi_name) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(root: &Path, rel: &str, content: &str) { + let path = root.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, content).unwrap(); + } + + fn names(list: &[&str]) -> BTreeSet { + list.iter().map(|name| name.to_string()).collect() + } + + /// A `.dist-info` install of `name` requiring `requires` (each a full + /// `Requires-Dist` value). + fn install(site: &Path, name: &str, version: &str, requires: &[&str]) { + let mut metadata = format!("Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"); + for requirement in requires { + metadata.push_str(&format!("Requires-Dist: {requirement}\n")); + } + metadata.push_str("\nRequires-Dist: body-text-is-not-a-header\n"); + write( + site, + &format!("{name}-{version}.dist-info/METADATA"), + &metadata, + ); + } + + async fn declared(files: &[(&str, &str)]) -> Option> { + let project = tempfile::tempdir().unwrap(); + for (rel, content) in files { + write(project.path(), rel, content); + } + declared_names(project.path()).await + } + + #[tokio::test] + async fn requirements_lines_name_their_packages() { + let content = "\ +# a comment, then a blank line + +Requests[security]>=2.0 ; python_version >= '3.8' # trailing comment +zope.interface==6.0 \\ + --hash=sha256:0000000000000000000000000000000000000000000000000000000000000000 +six @ https://patch.socket.dev/six-1.16.0-py2.py3-none-any.whl#sha256=00 +idna@https://example.test/idna-3.7-py3-none-any.whl +./wheels/typing_extensions-4.12.0-py3-none-any.whl +https://example.test/packages/attrs-23.2.0.tar.gz +git+https://example.test/org/repo.git@v1#egg=Private_Lib +-e . +.[dev] +--index-url https://example.test/simple +--extra-index-url https://example.test/extra +-c constraints.txt +"; + assert_eq!( + declared(&[ + ("requirements.txt", content), + // A constraints file adds no requirement. + ("constraints.txt", "urllib3==2.0.0\n"), + ]) + .await, + Some(names(&[ + "attrs", + "idna", + "private-lib", + "requests", + "six", + "typing-extensions", + "zope-interface", + ])) + ); + } + + #[tokio::test] + async fn a_requirements_file_with_no_requirement_declares_nothing() { + assert_eq!( + declared(&[("requirements.txt", "# only stdlib\n\n# (json, sys)\n")]).await, + Some(BTreeSet::new()) + ); + } + + #[tokio::test] + async fn includes_and_sibling_requirements_files_are_read() { + assert_eq!( + declared(&[ + ("requirements.txt", "-r requirements/base.txt\nflask\n"), + ("requirements/base.txt", "-r ../shared.txt\nclick\n"), + ("shared.txt", "jinja2\n"), + ("requirements/test.txt", "pytest\n"), + ("requirements/README.md", "not-a-requirement\n"), + ("requirements-dev.txt", "ruff\n"), + ("dev-requirements.txt", "mypy\n"), + ("requirements.in", "flask\n"), + // Not a requirements file by name: never read. + ("notes.txt", "this is not pip syntax ===\n"), + ]) + .await, + Some(names(&[ + "click", "flask", "jinja2", "mypy", "pytest", "ruff" + ])) + ); + } + + #[tokio::test] + async fn an_include_cycle_ends() { + assert_eq!( + declared(&[ + ("requirements.txt", "-r requirements-dev.txt\nflask\n"), + ("requirements-dev.txt", "-r requirements.txt\nruff\n"), + ]) + .await, + Some(names(&["flask", "ruff"])) + ); + } + + #[tokio::test] + async fn a_declaration_that_is_not_read_in_full_leaves_the_crawl_unscoped() { + let requirements = ("requirements.txt", "flask\n"); + for unread in [ + ("setup.py", "from setuptools import setup\nsetup()\n"), + ("setup.cfg", "[options]\ninstall_requires = six\n"), + ("poetry.lock", ""), + ("pdm.lock", ""), + ("uv.lock", "version = 1\n"), + ("pylock.toml", "lock-version = \"1.0\"\n"), + // Not valid TOML. + ("pyproject.toml", "[project\n"), + ( + "pyproject.toml", + "[project]\nname = \"app\"\ndynamic = [\"dependencies\"]\n", + ), + ( + "pyproject.toml", + "[project]\nname = \"app\"\ndynamic = [\"version\", \"optional-dependencies\"]\n", + ), + ( + "pyproject.toml", + "[tool.poetry.dependencies]\nflask = \"^3\"\n", + ), + ( + "pyproject.toml", + "[tool.poetry.group.dev.dependencies]\nruff = \"*\"\n", + ), + ( + "pyproject.toml", + "[tool.pdm.dev-dependencies]\ntest = [\"pytest\"]\n", + ), + ( + "pyproject.toml", + "[tool.uv]\ndev-dependencies = [\"ruff\"]\n", + ), + ( + "pyproject.toml", + "[tool.flit.metadata]\nrequires = [\"six\"]\n", + ), + // Not a PEP 508 requirement. + ( + "pyproject.toml", + "[project]\ndependencies = [\"./local\"]\n", + ), + ("pyproject.toml", "[project]\ndependencies = \"flask\"\n"), + ] { + assert_eq!(declared(&[requirements, unread]).await, None, "{unread:?}"); + } + for line in [ + // Another source directory: its metadata is not read. + "-e ./libs/shared", + "../shared", + // A url that names no package. + "https://example.test/download/latest", + "git+https://example.test/org/repo.git", + // pip expands these where it runs. + "flask==${FLASK_VERSION}", + "-r ${REQUIREMENTS_DIR}/base.txt", + // A missing include is pip's error; what it held is unknown. + "-r missing.txt", + // Not a requirement pip reads. + "flask/extra", + ] { + let content = format!("six\n{line}\n"); + assert_eq!( + declared(&[("requirements.txt", content.as_str())]).await, + None, + "{line:?}" + ); + } + // An unreadable sibling requirements file counts too. + assert_eq!( + declared(&[requirements, ("requirements-dev.txt", "-r missing.txt\n")]).await, + None + ); + } + + #[tokio::test] + async fn pyproject_declares_its_pep_621_and_pep_735_tables() { + let pyproject = r#" +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "My_App" +dynamic = ["version"] +dependencies = [ + "Flask>=3", + "requests[socks] ; python_version >= '3.9'", +] + +[project.optional-dependencies] +postgres = ["psycopg>=3"] + +[dependency-groups] +test = ["pytest", { include-group = "lint" }] +lint = ["ruff"] + +[tool.ruff] +line-length = 100 +"#; + assert_eq!( + declared(&[("pyproject.toml", pyproject)]).await, + Some(names(&[ + "flask", "my-app", "psycopg", "pytest", "requests", "ruff" + ])) + ); + // Tool configuration alone declares nothing, and does not stop the + // requirements files from being read. + assert_eq!( + declared(&[ + ("pyproject.toml", "[tool.black]\nline-length = 100\n"), + ("requirements.txt", "flask\n"), + ]) + .await, + Some(names(&["flask"])) + ); + assert_eq!( + declared(&[( + "pyproject.toml", + "[tool.poetry-dynamic-versioning]\nenable = true\n" + )]) + .await, + Some(BTreeSet::new()) + ); + } + + #[test] + fn the_closure_follows_installed_requirements() { + let tmp = tempfile::tempdir().unwrap(); + let (system, user) = (tmp.path().join("system"), tmp.path().join("user")); + install( + &system, + "requests", + "2.32.0", + &[ + "charset_normalizer<4,>=2", + "idna (<4,>=2.5)", + "urllib3<3,>=1.21.1", + "certifi>=2017.4.17", + // An extra nobody asked for is followed too. + "PySocks!=1.5.7,>=1.5.6; extra == \"socks\"", + ], + ); + install(&system, "urllib3", "2.2.0", &[]); + install(&system, "PySocks", "1.7.1", &[]); + // The requirement is met from another site dir of the interpreter. + install(&user, "certifi", "2024.2.2", &[]); + // A cycle. + install(&system, "idna", "3.7", &["requests"]); + // Installed, required by nothing the project declares. + install(&system, "setuptools", "70.0.0", &[]); + install(&system, "anyio", "4.13.0", &["sniffio>=1.1"]); + install(&system, "sniffio", "1.3.1", &[]); + let sites = [system, user]; + + let scope = required_closure(names(&["requests", "not-installed"]), &sites); + let mut scope: Vec<_> = scope.into_iter().collect(); + scope.sort(); + assert_eq!( + scope, + [ + "certifi", + // Required, not installed: a name, never a crawled package. + "charset-normalizer", + "idna", + "not-installed", + "pysocks", + "requests", + "urllib3", + ] + ); + assert!(required_closure(BTreeSet::new(), &sites).is_empty()); + } + + #[test] + fn the_closure_reads_legacy_egg_info_requirements() { + let tmp = tempfile::tempdir().unwrap(); + let site = tmp.path(); + write( + site, + "old_app-1.0.egg-info/PKG-INFO", + "Metadata-Version: 1.1\nName: old-app\nVersion: 1.0\n", + ); + write( + site, + "old_app-1.0.egg-info/requires.txt", + "six>=1.0\n\n[socks]\nPySocks\n\n[:python_version < \"3\"]\nenum34\n", + ); + // A bare-file `.egg-info` is its own PKG-INFO. + write( + site, + "six-1.16.0.egg-info", + "Metadata-Version: 2.1\nName: six\nVersion: 1.16.0\nRequires-Dist: typing\n", + ); + let mut scope: Vec<_> = required_closure(names(&["old-app"]), &[site.to_path_buf()]) + .into_iter() + .collect(); + scope.sort(); + assert_eq!(scope, ["enum34", "old-app", "pysocks", "six", "typing"]); + } + + #[test] + fn requirements_after_a_folded_header_are_read() { + let metadata = "Metadata-Version: 2.1\nName: app\nVersion: 1.0\nLicense: MIT\n \n Permission is hereby granted\nRequires-Dist: six\n\nRequires-Dist: body\n"; + assert_eq!(metadata_requires(metadata), ["six"]); + } + + #[tokio::test] + async fn project_scope_joins_the_declaration_and_the_closure() { + let tmp = tempfile::tempdir().unwrap(); + let (project, site) = (tmp.path().join("project"), tmp.path().join("site")); + write(&project, "requirements.txt", "flask\n"); + install(&site, "Flask", "3.0.0", &["Werkzeug>=3.0.0"]); + install(&site, "werkzeug", "3.0.1", &[]); + install(&site, "certifi", "2026.7.22", &[]); + let scope = project_scope(&project, std::slice::from_ref(&site)) + .await + .unwrap(); + assert_eq!( + scope, + HashSet::from(["flask".to_string(), "werkzeug".to_string()]) + ); + write(&project, "setup.py", ""); + assert_eq!(project_scope(&project, &[site]).await, None); + } +} diff --git a/crates/socket-patch-core/tests/crawler_python_e2e.rs b/crates/socket-patch-core/tests/crawler_python_e2e.rs index 79d6e811f..5219d4e25 100644 --- a/crates/socket-patch-core/tests/crawler_python_e2e.rs +++ b/crates/socket-patch-core/tests/crawler_python_e2e.rs @@ -1044,75 +1044,264 @@ async fn get_global_python_site_packages_discovers_pdm_global_project_out_of_tre // ── project-marker fallback in get_site_packages_paths ──────── -/// A project with `pyproject.toml` but no `.venv` must fall through -/// to global discovery — without this fallback, a fresh clone before -/// `uv sync` returns zero packages even when the project clearly -/// targets a Python ecosystem. +/// Env vars that pick a project's environment or interpreter. The +/// project-fallback tests unset them so an ambient value on the host +/// (an activated venv, a conda prefix) can't decide the result. +const PROJECT_ENV_VARS: &[&str] = &[ + "VIRTUAL_ENV", + "CONDA_PREFIX", + "PYENV_ROOT", + "POETRY_HOME", + "PYTHONUSERBASE", +]; + +/// Run `f` with HOME and PATH rebound and every [`PROJECT_ENV_VARS`] and +/// [`TOOL_DIR_VARS`] entry unset, restoring all of them after. PATH picks +/// the interpreter a project with no environment of its own installs into: +/// a directory holding [`install_fake_python`]'s shim, or an empty one for +/// a machine with no interpreter. +async fn with_project_env(home: &Path, path: &Path, f: F) -> T +where + F: FnOnce() -> Fut, + Fut: std::future::Future, +{ + let mut keys: Vec<&str> = vec!["HOME", "PATH"]; + keys.extend(PROJECT_ENV_VARS); + keys.extend(TOOL_DIR_VARS); + let saved: Vec<(&str, Option)> = + keys.iter().map(|k| (*k, std::env::var_os(k))).collect(); + for key in &keys { + std::env::remove_var(key); + } + std::env::set_var("HOME", home); + std::env::set_var("PATH", path); + let out = f().await; + for (key, value) in saved { + match value { + Some(v) => std::env::set_var(key, v), + None => std::env::remove_var(key), + } + } + out +} + +/// Install a fake `python3` into `bin_dir` that answers `--version` and +/// prints `sites` for every other invocation, as the crawler's `site` +/// query does for a real interpreter. +#[cfg(unix)] +fn install_fake_python(bin_dir: &Path, sites: &[&Path]) { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(bin_dir).unwrap(); + let mut script = String::from( + "#!/bin/sh\nif [ \"$1\" = --version ]; then\n echo 'Python 3.12.0'\n exit 0\nfi\n", + ); + for site in sites { + script.push_str(&format!("printf '%s\\n' '{}'\n", site.display())); + } + let bin = bin_dir.join("python3"); + std::fs::write(&bin, script).unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +/// A `.dist-info` install of `name` in `site`, requiring `requires`. +#[cfg(unix)] +fn install_dist(site: &Path, name: &str, version: &str, requires: &[&str]) { + let dist_info = site.join(format!("{name}-{version}.dist-info")); + std::fs::create_dir_all(&dist_info).unwrap(); + let mut metadata = format!("Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"); + for requirement in requires { + metadata.push_str(&format!("Requires-Dist: {requirement}\n")); + } + std::fs::write(dist_info.join("METADATA"), metadata).unwrap(); +} + +/// The `uv tool install` environment of `tool` under the stubbed HOME, in +/// the layout uv uses on this OS. +#[cfg(unix)] +fn uv_tool_site_packages(home: &Path, tool: &str) -> std::path::PathBuf { + let data = if cfg!(target_os = "macos") { + home.join("Library").join("Application Support") + } else { + home.join(".local").join("share") + }; + data.join("uv") + .join("tools") + .join(tool) + .join("lib") + .join("python3.12") + .join("site-packages") +} + +/// A project with a Python marker and no venv installs into the interpreter +/// on `PATH`, so that interpreter's own site-packages are the project's. +/// The environments other tools keep for themselves (`uv tool install`, +/// pipx) and the other interpreters on the machine are not: only `--global` +/// reads those. +#[cfg(unix)] #[tokio::test] #[serial] -async fn get_site_packages_paths_falls_back_via_pyproject_marker() { +async fn get_site_packages_paths_falls_back_to_the_interpreter_on_path() { let project = tempfile::tempdir().unwrap(); let home = tempfile::tempdir().unwrap(); - // Marker without venv. - tokio::fs::write( + let machine = tempfile::tempdir().unwrap(); + std::fs::write( project.path().join("pyproject.toml"), - b"[project]\nname = \"x\"\n", + "[project]\nname = \"x\"\n", ) - .await .unwrap(); - // Stage a uv-tools layout under the stubbed HOME so global - // discovery has something to find. - #[cfg(target_os = "macos")] - let staged = home - .path() - .join("Library") - .join("Application Support") - .join("uv") - .join("tools") - .join("ruff") - .join("lib") - .join("python3.11") - .join("site-packages"); - #[cfg(all(not(target_os = "macos"), not(windows)))] - let staged = home - .path() - .join(".local") - .join("share") - .join("uv") - .join("tools") - .join("ruff") - .join("lib") - .join("python3.11") - .join("site-packages"); - #[cfg(windows)] - let staged = home.path().join("uv-fake-staged"); - tokio::fs::create_dir_all(&staged).await.unwrap(); + let system_site = machine.path().join("lib/python3.12/site-packages"); + let user_site = home.path().join("user-site"); + std::fs::create_dir_all(&system_site).unwrap(); + install_fake_python(&machine.path().join("bin"), &[&system_site, &user_site]); + // Other environments on the machine. + let uv_tool = uv_tool_site_packages(home.path(), "poetry"); + let pipx = pipx_venv_site_packages(&home.path().join(".local").join("pipx"), "hatch"); + let conda = home.path().join("anaconda3/lib/python3.11/site-packages"); + for other in [&uv_tool, &pipx, &conda] { + std::fs::create_dir_all(other).unwrap(); + } - let prev_home = std::env::var("HOME").ok(); - std::env::set_var("HOME", home.path()); let crawler = PythonCrawler::new(); let opts = CrawlerOptions { cwd: project.path().to_path_buf(), global: false, global_prefix: None, }; - let result = crawler.get_site_packages_paths(&opts).await.unwrap(); - if let Some(v) = prev_home { - std::env::set_var("HOME", v); + let bin = machine.path().join("bin"); + let result = with_project_env(home.path(), &bin, || async { + crawler.get_site_packages_paths(&opts).await.unwrap() + }) + .await; + assert_eq!(result, vec![system_site.clone(), user_site]); + + // `--global` still reads every one of them. + let global = CrawlerOptions { + global: true, + ..opts + }; + let result = with_project_env(home.path(), &bin, || async { + crawler.get_site_packages_paths(&global).await.unwrap() + }) + .await; + for site in [&system_site, &uv_tool, &pipx, &conda] { + assert_surfaces(&result, site, "a --global site"); + } +} + +/// With no interpreter on `PATH` to ask, the well-known interpreter +/// locations stand in for it. Tool environments still don't. +#[tokio::test] +#[serial] +async fn get_site_packages_paths_without_an_interpreter_reads_the_well_known_locations() { + let project = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + let empty_path = tempfile::tempdir().unwrap(); + std::fs::write(project.path().join("requirements.txt"), "six\n").unwrap(); + let conda = home.path().join("anaconda3/lib/python3.11/site-packages"); + let pipx = pipx_venv_site_packages(&home.path().join(".local").join("pipx"), "hatch"); + for site in [&conda, &pipx] { + std::fs::create_dir_all(site).unwrap(); } + let crawler = PythonCrawler::new(); + let opts = CrawlerOptions { + cwd: project.path().to_path_buf(), + global: false, + global_prefix: None, + }; + let result = with_project_env(home.path(), empty_path.path(), || async { + crawler.get_site_packages_paths(&opts).await.unwrap() + }) + .await; #[cfg(not(windows))] - assert!( - result.iter().any(|p| p == &staged), - "pyproject.toml marker must trigger global fallback; got {result:?}" - ); - // On Windows the staged layout doesn't match the global crawler's - // search paths (different env var), so we only assert the gate - // engaged at all — i.e. some kind of result was produced. + { + assert_surfaces(&result, &conda, "a well-known interpreter location"); + assert!( + !result.contains(&pipx), + "a pipx app's environment is not the project's; got {result:?}" + ); + } #[cfg(windows)] let _ = result; } +/// A project that installs into a shared interpreter is crawled for the +/// packages it declares and what those require, not for everything else +/// installed there. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn crawl_all_in_a_shared_interpreter_keeps_only_the_projects_packages() { + let project = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + let machine = tempfile::tempdir().unwrap(); + let site = machine.path().join("lib/python3.12/site-packages"); + install_dist(&site, "Flask", "3.0.0", &["Werkzeug>=3.0.0"]); + install_dist(&site, "werkzeug", "3.0.1", &[]); + install_dist(&site, "certifi", "2026.7.22", &[]); + install_dist(&site, "setuptools", "80.10.2", &[]); + let bin = machine.path().join("bin"); + install_fake_python(&bin, &[&site]); + // Another tool's environment holds a package of its own. + let uv_tool = uv_tool_site_packages(home.path(), "poetry"); + install_dist(&uv_tool, "anyio", "4.13.0", &[]); + + let crawler = PythonCrawler::new(); + let opts = CrawlerOptions { + cwd: project.path().to_path_buf(), + global: false, + global_prefix: None, + }; + let crawl = || async { + let mut purls: Vec = with_project_env(home.path(), &bin, || async { + crawler.crawl_all(&opts).await + }) + .await + .into_iter() + .map(|package| package.purl) + .collect(); + purls.sort(); + purls + }; + let requirements = project.path().join("requirements.txt"); + + // Nothing declared: nothing in the interpreter is the project's. + std::fs::write(&requirements, "# stdlib only\n").unwrap(); + assert_eq!(crawl().await, Vec::::new()); + + // Declared but not installed. + std::fs::write(&requirements, "requests\nrich\n").unwrap(); + assert_eq!(crawl().await, Vec::::new()); + + // Declared and installed: the package and what it requires. + std::fs::write(&requirements, "flask\n").unwrap(); + assert_eq!( + crawl().await, + ["pkg:pypi/flask@3.0.0", "pkg:pypi/werkzeug@3.0.1"] + ); + + // A lookup by PURL is not scoped: a recorded patch names its package. + let certifi = "pkg:pypi/certifi@2026.7.22".to_string(); + let found = crawler + .find_by_purls(&site, std::slice::from_ref(&certifi)) + .await + .unwrap(); + assert!(found.contains_key(&certifi), "{found:?}"); + + // `setup.py` decides the dependencies in code, so the crawl is not + // scoped. It still reads only the project's interpreter. + std::fs::write(project.path().join("setup.py"), "").unwrap(); + assert_eq!( + crawl().await, + [ + "pkg:pypi/certifi@2026.7.22", + "pkg:pypi/flask@3.0.0", + "pkg:pypi/setuptools@80.10.2", + "pkg:pypi/werkzeug@3.0.1", + ] + ); +} + /// #964: a uv project (`uv.lock`) and a PEP 723 script lock (`*.py.lock`) /// only ever install into uv's own env: `.venv` / `UV_PROJECT_ENVIRONMENT` /// for a project, uv's cache for a script. With none synced yet nothing is @@ -1218,28 +1407,24 @@ async fn get_site_packages_paths_uv_lock_beside_poetry_keeps_fallback() { .join("site-packages"); tokio::fs::create_dir_all(&staged).await.unwrap(); - let prev_virtual_env = std::env::var("VIRTUAL_ENV").ok(); - std::env::remove_var("VIRTUAL_ENV"); - let prev_home = std::env::var("HOME").ok(); - std::env::set_var("HOME", home.path()); + // No interpreter on PATH: the well-known locations, which the staged + // conda prefix is one of, stand in for it. + let empty_path = tempfile::tempdir().unwrap(); let crawler = PythonCrawler::new(); let opts = CrawlerOptions { cwd: project.path().to_path_buf(), global: false, global_prefix: None, }; - let result = crawler.get_site_packages_paths(&opts).await.unwrap(); - if let Some(v) = prev_home { - std::env::set_var("HOME", v); - } - if let Some(v) = prev_virtual_env { - std::env::set_var("VIRTUAL_ENV", v); - } + let result = with_project_env(home.path(), empty_path.path(), || async { + crawler.get_site_packages_paths(&opts).await.unwrap() + }) + .await; #[cfg(not(windows))] assert!( result.iter().any(|p| p == &staged), - "uv.lock + poetry.lock must keep the global fallback; got {result:?}" + "uv.lock + poetry.lock must keep the interpreter fallback; got {result:?}" ); #[cfg(windows)] let _ = (result, staged); diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 236ad6665..16eca553c 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -950,6 +950,47 @@ so they do not depend on the order. socket-patch release that adds vlt support: an older release does not understand them. Hosted vlt pins need no ledger (v5.0): `rollback` restores them from the npm registry. +## PyPI: projects without a virtualenv + +A Python project with no environment of its own (no `.venv` or `venv`, no +activated environment, no environment its manager created) installs into +the interpreter on `PATH`. socket-patch reads that interpreter: it asks +`python3` (else `python`, else `py`), run from the project directory, for +its site-packages and user site, and reads only those directories. + +That interpreter is shared. Homebrew formulae, distro packages and other +projects install into it too, so a package being installed there does not +make it this project's. `scan` keeps only: + +- the packages the project declares: every requirement in a top-level + `*requirements*.txt` or `*requirements*.in` file, in a `.txt` or `.in` + file of a top-level `requirements/` directory and in their `-r` + includes, plus the `[project]` `dependencies` and + `optional-dependencies` and the `[dependency-groups]` of + `pyproject.toml`; +- the installed packages those require, through their `Requires-Dist` + metadata. Markers and extras are not evaluated, so an optional + requirement that is installed is kept. + +A project that declares nothing, or whose declared packages are not +installed, has no packages there. Install them first +(`pip install -r requirements.txt`), preferably into a virtualenv. + +The filter is skipped, and every package in the interpreter is reported, +when socket-patch cannot read every declaration: a `setup.py` or +`setup.cfg`, a `poetry.lock`, `pdm.lock`, `uv.lock` or PEP 751 lock, +`dynamic` dependencies, dependencies in a `[tool.poetry]`, `[tool.pdm]`, +`[tool.uv]` or `[tool.flit]` table, a requirement on a local directory, a +`${VAR}` in a requirements line, or an include that cannot be read. + +The other interpreters on the machine, and the environments tools keep for +themselves (`uv tool install`, pipx apps, the Poetry installer, PDM's +global project), are never read for a project. Use `--global` to patch +those. + +`apply`, `rollback` and `vex` find the packages of recorded patches by name +and version in the same interpreter. The filter applies to discovery only. + ## Maven & NuGet caveats Honest limits of the Maven and NuGet flows — documented behavior, not bugs: From 296b10ed6c21008c7ac9d9a33e4650f5aeb1ea82 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Thu, 19 Nov 2026 16:26:04 -0500 Subject: [PATCH 2/5] Address the code review of the Python declared-package scope - `scan --prune` no longer drops the record of a PyPI patch whose package the crawl does not report while an installed copy still carries the patch. The record holds the only before-blobs that can restore the copy. It is kept with a `pypi_installed_patch_kept` warning naming the `rollback` that restores the copy, as Cargo entries already are. - An interpreter on PATH that sits in a venv or a conda environment is the project's own environment, like an activated one, and is not scoped. - A package name is taken from an archive requirement only when it is a wheel. An sdist or a forge archive (`.../archive/release-1.0.zip`) is named however its author chose, so it leaves the crawl unscoped. - Hatch environments (`hatch.toml`, `[tool.hatch.envs]`) and `[tool.rye] dev-dependencies` leave the crawl unscoped. - A `pyproject.toml` that is there but cannot be read (a link leaving the repository) leaves the crawl unscoped instead of reading as absent. - Requirements files one directory down (`docs/requirements.txt`) are read, a linked `requirements/` directory is followed, and a path that reaches the project root from the file's directory (`-e ..`) is the project itself. - `get ` resolves a name among every package installed where the project installs, as its PURL would. - A requirement behind an extra is followed only when that extra is asked for, by a declaration or by a requiring package. One declared package with a large optional extra no longer pulls unrelated installed packages into the scope. - The Hatch scan helper of the lockfile VEX suite installs the fixture's own package, at its patched bytes, in the environment it activates, so the scan asks the API about the right package. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 30 +- crates/socket-patch-cli/src/commands/get.rs | 12 +- .../socket-patch-cli/src/commands/scan/gc.rs | 151 ++++- .../src/ecosystem_dispatch.rs | 120 +++- .../socket-patch-cli/tests/in_process_get.rs | 68 ++ .../tests/vex_pdm_hatch_common/mod.rs | 33 +- .../src/crawlers/python_crawler.rs | 52 +- .../src/crawlers/python_crawler/scope.rs | 625 ++++++++++++++---- .../src/vendor/pypi_requirements.rs | 7 +- .../tests/crawler_python_e2e.rs | 68 ++ docs/ecosystems.md | 47 +- 11 files changed, 1023 insertions(+), 190 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 97a7e6ffb..c7a3d86c0 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -348,7 +348,7 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc **Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. -`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. +`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` and `rollback --global` restore are looked up by PURL, and the wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. `scan` queries the patch API in `--batch-size` chunks. Authenticated runs POST `/v0/orgs/{slug}/patches/batch`; token-less runs POST `{proxy}/patch/batch` on the public proxy and degrade to per-package `GET /patch/by-package/:purl` requests in two cases: the deployed proxy predates the batch endpoint (legacy proxies answer the POST with their `400 "Unsupported endpoint"` catch-all), or the all-or-nothing batch validation rejects the chunk (e.g. a crawled PURL type the server doesn't recognize, such as `pkg:jsr/…` — the per-package path tolerates those individually, preserving the pre-batch scan semantics). Rate limits and over-capacity 503s surface instead of silently degrading. @@ -1218,22 +1218,33 @@ the model is **not uniform** today: interpreters on the machine and the environments tools keep for themselves (`uv tool install`, pipx apps, the Poetry installer, PDM's global project, uv- and PDM-managed interpreters) are read only under `--global`. When no interpreter answers, the well-known interpreter locations (`/usr`, - `/usr/local`, `~/.local`, Homebrew, the python.org framework, pyenv, conda) stand in for it. That + `/usr/local`, `~/.local`, Homebrew, the python.org framework, pyenv, conda) stand in for it. An + interpreter on `PATH` that sits in a venv or a conda environment (a `pyvenv.cfg` or `conda-meta` + at its root: a Docker image's `ENV PATH=/opt/venv/bin:$PATH`) is the project's own environment, + as an activated one is, and everything in it is the project's. Any other interpreter is shared with everything else installed there, so `scan` discovery keeps only the packages the project declares and the installed packages those require (their `Requires-Dist`, - transitively; markers and extras are not evaluated). The declarations read are the requirements - of every top-level `*requirements*.txt` / `*requirements*.in` file, of every `.txt` / `.in` file - in a top-level `requirements/` directory and of their `-r` includes, plus the PEP 621 `[project]` + transitively; a requirement behind an extra counts only when a declaration or a requiring + package asks for that extra, and no other marker is evaluated). The declarations read are the + requirements + of every `*requirements*.txt` / `*requirements*.in` file at the top level and one directory down + (`docs/requirements.txt`; hidden directories and `node_modules`, `site-packages`, `venv`, `env`, + `target`, `build`, `dist`, `__pycache__` are not searched), of every `.txt` / `.in` file in a + top-level `requirements/` directory and of their `-r` includes, plus the PEP 621 `[project]` `dependencies` / `optional-dependencies` and the PEP 735 `[dependency-groups]` of `pyproject.toml`. A project that declares nothing, or whose declared packages are not installed, has no packages there. Discovery is left unscoped (every package in that interpreter, as before) when a declaration is not read in full: a `setup.py` or `setup.cfg`; a `poetry.lock`, `pdm.lock`, `uv.lock` or PEP 751 / PEP 723 lock; `dynamic` dependencies; dependencies in a `[tool.poetry]`, - `[tool.pdm]`, `[tool.uv]` or `[tool.flit]` table; a requirement on a local directory or on a url - that names no package; a `${VAR}` in a requirements line; or an include that cannot be read. + `[tool.pdm]`, `[tool.uv]`, `[tool.rye]` or `[tool.flit]` table; Hatch environments (`hatch.toml`, + or a `[tool.hatch.envs]` table); a requirement on a local directory other than the project + itself, on an archive that is not a wheel (an sdist or a forge archive is named however its + author chose) or on a url that names no package; a `${VAR}` in a requirements line; or a + declaration that cannot be read (a missing include, a link leaving the repository). `apply`, `rollback` and `vex` look a recorded patch's package up by PURL in the same interpreter - and are not scoped. A project whose environment only its manager creates (uv, Pipenv, Poetry with - its virtualenvs on) still has nothing installed until that environment exists. + and are not scoped, and `get ` resolves a name among every package installed there. A + project whose environment only its manager creates (uv, Pipenv, Poetry with its virtualenvs on) + still has nothing installed until that environment exists. *Gem install roots (a refinement of "cwd-only", not an exception to the one-project model):* the crawler probes the project's Bundler install roots in **bundler's own precedence order** — the app @@ -2201,6 +2212,7 @@ command's integration tests check its output. | `vendor_revert_kept` | `skipped` + top-level error | remove (v5.0): the vendored revert drift-kept (`kept_artifact`), so the ledger entry AND the manifest entry were both kept. ANY drift-keep makes the run a `partialFailure` (exit 1) — part of the requested removal did not happen; when EVERY matching entry drift-kept, the top-level error carries this code (`summary.removed` stays 0; the identifier DID match, so never `not_found`). Remedy: re-run `scan --mode vendored` to normalize, then remove. A PyPI revert that restored its recorded wiring but kept the wheel because another project file still installs from it (`vendor_revert_residual_reference`, e.g. a `pipenv requirements` / `uv export` / `poetry export` requirements file) is a keep too, but not a drift (#1184): its skip reason, the per-entry warning, the top-level message and the message of rollback's `failed` / `vendor_revert_kept` event say that a project file still installs from the vendored artifact, and the remedy is to point the file named by `vendor_revert_residual_reference` back at the registry release (or re-export it from the restored lock), then remove (or roll back) again. Its `vendor_artifact_kept` advisory says the same, and a hosted takeover refused for it (`redirect_vendored_revert_failed`) names the file instead of a wiring edit. Rollback reports a drift-keep as a `failed` event with this code (exit 1). | | `hosted_reverted` | `removed` | remove (v5.0): a hosted lockfile pin was restored to its upstream registry entry as part of removing the patch (`verified` on dry-run). Beside a manifest entry it bypasses `summary.removed` like `vendor_reverted`. v5.0: carries `details.mode: "hosted"`. | | `hosted_revert_failed` | top-level error | remove (v5.0): a matched hosted pin could not be restored to its upstream registry entry (`--offline`, a registry that does not answer, `bun.lockb`, a lock shape the restore refuses — see "Hosted unwind coverage"), or writing the restored files failed; the message names the `git checkout -- ` remedy. The manifest was not modified, exit 1. Rollback's counterpart is a `failed` `hosted_restore_refused` event (exit 1). v4's `hosted_revert_unsupported` is no longer emitted (every ecosystem has a restore). | +| `pypi_installed_patch_kept` | `scan --prune`/`--sync` top-level `warnings[]` (human: `GC: …`) | a PyPI manifest entry the crawl does not report was NOT pruned because an installed copy still carries the agent-mode patch: a package a project with no environment of its own stopped declaring, or a copy in another interpreter or a tool's environment that an earlier release's project scan patched. The record holds the only blobs that can restore it. The detail names the purl and `socket-patch rollback ` (with `--global` when the copy is outside the interpreter the project installs into), which restores the copy and drops the entry. Never affects the exit. | | `cargo_cache_patch_kept` | `scan --prune`/`--sync` top-level `warnings[]` (human: `GC: …`) | a Cargo manifest entry the crawl no longer reports (the lock bumped or dropped the crate) was NOT pruned because its copy in the shared `$CARGO_HOME/registry/src` cache still carries the agent-mode patch; the record holds the only blobs that can restore it. The detail names the purl and `socket-patch rollback ` (with `--global` when a `cargo vendor` dir hides the registry cache from the project crawl), which restores the copy and drops the entry. Never affects the exit. | | `reinstall_required` | rollback `warnings[]` | rollback (v5.0): vendored/hosted wiring was unwound, but installed trees keep their patched bytes until the next package-manager install — the stale-install advisory. When the run also emits a Bun advisory (`vendor_bun_reinstall_required` / `redirect_bun_reinstall_required`) the detail and the human note add " (Bun: a plain `bun install` keeps them; run `bun install --force`)". When it emits a PyPI advisory (`vendor_pypi_reinstall_required` / `redirect_pypi_reinstall_required`) they add " (pip, PDM, uv and Pipenv keep a same-version install through a plain install or sync: run the reinstall the pypi_reinstall_required warning names)". When it emits `upstream_gem_stale_install` (a gem left on its patched build) they add " (Bundler: `bundle install` keeps an installed gem; see the gem warning for what to run)". | | `hosted_state_not_preservable` | rollback / remove `warnings[]` | rollback `--preserve-state` (v5.0): hosted pins were restored to upstream anyway — the lockfile pins are hosted mode's only record, so there is no local state to preserve; re-run `scan --mode hosted` to re-wire. (`remove --preserve-state` reports the same code in its `warnings[]` — manifest-backed and hosted-only alike — and prints it as a `Note:` on stderr in human mode.) | diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 2a6701060..c46839a7d 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -42,7 +42,9 @@ pub use crate::commands::agent_download::{ download_and_apply_patches_into, download_and_apply_patches_with, DownloadParams, DownloadRun, }; use crate::commands::apply::ApplyRunReport; -use crate::ecosystem_dispatch::{crawl_ecosystems, find_packages_for_rollback, partition_purls}; +use crate::ecosystem_dispatch::{ + crawl_ecosystems_for_name, find_packages_for_rollback, partition_purls, +}; use crate::json_envelope::{ usage_error, Command as JsonCommand, Envelope, EnvelopeError, PatchAction as EventAction, PatchEvent, RunWarning, Status, @@ -1435,9 +1437,13 @@ pub async fn run(args: GetArgs) -> i32 { TargetKind::Name => { status.set("Enumerating packages..."); // `--ecosystems` scopes the crawl, so a name can only resolve - // inside the selected ecosystems. + // inside the selected ecosystems. A name resolves among every + // installed package, as its PURL would: a Python project with + // no environment of its own is otherwise crawled only for the + // packages it declares. let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty()); - let (all_packages, _, _) = crawl_ecosystems(&args.common.crawler_options(), only).await; + let (all_packages, _, _) = + crawl_ecosystems_for_name(&args.common.crawler_options(), only).await; if all_packages.is_empty() { status.finish(); diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index 68fa2a87a..6c15a698a 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -286,7 +286,8 @@ async fn apply_gc_locked( }; let mut prunable = detect_prunable(&manifest, scanned_purls, vendored); keep_project_entries(common, &mut prunable).await; - let kept = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await; + let mut kept = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await; + kept.extend(keep_patched_pypi_copies(common, &manifest, socket_dir, &mut prunable).await); for purl in &prunable { manifest.patches.remove(purl); } @@ -405,6 +406,45 @@ async fn keep_patched_cargo_copies( .collect() } +/// Drop from `prunable` every PyPI entry whose agent-mode patch is still +/// on disk in a copy the crawl does not report: a project with no +/// environment of its own is crawled for the packages it declares, in the +/// one interpreter it installs into, but a package it stopped declaring, +/// or one an earlier release patched in another interpreter or a tool's +/// environment, keeps its patched copy. The manifest record holds the only +/// before-blobs that can restore that copy, so it is kept, with one +/// `pypi_installed_patch_kept` warning per entry naming the `rollback` that +/// restores the copy and then drops the record. +async fn keep_patched_pypi_copies( + common: &GlobalArgs, + manifest: &PatchManifest, + socket_dir: &Path, + prunable: &mut Vec, +) -> Vec<(&'static str, String)> { + let kept = crate::ecosystem_dispatch::pypi_copies_still_patched( + manifest, + prunable.iter(), + &common.crawler_options(), + &socket_dir.join("blobs"), + ) + .await; + prunable.retain(|p| !kept.contains(p)); + kept.into_iter() + .map(|purl| { + ( + "pypi_installed_patch_kept", + format!( + "kept {purl}: the scan no longer reports it as one of the project's \ + packages, but an installed copy is still patched (or could not be \ + read to tell); run `socket-patch rollback {purl}` (with `--global` \ + when the copy is in another interpreter or a tool's environment) \ + to restore that copy and drop the entry" + ), + ) + }) + .collect() +} + /// The vendored-state half of the GC alone, for a `--prune` whose crawl /// found nothing (the manifest half is skipped there: pruning against an /// empty crawl would drop every entry). Reverting entries whose patch left @@ -470,6 +510,7 @@ async fn preview_apply_gc( let mut prunable = detect_prunable(&manifest, scanned_purls, vendored); keep_project_entries(common, &mut prunable).await; let _ = keep_patched_cargo_copies(common, &manifest, socket_dir, &mut prunable).await; + let _ = keep_patched_pypi_copies(common, &manifest, socket_dir, &mut prunable).await; // The sweep derives the referenced set from this in-memory manifest. for purl in &prunable { manifest.patches.remove(purl); @@ -1630,4 +1671,112 @@ mod tests { ] ); } + + /// A PyPI entry the crawl does not report is kept while an installed + /// copy still carries its patch. A project with no environment of its + /// own is crawled only for the packages it declares, so a package it + /// stopped declaring drops out of the crawl with its copy still + /// patched, and the record's before-blobs are the only way to restore + /// that copy. An entry whose copy is back to the original is pruned. + #[tokio::test] + async fn prune_keeps_a_pypi_entry_whose_installed_copy_is_still_patched() { + use socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes as hash; + const ORIGINAL: &[u8] = b"VERSION = 'original'\n"; + const PATCHED: &[u8] = b"VERSION = 'patched'\n"; + + let tmp = tempfile::tempdir().unwrap(); + let site = tmp.path().join("site-packages"); + for (name, module) in [("stillpatched", PATCHED), ("restored", ORIGINAL)] { + let dist = site.join(format!("{name}-1.0.0.dist-info")); + std::fs::create_dir_all(&dist).unwrap(); + std::fs::write( + dist.join("METADATA"), + format!("Metadata-Version: 2.1\nName: {name}\nVersion: 1.0.0\n"), + ) + .unwrap(); + std::fs::create_dir_all(site.join(name)).unwrap(); + std::fs::write(site.join(name).join("__init__.py"), module).unwrap(); + } + + let project = tmp.path().join("project"); + let socket_dir = project.join(".socket"); + let blobs = socket_dir.join("blobs"); + std::fs::create_dir_all(&blobs).unwrap(); + for content in [ORIGINAL, PATCHED] { + std::fs::write(blobs.join(hash(content)), content).unwrap(); + } + let record = |name: &str, uuid: &str| { + serde_json::json!({ + "uuid": uuid, + "exportedAt": "2026-01-01T00:00:00Z", + "files": { format!("{name}/__init__.py"): { + "beforeHash": hash(ORIGINAL), + "afterHash": hash(PATCHED), + }}, + "vulnerabilities": {}, + "description": "seed", + "license": "MIT", + "tier": "free", + }) + }; + let kept = "pkg:pypi/stillpatched@1.0.0"; + let pruned = "pkg:pypi/restored@1.0.0"; + let manifest_path = socket_dir.join("manifest.json"); + let manifest = serde_json::json!({ "patches": { + kept: record("stillpatched", "22222222-2222-4222-8222-222222222222"), + pruned: record("restored", "33333333-3333-4333-8333-333333333333"), + }}); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + // The crawl reported neither package. `--global-prefix` names the + // site dir their copies are looked up in by PURL. + let scanned = scanned(&["pkg:pypi/declared@1.0.0"]); + for dry_run in [true, false] { + let common = crate::args::GlobalArgs { + cwd: project.clone(), + global_prefix: Some(site.clone()), + dry_run, + ..Default::default() + }; + let gc = if dry_run { + preview_apply_gc( + &common, + &manifest_path, + &socket_dir, + &scanned, + &no_vendored(), + ) + .await + } else { + run_apply_gc( + &common, + &manifest_path, + &socket_dir, + &scanned, + &no_vendored(), + ) + .await + }; + assert_eq!(gc.pruned, vec![pruned.to_string()], "dry_run={dry_run}"); + if !dry_run { + assert!( + gc.warnings.iter().any(|(code, detail)| { + *code == "pypi_installed_patch_kept" && detail.contains(kept) + }), + "the kept entry must be explained: {gc:?}" + ); + } + } + let manifest = read_manifest(&manifest_path).await.unwrap().unwrap(); + assert!(manifest.patches.contains_key(kept), "{manifest:?}"); + assert!(!manifest.patches.contains_key(pruned), "{manifest:?}"); + assert!( + blobs.join(hash(ORIGINAL)).exists(), + "the kept entry's before-blob is its only restore data" + ); + } } diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index d98b38bcc..e34ea3816 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -49,19 +49,83 @@ pub async fn cargo_copies_still_patched<'a>( blobs_path: &std::path::Path, shadowed_registry: bool, ) -> Vec { - use socket_patch_core::patch::rollback::{verify_file_rollback, VerifyRollbackStatus}; - let cargo: Vec = purls - .into_iter() - .filter(|p| Ecosystem::from_purl(p) == Some(Ecosystem::Cargo)) - .filter(|p| manifest.patches.contains_key(p.as_str())) - .cloned() - .collect(); + let cargo = manifest_purls_of(manifest, purls, Ecosystem::Cargo); if cargo.is_empty() { return Vec::new(); } let found = find_cargo_copies(cargo, options, shadowed_registry).await; + purls_still_patched(manifest, &found, blobs_path).await +} + +/// Of `purls` (manifest keys), the PyPI ones whose agent-mode in-place +/// patch may still be on disk, judged as [`cargo_copies_still_patched`] +/// judges a crate. Sorted. +/// +/// A project with no environment of its own installs into an interpreter +/// it shares with the rest of the machine, and its crawl reports only the +/// packages it declares. A copy patched while the project declared the +/// package, or by a release whose project crawl read every interpreter and +/// tool environment on the machine, outlives that: nothing uninstalls it. +/// Its manifest record holds the only before-blobs that can restore the +/// copy, so `scan --prune` keeps the record. The copies looked up are the +/// ones `rollback` restores (by PURL, in the project's interpreter) and, +/// for a project run, the ones `rollback --global` restores. +pub async fn pypi_copies_still_patched<'a>( + manifest: &socket_patch_core::manifest::schema::PatchManifest, + purls: impl IntoIterator, + options: &CrawlerOptions, + blobs_path: &std::path::Path, +) -> Vec { + let pypi = manifest_purls_of(manifest, purls, Ecosystem::Pypi); + if pypi.is_empty() { + return Vec::new(); + } + let partitioned = HashMap::from([(Ecosystem::Pypi, pypi)]); + let mut found = find_all_packages_for_rollback(&partitioned, options, true).await; + if !options.global && options.global_prefix.is_none() { + let machine = CrawlerOptions { + cwd: options.cwd.clone(), + global: true, + global_prefix: None, + }; + for (purl, paths) in find_all_packages_for_rollback(&partitioned, &machine, true).await { + let copies = found.entry(purl).or_default(); + for path in paths { + if !copies.contains(&path) { + copies.push(path); + } + } + } + } + purls_still_patched(manifest, &found, blobs_path).await +} + +/// The `purls` of `ecosystem` that `manifest` holds a record for. +fn manifest_purls_of<'a>( + manifest: &socket_patch_core::manifest::schema::PatchManifest, + purls: impl IntoIterator, + ecosystem: Ecosystem, +) -> Vec { + purls + .into_iter() + .filter(|p| Ecosystem::from_purl(p) == Some(ecosystem)) + .filter(|p| manifest.patches.contains_key(p.as_str())) + .cloned() + .collect() +} + +/// The purls of `found` with a copy that may still carry its manifest +/// record's patch: at least one file at the record's afterHash, or one that +/// cannot be read to tell (an I/O error, an unsafe key: kept fail-closed). +/// Sorted. +async fn purls_still_patched( + manifest: &socket_patch_core::manifest::schema::PatchManifest, + found: &HashMap>, + blobs_path: &std::path::Path, +) -> Vec { + use socket_patch_core::patch::rollback::{verify_file_rollback, VerifyRollbackStatus}; let mut patched = Vec::new(); - for (purl, paths) in &found { + for (purl, paths) in found { let Some(record) = manifest.patches.get(purl) else { continue; }; @@ -1469,7 +1533,26 @@ pub async fn crawl_ecosystems( HashMap, Option, ) { - let (packages, counts, skipped_config_path, _) = crawl_every_ecosystem(options, only).await; + let (packages, counts, skipped_config_path, _) = + crawl_every_ecosystem(options, only, true).await; + (packages, counts, skipped_config_path) +} + +/// [`crawl_ecosystems`] for resolving a package the user named +/// (`get `). A Python project with no environment of its own is +/// crawled for every package installed where it installs +/// (`PythonCrawler::crawl_all_installed`), not only the ones it declares: +/// the name says the package is wanted, as its PURL would. +pub async fn crawl_ecosystems_for_name( + options: &CrawlerOptions, + only: Option<&[String]>, +) -> ( + Vec, + HashMap, + Option, +) { + let (packages, counts, skipped_config_path, _) = + crawl_every_ecosystem(options, only, false).await; (packages, counts, skipped_config_path) } @@ -1504,7 +1587,7 @@ pub async fn crawl_ecosystems_with_npm( Option, ) { let (packages, counts, skipped_config_path, npm_roots) = - crawl_every_ecosystem(options, only).await; + crawl_every_ecosystem(options, only, true).await; let snapshot = counts .get(&Ecosystem::Npm) .map(|&npm_count| NpmCrawlSnapshot { @@ -1626,11 +1709,24 @@ pub(crate) async fn own_install_roots( roots } +/// The PyPI half of [`crawl_every_ecosystem`]: the project's packages +/// (`declared_only`), or every package installed where it installs. +async fn crawl_pypi(options: &CrawlerOptions, declared_only: bool) -> Vec { + let crawler = PythonCrawler::new(); + if declared_only { + crawler.crawl_all(options).await + } else { + crawler.crawl_all_installed(options).await + } +} + /// The crawl behind the entry points above; the fourth element is the npm /// crawler's `node_modules` roots (empty when npm was not selected). +/// `pypi_declared_only`: see [`crawl_ecosystems_for_name`]. async fn crawl_every_ecosystem( options: &CrawlerOptions, only: Option<&[String]>, + pypi_declared_only: bool, ) -> ( Vec, HashMap, @@ -1668,7 +1764,7 @@ async fn crawl_every_ecosystem( NpmCrawler::for_options(options).crawl_all_with_roots(options) ) .await, - crawl!(Ecosystem::Pypi, PythonCrawler::new().crawl_all(options)).await, + crawl!(Ecosystem::Pypi, crawl_pypi(options, pypi_declared_only)).await, crawl!(Ecosystem::Cargo, CargoCrawler.crawl_all(options)).await, crawl!( Ecosystem::Gem, @@ -1687,7 +1783,7 @@ async fn crawl_every_ecosystem( Ecosystem::Npm, NpmCrawler::for_options(options).crawl_all_with_roots(options) ), - crawl!(Ecosystem::Pypi, PythonCrawler::new().crawl_all(options)), + crawl!(Ecosystem::Pypi, crawl_pypi(options, pypi_declared_only)), crawl!(Ecosystem::Cargo, CargoCrawler.crawl_all(options)), crawl!( Ecosystem::Gem, diff --git a/crates/socket-patch-cli/tests/in_process_get.rs b/crates/socket-patch-cli/tests/in_process_get.rs index 6e7709c22..7a502f4f6 100644 --- a/crates/socket-patch-cli/tests/in_process_get.rs +++ b/crates/socket-patch-cli/tests/in_process_get.rs @@ -603,6 +603,74 @@ async fn get_package_name_matches_pypi_spellings_pip_accepts() { } } +/// A name given to `get` resolves among every package installed where the +/// project installs, declared or not. A Python project with no environment +/// of its own is otherwise crawled only for the packages it declares, but +/// the name says this one is wanted, as its PURL would. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn get_package_name_resolves_an_undeclared_package_in_the_path_interpreter() { + use std::os::unix::fs::PermissionsExt; + + let purl = "pkg:pypi/undeclared-pkg@2.0.0"; + let encoded = "pkg%3Apypi%2Fundeclared-pkg%402.0.0"; + let (server, url) = start_wiremock().await; + make_search_mock_one(&server, "by-package", encoded, UUID, purl, "free").await; + make_view_mock(&server, UUID, purl, "free").await; + + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("proj"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), "declared-pkg\n").unwrap(); + // The interpreter on PATH, and what is installed in it. + let site = tmp.path().join("system/lib/python3.12/site-packages"); + for (name, version) in [("declared_pkg", "1.0.0"), ("undeclared_pkg", "2.0.0")] { + let dist = site.join(format!("{name}-{version}.dist-info")); + std::fs::create_dir_all(&dist).unwrap(); + std::fs::write( + dist.join("METADATA"), + format!("Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"), + ) + .unwrap(); + } + let bin = tmp.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let python = bin.join("python3"); + std::fs::write( + &python, + format!( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ + printf '%s\\n' '{}'\n", + site.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let saved_path = std::env::var_os("PATH"); + let saved_venv = std::env::var_os("VIRTUAL_ENV"); + let mut path = vec![bin.clone()]; + path.extend(std::env::split_paths( + &saved_path.clone().unwrap_or_default(), + )); + std::env::set_var("PATH", std::env::join_paths(path).unwrap()); + std::env::remove_var("VIRTUAL_ENV"); + let mut args = default_args("undeclared-pkg", &project); + args.common.api_url = Some(url); + let code = run(args).await; + match saved_path { + Some(v) => std::env::set_var("PATH", v), + None => std::env::remove_var("PATH"), + } + if let Some(v) = saved_venv { + std::env::set_var("VIRTUAL_ENV", v); + } + + assert_eq!(code, 0, "a named, installed package must resolve"); + assert_patch_saved(&project, purl, UUID); +} + // --------------------------------------------------------------------------- // The shared target grammar (B11, B56, B57) // --------------------------------------------------------------------------- diff --git a/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs b/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs index b59f5d9fd..fecfd71b1 100644 --- a/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs +++ b/crates/socket-patch-cli/tests/vex_pdm_hatch_common/mod.rs @@ -420,23 +420,18 @@ pub fn path_with_fake_hatch(scratch: &Path) -> std::ffi::OsString { std::env::join_paths(paths).unwrap() } -/// A virtualenv outside the project that holds one package unrelated to the -/// fixture, for a scan to find installed. Hatch has no lockfile, so `scan` -/// learns a Hatch project's packages only from what is installed, and the -/// hosted cells wire a checkout with nothing installed. [`ScanApi`] answers -/// any batch query with the fixture's patch, so one installed package of -/// any name is enough for the scan to ask. Without it the scan asks only -/// when the host's own Python holds a package the project declares. -fn placeholder_venv(scratch: &Path) -> PathBuf { - let venv = "placeholder-venv"; - put( - scratch, - &format!( - "{}/placeholder-0.0.0.dist-info/METADATA", - site_packages_rel(venv) - ), - b"Metadata-Version: 2.1\nName: placeholder\nVersion: 0.0.0\n", - ); +/// A virtualenv outside the project with the fixture's package installed +/// at its patched bytes, as it is once reinstalled from the hosted wheel. +/// Hatch has no lockfile, so `scan` learns a Hatch project's packages only +/// from what is installed, and the hosted cells wire a checkout with +/// nothing installed in it. Activating this environment for the scan gives +/// it the fixture's package to ask the API about. An unpatched copy would +/// not do: the hosted stale-install guard reports it and keeps it out of +/// the same-run VEX. Without the environment the scan asks only when the +/// host's own Python holds a package the project declares. +fn installed_fixture_venv(scratch: &Path) -> PathBuf { + let venv = "installed-fixture-venv"; + install(scratch, venv, PATCHED); put( scratch, &format!("{venv}/pyvenv.cfg"), @@ -480,9 +475,9 @@ pub fn run_scan( let mut cmd = cli(); cmd.env("PATH", path_with_fake_hatch(scratch)); // A hosted scan of a project with no lock and no environment has - // nothing to ask the API about: see `placeholder_venv`. + // nothing to ask the API about: see `installed_fixture_venv`. if mode == Mode::Hosted && !cwd.join("pdm.lock").exists() && !cwd.join(".venv").exists() { - cmd.env("VIRTUAL_ENV", placeholder_venv(scratch)); + cmd.env("VIRTUAL_ENV", installed_fixture_venv(scratch)); } let out = cmd .args(&args) diff --git a/crates/socket-patch-core/src/crawlers/python_crawler.rs b/crates/socket-patch-core/src/crawlers/python_crawler.rs index e3f1d7035..009829ff8 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler.rs @@ -385,6 +385,21 @@ fn venv_root_of_site(site: &Path) -> Option { .map(Path::to_path_buf) } +/// The environment a `site-packages` dir belongs to, when it is one a +/// project has to itself: a venv ([`venv_root_of_site`]) or a conda +/// environment, whose root holds `conda-meta`. `None` for an interpreter +/// installed for the whole machine (the distro's, Homebrew's, python.org's, +/// a version manager's). +fn own_environment_of_site(site: &Path) -> Option { + venv_root_of_site(site).or_else(|| { + site.ancestors() + .skip(1) + .take(3) + .find(|dir| dir.join("conda-meta").is_dir()) + .map(Path::to_path_buf) + }) +} + /// The base interpreter's prefix for a venv whose `pyvenv.cfg` names `home`: /// the nearest ancestor of `home` (or of the resolved interpreter in it, for /// a symlinked one such as Homebrew's `opt/python@3.X/bin`) holding the @@ -3479,7 +3494,10 @@ async fn local_site_packages_with( /// the process environment), plus whether the dirs are the shared /// interpreter's ([`project_interpreter_site_packages`]) rather than an /// environment of the project's own. What is installed in a shared -/// interpreter is not all this project's: see [`scope`]. +/// interpreter is not all this project's: see [`scope`]. An interpreter on +/// `PATH` that sits in a venv or a conda environment (a Docker image's +/// `ENV PATH=/opt/venv/bin:$PATH`, with no `VIRTUAL_ENV`) is the project's +/// own environment, like an activated one. async fn local_sites_with( cwd: &Path, var: &impl Fn(&str) -> Option, @@ -3505,7 +3523,15 @@ async fn local_sites_with( return (Vec::new(), false); } if is_python_project(cwd).await { - return (project_interpreter_site_packages(cwd).await, true); + let sites = project_interpreter_site_packages(cwd).await; + let probed = sites.clone(); + let own = run_blocking(move || { + probed + .iter() + .any(|site| own_environment_of_site(site).is_some()) + }) + .await; + return (sites, !own); } (Vec::new(), false) } @@ -3630,17 +3656,37 @@ impl PythonCrawler { self.crawl_all_with(options, &var).await } + /// [`Self::crawl_all`] without the declared-package scope: every + /// package installed where the project installs. For a caller that was + /// told which package to look for (`get `): the name says the + /// package is wanted, whether or not the project declares it. + pub async fn crawl_all_installed(&self, options: &CrawlerOptions) -> Vec { + let var = |name: &str| std::env::var(name).ok(); + self.crawl_with(options, &var, false).await + } + /// [`Self::crawl_all`] over an explicit environment. async fn crawl_all_with( &self, options: &CrawlerOptions, var: &impl Fn(&str) -> Option, + ) -> Vec { + self.crawl_with(options, var, true).await + } + + /// The crawl behind [`Self::crawl_all`] (`declared_only`) and + /// [`Self::crawl_all_installed`]. + async fn crawl_with( + &self, + options: &CrawlerOptions, + var: &impl Fn(&str) -> Option, + declared_only: bool, ) -> Vec { let mut packages = Vec::new(); let mut seen = HashSet::new(); let (sp_paths, shared) = self.sites_with(options, var).await; - let scope = if shared { + let scope = if shared && declared_only { scope::project_scope(&options.cwd, &sp_paths).await } else { None diff --git a/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs index 76065385b..bd71300d1 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs @@ -16,7 +16,7 @@ //! another manager's lock, a requirement on a local directory) leaves the //! crawl unscoped, as it was before the scope existed. -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::path::{Path, PathBuf}; use toml_edit::{DocumentMut, Item}; @@ -24,13 +24,16 @@ use toml_edit::{DocumentMut, Item}; use super::{canonicalize_pypi_name, read_egg_info_metadata_sync, read_python_metadata_sync}; use crate::crawlers::listing::list_dir_sync; use crate::utils::fs::{is_dir_sync, read_regular_to_string_sync, run_blocking}; +use crate::utils::relpath::normalize_rel_keeping_escapes; use crate::utils::requirements::{ archive_filename_coords, editable_location, egg_name, has_env_reference, logical_lines, names_before_at, parse_requirement, pip_reads_as_path, requirement_name, strip_comment, strip_path_extras, }; use crate::vendor::lock_inventory::ProjectView; -use crate::vendor::pypi_requirements::{decode_requirements, requirements_includes}; +use crate::vendor::pypi_requirements::{ + decode_requirements, requirements_includes, NOT_READER_DIRS, +}; /// The canonical names of the packages that belong to the project at `cwd` /// among the distributions installed in `sites`: the ones it declares and, @@ -43,20 +46,47 @@ pub(super) async fn project_scope(cwd: &Path, sites: &[PathBuf]) -> Option>; + +/// Records in `declared` that the project asks for `name`, with the extras +/// spelled between the brackets of its requirement (`socks, security`). +fn declare(declared: &mut Declared, name: &str, extras: Option<&str>) { + declared + .entry(canonicalize_pypi_name(name)) + .or_default() + .extend(extras_of(extras)); +} + +/// The canonical names of the extras spelled between a requirement's +/// brackets. +fn extras_of(extras: Option<&str>) -> impl Iterator + '_ { + extras + .into_iter() + .flat_map(|extras| extras.split(',')) + .map(canonicalize_pypi_name) + .filter(|extra| !extra.is_empty()) +} + /// Files that decide a project's dependencies in a way this module does -/// not read: setuptools code and its legacy config, and the locks of the -/// managers whose projects can still install into the shared interpreter -/// (Poetry with `virtualenvs.create = false`, PDM without a venv). +/// not read: setuptools code and its legacy config, Hatch's environment +/// file, and the locks of the managers whose projects can still install +/// into the shared interpreter (Poetry with `virtualenvs.create = false`, +/// PDM without a venv). A `uv.lock` and the PEP 751 / PEP 723 locks are +/// found by name pattern in [`declared_names`]. const UNREAD_DECLARATIONS: &[&str] = &[ "setup.py", "setup.cfg", - "uv.lock", + "hatch.toml", "poetry.lock", "pdm.lock", ]; /// `pyproject.toml` tables, under `[tool]`, where a manager keeps /// dependencies in its own format instead of the PEP 621 `[project]` table. +/// A Hatch environment of `type = "system"` installs its `dependencies` +/// into the shared interpreter, so those tables count too. const UNREAD_TOOL_TABLES: &[&[&str]] = &[ &["poetry", "dependencies"], &["poetry", "dev-dependencies"], @@ -64,59 +94,81 @@ const UNREAD_TOOL_TABLES: &[&[&str]] = &[ &["pdm", "dev-dependencies"], &["uv", "dev-dependencies"], &["flit", "metadata"], + &["hatch", "envs"], + &["rye", "dev-dependencies"], ]; -/// The canonical names the project at `cwd` declares as dependencies, over -/// all of its requirements files and its `pyproject.toml`. `None` when one -/// of its declarations is not read in full (see the module docs). -async fn declared_names(cwd: &Path) -> Option> { +/// The packages the project at `cwd` declares as dependencies, over all of +/// its requirements files and its `pyproject.toml`. `None` when one of its +/// declarations is not read in full (see the module docs). +async fn declared_names(cwd: &Path) -> Option { let view = ProjectView::Disk(cwd); for name in UNREAD_DECLARATIONS { if view.exists_no_follow(name).await { return None; } } - // A PEP 751 or PEP 723 lock lists a resolved set this module does not - // read either. + // A `uv.lock`, PEP 751 or PEP 723 lock lists a resolved set this module + // does not read either. if crate::utils::python_lock::python_lock_paths(cwd).is_ok_and(|locks| !locks.is_empty()) { return None; } - let mut names = BTreeSet::new(); + let mut names = Declared::new(); match view.read_text("pyproject.toml").await { Ok(text) => pyproject_declares(&text, &mut names)?, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} - Err(_) => return None, + // A read that fails on a file that is there (a link leaving the + // repository, which reads as not found) hides its declarations. + Err(_) if view.exists_no_follow("pyproject.toml").await => return None, + Err(_) => {} } let files = requirements_files(&view).await?; requirements_declare(&view, files, &mut names).await?; Some(names) } -/// The pip requirements files the project keeps: every top-level `*.txt` or -/// `*.in` file with `requirements` in its name (`requirements.txt`, -/// `requirements-dev.txt`, `dev-requirements.txt`, `requirements.in`) and -/// every `*.txt` or `*.in` file in a top-level `requirements/` directory, -/// whatever its name. A project installs from several of them, so a -/// package any of them names is one of its packages. `None` when the -/// project directory cannot be listed. +/// The pip requirements files the project keeps: every `*.txt` or `*.in` +/// file with `requirements` in its name (`requirements.txt`, +/// `requirements-dev.txt`, `dev-requirements.txt`, `requirements.in`) at the +/// top level and one directory down (`docs/requirements.txt`, +/// `tests/requirements.txt`), and every `*.txt` or `*.in` file in a +/// top-level `requirements/` directory, whatever its name. A project +/// installs from several of them, so a package any of them names is one of +/// its packages. Hidden directories and [`NOT_READER_DIRS`] hold installed +/// packages and build output, not the project's own files. `None` when the +/// project directory, or its `requirements/` directory, cannot be listed. async fn requirements_files(view: &ProjectView<'_>) -> Option> { - let pip_reads = |name: &str| { + let named = |name: &str, any_name: bool| { let lower = name.to_ascii_lowercase(); - lower.ends_with(".txt") || lower.ends_with(".in") + (lower.ends_with(".txt") || lower.ends_with(".in")) + && (any_name || lower.contains("requirements")) }; let mut files = Vec::new(); for entry in view.list_dir("").await.ok()? { - if entry.is_dir { - if entry.name == "requirements" { - for child in view.list_dir(&entry.name).await.ok()? { - if !child.is_dir && pip_reads(&child.name) { - files.push(format!("{}/{}", entry.name, child.name)); - } - } + // A link to a directory is one too (`requirements -> ../shared`). + let is_dir = entry.is_dir + || view + .disk_root() + .is_some_and(|root| root.join(&entry.name).is_dir()); + if !is_dir { + if named(&entry.name, false) { + files.push(entry.name); + } + continue; + } + if entry.name.starts_with('.') || NOT_READER_DIRS.contains(&entry.name.as_str()) { + continue; + } + let requirements_dir = entry.name == "requirements"; + let children = match view.list_dir(&entry.name).await { + Ok(children) => children, + Err(_) if requirements_dir => return None, + // Any other directory is only searched as a courtesy. + Err(_) => continue, + }; + for child in children { + if !child.is_dir && named(&child.name, requirements_dir) { + files.push(format!("{}/{}", entry.name, child.name)); } - } else if pip_reads(&entry.name) && entry.name.to_ascii_lowercase().contains("requirements") - { - files.push(entry.name); } } Some(files) @@ -129,7 +181,7 @@ async fn requirements_files(view: &ProjectView<'_>) -> Option> { async fn requirements_declare( view: &ProjectView<'_>, files: Vec, - names: &mut BTreeSet, + names: &mut Declared, ) -> Option<()> { let mut visited: HashSet = HashSet::new(); let mut pending = files; @@ -143,17 +195,17 @@ async fn requirements_declare( .and_then(decode_requirements) .ok()?; for line in logical_lines(&content) { - line_declares(strip_comment(&line.text), names)?; + line_declares(strip_comment(&line.text), &rel, names)?; } pending.extend(requirements_includes(&rel, &content)); } Some(()) } -/// Adds to `names` the package one requirements line (comment stripped) -/// installs. `None` when the line installs something whose name cannot be -/// told from the file. -fn line_declares(code: &str, names: &mut BTreeSet) -> Option<()> { +/// Adds to `names` the package one line (comment stripped) of the +/// requirements file `rel` installs. `None` when the line installs +/// something whose name cannot be told from the file. +fn line_declares(code: &str, rel: &str, names: &mut Declared) -> Option<()> { let code = code.trim(); if code.is_empty() { return Some(()); @@ -164,7 +216,7 @@ fn line_declares(code: &str, names: &mut BTreeSet) -> Option<()> { return None; } if let Some(location) = editable_location(code) { - return location_declares(location, names); + return location_declares(location, rel, names); } // Every other option line installs nothing itself: the walk follows // `-r`, `-c` only constrains, and the rest configure pip. @@ -173,31 +225,53 @@ fn line_declares(code: &str, names: &mut BTreeSet) -> Option<()> { } let token = code.split_whitespace().next()?; if !names_before_at(token) && (token.contains("://") || pip_reads_as_path(token)) { - return location_declares(token, names); + return location_declares(token, rel, names); } - names.insert(canonicalize_pypi_name(parse_requirement(code)?.name)); + let requirement = parse_requirement(code)?; + declare(names, requirement.name, requirement.extras); Some(()) } -/// Adds to `names` the package a path, archive or url requirement installs: -/// the one its `#egg=` fragment or its archive file name gives. The project -/// directory itself (`.`, `-e .`, `.[dev]`) adds nothing here, since its -/// dependencies are the ones `pyproject.toml` declares. `None` for any other -/// location, such as a sibling source directory, whose metadata this module -/// does not read. -fn location_declares(location: &str, names: &mut BTreeSet) -> Option<()> { +/// Adds to `names` the package a path, archive or url requirement of the +/// requirements file `rel` installs: the one its `#egg=` fragment or its +/// wheel file name gives. The project directory itself adds nothing here, +/// since its dependencies are the ones `pyproject.toml` declares. pip +/// resolves a relative path against the directory it runs in, which is the +/// project root (`-e .`, `.[dev]`) or the directory of the file +/// (`docs/requirements.txt` holding `-e ..`), so a path that reaches the +/// project root from either is the project. `None` for any other location: +/// a sibling source directory, whose metadata this module does not read, +/// and an sdist or forge archive, which is named however its author chose +/// (`…/archive/release-1.0.zip` installs no package called `release`). +fn location_declares(location: &str, rel: &str, names: &mut Declared) -> Option<()> { if let Some(name) = egg_name(location) { - names.insert(canonicalize_pypi_name(name)); + declare(names, name, None); return Some(()); } - let path = location.split(['#', '?', ';']).next().unwrap_or(location); - let path = strip_path_extras(path); - if path.trim_end_matches(['/', '\\']) == "." { - return Some(()); + let with_extras = location.split(['#', '?', ';']).next().unwrap_or(location); + let path = strip_path_extras(with_extras); + // `wheels/six-….whl[socks]`: the text `strip_path_extras` took off. + let extras = with_extras[path.len()..] + .strip_prefix('[') + .and_then(|extras| extras.strip_suffix(']')); + if !path.is_empty() && !path.contains("://") { + let from_file = match rel.rsplit_once('/') { + Some((dir, _)) => format!("{dir}/{path}"), + None => path.to_string(), + }; + if [path, from_file.as_str()] + .iter() + .any(|path| normalize_rel_keeping_escapes(path).is_empty()) + { + return Some(()); + } } let leaf = path.rsplit(['/', '\\']).next()?; + if !leaf.ends_with(".whl") { + return None; + } let (distribution, _) = archive_filename_coords(leaf)?; - names.insert(canonicalize_pypi_name(distribution)); + declare(names, distribution, extras); Some(()) } @@ -208,7 +282,7 @@ fn location_declares(location: &str, names: &mut BTreeSet) -> Option<()> /// does not parse, a dependency list the build backend fills in at build /// time (`dynamic`), an entry that is not a PEP 508 requirement, and /// dependencies kept in a tool's own table ([`UNREAD_TOOL_TABLES`]). -fn pyproject_declares(text: &str, names: &mut BTreeSet) -> Option<()> { +fn pyproject_declares(text: &str, names: &mut Declared) -> Option<()> { let document: DocumentMut = text.parse().ok()?; let root = document.as_item(); let unread = UNREAD_TOOL_TABLES @@ -227,7 +301,7 @@ fn pyproject_declares(text: &str, names: &mut BTreeSet) -> Option<()> { } } if let Some(name) = project.get("name").and_then(Item::as_str) { - names.insert(canonicalize_pypi_name(name)); + declare(names, name, None); } if let Some(dependencies) = project.get("dependencies") { array_declares(dependencies, names)?; @@ -256,25 +330,38 @@ fn lookup<'a>(item: &'a Item, path: &[&str]) -> Option<&'a Item> { /// `{include-group = "…"}` entry names another group of the same table, /// which is read on its own. `None` when `item` is not an array or holds an /// entry that is neither. -fn array_declares(item: &Item, names: &mut BTreeSet) -> Option<()> { +fn array_declares(item: &Item, names: &mut Declared) -> Option<()> { for entry in item.as_array()? { if entry.is_inline_table() { continue; } - names.insert(canonicalize_pypi_name( - parse_requirement(entry.as_str()?)?.name, - )); + let requirement = parse_requirement(entry.as_str()?)?; + declare(names, requirement.name, requirement.extras); } Some(()) } -/// `declared`, plus every package the distributions installed in `sites` -/// under those names require, transitively. Markers and extras are not -/// evaluated: a requirement that applies only on another platform, or only -/// with an extra nobody asked for, is followed too. That errs toward -/// keeping a package, which is what the crawl did before the scope existed. -fn required_closure(declared: BTreeSet, sites: &[PathBuf]) -> HashSet { - let mut requires: HashMap> = HashMap::new(); +/// One requirement of an installed distribution. +#[derive(Debug, PartialEq, Eq)] +struct Requires { + /// The canonical name of the required package. + name: String, + /// The extras of that package the requirement asks for. + extras: Vec, + /// The extras of the requiring distribution that turn the requirement + /// on (`; extra == "socks"`). Empty when it applies without one. + gates: Vec, +} + +/// The names in `declared`, plus every package the distributions installed +/// in `sites` under those names require, transitively. A requirement behind +/// an extra is followed only when that extra was asked for, by a +/// declaration (`requests[socks]`) or by the requirement that led to the +/// package. Every other marker is taken to hold: a requirement that +/// applies only on another platform is followed too, which errs toward +/// keeping a package, as the crawl did before the scope existed. +fn required_closure(declared: Declared, sites: &[PathBuf]) -> HashSet { + let mut requires: HashMap> = HashMap::new(); for site in sites { for entry in list_dir_sync(site) { let file_name = entry.name.to_string_lossy(); @@ -295,30 +382,48 @@ fn required_closure(declared: BTreeSet, sites: &[PathBuf]) -> HashSet = declared.into_iter().collect(); - while let Some(name) = pending.pop() { - if !scope.insert(name.clone()) { + // What is asked of a package: itself (`None`), or one of its extras. + let mut pending: Vec<(String, Option)> = Vec::new(); + for (name, extras) in declared { + pending.extend(extras.into_iter().map(|extra| (name.clone(), Some(extra)))); + pending.push((name, None)); + } + let mut asked: HashSet<(String, Option)> = HashSet::new(); + while let Some((name, extra)) = pending.pop() { + if !asked.insert((name.clone(), extra.clone())) { continue; } - if let Some(required) = requires.get(&name) { - pending.extend(required.iter().cloned()); + for requirement in requires.get(&name).into_iter().flatten() { + let applies = match &extra { + None => requirement.gates.is_empty(), + Some(extra) => requirement.gates.contains(extra), + }; + if applies { + pending.push((requirement.name.clone(), None)); + pending.extend( + requirement + .extras + .iter() + .map(|extra| (requirement.name.clone(), Some(extra.clone()))), + ); + } } + scope.insert(name); } scope } -/// The canonical names a `.dist-info` directory's `METADATA` requires. -fn dist_info_requires(dist_info: &Path) -> Vec { +/// The requirements in a `.dist-info` directory's `METADATA`. +fn dist_info_requires(dist_info: &Path) -> Vec { read_regular_to_string_sync(&dist_info.join("METADATA")) .map(|content| metadata_requires(&content)) .unwrap_or_default() } -/// The canonical names a legacy `.egg-info` entry requires: the -/// `Requires-Dist` headers of its `PKG-INFO` (the entry itself when it is a -/// bare file) and, for a directory, every line of its `requires.txt`, whose -/// `[extra]` and `[:marker]` section headers name no package. -fn egg_info_requires(egg_info: &Path) -> Vec { +/// The requirements of a legacy `.egg-info` entry: the `Requires-Dist` +/// headers of its `PKG-INFO` (the entry itself when it is a bare file) and, +/// for a directory, the lines of its `requires.txt`. +fn egg_info_requires(egg_info: &Path) -> Vec { let requires_of = |path: &Path| { read_regular_to_string_sync(path) .map(|content| metadata_requires(&content)) @@ -329,30 +434,103 @@ fn egg_info_requires(egg_info: &Path) -> Vec { } let mut required = requires_of(&egg_info.join("PKG-INFO")); if let Ok(content) = read_regular_to_string_sync(&egg_info.join("requires.txt")) { - required.extend( - content - .lines() - .filter_map(requirement_name) - .map(canonicalize_pypi_name), - ); + required.extend(requires_txt(&content)); } required } -/// The canonical names in the `Requires-Dist` headers of a core-metadata -/// file. The header block ends at the first empty line, as an email parser -/// reads it: a whitespace-only line continues the header before it (a -/// multi-line `License`), so it does not hide the requirements after it. -fn metadata_requires(content: &str) -> Vec { +/// The requirements in the `Requires-Dist` headers of a core-metadata file. +/// The header block ends at the first empty line, as an email parser reads +/// it: a whitespace-only line continues the header before it (a multi-line +/// `License`), so it does not hide the requirements after it. +fn metadata_requires(content: &str) -> Vec { content .lines() .take_while(|line| !line.is_empty()) .filter_map(|line| line.strip_prefix("Requires-Dist:")) - .filter_map(requirement_name) - .map(canonicalize_pypi_name) + .filter_map(|requirement| requires(requirement, None)) .collect() } +/// The requirements in a setuptools `requires.txt`. A `[extra]` or +/// `[extra:marker]` section header puts the lines under it behind that +/// extra; `[:marker]` and the lines before any header apply without one. +fn requires_txt(content: &str) -> Vec { + let mut section: Option = None; + let mut required = Vec::new(); + for line in content.lines().map(str::trim) { + if let Some(header) = line.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + let extra = canonicalize_pypi_name(header.split(':').next().unwrap_or(header)); + section = Some(extra).filter(|extra| !extra.is_empty()); + } else { + required.extend(requires(line, section.as_deref())); + } + } + required +} + +/// One PEP 508 requirement of an installed distribution, behind `section` +/// (a `requires.txt` extra) or behind the extras its own marker tests. A +/// text this grammar does not read as a requirement still names its +/// package, and applies without an extra. +fn requires(requirement: &str, section: Option<&str>) -> Option { + let (name, extras, marker) = match parse_requirement(requirement) { + Some(parsed) => (parsed.name, parsed.extras, parsed.marker), + None => (requirement_name(requirement)?, None, None), + }; + let gates = match section { + Some(extra) => vec![extra.to_string()], + None => marker.map(marker_gates).unwrap_or_default(), + }; + Some(Requires { + name: canonicalize_pypi_name(name), + extras: extras_of(extras).collect(), + gates, + }) +} + +/// The extras of the requiring distribution that turn on a requirement +/// with `marker`; empty when it can apply without one. The marker is read +/// as its ` or ` branches: a branch that tests `extra == ""` holds +/// with that extra, and any other branch can hold on its own, which makes +/// the requirement unconditional. A branch cut inside parentheses, a +/// negated test or a reversed one (`"x" == extra`) reads as one that can +/// hold on its own, so a misread only ever follows a requirement. +fn marker_gates(marker: &str) -> Vec { + let mut gates = Vec::new(); + for branch in marker.split(" or ") { + match branch_extra(branch) { + Some(extra) => gates.push(extra), + None => return Vec::new(), + } + } + gates +} + +/// The extra a marker branch tests with `extra == ""`, canonical. +fn branch_extra(branch: &str) -> Option { + let mut rest = branch; + while let Some(at) = rest.find("extra") { + let (before, after) = (&rest[..at], &rest[at + "extra".len()..]); + rest = after; + // `extra` is the whole variable, not the tail of another name. + if before.ends_with(|c: char| c.is_ascii_alphanumeric() || c == '_') { + continue; + } + let Some(value) = after.trim_start().strip_prefix("==") else { + continue; + }; + let value = value.trim_start(); + let Some(quote) = value.chars().next().filter(|c| matches!(c, '"' | '\'')) else { + continue; + }; + if let Some(end) = value[1..].find(quote) { + return Some(canonicalize_pypi_name(&value[1..1 + end])); + } + } + None +} + #[cfg(test)] mod tests { use super::*; @@ -382,7 +560,8 @@ mod tests { ); } - async fn declared(files: &[(&str, &str)]) -> Option> { + /// What the project made of `files` declares, extras included. + async fn declares(files: &[(&str, &str)]) -> Option { let project = tempfile::tempdir().unwrap(); for (rel, content) in files { write(project.path(), rel, content); @@ -390,6 +569,26 @@ mod tests { declared_names(project.path()).await } + /// The names of [`declares`]. + async fn declared(files: &[(&str, &str)]) -> Option> { + Some(declares(files).await?.into_keys().collect()) + } + + /// A declaration of `packages`, each with the extras asked of it. + fn asking(packages: &[(&str, &[&str])]) -> Declared { + packages + .iter() + .map(|(name, extras)| (name.to_string(), names(extras))) + .collect() + } + + /// The closure of `declared` over `sites`, sorted. + fn closure(declared: Declared, sites: &[PathBuf]) -> Vec { + let mut scope: Vec<_> = required_closure(declared, sites).into_iter().collect(); + scope.sort(); + scope + } + #[tokio::test] async fn requirements_lines_name_their_packages() { let content = "\ @@ -401,7 +600,7 @@ zope.interface==6.0 \\ six @ https://patch.socket.dev/six-1.16.0-py2.py3-none-any.whl#sha256=00 idna@https://example.test/idna-3.7-py3-none-any.whl ./wheels/typing_extensions-4.12.0-py3-none-any.whl -https://example.test/packages/attrs-23.2.0.tar.gz +https://example.test/packages/attrs-23.2.0-py3-none-any.whl git+https://example.test/org/repo.git@v1#egg=Private_Lib -e . .[dev] @@ -448,12 +647,22 @@ git+https://example.test/org/repo.git@v1#egg=Private_Lib ("requirements-dev.txt", "ruff\n"), ("dev-requirements.txt", "mypy\n"), ("requirements.in", "flask\n"), + // One directory down. `-e ..` there is the project itself, + // as pip reads it when run from that directory. + ("docs/requirements.txt", "-e ..\nsphinx\n"), + ("tests/Requirements-Test.TXT", "-e .[test]\ncoverage\n"), // Not a requirements file by name: never read. ("notes.txt", "this is not pip syntax ===\n"), + ("docs/notes.txt", "this is not pip syntax ===\n"), + // Two directories down, installed packages and hidden + // directories: never read. + ("docs/api/requirements.txt", "too-deep\n"), + ("node_modules/requirements.txt", "not-the-projects\n"), + (".tox/requirements.txt", "not-the-projects\n"), ]) .await, Some(names(&[ - "click", "flask", "jinja2", "mypy", "pytest", "ruff" + "click", "coverage", "flask", "jinja2", "mypy", "pytest", "ruff", "sphinx" ])) ); } @@ -510,6 +719,16 @@ git+https://example.test/org/repo.git@v1#egg=Private_Lib "pyproject.toml", "[tool.flit.metadata]\nrequires = [\"six\"]\n", ), + // A Hatch environment can install into the shared interpreter. + ( + "pyproject.toml", + "[tool.hatch.envs.default]\ndependencies = [\"six\"]\n", + ), + ("hatch.toml", "[envs.default]\ndependencies = [\"six\"]\n"), + ( + "pyproject.toml", + "[tool.rye]\ndev-dependencies = [\"ruff\"]\n", + ), // Not a PEP 508 requirement. ( "pyproject.toml", @@ -523,9 +742,15 @@ git+https://example.test/org/repo.git@v1#egg=Private_Lib // Another source directory: its metadata is not read. "-e ./libs/shared", "../shared", + "-e ..", // A url that names no package. "https://example.test/download/latest", "git+https://example.test/org/repo.git", + // An archive is named however its author chose: only a wheel's + // file name is its distribution's. + "https://example.test/org/mylib/archive/release-1.0.zip", + "https://example.test/packages/attrs-23.2.0.tar.gz", + "./dist/mylib-1.0.tar.gz", // pip expands these where it runs. "flask==${FLASK_VERSION}", "-r ${REQUIREMENTS_DIR}/base.txt", @@ -541,10 +766,55 @@ git+https://example.test/org/repo.git@v1#egg=Private_Lib "{line:?}" ); } - // An unreadable sibling requirements file counts too. - assert_eq!( - declared(&[requirements, ("requirements-dev.txt", "-r missing.txt\n")]).await, - None + // An unreadable sibling requirements file counts too, at the top + // level and one directory down. + for sibling in ["requirements-dev.txt", "docs/requirements.txt"] { + assert_eq!( + declared(&[requirements, (sibling, "-r missing.txt\n")]).await, + None, + "{sibling}" + ); + } + } + + /// A declaration reached through a link is read, or leaves the crawl + /// unscoped when the link leaves the repository. It is never taken for + /// absent, which would drop the packages it declares. + #[cfg(unix)] + #[tokio::test] + async fn a_linked_declaration_is_never_taken_for_absent() { + use std::os::unix::fs::symlink; + let tmp = tempfile::tempdir().unwrap(); + let (project, shared) = (tmp.path().join("project"), tmp.path().join("shared")); + write( + &shared, + "pyproject.toml", + "[project]\nname = \"app\"\ndependencies = [\"flask\"]\n", + ); + write(&shared, "requirements/base.txt", "click\n"); + write(&project, "requirements.txt", "six\n"); + + symlink( + shared.join("pyproject.toml"), + project.join("pyproject.toml"), + ) + .unwrap(); + let declared = declared_names(&project).await; + assert!( + declared + .as_ref() + .is_none_or(|names| names.contains_key("flask")), + "{declared:?}" + ); + + std::fs::remove_file(project.join("pyproject.toml")).unwrap(); + symlink(shared.join("requirements"), project.join("requirements")).unwrap(); + let declared = declared_names(&project).await; + assert!( + declared + .as_ref() + .is_none_or(|names| names.contains_key("click")), + "{declared:?}" ); } @@ -611,8 +881,9 @@ line-length = 100 "charset_normalizer<4,>=2", "idna (<4,>=2.5)", "urllib3<3,>=1.21.1", - "certifi>=2017.4.17", - // An extra nobody asked for is followed too. + // Another platform's requirement is followed: only `extra` + // is evaluated. + "certifi>=2017.4.17; sys_platform == \"win32\"", "PySocks!=1.5.7,>=1.5.6; extra == \"socks\"", ], ); @@ -626,25 +897,41 @@ line-length = 100 install(&system, "setuptools", "70.0.0", &[]); install(&system, "anyio", "4.13.0", &["sniffio>=1.1"]); install(&system, "sniffio", "1.3.1", &[]); + // Asks for an extra of what it requires. + install(&system, "proxy-client", "1.0", &["Requests[SOCKS]>=2"]); let sites = [system, user]; - let scope = required_closure(names(&["requests", "not-installed"]), &sites); - let mut scope: Vec<_> = scope.into_iter().collect(); - scope.sort(); + let without_extra = [ + "certifi", + // Required, not installed: a name, never a crawled package. + "charset-normalizer", + "idna", + "not-installed", + "requests", + "urllib3", + ]; assert_eq!( - scope, - [ - "certifi", - // Required, not installed: a name, never a crawled package. - "charset-normalizer", - "idna", - "not-installed", - "pysocks", - "requests", - "urllib3", - ] + closure(asking(&[("requests", &[]), ("not-installed", &[])]), &sites), + without_extra + ); + // The extra's requirement counts once the extra is asked for, by + // the project or by a package it requires. + let mut with_extra = without_extra.to_vec(); + with_extra.insert(4, "pysocks"); + assert_eq!( + closure( + asking(&[("requests", &["socks"]), ("not-installed", &[])]), + &sites + ), + with_extra ); - assert!(required_closure(BTreeSet::new(), &sites).is_empty()); + with_extra.remove(3); + with_extra.insert(3, "proxy-client"); + assert_eq!( + closure(asking(&[("proxy-client", &[])]), &sites), + with_extra + ); + assert!(closure(Declared::new(), &sites).is_empty()); } #[test] @@ -659,7 +946,8 @@ line-length = 100 write( site, "old_app-1.0.egg-info/requires.txt", - "six>=1.0\n\n[socks]\nPySocks\n\n[:python_version < \"3\"]\nenum34\n", + "six>=1.0\n\n[socks]\nPySocks\n\n[:python_version < \"3\"]\nenum34\n\n\ + [tls:sys_platform == \"win32\"]\nwincertstore\n", ); // A bare-file `.egg-info` is its own PKG-INFO. write( @@ -667,17 +955,104 @@ line-length = 100 "six-1.16.0.egg-info", "Metadata-Version: 2.1\nName: six\nVersion: 1.16.0\nRequires-Dist: typing\n", ); - let mut scope: Vec<_> = required_closure(names(&["old-app"]), &[site.to_path_buf()]) - .into_iter() - .collect(); - scope.sort(); - assert_eq!(scope, ["enum34", "old-app", "pysocks", "six", "typing"]); + let sites = [site.to_path_buf()]; + assert_eq!( + closure(asking(&[("old-app", &[])]), &sites), + ["enum34", "old-app", "six", "typing"] + ); + assert_eq!( + closure(asking(&[("old-app", &["socks", "tls"])]), &sites), + [ + "enum34", + "old-app", + "pysocks", + "six", + "typing", + "wincertstore" + ] + ); } #[test] fn requirements_after_a_folded_header_are_read() { let metadata = "Metadata-Version: 2.1\nName: app\nVersion: 1.0\nLicense: MIT\n \n Permission is hereby granted\nRequires-Dist: six\n\nRequires-Dist: body\n"; - assert_eq!(metadata_requires(metadata), ["six"]); + let names: Vec = metadata_requires(metadata) + .into_iter() + .map(|requirement| requirement.name) + .collect(); + assert_eq!(names, ["six"]); + } + + #[test] + fn a_marker_gates_a_requirement_only_on_the_extras_it_tests() { + let gates = |marker: &str| marker_gates(marker); + assert_eq!(gates("extra == \"socks\""), ["socks"]); + assert_eq!(gates("extra=='Use_Chardet.On-Py3'"), ["use-chardet-on-py3"]); + assert_eq!( + gates("python_version >= \"3.8\" and extra == 'test'"), + ["test"] + ); + assert_eq!(gates("extra == \"a\" or extra == \"b\""), ["a", "b"]); + // A branch that can hold without an extra makes it unconditional, + // and so does anything this reader does not take for the test. + for unconditional in [ + "sys_platform == \"win32\"", + "extra == \"a\" or sys_platform == \"win32\"", + "extra != \"a\"", + "\"a\" == extra", + "extras == \"a\"", + "my_extra == \"a\"", + "extra == a", + "extra == \"a", + "(extra == \"a\" or os_name == \"nt\") and python_version < \"3\"", + ] { + assert!(gates(unconditional).is_empty(), "{unconditional}"); + } + assert_eq!( + requires("PySocks (!=1.5.7,>=1.5.6) ; extra == 'socks'", None), + Some(Requires { + name: "pysocks".into(), + extras: vec![], + gates: vec!["socks".into()], + }) + ); + assert_eq!( + requires("urllib3[brotli,socks]>=2", None), + Some(Requires { + name: "urllib3".into(), + extras: vec!["brotli".into(), "socks".into()], + gates: vec![], + }) + ); + // Not a requirement this grammar reads: the name still counts. + assert_eq!( + requires("odd-name ???", None).map(|requirement| requirement.name), + Some("odd-name".into()) + ); + } + + #[tokio::test] + async fn declarations_keep_the_extras_they_ask_for() { + let declared = declares(&[ + ( + "requirements.txt", + "Requests[Security, socks]>=2\n./wheels/httpx-0.27.0-py3-none-any.whl[http2]\n", + ), + ( + "pyproject.toml", + "[project]\nname = \"app\"\ndependencies = [\"requests[use_chardet_on_py3]\"]\n", + ), + ]) + .await + .unwrap(); + assert_eq!( + declared, + asking(&[ + ("app", &[]), + ("httpx", &["http2"]), + ("requests", &["security", "socks", "use-chardet-on-py3"]), + ]) + ); } #[tokio::test] diff --git a/crates/socket-patch-core/src/vendor/pypi_requirements.rs b/crates/socket-patch-core/src/vendor/pypi_requirements.rs index 8a071598c..79f436fa1 100644 --- a/crates/socket-patch-core/src/vendor/pypi_requirements.rs +++ b/crates/socket-patch-core/src/vendor/pypi_requirements.rs @@ -1724,9 +1724,10 @@ fn requirements_file_name(name: &str) -> bool { lower.ends_with(".txt") || lower.ends_with(".in") } -/// Top-level directories never searched for constraint readers: installed -/// packages and build output, not the project's own requirements. -const NOT_READER_DIRS: &[&str] = &[ +/// Top-level directories never searched for the project's own requirements +/// files (constraint readers here, the declared-package scope of the Python +/// crawler): installed packages and build output. +pub(crate) const NOT_READER_DIRS: &[&str] = &[ "node_modules", "site-packages", "venv", diff --git a/crates/socket-patch-core/tests/crawler_python_e2e.rs b/crates/socket-patch-core/tests/crawler_python_e2e.rs index 5219d4e25..235d0091f 100644 --- a/crates/socket-patch-core/tests/crawler_python_e2e.rs +++ b/crates/socket-patch-core/tests/crawler_python_e2e.rs @@ -1288,6 +1288,26 @@ async fn crawl_all_in_a_shared_interpreter_keeps_only_the_projects_packages() { .unwrap(); assert!(found.contains_key(&certifi), "{found:?}"); + // A caller that names a package asks about everything installed + // there, declared or not. + let mut installed: Vec = with_project_env(home.path(), &bin, || async { + crawler.crawl_all_installed(&opts).await + }) + .await + .into_iter() + .map(|package| package.purl) + .collect(); + installed.sort(); + assert_eq!( + installed, + [ + "pkg:pypi/certifi@2026.7.22", + "pkg:pypi/flask@3.0.0", + "pkg:pypi/setuptools@80.10.2", + "pkg:pypi/werkzeug@3.0.1", + ] + ); + // `setup.py` decides the dependencies in code, so the crawl is not // scoped. It still reads only the project's interpreter. std::fs::write(project.path().join("setup.py"), "").unwrap(); @@ -1302,6 +1322,54 @@ async fn crawl_all_in_a_shared_interpreter_keeps_only_the_projects_packages() { ); } +/// An interpreter on `PATH` that sits in a venv or a conda environment is +/// the project's own environment, with or without `VIRTUAL_ENV` (a Docker +/// image's `ENV PATH=/opt/venv/bin:$PATH`). Everything installed there is +/// the project's, declared or not, as in an activated environment. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn crawl_all_of_an_environment_on_path_is_not_scoped() { + for marker in ["pyvenv.cfg", "conda-meta"] { + let project = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + let machine = tempfile::tempdir().unwrap(); + std::fs::write(project.path().join("requirements.txt"), "flask\n").unwrap(); + let prefix = machine.path().join("opt/env"); + let site = prefix.join("lib/python3.12/site-packages"); + install_dist(&site, "Flask", "3.0.0", &[]); + // Installed by hand, named in no requirements file. + install_dist(&site, "gunicorn", "22.0.0", &[]); + if marker == "pyvenv.cfg" { + std::fs::write(prefix.join(marker), "home = /usr/bin\n").unwrap(); + } else { + std::fs::create_dir_all(prefix.join(marker)).unwrap(); + } + let bin = prefix.join("bin"); + install_fake_python(&bin, &[&site]); + + let crawler = PythonCrawler::new(); + let opts = CrawlerOptions { + cwd: project.path().to_path_buf(), + global: false, + global_prefix: None, + }; + let mut purls: Vec = with_project_env(home.path(), &bin, || async { + crawler.crawl_all(&opts).await + }) + .await + .into_iter() + .map(|package| package.purl) + .collect(); + purls.sort(); + assert_eq!( + purls, + ["pkg:pypi/flask@3.0.0", "pkg:pypi/gunicorn@22.0.0"], + "{marker}" + ); + } +} + /// #964: a uv project (`uv.lock`) and a PEP 723 script lock (`*.py.lock`) /// only ever install into uv's own env: `.venv` / `UV_PROJECT_ENVIRONMENT` /// for a project, uv's cache for a script. With none synced yet nothing is diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 16eca553c..4bbe707aa 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -958,19 +958,24 @@ the interpreter on `PATH`. socket-patch reads that interpreter: it asks `python3` (else `python`, else `py`), run from the project directory, for its site-packages and user site, and reads only those directories. -That interpreter is shared. Homebrew formulae, distro packages and other -projects install into it too, so a package being installed there does not -make it this project's. `scan` keeps only: - -- the packages the project declares: every requirement in a top-level - `*requirements*.txt` or `*requirements*.in` file, in a `.txt` or `.in` - file of a top-level `requirements/` directory and in their `-r` - includes, plus the `[project]` `dependencies` and - `optional-dependencies` and the `[dependency-groups]` of - `pyproject.toml`; +An interpreter on `PATH` that sits in a virtualenv or a conda environment +(a Docker image's `ENV PATH=/opt/venv/bin:$PATH`) is the project's own +environment, like an activated one, and everything in it is the project's. + +Any other interpreter is shared. Homebrew formulae, distro packages and +other projects install into it too, so a package being installed there does +not make it this project's. `scan` keeps only: + +- the packages the project declares: every requirement in a + `*requirements*.txt` or `*requirements*.in` file at the top level or one + directory down (`docs/requirements.txt`), in a `.txt` or `.in` file of a + top-level `requirements/` directory and in their `-r` includes, plus the + `[project]` `dependencies` and `optional-dependencies` and the + `[dependency-groups]` of `pyproject.toml`; - the installed packages those require, through their `Requires-Dist` - metadata. Markers and extras are not evaluated, so an optional - requirement that is installed is kept. + metadata. A requirement behind an extra counts only when that extra is + asked for (`requests[socks]`). Other markers, such as a platform test, + are not evaluated. A project that declares nothing, or whose declared packages are not installed, has no packages there. Install them first @@ -980,8 +985,11 @@ The filter is skipped, and every package in the interpreter is reported, when socket-patch cannot read every declaration: a `setup.py` or `setup.cfg`, a `poetry.lock`, `pdm.lock`, `uv.lock` or PEP 751 lock, `dynamic` dependencies, dependencies in a `[tool.poetry]`, `[tool.pdm]`, -`[tool.uv]` or `[tool.flit]` table, a requirement on a local directory, a -`${VAR}` in a requirements line, or an include that cannot be read. +`[tool.uv]`, `[tool.rye]` or `[tool.flit]` table, Hatch environments +(`hatch.toml` or a `[tool.hatch.envs]` table), a requirement on a local +directory other than the project itself or on an archive that is not a +wheel, a `${VAR}` in a requirements line, or a declaration that cannot be +read. The other interpreters on the machine, and the environments tools keep for themselves (`uv tool install`, pipx apps, the Poetry installer, PDM's @@ -989,7 +997,16 @@ global project), are never read for a project. Use `--global` to patch those. `apply`, `rollback` and `vex` find the packages of recorded patches by name -and version in the same interpreter. The filter applies to discovery only. +and version in the same interpreter, and `socket-patch get ` resolves +a name among everything installed there. The filter applies to `scan` +discovery only. + +`scan --prune` does not drop the record of a patch whose package is no +longer reported while an installed copy is still patched +(`pypi_installed_patch_kept`): the record holds the only data that can +restore that copy. `socket-patch rollback ` restores it and drops the +record; add `--global` when the copy is in another interpreter or a tool's +environment. ## Maven & NuGet caveats From 73e94d8089cde825fc319e30756fe208550ed97b Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 08:05:34 -0500 Subject: [PATCH 3/5] Address the second code review of the Python declared-package scope - A package the project's patch manifest records stays one of its packages when no requirements file names it (`get ` patched it on purpose). Left out of the scope, it got no newer patch and every `scan --prune` reported its record as one to roll back. - With no interpreter to ask, the well-known locations that stand in for it are always shared. A conda root or a pyenv-virtualenv among them no longer made the whole list the project's own environment. - A venv reached through PATH is read like an activated one: its own directories, then what its `pyvenv.cfg` lets in. The interpreter's user site, which such a venv does not import from, is no longer crawled. - The conda root (`base`) is the machine's default interpreter and carries conda's own dependencies, so it is shared and scoped. A conda environment other than the root is still the project's own. - The crawl stays unscoped when nothing states the project's dependencies: its only marker is a `pyproject.toml` that configures tools and no requirements file is found. Its requirements are then kept somewhere the scope does not look. - `scan --prune` looks for still-patched copies outside the project's interpreter only for a project that installs into a shared one. A project with an environment of its own never patched a copy outside it, so another project's patched copy no longer keeps its stale record. - A prune under `--global` / `--global-prefix` keeps every entry whose package is installed where the project installs, declared or not, as it did before the scope. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 25 ++- .../socket-patch-cli/src/commands/scan/gc.rs | 6 +- .../src/ecosystem_dispatch.rs | 13 +- .../tests/in_process_python_envs.rs | 70 +++++++ .../src/crawlers/python_crawler.rs | 176 +++++++++++------- .../src/crawlers/python_crawler/scope.rs | 109 +++++++++-- .../tests/crawler_python_e2e.rs | 81 +++++++- docs/ecosystems.md | 25 ++- 8 files changed, 398 insertions(+), 107 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d5ec59bc9..d4b67d60d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -362,7 +362,7 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc **Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. -`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` and `rollback --global` restore are looked up by PURL, and the wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. +`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` restores are looked up by PURL, and for a project that installs into a shared interpreter so are the ones `rollback --global` restores (a project with an environment of its own never patched a copy outside it). The wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. `scan` queries the patch API in `--batch-size` chunks. Authenticated runs POST `/v0/orgs/{slug}/patches/batch`; token-less runs POST `{proxy}/patch/batch` on the public proxy and degrade to per-package `GET /patch/by-package/:purl` requests in two cases: the deployed proxy predates the batch endpoint (legacy proxies answer the POST with their `400 "Unsupported endpoint"` catch-all), or the all-or-nothing batch validation rejects the chunk (e.g. a crawled PURL type the server doesn't recognize, such as `pkg:jsr/…` — the per-package path tolerates those individually, preserving the pre-batch scan semantics). Rate limits and over-capacity 503s surface instead of silently degrading. @@ -1369,11 +1369,14 @@ the model is **not uniform** today: interpreters on the machine and the environments tools keep for themselves (`uv tool install`, pipx apps, the Poetry installer, PDM's global project, uv- and PDM-managed interpreters) are read only under `--global`. When no interpreter answers, the well-known interpreter locations (`/usr`, - `/usr/local`, `~/.local`, Homebrew, the python.org framework, pyenv, conda) stand in for it. An - interpreter on `PATH` that sits in a venv or a conda environment (a `pyvenv.cfg` or `conda-meta` - at its root: a Docker image's `ENV PATH=/opt/venv/bin:$PATH`) is the project's own environment, - as an activated one is, and everything in it is the project's. Any other - interpreter is shared with everything else installed there, so `scan` discovery keeps only the + `/usr/local`, `~/.local`, Homebrew, the python.org framework, pyenv, conda) stand in for it, and + they are shared whatever environments sit among them. An interpreter on `PATH` that sits in a + venv (a `pyvenv.cfg` at its root: a Docker image's `ENV PATH=/opt/venv/bin:$PATH`) is the + project's own environment and is read as an activated one is: the venv's directories, then what + its `pyvenv.cfg` lets in. So is one in a conda environment other than the root (`conda-meta` at + its root and no `condabin`). Everything in such an environment is the project's. Any other + interpreter, the conda root included, is shared with everything else installed there, so `scan` + discovery keeps only the packages the project declares and the installed packages those require (their `Requires-Dist`, transitively; a requirement behind an extra counts only when a declaration or a requiring package asks for that extra, and no other marker is evaluated). The declarations read are the @@ -1383,9 +1386,13 @@ the model is **not uniform** today: `target`, `build`, `dist`, `__pycache__` are not searched), of every `.txt` / `.in` file in a top-level `requirements/` directory and of their `-r` includes, plus the PEP 621 `[project]` `dependencies` / `optional-dependencies` and the PEP 735 `[dependency-groups]` of - `pyproject.toml`. A project that declares nothing, or whose declared packages are not installed, - has no packages there. Discovery is left unscoped (every package in that interpreter, as before) - when a declaration is not read in full: a `setup.py` or `setup.cfg`; a `poetry.lock`, `pdm.lock`, + `pyproject.toml`. A package `.socket/manifest.json` records a patch for is the project's too, + declared or not (the package itself, not what it requires). A project that declares nothing (a + requirements file with no requirement, a `[project]` table with no dependencies), or whose + declared packages are not installed, has no packages there. Discovery is left unscoped (every + package in that interpreter, as before) when nothing states the project's dependencies (its only + marker is a `pyproject.toml` that configures tools, and no requirements file is found) and when a + declaration is not read in full: a `setup.py` or `setup.cfg`; a `poetry.lock`, `pdm.lock`, `uv.lock` or PEP 751 / PEP 723 lock; `dynamic` dependencies; dependencies in a `[tool.poetry]`, `[tool.pdm]`, `[tool.uv]`, `[tool.rye]` or `[tool.flit]` table; Hatch environments (`hatch.toml`, or a `[tool.hatch.envs]` table); a requirement on a local directory other than the project diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index 6c15a698a..89d819d1a 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -332,8 +332,12 @@ async fn keep_project_entries(common: &GlobalArgs, prunable: &mut Vec) { global_prefix: None, ..common.clone() }; + // Every package installed where the project installs, not only the + // ones a Python project with no environment of its own declares: a + // record for an undeclared one (`get `) is the project's too. let (installed, _, _) = - crate::ecosystem_dispatch::crawl_ecosystems(&project.crawler_options(), None).await; + crate::ecosystem_dispatch::crawl_ecosystems_for_name(&project.crawler_options(), None) + .await; let ctx = crate::commands::context::ProjectContext::new(&project); let locked = &ctx.locks().await.entries; let accounted: HashSet = installed diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index e20999434..a803cfbd7 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -68,8 +68,12 @@ pub async fn cargo_copies_still_patched<'a>( /// tool environment on the machine, outlives that: nothing uninstalls it. /// Its manifest record holds the only before-blobs that can restore the /// copy, so `scan --prune` keeps the record. The copies looked up are the -/// ones `rollback` restores (by PURL, in the project's interpreter) and, -/// for a project run, the ones `rollback --global` restores. +/// ones `rollback` restores (by PURL, where `options` installs) and, for a +/// project that installs into a shared interpreter, the ones `rollback +/// --global` restores. A project with an environment of its own never +/// patched a copy outside it, so a same-version copy elsewhere on the +/// machine, patched under another project's record, does not keep this +/// project's. pub async fn pypi_copies_still_patched<'a>( manifest: &socket_patch_core::manifest::schema::PatchManifest, purls: impl IntoIterator, @@ -82,7 +86,10 @@ pub async fn pypi_copies_still_patched<'a>( } let partitioned = HashMap::from([(Ecosystem::Pypi, pypi)]); let mut found = find_all_packages_for_rollback(&partitioned, options, true).await; - if !options.global && options.global_prefix.is_none() { + if PythonCrawler::new() + .installs_into_a_shared_interpreter(options) + .await + { let machine = CrawlerOptions { cwd: options.cwd.clone(), global: true, diff --git a/crates/socket-patch-cli/tests/in_process_python_envs.rs b/crates/socket-patch-cli/tests/in_process_python_envs.rs index 72877af77..bd8da9c48 100644 --- a/crates/socket-patch-cli/tests/in_process_python_envs.rs +++ b/crates/socket-patch-cli/tests/in_process_python_envs.rs @@ -1075,6 +1075,76 @@ async fn requirements_project_without_a_venv_scans_only_what_it_declares() { } } +/// A package the project's patch manifest records stays one of the +/// project's packages when no requirements file names it: `get ` +/// patched it on purpose. The scan keeps asking about it, so a newer patch +/// is offered and `--prune` does not take its record for a stale one. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn requirements_project_without_a_venv_keeps_scanning_a_recorded_package() { + use std::os::unix::fs::PermissionsExt; + + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("proj"); + std::fs::create_dir_all(project.join(".socket")).unwrap(); + std::fs::write(project.join("requirements.txt"), "declared_pkg\n").unwrap(); + std::fs::write( + project.join(".socket/manifest.json"), + serde_json::json!({ "patches": { "pkg:pypi/recorded-pkg@3.0.0": { + "uuid": "11111111-1111-4111-8111-111111111111", + "exportedAt": "2026-01-01T00:00:00Z", + "files": {}, + "vulnerabilities": {}, + "description": "seed", + "license": "MIT", + "tier": "free", + }}}) + .to_string(), + ) + .unwrap(); + let site = tmp.path().join("system/lib/python3.12/site-packages"); + std::fs::create_dir_all(&site).unwrap(); + write_dist_info(&site, "declared_pkg", "1.0.0"); + write_dist_info(&site, "recorded_pkg", "3.0.0"); + write_dist_info(&site, "system_decoy", "6.6.6"); + let bin = tmp.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let python = bin.join("python3"); + std::fs::write( + &python, + format!( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ + printf '%s\\n' '{}'\n", + site.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let server = MockServer::start().await; + mock_batch_empty(&server).await; + let saved_path = std::env::var_os("PATH"); + let mut path = vec![bin.clone()]; + path.extend(std::env::split_paths( + &saved_path.clone().unwrap_or_default(), + )); + std::env::set_var("PATH", std::env::join_paths(path).unwrap()); + let mut args = default_args(&project, server.uri()); + args.mode = Some(socket_patch_cli::commands::scan::ScanMode::Agent); + let code = scan_scrubbed(args).await; + match saved_path { + Some(v) => std::env::set_var("PATH", v), + None => std::env::remove_var("PATH"), + } + + assert_eq!(code, 0); + let bodies = batch_bodies(&server).await; + assert_discovered(&bodies, "pkg:pypi/declared-pkg@1.0.0"); + assert_discovered(&bodies, "pkg:pypi/recorded-pkg@3.0.0"); + assert_not_discovered(&bodies, "pkg:pypi/system-decoy"); +} + /// #525: uv syncs into `UV_PROJECT_ENVIRONMENT`, absolute or relative to the /// project, and ignores an activated `VIRTUAL_ENV` for project commands. #[tokio::test] diff --git a/crates/socket-patch-core/src/crawlers/python_crawler.rs b/crates/socket-patch-core/src/crawlers/python_crawler.rs index 009829ff8..353723d30 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler.rs @@ -385,19 +385,17 @@ fn venv_root_of_site(site: &Path) -> Option { .map(Path::to_path_buf) } -/// The environment a `site-packages` dir belongs to, when it is one a -/// project has to itself: a venv ([`venv_root_of_site`]) or a conda -/// environment, whose root holds `conda-meta`. `None` for an interpreter -/// installed for the whole machine (the distro's, Homebrew's, python.org's, -/// a version manager's). -fn own_environment_of_site(site: &Path) -> Option { - venv_root_of_site(site).or_else(|| { - site.ancestors() - .skip(1) - .take(3) - .find(|dir| dir.join("conda-meta").is_dir()) - .map(Path::to_path_buf) - }) +/// The conda environment a `site-packages` dir belongs to, when it is one +/// a project has to itself: a prefix holding `conda-meta` that is not the +/// conda root. The root (`base`, which also holds `condabin`) is the +/// machine's default interpreter and carries conda's own dependencies, as +/// Homebrew's Python carries Homebrew's. +fn conda_env_of_site(site: &Path) -> Option { + site.ancestors() + .skip(1) + .take(3) + .find(|dir| dir.join("conda-meta").is_dir() && !dir.join("condabin").is_dir()) + .map(Path::to_path_buf) } /// The base interpreter's prefix for a venv whose `pyvenv.cfg` names `home`: @@ -2815,21 +2813,59 @@ fn memoized_site_query(runner: &ProbeRunner) -> Option { /// project: under `--global` no project's `.python-version` picks the /// Python a pyenv shim runs. pub async fn get_global_python_site_packages() -> Vec { - system_python_site_packages(ProbeRunner::global(), SystemReach::Machine).await + system_python_site_packages(ProbeRunner::global()).await } /// The `site-packages` of the interpreter a project with no environment of -/// its own installs into: the Python on `PATH`, asked from the project's +/// its own installs into, and whether that interpreter is shared with the +/// rest of the machine. +/// +/// The interpreter is the Python on `PATH`, asked from the project's /// directory (`--cwd`) so a version manager's shim follows that project's -/// `.python-version`. Only that interpreter's own answer counts. The other -/// interpreters on the machine, and the environments tools keep for -/// themselves, hold other projects' packages: `pip install -r -/// requirements.txt` never puts this project's there. +/// `.python-version`. Only its own answer counts. The other interpreters +/// on the machine, and the environments tools keep for themselves, hold +/// other projects' packages: `pip install -r requirements.txt` never puts +/// this project's there. /// -/// When no interpreter answers (none on `PATH`, or a shim that fails), the -/// well-known interpreter locations stand in for it. -async fn project_interpreter_site_packages(cwd: &Path) -> Vec { - system_python_site_packages(ProbeRunner::project(cwd), SystemReach::Project).await +/// * An interpreter in a venv (a Docker image's `ENV +/// PATH=/opt/venv/bin:$PATH`, with no `VIRTUAL_ENV`) is the project's own +/// environment, read like an activated one: the venv's dirs, then what +/// its `pyvenv.cfg` lets in. The interpreter also names its user site, +/// which a venv does not import from unless it takes the system site +/// packages. +/// * An interpreter in a conda environment other than the root is the +/// project's own too ([`conda_env_of_site`]). +/// * Any other interpreter is shared: what is installed in it is not all +/// this project's (see [`scope`]). +/// * When no interpreter answers (none on `PATH`, or a shim that fails), +/// the well-known interpreter locations stand in for it. They are every +/// project's, whatever environments sit among them. +async fn project_interpreter_sites( + cwd: &Path, + var: &impl Fn(&str) -> Option, +) -> (Vec, bool) { + let answered = interpreter_site_packages(ProbeRunner::project(cwd)).await; + if answered.is_empty() { + let stand_ins = with_well_known_site_packages(answered, SystemReach::Project).await; + return (stand_ins, true); + } + let probed = answered.clone(); + let (venv_sites, conda_env) = run_blocking(move || { + let venv_sites: Vec = probed + .iter() + .filter(|site| venv_root_of_site(site).is_some()) + .cloned() + .collect(); + let conda_env = probed.iter().any(|site| conda_env_of_site(site).is_some()); + (venv_sites, conda_env) + }) + .await; + if !venv_sites.is_empty() { + let mut sites = venv_sites; + add_system_site_packages(&mut sites, var); + return (sites, false); + } + (answered, !conda_env) } /// How far a search of the system Python reaches. @@ -2838,42 +2874,60 @@ enum SystemReach { /// `--global`: every interpreter on the machine, and the environments /// tools keep for themselves. Machine, - /// A project with no environment of its own: the one interpreter it - /// installs into (see [`project_interpreter_site_packages`]). + /// A project with no environment of its own whose interpreter did not + /// answer (see [`project_interpreter_sites`]): the interpreters on the + /// machine, never a tool's environment. Project, } -/// The system Python `site-packages` within `reach`, the interpreter asked -/// through `runner`. -async fn system_python_site_packages(runner: ProbeRunner, reach: SystemReach) -> Vec { - let mut results = Vec::new(); - let mut seen = HashSet::new(); +/// The system Python `site-packages` of the whole machine, the interpreter +/// asked through `runner`. +async fn system_python_site_packages(runner: ProbeRunner) -> Vec { + let answered = interpreter_site_packages(runner).await; + with_well_known_site_packages(answered, SystemReach::Machine).await +} - fn add_path(p: PathBuf, seen: &mut HashSet, results: &mut Vec) { +/// The directories the interpreter `runner` finds names as its site and +/// user-site packages, absolute and without repeats. Empty when no +/// interpreter answers. +async fn interpreter_site_packages(runner: ProbeRunner) -> Vec { + // Subprocesses: on the blocking pool. + let site_output = run_blocking(move || memoized_site_query(&runner)).await; + let mut results: Vec = Vec::new(); + for p in site_output + .iter() + .flat_map(|stdout| parse_python_site_packages_output(stdout)) + { let resolved = if p.is_absolute() { p } else { std::path::absolute(&p).unwrap_or(p) }; - if seen.insert(resolved.clone()) { + if !results.contains(&resolved) { results.push(resolved); } } + results +} - // 1. Ask Python for site-packages (subprocesses: on the blocking pool) - let site_output = run_blocking(move || memoized_site_query(&runner)).await; - if let Some(stdout) = site_output { - for p in parse_python_site_packages_output(&stdout) { - add_path(p, &mut seen, &mut results); - } - } +/// `answered` (an interpreter's own answer), then the well-known +/// interpreter locations and, within `reach`, the tool environments. +async fn with_well_known_site_packages(answered: Vec, reach: SystemReach) -> Vec { + let mut seen: HashSet = answered.iter().cloned().collect(); + let mut results = answered; - // A project installs into one interpreter, and it just answered. - if reach == SystemReach::Project && !results.is_empty() { - return results; + fn add_path(p: PathBuf, seen: &mut HashSet, results: &mut Vec) { + let resolved = if p.is_absolute() { + p + } else { + std::path::absolute(&p).unwrap_or(p) + }; + if seen.insert(resolved.clone()) { + results.push(resolved); + } } - // 2. Well-known system paths + // Well-known system paths let home_dir = crate::utils::fs::home_dir(); // Helper closure to scan base/{lib,lib64}/python3.*/[dist|site]-packages. @@ -3491,13 +3545,10 @@ async fn local_site_packages_with( /// Local-mode discovery for [`PythonCrawler::get_site_packages_paths`] /// over an explicit environment (tests pass a closure instead of mutating -/// the process environment), plus whether the dirs are the shared -/// interpreter's ([`project_interpreter_site_packages`]) rather than an -/// environment of the project's own. What is installed in a shared -/// interpreter is not all this project's: see [`scope`]. An interpreter on -/// `PATH` that sits in a venv or a conda environment (a Docker image's -/// `ENV PATH=/opt/venv/bin:$PATH`, with no `VIRTUAL_ENV`) is the project's -/// own environment, like an activated one. +/// the process environment), plus whether the dirs are a shared +/// interpreter's ([`project_interpreter_sites`]) rather than an environment +/// of the project's own. What is installed in a shared interpreter is not +/// all this project's: see [`scope`]. async fn local_sites_with( cwd: &Path, var: &impl Fn(&str) -> Option, @@ -3523,15 +3574,7 @@ async fn local_sites_with( return (Vec::new(), false); } if is_python_project(cwd).await { - let sites = project_interpreter_site_packages(cwd).await; - let probed = sites.clone(); - let own = run_blocking(move || { - probed - .iter() - .any(|site| own_environment_of_site(site).is_some()) - }) - .await; - return (sites, !own); + return project_interpreter_sites(cwd, var).await; } (Vec::new(), false) } @@ -3596,10 +3639,9 @@ impl PythonCrawler { /// Pipenv's own (`is_pipenv_project`), uv's own (see /// `uv_owns_project_env`) or Poetry's own (see /// `poetry_owns_project_env`), fall through to the interpreter - /// the project installs into - /// (`project_interpreter_site_packages`): the Python on `PATH`, - /// not every interpreter and tool environment on the machine, - /// which only `--global` reads. + /// the project installs into (`project_interpreter_sites`): the + /// Python on `PATH`, not every interpreter and tool environment + /// on the machine, which only `--global` reads. /// /// A fresh uv clone (`uv.lock`, no `.venv` yet) returns nothing: /// its lock-only packages come from `uv.lock` instead. @@ -3642,6 +3684,14 @@ impl PythonCrawler { (sites, shared) } + /// Whether the project at `options.cwd` has no environment of its own + /// and installs into an interpreter it shares with the rest of the + /// machine. Never so under `--global` / `--global-prefix`. + pub async fn installs_into_a_shared_interpreter(&self, options: &CrawlerOptions) -> bool { + let var = |name: &str| std::env::var(name).ok(); + self.sites_with(options, &var).await.1 + } + /// Crawl all discovered `site-packages` and return every package found. /// /// A project with no environment of its own is crawled in the diff --git a/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs index bd71300d1..7fb4fa72d 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler/scope.rs @@ -37,13 +37,38 @@ use crate::vendor::pypi_requirements::{ /// The canonical names of the packages that belong to the project at `cwd` /// among the distributions installed in `sites`: the ones it declares and, -/// transitively, the ones those require. `None` when the project declares -/// dependencies in a way this module does not read in full; the crawl then -/// stays unscoped. +/// transitively, the ones those require, plus the ones its patch manifest +/// records ([`recorded_names`]). `None` when the project declares +/// dependencies in a way this module does not read in full, or in no place +/// this module reads; the crawl then stays unscoped. pub(super) async fn project_scope(cwd: &Path, sites: &[PathBuf]) -> Option> { let declared = declared_names(cwd).await?; let sites = sites.to_vec(); - Some(run_blocking(move || required_closure(declared, &sites)).await) + let mut scope = run_blocking(move || required_closure(declared, &sites)).await; + scope.extend(recorded_names(cwd).await); + Some(scope) +} + +/// The canonical names of the PyPI packages the project's patch manifest +/// (`.socket/manifest.json`) records. A recorded patch names its package: +/// `get ` patched it on purpose, or an earlier scan did, so it stays +/// one of the project's packages whether or not a requirements file names +/// it. Left out of the scope, it would get no newer patch and `scan +/// --prune` would report its record as one to roll back. Only the package +/// itself counts: what it requires is not the project's on its account. A +/// manifest kept elsewhere (`--manifest-path`) is not read here, and its +/// packages are judged by the project's declarations alone. +async fn recorded_names(cwd: &Path) -> Vec { + let path = cwd.join(crate::constants::DEFAULT_PATCH_MANIFEST_PATH); + let Ok(Some(manifest)) = crate::manifest::operations::read_manifest(&path).await else { + return Vec::new(); + }; + manifest + .patches + .keys() + .filter_map(|purl| crate::utils::purl::parse_pypi_purl(purl)) + .map(|(name, _)| canonicalize_pypi_name(&name)) + .collect() } /// What a project declares: the canonical name of each package, and the @@ -100,7 +125,12 @@ const UNREAD_TOOL_TABLES: &[&[&str]] = &[ /// The packages the project at `cwd` declares as dependencies, over all of /// its requirements files and its `pyproject.toml`. `None` when one of its -/// declarations is not read in full (see the module docs). +/// declarations is not read in full (see the module docs), and when nothing +/// that states dependencies was found: a project whose only marker is a +/// `pyproject.toml` that configures tools keeps its requirements somewhere +/// this module does not look (`deploy/docker/requirements.txt`), if it has +/// any. A requirements file with no requirement in it is a statement: the +/// project declares none. async fn declared_names(cwd: &Path) -> Option { let view = ProjectView::Disk(cwd); for name in UNREAD_DECLARATIONS { @@ -114,16 +144,18 @@ async fn declared_names(cwd: &Path) -> Option { return None; } let mut names = Declared::new(); + let mut states_dependencies = false; match view.read_text("pyproject.toml").await { - Ok(text) => pyproject_declares(&text, &mut names)?, + Ok(text) => states_dependencies |= pyproject_declares(&text, &mut names)?, // A read that fails on a file that is there (a link leaving the // repository, which reads as not found) hides its declarations. Err(_) if view.exists_no_follow("pyproject.toml").await => return None, Err(_) => {} } let files = requirements_files(&view).await?; + states_dependencies |= !files.is_empty(); requirements_declare(&view, files, &mut names).await?; - Some(names) + states_dependencies.then_some(names) } /// The pip requirements files the project keeps: every `*.txt` or `*.in` @@ -277,12 +309,13 @@ fn location_declares(location: &str, rel: &str, names: &mut Declared) -> Option< /// Adds to `names` what a `pyproject.toml` declares: the PEP 621 `[project]` /// name, `dependencies` and `optional-dependencies`, and the PEP 735 -/// `[dependency-groups]`. A file with none of those tables (linter and -/// formatter configuration only) declares nothing. `None` for a file that -/// does not parse, a dependency list the build backend fills in at build -/// time (`dynamic`), an entry that is not a PEP 508 requirement, and -/// dependencies kept in a tool's own table ([`UNREAD_TOOL_TABLES`]). -fn pyproject_declares(text: &str, names: &mut Declared) -> Option<()> { +/// `[dependency-groups]`. `Some(false)` for a file with none of those +/// tables (linter and formatter configuration only): it says nothing about +/// dependencies. `None` for a file that does not parse, a dependency list +/// the build backend fills in at build time (`dynamic`), an entry that is +/// not a PEP 508 requirement, and dependencies kept in a tool's own table +/// ([`UNREAD_TOOL_TABLES`]). +fn pyproject_declares(text: &str, names: &mut Declared) -> Option { let document: DocumentMut = text.parse().ok()?; let root = document.as_item(); let unread = UNREAD_TOOL_TABLES @@ -317,7 +350,7 @@ fn pyproject_declares(text: &str, names: &mut Declared) -> Option<()> { array_declares(group, names)?; } } - Some(()) + Some(root.get("project").is_some() || root.get("dependency-groups").is_some()) } /// The item at `path` under `item`, each step through a table. @@ -859,13 +892,22 @@ line-length = 100 .await, Some(names(&["flask"])) ); + // A `[project]` table with no dependencies states that there are + // none. + assert_eq!( + declared(&[("pyproject.toml", "[project]\nname = \"app\"\n")]).await, + Some(names(&["app"])) + ); + // Tool configuration and nothing else: the project's dependencies + // are stated somewhere this module does not look, if anywhere, so + // the crawl is not scoped. assert_eq!( declared(&[( "pyproject.toml", "[tool.poetry-dynamic-versioning]\nenable = true\n" )]) .await, - Some(BTreeSet::new()) + None ); } @@ -1073,4 +1115,41 @@ line-length = 100 write(&project, "setup.py", ""); assert_eq!(project_scope(&project, &[site]).await, None); } + + /// A package the project's patch manifest records stays the project's + /// when no requirements file names it: `get ` patched it on + /// purpose. Only that package: what it requires is not. + #[tokio::test] + async fn a_recorded_patch_keeps_its_package_in_the_scope() { + let tmp = tempfile::tempdir().unwrap(); + let (project, site) = (tmp.path().join("project"), tmp.path().join("site")); + write(&project, "requirements.txt", "flask\n"); + install(&site, "Flask", "3.0.0", &[]); + install(&site, "requests", "2.32.0", &["urllib3<3"]); + install(&site, "urllib3", "2.2.0", &[]); + let record = r#"{ + "uuid": "11111111-1111-4111-8111-111111111111", + "exportedAt": "2026-01-01T00:00:00Z", + "files": {}, + "vulnerabilities": {}, + "description": "seed", + "license": "MIT", + "tier": "free" + }"#; + write( + &project, + ".socket/manifest.json", + &format!( + r#"{{"patches": {{ + "pkg:pypi/Requests@2.32.0?artifact_id=py3-none-any-whl": {record}, + "pkg:npm/left-pad@1.3.0": {record} + }}}}"# + ), + ); + let scope = project_scope(&project, &[site]).await.unwrap(); + assert_eq!( + scope, + HashSet::from(["flask".to_string(), "requests".to_string()]) + ); + } } diff --git a/crates/socket-patch-core/tests/crawler_python_e2e.rs b/crates/socket-patch-core/tests/crawler_python_e2e.rs index 235d0091f..7fee8878b 100644 --- a/crates/socket-patch-core/tests/crawler_python_e2e.rs +++ b/crates/socket-patch-core/tests/crawler_python_e2e.rs @@ -1340,13 +1340,22 @@ async fn crawl_all_of_an_environment_on_path_is_not_scoped() { install_dist(&site, "Flask", "3.0.0", &[]); // Installed by hand, named in no requirements file. install_dist(&site, "gunicorn", "22.0.0", &[]); + // The interpreter names its user site too. A venv that does not + // take the system site packages never imports from it; a conda + // environment does. + let user_site = home.path().join("user-site"); + install_dist(&user_site, "userpkg", "1.0.0", &[]); if marker == "pyvenv.cfg" { - std::fs::write(prefix.join(marker), "home = /usr/bin\n").unwrap(); + std::fs::write( + prefix.join(marker), + "home = /usr/bin\ninclude-system-site-packages = false\n", + ) + .unwrap(); } else { std::fs::create_dir_all(prefix.join(marker)).unwrap(); } let bin = prefix.join("bin"); - install_fake_python(&bin, &[&site]); + install_fake_python(&bin, &[&site, &user_site]); let crawler = PythonCrawler::new(); let opts = CrawlerOptions { @@ -1362,14 +1371,72 @@ async fn crawl_all_of_an_environment_on_path_is_not_scoped() { .map(|package| package.purl) .collect(); purls.sort(); - assert_eq!( - purls, - ["pkg:pypi/flask@3.0.0", "pkg:pypi/gunicorn@22.0.0"], - "{marker}" - ); + let mut expected = vec!["pkg:pypi/flask@3.0.0", "pkg:pypi/gunicorn@22.0.0"]; + if marker == "conda-meta" { + expected.push("pkg:pypi/userpkg@1.0.0"); + } + assert_eq!(purls, expected, "{marker}"); + + // The conda root is the machine's default interpreter, which + // carries conda's own dependencies: it is shared, and scoped. + if marker == "conda-meta" { + std::fs::create_dir_all(prefix.join("condabin")).unwrap(); + let purls: Vec = with_project_env(home.path(), &bin, || async { + crawler.crawl_all(&opts).await + }) + .await + .into_iter() + .map(|package| package.purl) + .collect(); + assert_eq!(purls, ["pkg:pypi/flask@3.0.0"], "the conda root"); + } } } +/// With no interpreter to ask, the well-known locations that stand in for +/// it are every project's, whatever environments sit among them: a conda +/// root under HOME does not make the whole list the project's own. +#[cfg(unix)] +#[tokio::test] +#[serial] +async fn crawl_all_without_an_interpreter_is_scoped() { + let project = tempfile::tempdir().unwrap(); + let home = tempfile::tempdir().unwrap(); + let empty_path = tempfile::tempdir().unwrap(); + std::fs::write( + project.path().join("requirements.txt"), + "sp-fallback-declared\n", + ) + .unwrap(); + let conda = home.path().join("miniconda3"); + std::fs::create_dir_all(conda.join("conda-meta")).unwrap(); + let site = conda.join("lib/python3.12/site-packages"); + install_dist(&site, "sp-fallback-declared", "1.0.0", &[]); + install_dist(&site, "sp-fallback-decoy", "6.6.6", &[]); + + let crawler = PythonCrawler::new(); + let opts = CrawlerOptions { + cwd: project.path().to_path_buf(), + global: false, + global_prefix: None, + }; + let purls: Vec = with_project_env(home.path(), empty_path.path(), || async { + crawler.crawl_all(&opts).await + }) + .await + .into_iter() + .map(|package| package.purl) + .collect(); + assert!( + purls.contains(&"pkg:pypi/sp-fallback-declared@1.0.0".to_string()), + "{purls:?}" + ); + assert!( + !purls.iter().any(|purl| purl.contains("sp-fallback-decoy")), + "{purls:?}" + ); +} + /// #964: a uv project (`uv.lock`) and a PEP 723 script lock (`*.py.lock`) /// only ever install into uv's own env: `.venv` / `UV_PROJECT_ENVIRONMENT` /// for a project, uv's cache for a script. With none synced yet nothing is diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 84f84de51..1a69fca67 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -958,13 +958,15 @@ the interpreter on `PATH`. socket-patch reads that interpreter: it asks `python3` (else `python`, else `py`), run from the project directory, for its site-packages and user site, and reads only those directories. -An interpreter on `PATH` that sits in a virtualenv or a conda environment -(a Docker image's `ENV PATH=/opt/venv/bin:$PATH`) is the project's own -environment, like an activated one, and everything in it is the project's. +An interpreter on `PATH` that sits in a virtualenv (a Docker image's +`ENV PATH=/opt/venv/bin:$PATH`) or in a conda environment other than the +root is the project's own environment, like an activated one, and +everything in it is the project's. -Any other interpreter is shared. Homebrew formulae, distro packages and -other projects install into it too, so a package being installed there does -not make it this project's. `scan` keeps only: +Any other interpreter is shared, the conda root (`base`) included. +Homebrew formulae, distro packages, conda's own dependencies and other +projects install into it too, so a package being installed there does not +make it this project's. `scan` keeps only: - the packages the project declares: every requirement in a `*requirements*.txt` or `*requirements*.in` file at the top level or one @@ -975,14 +977,18 @@ not make it this project's. `scan` keeps only: - the installed packages those require, through their `Requires-Dist` metadata. A requirement behind an extra counts only when that extra is asked for (`requests[socks]`). Other markers, such as a platform test, - are not evaluated. + are not evaluated; +- the packages `.socket/manifest.json` records a patch for, declared or + not: `socket-patch get ` patched them on purpose. A project that declares nothing, or whose declared packages are not installed, has no packages there. Install them first (`pip install -r requirements.txt`), preferably into a virtualenv. The filter is skipped, and every package in the interpreter is reported, -when socket-patch cannot read every declaration: a `setup.py` or +when nothing states the project's dependencies (its only marker is a +`pyproject.toml` that configures tools, and it has no requirements file in +the places above) and when socket-patch cannot read every declaration: a `setup.py` or `setup.cfg`, a `poetry.lock`, `pdm.lock`, `uv.lock` or PEP 751 lock, `dynamic` dependencies, dependencies in a `[tool.poetry]`, `[tool.pdm]`, `[tool.uv]`, `[tool.rye]` or `[tool.flit]` table, Hatch environments @@ -1006,7 +1012,8 @@ longer reported while an installed copy is still patched (`pypi_installed_patch_kept`): the record holds the only data that can restore that copy. `socket-patch rollback ` restores it and drops the record; add `--global` when the copy is in another interpreter or a tool's -environment. +environment. Copies outside the interpreter are looked for only when the +project installs into a shared one. ## Maven & NuGet caveats From f730f9b26fc035f80c69a97866a029ce4c6b11b6 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 09:21:20 -0500 Subject: [PATCH 4/5] Resolve a name given to show among every installed package `show ` looked the name up in the scoped crawl, so in a Python project with no environment of its own it reported an installed package the project does not declare as not installed. `get ` already used the unscoped listing; `show` now shares it, as the two share the name matcher. The plain `crawl_ecosystems` has no caller left outside the tests, so it is compiled for them only. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 3 +- crates/socket-patch-cli/src/commands/show.rs | 8 +- .../src/ecosystem_dispatch.rs | 7 +- crates/socket-patch-cli/tests/show_e2e.rs | 90 +++++++++++++++++++ docs/ecosystems.md | 4 +- 5 files changed, 106 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 3bf57c32e..12abe22ab 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1402,7 +1402,8 @@ the model is **not uniform** today: author chose) or on a url that names no package; a `${VAR}` in a requirements line; or a declaration that cannot be read (a missing include, a link leaving the repository). `apply`, `rollback` and `vex` look a recorded patch's package up by PURL in the same interpreter - and are not scoped, and `get ` resolves a name among every package installed there. A + and are not scoped, and `get ` and `show ` resolve a name among every package + installed there. A project whose environment only its manager creates (uv, Pipenv, Poetry with its virtualenvs on) still has nothing installed until that environment exists. diff --git a/crates/socket-patch-cli/src/commands/show.rs b/crates/socket-patch-cli/src/commands/show.rs index 693482833..fb7946ec6 100644 --- a/crates/socket-patch-cli/src/commands/show.rs +++ b/crates/socket-patch-cli/src/commands/show.rs @@ -26,7 +26,7 @@ use socket_patch_core::utils::purl::normalize_purl; use socket_patch_core::utils::target::{Target, TargetKind}; use crate::args::{apply_env_toggles, GlobalArgs}; -use crate::ecosystem_dispatch::{crawl_ecosystems, installed_target_matches}; +use crate::ecosystem_dispatch::{crawl_ecosystems_for_name, installed_target_matches}; use crate::ui::diff::{file_diff, FileDiff}; use crate::ui::{self, plural, select_one, Style}; @@ -587,8 +587,12 @@ async fn candidates(args: &ShowArgs, target: &Target, client: &ApiClient) -> Res TargetKind::Ghsa => client.search_patches_by_ghsa(target.as_str()).await, TargetKind::Purl => client.search_patches_by_package(target.as_str()).await, TargetKind::Uuid | TargetKind::Name => { + // A name resolves among every installed package, as `get` + // resolves it: a Python project with no environment of its own + // is otherwise crawled only for the packages it declares. let only = args.common.ecosystems.as_deref().filter(|l| !l.is_empty()); - let (packages, _, _) = crawl_ecosystems(&args.common.crawler_options(), only).await; + let (packages, _, _) = + crawl_ecosystems_for_name(&args.common.crawler_options(), only).await; let matched = installed_target_matches(target, &packages); if matched.is_empty() { return Err(Lookup::Target(format!( diff --git a/crates/socket-patch-cli/src/ecosystem_dispatch.rs b/crates/socket-patch-cli/src/ecosystem_dispatch.rs index a803cfbd7..7d7f510d4 100644 --- a/crates/socket-patch-cli/src/ecosystem_dispatch.rs +++ b/crates/socket-patch-cli/src/ecosystem_dispatch.rs @@ -1556,6 +1556,11 @@ where /// entry. Each crawler reports only its own ecosystem's purls, so the /// selected ecosystems' packages, their order and their counts are exactly /// the full crawl's. +/// +/// Every command that crawls keeps something more: `scan` the npm half +/// ([`crawl_ecosystems_with_npm`]), `get` and `show` every installed Python +/// package ([`crawl_ecosystems_for_name`]). This plain form is the tests'. +#[cfg(test)] pub async fn crawl_ecosystems( options: &CrawlerOptions, only: Option<&[String]>, @@ -1570,7 +1575,7 @@ pub async fn crawl_ecosystems( } /// [`crawl_ecosystems`] for resolving a package the user named -/// (`get `). A Python project with no environment of its own is +/// (`get `, `show `). A Python project with no environment of its own is /// crawled for every package installed where it installs /// (`PythonCrawler::crawl_all_installed`), not only the ones it declares: /// the name says the package is wanted, as its PURL would. diff --git a/crates/socket-patch-cli/tests/show_e2e.rs b/crates/socket-patch-cli/tests/show_e2e.rs index 3d8c46f90..4e45dce91 100644 --- a/crates/socket-patch-cli/tests/show_e2e.rs +++ b/crates/socket-patch-cli/tests/show_e2e.rs @@ -280,6 +280,96 @@ async fn show_resolves_a_purl_to_its_best_ranked_patch() { ); } +/// A name given to `show` resolves among every package installed where +/// the project installs, as `get` resolves it. A Python project with no +/// environment of its own is otherwise crawled only for the packages it +/// declares. +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn show_resolves_the_name_of_an_installed_package_the_project_does_not_declare() { + use std::os::unix::fs::PermissionsExt; + + let purl = "pkg:pypi/undeclared-pkg@2.0.0"; + let mock = MockServer::start().await; + let mut body = view(true); + body["purl"] = serde_json::json!(purl); + mount_view(&mock, body).await; + Mock::given(method("GET")) + .and(path(format!( + "/v0/orgs/{ORG}/patches/by-package/{}", + purl.replace(':', "%3A") + .replace('/', "%2F") + .replace('@', "%40") + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": UUID, "purl": purl, "publishedAt": "2026-08-03T00:00:00Z", + "description": "", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }], + "canAccessPaidPatches": true + }))) + .mount(&mock) + .await; + + let tmp = tempfile::tempdir().unwrap(); + let project = tmp.path().join("proj"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), "declared-pkg\n").unwrap(); + // The interpreter on PATH, and what is installed in it. + let site = tmp.path().join("system/lib/python3.12/site-packages"); + for (name, version) in [("declared_pkg", "1.0.0"), ("undeclared_pkg", "2.0.0")] { + let dist = site.join(format!("{name}-{version}.dist-info")); + std::fs::create_dir_all(&dist).unwrap(); + std::fs::write( + dist.join("METADATA"), + format!("Metadata-Version: 2.1\nName: {name}\nVersion: {version}\n"), + ) + .unwrap(); + } + let bin = tmp.path().join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let python = bin.join("python3"); + std::fs::write( + &python, + format!( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ + printf '%s\\n' '{}'\n", + site.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut search_path = vec![bin]; + search_path.extend(std::env::split_paths( + &std::env::var_os("PATH").unwrap_or_default(), + )); + + let out = hermetic_command(&binary()) + .args(["show", "undeclared-pkg", "--stat"]) + .args([ + "--api-url", + &mock.uri(), + "--api-token", + "fake-token", + "--org", + ORG, + ]) + .env("PATH", std::env::join_paths(search_path).unwrap()) + .env_remove("VIRTUAL_ENV") + .current_dir(&project) + .output() + .expect("run socket-patch show"); + let stdout = String::from_utf8_lossy(&out.stdout); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!( + out.status.code(), + Some(0), + "stdout={stdout}; stderr={stderr}" + ); + assert!(stdout.contains(purl), "stdout={stdout}; stderr={stderr}"); +} + /// A token the patch service refuses is not the end of it: the public /// service, which has the free patches, is asked for the patch. When it /// has none either, the refusal is what is reported: it is the cause, and diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2f0ea5b16..0295db193 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1003,8 +1003,8 @@ global project), are never read for a project. Use `--global` to patch those. `apply`, `rollback` and `vex` find the packages of recorded patches by name -and version in the same interpreter, and `socket-patch get ` resolves -a name among everything installed there. The filter applies to `scan` +and version in the same interpreter, and `socket-patch get ` and +`socket-patch show ` resolve a name among everything installed there. The filter applies to `scan` discovery only. `scan --prune` does not drop the record of a patch whose package is no From 0ce837e59e9a1ea972495fff41344b1d3ecd6ba9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 12:05:44 -0500 Subject: [PATCH 5/5] Name still-patched copies when a prune is skipped, and say when packages were left out - When the crawl is empty the manifest half of `scan --prune` is skipped, so a project whose only records are for copies outside its interpreter got no pointer to the `rollback --global` that restores them. The skipped prune now reports `pypi_installed_patch_kept` for each recorded PyPI patch that is still on disk. No record is dropped on that path. - A scan that finds nothing because every package in the interpreter on PATH was left out as undeclared now ends with a line saying so, in place of "install first", which sent the user to install what is already there. - A pixi project that pip also installs keeps the interpreter crawl. Its test staged the package in a conda root under HOME, which the fallback does not read when an interpreter answers; it now installs the declared package in a stub interpreter on PATH, and the three tests that use one share the stub. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- .../socket-patch-cli/src/commands/scan/gc.rs | 19 +++ .../socket-patch-cli/src/commands/scan/mod.rs | 46 ++++-- .../src/commands/scan/render.rs | 38 +++++ .../tests/e2e_pypi_multi_copy.rs | 136 ++++++++++++++++++ .../tests/in_process_python_envs.rs | 125 ++++++++-------- .../src/crawlers/python_crawler.rs | 11 ++ docs/ecosystems.md | 8 +- 8 files changed, 314 insertions(+), 75 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74c5ab512..7a06cadb7 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -362,7 +362,7 @@ For a **9.0 root lock**, the CLI ensures `pnpm-workspace.yaml` carries `trustLoc **Agent-flow run-level warnings (additive).** An agent-mode apply (`--mode agent` / `--sync`, `--json`) may add a top-level `warnings[]` array of `{code, detail}` entries to the scan envelope (absent when none fired; each is also mirrored to stderr unless `--silent`). They surface cross-mode state the apply cannot change — never a status or exit-code change (hosted refusals set the precedent: exit 0 + warning). Codes (stable; new codes are additive/MINOR): `vendored_ownership_retained` — vendor-owned package(s) were skipped before download (each is also a `skipped` / `vendored` event); the detail names the purls and the migration path (`remove `, or `vendor --revert` which unwinds every vendored package, then re-run). `hosted_wiring_retained` — the lockfiles still pin scanned package(s) to a hosted patch (the agent run does not unwind hosted wiring — as of v5.0 that is `socket-patch rollback`'s job, which restores the upstream registry entries, or `remove ` per package); the detail names the purls and the options (stay `--mode hosted`, migrate via `scan --mode vendored`, or `socket-patch rollback`). The warning keys on the hosted pins lockfile discovery finds at scan time, so a flow that restored the upstream entries retires it. The human path prints the same `hosted_wiring_retained` text to stderr after an apply; the vendored counterpart is already covered by its per-package `[skip] … (vendored …)` lines. `ownership_not_restored` (v5.0; `apply` and `rollback` `warnings[]` alike) — a file WAS patched (or restored) but could not be given its original uid/gid (its mode is kept; the group is kept when the caller belongs to it); the detail is `: : patched, but ownership could not be restored to uid N gid M: ` and the human line `Warning: ` (stderr, muted by `--silent`); never a status or exit change. `go_installed_tool_stale` (v5.0; `apply`, dry runs included) — a `--global` Go apply patched a module cache copy that a tool installed with `go install` was built from before the patch; the detail names the binary and the `go install @` remedy (or, when they can't be inspected, what could not be checked); never a status or exit change. `stale_bytecode_not_removed` (`apply` and `rollback` `warnings[]` alike) — a `.py` file WAS patched (or restored) but CPython bytecode compiled from its previous bytes (`__pycache__/.[.opt-N].pyc`) could not be deleted, so Python may keep running the old code until it is removed; the detail is `: could not remove stale Python bytecode (: , …); …` and the human line `Warning: `; never a status or exit change. `patch_files_skipped` (`apply --force`) — a file of the patch is not on disk and was skipped; the detail is `: N patch file(s) not found on disk and skipped (--force): , …` and the human line `Warning: `. The package's event is `applied` with the files that were written, or, when the run wrote none and the files that exist are patched, `skipped` / `already_patched`; never a status or exit change. `cargo_build_cache_stale` (v5.0; `apply` and `rollback` `warnings[]` alike) — a cargo crate's bytes changed but its compiled copy in a project build directory could not be invalidated (a fingerprint directory that could not be removed, or a `build.build-dir` with a `{workspace-path-hash}` template); the detail names the crates to `cargo clean -p` before the next build, which may otherwise link the stale code; never a status or exit change. -`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` restores are looked up by PURL, and for a project that installs into a shared interpreter so are the ones `rollback --global` restores (a project with an environment of its own never patched a copy outside it). The wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. +`scan --prune` opts into garbage collection. When set, `scan` removes manifest entries for packages no longer present in the crawl, then deletes orphan blob files, and every obsolete diff and package archive, from `.socket/`. A blob is an orphan when no patch left in the manifest references it: the afterHash and beforeHash blobs of every remaining patch are kept, the same retention policy `repair` uses (the beforeHash blobs are an offline rollback's only restore data, and `repair` downloads afterHash blobs only). Diff and legacy package archives are never kept, even for a remaining patch: nothing reads them any more. Off by default (v3.0) so a temporary uninstall doesn't silently destroy manifest state. Under `--global`/`--global-prefix` the crawl covers only the global installs while the manifest is still `--cwd`'s, so the prune also keeps every entry the `--cwd` project accounts for (its installed packages and its lockfile-listed ones, exactly what the project's own `--prune` keeps): a global prune removes only entries neither scope has. Only entries whose ecosystem this run actually crawled are eligible: a `pkg:/` with no crawler in this build (a newer CLI's ecosystem in the committed manifest) is exempt — the crawl never looked for them, so their absence is not evidence of removal (same fail-safe as the `--ecosystems` filter, which narrows the query but never the prune's installed set). A Cargo entry is also exempt while its agent-mode copy is still patched: the project crawl looks up only the crates `Cargo.lock` resolves, but a crate the lock bumped or dropped keeps its patched copy in the machine-wide `$CARGO_HOME/registry/src` cache (nothing deletes it), and the entry holds the only blobs that can restore that copy. The wet pass keeps it with a `cargo_cache_patch_kept` warning naming the `socket-patch rollback ` that restores the copy and drops the entry; the `--dry-run` preview reports no event (and no warning) for it. A PyPI entry is exempt the same way: a project with no environment of its own is crawled only for the packages it declares, in the one interpreter it installs into, so a package it stopped declaring, or one an earlier release patched in another interpreter or a tool's environment, drops out of the crawl with its copy still patched. The copies `rollback ` restores are looked up by PURL, and for a project that installs into a shared interpreter so are the ones `rollback --global` restores (a project with an environment of its own never patched a copy outside it). The wet pass keeps an entry with a still-patched copy with a `pypi_installed_patch_kept` warning. A prune that an empty crawl skips drops no record, and reports the same warning for each recorded PyPI patch that is still on disk. The pass also reconciles vendored state (runs FIRST, under ONE apply-lock acquisition shared with the manifest prune — lock contention skips the whole pass without failing the scan; `--lock-timeout` is honored and a lock I/O error is reported rather than swallowed; the existence gate — a manifest file OR a vendor ledger file, both cheap stats; an emptied ledger is deleted on save, so its presence is its content proxy — runs BEFORE the lock, so a bare project never gets a `.socket/`; in the vendored scan arms the pass runs AFTER the vendor step): (a) ledger entries still tracked by a manifest record (manifest-mode entries written by standalone `vendor`) whose patch is gone from the manifest are reverted — `detached` entries (every `scan`/`get --mode vendored` entry, v5.0) have no manifest record to lose and are exempt from this leg; (b) EVERY ledger entry whose dependency is no longer in the lockfile graph is reverted and any manifest entry it still had dropped (v5.0: the check is about the lockfile, not the manifest, so embedded-record entries are no longer exempt; a missing or undeterminable lockfile keeps the entry, fail-safe); and (c) orphan `.socket/vendor//` dirs with no ledger entry are swept. The prune never deletes a zero-patch `.socket/manifest.json` (its `{"patches": {}}` + `setup` block stay). Under `--json` (v5.0, MAJOR) the pass is recorded into the scan envelope: each pruned manifest entry is a `removed` event with `details.manifest: true`, each reverted vendored entry a `removed` event (`errorCode: "vendor_reverted"`, `details.mode: "vendored"`), each drift-kept entry a `skipped` / `vendor_revert_kept` event and each entry whose revert failed a `skipped` / `vendor_revert_failed` event (a GC revert failure never fails the run); a `--dry-run` preview reports the removals as `verified`. The artifact sweep is the envelope's `gc` (`summary.bytesFreed` mirrors it) and the orphan vendor dirs swept are the top-level `removedVendorOrphanDirs` count. The pass's warnings join the top-level `warnings[]`: `vendor_state_write_failed` (entries were reverted but the ledger rewrite failed), `manifest_write_failed` (the pruned manifest could not be written: no entry was pruned and no blob, diff or package archive was swept, since the manifest on disk still references them), `cleanup_failed` (an orphan sweep failed mid-way, or `.socket/` or one of its `blobs/`, `diffs/`, `packages/` directories is a symlink, which is never swept), `cargo_cache_patch_kept` (see above), and the reinstall advisories of the vendored reverts (`vendor_bun_reinstall_required`, `vendor_vlt_reinstall_required`, `vendor_pypi_reinstall_required`; a revert's other warnings, such as `vendor_lock_entry_removed` or a drift keep's, are not repeated). A pass skipped at the lock (`lock_held` | `lock_io`) has no `gc` and no events, only a `gc_skipped` warning whose detail ends with the code. Human mode prints `GC: skipped: .`, one `GC: .` line per warning, and `GC: failed to revert N vendored entries: …` (singular for one). A drift keep is an entry the revert deliberately preserved (`vendor_artifact_kept` — undo the drift and re-run `vendor --revert` to finish); the preview cannot see drift (backends return before the wiring replay on dry runs), so its `verified` reverts may over-promise what a wet run will actually reclaim. `scan` queries the patch API in `--batch-size` chunks. Authenticated runs POST `/v0/orgs/{slug}/patches/batch`; token-less runs POST `{proxy}/patch/batch` on the public proxy and degrade to per-package `GET /patch/by-package/:purl` requests in two cases: the deployed proxy predates the batch endpoint (legacy proxies answer the POST with their `400 "Unsupported endpoint"` catch-all), or the all-or-nothing batch validation rejects the chunk (e.g. a crawled PURL type the server doesn't recognize, such as `pkg:jsr/…` — the per-package path tolerates those individually, preserving the pre-batch scan semantics). Rate limits and over-capacity 503s surface instead of silently degrading. @@ -1391,7 +1391,9 @@ the model is **not uniform** today: `pyproject.toml`. A package `.socket/manifest.json` records a patch for is the project's too, declared or not (the package itself, not what it requires). A project that declares nothing (a requirements file with no requirement, a `[project]` table with no dependencies), or whose - declared packages are not installed, has no packages there. Discovery is left unscoped (every + declared packages are not installed, has no packages there; when that leaves a human-mode scan + with nothing at all, its closing line says how many installed packages were left out as + undeclared instead of asking for an install. Discovery is left unscoped (every package in that interpreter, as before) when nothing states the project's dependencies (its only marker is a `pyproject.toml` that configures tools, and no requirements file is found) and when a declaration is not read in full: a `setup.py` or `setup.cfg`; a `poetry.lock`, `pdm.lock`, diff --git a/crates/socket-patch-cli/src/commands/scan/gc.rs b/crates/socket-patch-cli/src/commands/scan/gc.rs index 89d819d1a..923d813b1 100644 --- a/crates/socket-patch-cli/src/commands/scan/gc.rs +++ b/crates/socket-patch-cli/src/commands/scan/gc.rs @@ -449,6 +449,25 @@ async fn keep_patched_pypi_copies( .collect() } +/// The `pypi_installed_patch_kept` warnings of a `--prune` whose crawl +/// found nothing. The manifest half of the GC is skipped there, so no +/// record is dropped, but a recorded PyPI patch can still be on disk in a +/// copy the scan no longer reaches (another interpreter, a tool's +/// environment), and this warning is what names the `rollback` that +/// restores it. Read-only: no lock, nothing written. +pub(super) async fn kept_pypi_patch_warnings( + common: &GlobalArgs, + manifest_path: &Path, + socket_dir: &Path, +) -> Vec<(&'static str, String)> { + let Ok(Some(manifest)) = read_manifest(manifest_path).await else { + return Vec::new(); + }; + let mut recorded: Vec = manifest.patches.keys().cloned().collect(); + recorded.sort(); + keep_patched_pypi_copies(common, &manifest, socket_dir, &mut recorded).await +} + /// The vendored-state half of the GC alone, for a `--prune` whose crawl /// found nothing (the manifest half is skipped there: pruning against an /// empty crawl would drop every entry). Reverting entries whose patch left diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 0fd37f39b..50e7adabd 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -2914,6 +2914,18 @@ async fn scan_project( projects_left_warnings(&left), ); } + // The prune is skipped on an empty crawl, so no record is dropped + // here. A recorded PyPI patch can still be on disk in a copy this + // scan no longer reaches, and its warning is what names the + // `rollback` that restores it. + if prune && !hosted { + layout_refusals.extend( + gc::kept_pypi_patch_warnings(&args.common, &manifest_path, &socket_dir) + .await + .into_iter() + .map(|(code, detail)| (code.to_string(), detail)), + ); + } status.finish(); if human { print_layout_refusals(&layout_refusals, &project_patch_notice, args.common.silent); @@ -3027,14 +3039,32 @@ async fn scan_project( ) ); } else if !policy.root_excluded() { - println!( - "{}", - render::no_packages_message( - args.common.is_global(), - args.common.ecosystems.as_deref(), - &args.paths, - ) - ); + // Nothing was crawled at all, yet the Python on PATH holds + // packages the project does not declare: say that they + // were left out, not that nothing is installed. + let undeclared = if scanned_purls.is_empty() + && args.paths.is_empty() + && !args.common.is_global() + && args.common.ecosystem_selected(Ecosystem::Pypi) + { + socket_patch_core::crawlers::PythonCrawler::new() + .undeclared_installed(&crawler_options) + .await + } else { + 0 + }; + if undeclared > 0 { + println!("{}", render::no_declared_python_packages(undeclared)); + } else { + println!( + "{}", + render::no_packages_message( + args.common.is_global(), + args.common.ecosystems.as_deref(), + &args.paths, + ) + ); + } } policy.print_human(args.common.silent, args.common.verbose); } diff --git a/crates/socket-patch-cli/src/commands/scan/render.rs b/crates/socket-patch-cli/src/commands/scan/render.rs index 109184961..b4e707bbf 100644 --- a/crates/socket-patch-cli/src/commands/scan/render.rs +++ b/crates/socket-patch-cli/src/commands/scan/render.rs @@ -83,6 +83,28 @@ pub(crate) fn no_packages_unreadable(warnings: usize) -> String { } } +/// What an empty crawl says when the Python on `PATH` does hold packages, +/// `undeclared` of them, and the project declares none: they are left out +/// as not the project's (a project with no environment of its own shares +/// that interpreter), and "install first" alone would not say so. +pub(crate) fn no_declared_python_packages(undeclared: usize) -> String { + let (installed, them) = if undeclared == 1 { + ( + "the 1 package installed in the Python on PATH is not one".to_string(), + "it", + ) + } else { + ( + format!("the {undeclared} packages installed in the Python on PATH are not ones"), + "them", + ) + }; + format!( + "No packages found: {installed} this project declares. Install its requirements \ + first; `--global` scans {them} with every other package on the machine." + ) +} + /// What an empty crawl says, naming the filter that emptied it when there /// was one (`--ecosystems`, PATH scoping) instead of a generic /// "install first" hint. @@ -903,6 +925,22 @@ mod tests { ); } + #[test] + fn an_empty_crawl_says_when_installed_packages_were_left_out_as_undeclared() { + assert_eq!( + no_declared_python_packages(18), + "No packages found: the 18 packages installed in the Python on PATH are not ones \ + this project declares. Install its requirements first; `--global` scans them \ + with every other package on the machine." + ); + assert_eq!( + no_declared_python_packages(1), + "No packages found: the 1 package installed in the Python on PATH is not one this \ + project declares. Install its requirements first; `--global` scans it with every \ + other package on the machine." + ); + } + #[test] fn no_packages_message_names_the_filter() { assert_eq!( diff --git a/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs b/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs index 7054a39fb..cfc7f3d23 100644 --- a/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs +++ b/crates/socket-patch-cli/tests/e2e_pypi_multi_copy.rs @@ -288,3 +288,139 @@ fn global_system_and_user_site_copies_are_all_patched() { ], ); } + +/// A stub `python3` in `bin` that answers `--version` and names `sites` as +/// its site-packages, as the crawler's `site` query reads a real one. +#[cfg(unix)] +fn stub_python(bin: &Path, sites: &[&Path]) { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(bin).unwrap(); + let mut script = String::from( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n", + ); + for site in sites { + script.push_str(&format!("printf '%s\\n' '{}'\n", site.display())); + } + let stub = bin.join("python3"); + std::fs::write(&stub, script).unwrap(); + std::fs::set_permissions(&stub, std::fs::Permissions::from_mode(0o755)).unwrap(); +} + +/// A project with no environment of its own is scanned in the interpreter +/// on `PATH`, for the packages it declares. A patch an earlier run left in +/// another environment on the machine is out of that scan's reach, and so +/// is its record: the scan finds nothing, and a `--prune` is skipped. The +/// run still names the record and the `rollback` that restores the copy, +/// and keeps the record. +#[cfg(unix)] +#[test] +fn a_skipped_prune_names_a_patch_still_installed_outside_the_projects_interpreter() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let home = root.join("home"); + let project = root.join("work"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), "# no dependencies\n").unwrap(); + stage_patch(&project); + // The interpreter on PATH holds nothing of the project's. + let system_site = root.join("usr/lib/python3/dist-packages"); + std::fs::create_dir_all(&system_site).unwrap(); + let bin = root.join("bin"); + stub_python(&bin, &[&system_site]); + // A pipx app's environment holds the patched copy. + let tool_site = home.join(".local/pipx/venvs/sometool/lib/python3.12/site-packages"); + let tool_copy = install_dupkit(&tool_site); + std::fs::write(&tool_copy, PATCHED).unwrap(); + + let path = format!("{}:/usr/bin:/bin", bin.display()); + let env = [("PATH", path.as_str()), ("HOME", home.to_str().unwrap())]; + let (code, stdout, stderr) = run( + &project, + &["scan", "--mode", "agent", "--prune", "--json"], + &env, + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let json = envelope(&stdout, &stderr); + let warnings = json["warnings"].as_array().cloned().unwrap_or_default(); + assert!( + warnings.iter().any(|w| { + w["code"] == "pypi_installed_patch_kept" + && w["detail"] + .as_str() + .is_some_and(|d| d.contains(PURL) && d.contains("--global")) + }), + "the still-patched copy must be named: {json:#}" + ); + let manifest: Value = + serde_json::from_slice(&std::fs::read(project.join(".socket/manifest.json")).unwrap()) + .unwrap(); + assert!(manifest["patches"].get(PURL).is_some(), "{manifest:#}"); + assert_eq!(std::fs::read(&tool_copy).unwrap(), PATCHED); + + // Restored copy: nothing to name. + std::fs::write(&tool_copy, ORIGINAL).unwrap(); + let (code, stdout, stderr) = run( + &project, + &["scan", "--mode", "agent", "--prune", "--json"], + &env, + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let json = envelope(&stdout, &stderr); + assert!( + !json["warnings"] + .as_array() + .into_iter() + .flatten() + .any(|w| w["code"] == "pypi_installed_patch_kept"), + "{json:#}" + ); +} + +/// When a scan finds nothing because every package in the interpreter on +/// `PATH` was left out as not the project's, it says so: "install first" +/// alone would send the user to install what is already there. +#[cfg(unix)] +#[test] +fn an_empty_scan_says_when_installed_packages_were_left_out_as_undeclared() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let home = root.join("home"); + std::fs::create_dir_all(&home).unwrap(); + let project = root.join("work"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write(project.join("requirements.txt"), "# no dependencies\n").unwrap(); + let system_site = root.join("usr/lib/python3/dist-packages"); + std::fs::create_dir_all(&system_site).unwrap(); + let bin = root.join("bin"); + stub_python(&bin, &[&system_site]); + let path = format!("{}:/usr/bin:/bin", bin.display()); + let env = [("PATH", path.as_str()), ("HOME", home.to_str().unwrap())]; + let scan = || { + run( + &project, + &["scan", "--mode", "agent", "--ecosystems", "pypi"], + &env, + ) + }; + + // An interpreter with nothing installed: the plain message. + let (code, stdout, stderr) = scan(); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("No pypi packages found."), "{stdout}"); + + install_dupkit(&system_site); + let (code, stdout, stderr) = scan(); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains( + "No packages found: the 1 package installed in the Python on PATH is not one this \ + project declares." + ), + "{stdout}" + ); + + // Once the project declares it, it is scanned like any other. + std::fs::write(project.join("requirements.txt"), "dupkit\n").unwrap(); + let (_, stdout, _) = scan(); + assert!(!stdout.contains("No packages found"), "{stdout}"); +} diff --git a/crates/socket-patch-cli/tests/in_process_python_envs.rs b/crates/socket-patch-cli/tests/in_process_python_envs.rs index 8af44a6da..f02da10f0 100644 --- a/crates/socket-patch-cli/tests/in_process_python_envs.rs +++ b/crates/socket-patch-cli/tests/in_process_python_envs.rs @@ -985,6 +985,44 @@ async fn uv_fresh_checkout_never_scans_the_system_python() { } } +/// A stub `python3` under `root` that names `site` as its site-packages, +/// as the crawler's `site` query reads a real interpreter. Returns its +/// directory, for [`scan_with_first_on_path`]. +#[cfg(unix)] +fn stub_python(root: &Path, site: &Path) -> std::path::PathBuf { + use std::os::unix::fs::PermissionsExt; + let bin = root.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let python = bin.join("python3"); + std::fs::write( + &python, + format!( + "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ + printf '%s\\n' '{}'\n", + site.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + bin +} + +/// Run `scan` with `bin` in front of the host's `PATH` (which the scan +/// still needs for its other tools), restoring `PATH` afterwards. +#[cfg(unix)] +async fn scan_with_first_on_path(bin: &Path, scan: impl std::future::Future) -> i32 { + let saved = std::env::var_os("PATH"); + let mut path = vec![bin.to_path_buf()]; + path.extend(std::env::split_paths(&saved.clone().unwrap_or_default())); + std::env::set_var("PATH", std::env::join_paths(path).unwrap()); + let code = scan.await; + match saved { + Some(v) => std::env::set_var("PATH", v), + None => std::env::remove_var("PATH"), + } + code +} + /// A project whose only Python manifest is `requirements.txt`, with no /// venv, installs into the interpreter on `PATH`, which other projects and /// tools share. Only the packages it declares, and what those require, @@ -998,7 +1036,6 @@ async fn uv_fresh_checkout_never_scans_the_system_python() { #[serial] async fn requirements_project_without_a_venv_scans_only_what_it_declares() { use socket_patch_cli::commands::scan::ScanMode; - use std::os::unix::fs::PermissionsExt; for (requirements, declared_is_found) in [ // Nothing declared: nothing in the interpreter is the project's. @@ -1015,19 +1052,7 @@ async fn requirements_project_without_a_venv_scans_only_what_it_declares() { std::fs::create_dir_all(&site).unwrap(); write_dist_info(&site, "declared_pkg", "1.0.0"); write_dist_info(&site, "system_decoy", "6.6.6"); - let bin = tmp.path().join("bin"); - std::fs::create_dir_all(&bin).unwrap(); - let python = bin.join("python3"); - std::fs::write( - &python, - format!( - "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ - printf '%s\\n' '{}'\n", - site.display() - ), - ) - .unwrap(); - std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + let bin = stub_python(tmp.path(), &site); // A pipx app's own environment under HOME. let home = tmp.path().join("home"); let tool = home.join(".local/pipx/venvs/hatch/lib/python3.12/site-packages"); @@ -1037,23 +1062,16 @@ async fn requirements_project_without_a_venv_scans_only_what_it_declares() { let server = MockServer::start().await; mock_batch_empty(&server).await; let saved: Vec<(&str, Option)> = - ["HOME", "PATH", "PIPX_HOME", "XDG_DATA_HOME"] + ["HOME", "PIPX_HOME", "XDG_DATA_HOME"] .into_iter() .map(|key| (key, std::env::var_os(key))) .collect(); - // The stub goes in front of the host's PATH, which the scan - // still needs for its other tools. - let mut path = vec![bin.clone()]; - path.extend(std::env::split_paths( - &std::env::var_os("PATH").unwrap_or_default(), - )); - std::env::set_var("PATH", std::env::join_paths(path).unwrap()); std::env::set_var("HOME", &home); std::env::remove_var("PIPX_HOME"); std::env::remove_var("XDG_DATA_HOME"); let mut args = default_args(&project, server.uri()); args.mode = Some(mode); - let code = scan_scrubbed(args).await; + let code = scan_with_first_on_path(&bin, scan_scrubbed(args)).await; for (key, value) in saved { match value { Some(v) => std::env::set_var(key, v), @@ -1083,8 +1101,6 @@ async fn requirements_project_without_a_venv_scans_only_what_it_declares() { #[tokio::test] #[serial] async fn requirements_project_without_a_venv_keeps_scanning_a_recorded_package() { - use std::os::unix::fs::PermissionsExt; - let tmp = tempfile::tempdir().unwrap(); let project = tmp.path().join("proj"); std::fs::create_dir_all(project.join(".socket")).unwrap(); @@ -1108,35 +1124,13 @@ async fn requirements_project_without_a_venv_keeps_scanning_a_recorded_package() write_dist_info(&site, "declared_pkg", "1.0.0"); write_dist_info(&site, "recorded_pkg", "3.0.0"); write_dist_info(&site, "system_decoy", "6.6.6"); - let bin = tmp.path().join("bin"); - std::fs::create_dir_all(&bin).unwrap(); - let python = bin.join("python3"); - std::fs::write( - &python, - format!( - "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'Python 3.12.0'; exit 0; fi\n\ - printf '%s\\n' '{}'\n", - site.display() - ), - ) - .unwrap(); - std::fs::set_permissions(&python, std::fs::Permissions::from_mode(0o755)).unwrap(); + let bin = stub_python(tmp.path(), &site); let server = MockServer::start().await; mock_batch_empty(&server).await; - let saved_path = std::env::var_os("PATH"); - let mut path = vec![bin.clone()]; - path.extend(std::env::split_paths( - &saved_path.clone().unwrap_or_default(), - )); - std::env::set_var("PATH", std::env::join_paths(path).unwrap()); let mut args = default_args(&project, server.uri()); args.mode = Some(socket_patch_cli::commands::scan::ScanMode::Agent); - let code = scan_scrubbed(args).await; - match saved_path { - Some(v) => std::env::set_var("PATH", v), - None => std::env::remove_var("PATH"), - } + let code = scan_with_first_on_path(&bin, scan_scrubbed(args)).await; assert_eq!(code, 0); let bodies = batch_bodies(&server).await; @@ -1309,20 +1303,22 @@ async fn pixi_fresh_checkout_never_scans_the_system_python() { /// the project's packages may be in an interpreter outside pixi's /// environments (a container image that runs `pip install -r /// requirements.txt`). With no pixi environment installed, such a project -/// still gets the crawl a requirements project always had, here reaching -/// the conda root under the stubbed HOME, in every mode. +/// still gets the crawl a requirements project has, in every mode: the +/// packages it declares, in the interpreter on `PATH`. +#[cfg(unix)] #[tokio::test] #[serial] async fn pixi_project_that_pip_also_installs_keeps_the_interpreter_crawl() { use socket_patch_cli::commands::scan::ScanMode; // A requirements file, or a `pyproject.toml` packaged with a build // backend (a library that keeps pixi for development and is `pip - // install`ed elsewhere). + // install`ed elsewhere). The requirement is not pinned, so only the + // installed copy says which release there is to ask about. let pip_files = [ - ("requirements.txt", "image-pkg==1.0.0\n"), + ("requirements.txt", "image-pkg\n"), ( "pyproject.toml", - "[project]\nname = \"lib\"\nversion = \"0.1.0\"\n\n[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n", + "[project]\nname = \"lib\"\nversion = \"0.1.0\"\ndependencies = [\"image-pkg\"]\n\n[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n", ), ]; for ((pip_file, text), mode) in pip_files.into_iter().flat_map(|file| { @@ -1337,20 +1333,23 @@ async fn pixi_project_that_pip_also_installs_keeps_the_interpreter_crawl() { std::fs::write(project.join("pixi.lock"), "version: 6\n").unwrap(); std::fs::write(project.join(pip_file), text).unwrap(); let home = tmp.path().join("home"); - let system = home - .join("anaconda3") - .join("lib") - .join("python3.11") - .join("site-packages"); - std::fs::create_dir_all(&system).unwrap(); - write_dist_info(&system, "image_pkg", "1.0.0"); + std::fs::create_dir_all(&home).unwrap(); + // The interpreter on PATH, where the image installed the project's + // requirements beside what it shipped with. + let site = tmp.path().join("system/lib/python3.12/site-packages"); + std::fs::create_dir_all(&site).unwrap(); + write_dist_info(&site, "image_pkg", "1.0.0"); + write_dist_info(&site, "system_decoy", "6.6.6"); + let bin = stub_python(tmp.path(), &site); let server = MockServer::start().await; mock_batch_empty(&server).await; let mut args = default_args(&project, server.uri()); args.mode = Some(mode); - let code = scan_unactivated(args, &home).await; + let code = scan_with_first_on_path(&bin, scan_unactivated(args, &home)).await; assert_eq!(code, 0, "{pip_file} {mode:?}"); - assert_discovered(&batch_bodies(&server).await, "pkg:pypi/image-pkg@1.0.0"); + let bodies = batch_bodies(&server).await; + assert_discovered(&bodies, "pkg:pypi/image-pkg@1.0.0"); + assert_not_discovered(&bodies, "pkg:pypi/system-decoy"); } } diff --git a/crates/socket-patch-core/src/crawlers/python_crawler.rs b/crates/socket-patch-core/src/crawlers/python_crawler.rs index 830241835..d63786675 100644 --- a/crates/socket-patch-core/src/crawlers/python_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/python_crawler.rs @@ -3787,6 +3787,17 @@ impl PythonCrawler { self.crawl_with(options, &var, false).await } + /// How many packages installed where the project installs + /// [`Self::crawl_all`] leaves out because the project does not declare + /// them. Zero for a project with an environment of its own, under + /// `--global`, and when the crawl is not scoped. + pub async fn undeclared_installed(&self, options: &CrawlerOptions) -> usize { + let var = |name: &str| std::env::var(name).ok(); + let installed = self.crawl_with(options, &var, false).await.len(); + let declared = self.crawl_with(options, &var, true).await.len(); + installed.saturating_sub(declared) + } + /// [`Self::crawl_all`] over an explicit environment. async fn crawl_all_with( &self, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 20f380847..c2451422f 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -984,7 +984,10 @@ make it this project's. `scan` keeps only: A project that declares nothing, or whose declared packages are not installed, has no packages there. Install them first -(`pip install -r requirements.txt`), preferably into a virtualenv. +(`pip install -r requirements.txt`), preferably into a virtualenv. When +the interpreter does hold packages and the project declares none of them, +the scan ends with `No packages found: the N packages installed in the +Python on PATH are not ones this project declares`. The filter is skipped, and every package in the interpreter is reported, when nothing states the project's dependencies (its only marker is a @@ -1014,7 +1017,8 @@ longer reported while an installed copy is still patched restore that copy. `socket-patch rollback ` restores it and drops the record; add `--global` when the copy is in another interpreter or a tool's environment. Copies outside the interpreter are looked for only when the -project installs into a shared one. +project installs into a shared one. A `--prune` that is skipped because +the scan found nothing reports the same warning, and drops no record. ## PyPI: pixi projects