From f823816cc600aa9d06d5e5a8c145b5682530a3af Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 10:52:01 -0500 Subject: [PATCH 1/2] Skip a compiled conda build instead of failing on it A compiled conda build of a Python package (pillow, numpy, pyyaml from conda-forge) is never the PyPI wheel a patch is made from, so nothing may be written to it. `apply` refused such a copy with `conda_build_not_pypi_release` and exit 1. That failed a run over a package socket-patch does not support yet: a manifest recorded where PyPI wheels are installed, then applied in a pixi or conda environment, could not pass. `scan --mode agent` already left the same patch out with a warning and exit 0. Compiled conda packages are now skipped: - `apply` writes nothing to the copy (also under `--force`), warns once per copy, emits a `skipped` event per record and copy, counts the records as `N not supported`, and leaves the exit status as it is. A copy that already holds a patch is still reported as already patched. - The skip is the copy's, for every record of the release, whether or not its files match one. The usual compiled build (a recipe-patched source, no wheel extension modules) used to fail as "no matching variant found". - `apply --check` does not call the copy drift. It settles a compiled copy as `apply` does, once over every record of its release and per release, so a copy that holds one record's patch is in sync, and another package in the same site-packages is judged on its own. - Under `--json`, a `scan` / `get` whose apply skips a copy of a record the run did not select carries that skip. Pure-Python conda builds are unchanged: patched when every replaced file is the release's, refused for a platform wheel's record on its own or a file that differs. Whether a copy with no `WHEEL` (an `.egg-info` install) is compiled is now read from the conda package's own file list, its record in the environment's `conda-meta`. The files of its top-level names were the only evidence before, which took a shared library another distribution put into a shared namespace package for its own, and missed one in a module the metadata does not name; with the answer now deciding between a skip and a write, both matter. That reading remains for a copy no record lists. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 5 +- .../src/commands/agent_download.rs | 11 +- crates/socket-patch-cli/src/commands/apply.rs | 473 ++++++++++++++++-- .../tests/apply/e2e_safety_advisories.rs | 468 ++++++++++++++--- crates/socket-patch-core/src/patch/apply.rs | 15 +- .../socket-patch-core/src/patch/conda_copy.rs | 353 ++++++++++++- docs/ecosystems.md | 46 +- docs/testing/pixi-compatibility.md | 5 +- 8 files changed, 1216 insertions(+), 160 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 241618164..cfa3adfed 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -282,7 +282,7 @@ Beyond the globals above, each subcommand defines a small set of local arguments | Subcommand | Local arg | Env var | Purpose | |---|---|---|---| | `apply` | `--force` / `-f` | — | Bypass beforeHash check. A file of the patch that is missing on disk is skipped instead of failing the package, and named in a `patch_files_skipped` warning | -| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found` or `no_matching_variant`, status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.``: `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | +| `apply` | `--check` | — | Read-only audit that every in-scope (`--ecosystems`) manifest patch is in place, for CI / GitHub-App auditing (v5.0: previously Go-only, which passed on any unpatched non-Go tree). Local Go patches: the committed `.socket/go-patches/` copies and `go.mod` `replace` directives match the manifest (`go_redirect_drift`). Every other patch: each installed copy hashes to the record's `afterHash` — the `vex` verifier over the `vex` copy lookup; the copies are narrowed by `apply`'s own rules: a release variant (a qualified purl such as `?artifact_id=` / `?platform=`) is judged only on the copies holding its distribution, matched against every variant of its base as `apply` matches them, and an installed copy that holds none of them is drift of the base purl (`no_matching_variant`, the copy `apply` fails with "no matching variant found"; a Gradle / Ivy cache dir is exempt, as in `apply`); for gem, once a bundle-store copy exists the `gem env` fallback-home copies are not judged (`apply` treats them as best-effort). Drift is a `failed` event per patch with `errorCode` `not_applied` (still unpatched), `hash_mismatch` (neither the original nor the patched bytes), `file_not_found` or `no_matching_variant`, status `partialFailure`, exit 1, and the human `Error: Patches are OUT OF SYNC:` report (printed even under `--silent`), which ends with the remedy ``Run `socket-patch apply ` to regenerate them.``: `` repeats the check's own `--cwd`, `--manifest-path`, `-g` / `--global-prefix` and `--ecosystems` (each shell-quoted when needed), so running it verbatim heals the tree that was checked (v5.0, #1219). In sync is exit 0: `Patches are in sync (N checked).` and, under `--json`, a `skipped` event per verified patch (`errorCode: already_patched`). A record of an ecosystem this CLI does not support is not checked and the line says so instead (`unsupported_ecosystem`); a key that is not a purl is drift (`invalid_purl`). A patch with no installed copy is skipped as `apply` skips it (`package_not_installed`; the human line adds `M not installed, skipped`). A copy `apply` skips as not supported yet (a compiled conda build of a Python package that does not hold the patch) is not drift either: a `Warning:` line per copy, a `skipped` event per record and copy (`errorCode: conda_build_not_pypi_release`), and `K not supported, skipped` on the human line for the records with no other copy (see "Agent-mode apply to a conda build"). Vendor-owned patches are excluded (`vendor --check` audits them). Lock-free, fetch-free, offline-safe; it never writes. An unreadable manifest is drift (`manifest_unreadable`, exit 1) | | `vendor` | `--force` / `-f` | — | Bypass the installed-variant probe for multi-release ecosystems. That is its only effect: vendoring commits the patch server's verified artifact and never reads the installed files' content, so a missing or mismatched installed file vendors the same with or without `--force` (no warning) | | `vendor` | `--revert` | `SOCKET_VENDOR_REVERT` | Undo vendoring: restore recorded original lockfile fragments + remove `.socket/vendor/` artifacts. Works without a manifest. A package vendored over a hosted pin returns to its upstream registry entry, never to hosted (see "Takeover reconciliation") | | `vendor` | `--check` | — | Offline, read-only artifact and wiring audit; exits 1 on drift. Conflicts with `--revert`. | @@ -1460,7 +1460,7 @@ socket-patch creates `.socket/` and everything under it itself and never writes - **Inline blobs in `get`**: a patch view's `blobContent` / `beforeBlobContent` must hash (git-sha256) to the `afterHash` / `beforeHash` it is stored under, or the patch fails with `content hash mismatch: content hashes to ` before anything is written, the same rule a downloaded blob is held to. An existing blob that already verifies is never rewritten; every blob is staged and renamed into place, never truncated in place. - **Ledgers**: the vendored ledger (`.socket/vendor/state.json`) and the pre-v5 hosted redirect ledger are refused when `.socket` itself, a directory below it or the ledger file is a link (`vendor_dir_symlink_unsupported` for the vendored flows), so a hosted run that still has to update a pre-v5 redirect ledger fails under a linked `.socket`. - **Agent-mode apply and rollback outside the install tree**: `apply` and `rollback` (dry run included) refuse a package whose written directories resolve outside the install tree they were found in: a Composer path repository (`vendor//` linked to first-party source), a `flit install --symlink` / editable-by-link package, or a package directory a package manager links into `site-packages` from its own prefix (Homebrew's Cellar, a Nix store path). The per-package error carries `outside the install tree`. For `apply` the remedy is to patch that source directly or install the package as a copy; for `rollback` it is to restore that source from version control, since socket-patch does not write into a tree it does not own. -- **Agent-mode apply to a conda build**: a PyPI patch is applied to a copy conda built (a copy in a conda prefix whose `INSTALLER` says `conda`, or that has none, or whose metadata cannot be found) only as the PyPI release it repackages. It is refused, with the per-package error starting `conda_build_not_pypi_release` and ending with the `socket-patch remove ` that drops the record, and nothing written, when the patch's `artifact_id` is a platform wheel (a `…-whl` that is not `…-none-any-whl`), when the copy holds compiled code (its `WHEEL` says `Root-Is-Purelib: false`, or, with no `WHEEL`, a shared library is named after one of its top-level modules or sits in one of its top-level packages), when the copy's metadata was not found and the patch does not name a pure-Python wheel, or when the patch replaces no existing file. A copy whose files all hold the patch already is not refused: nothing is written, and it is reported as already patched. For a conda build a replaced file that hashes to neither side of the patch is an error whatever was passed: `--force` and `--allow-patch-conflicts` act as the default policy (content an earlier Socket patch wrote still gives way), `--force` does not skip a missing file, and `--strict` is unchanged. `scan --mode agent` and `get` leave a patch out (warning `conda_build_not_pypi_release`, detail `: `, exit status unchanged) when every installed copy of its package refuses it by the rules that need no file hash; `--all-releases` keeps it. A release can have more than one record (the pure-Python wheel's beside a platform wheel's or the source distribution's). On each copy the records a conda build refuses by those rules are tried after the others, whatever order the manifest holds them in, and such a record is an error only when it is the first one tried on the copy: after another record of the release it is reported as already patched when its files hold the patch, and is otherwise not reported at all (neither as failed nor as `package_not_installed`), since the copy's outcome is the earlier record's. `scan` and `get` leave such a record out without the warning when they keep another record of that release. A copy pip or uv installed into a conda prefix is not a conda build. Files a patch does not replace are not compared. +- **Agent-mode apply to a conda build**: a PyPI patch is applied to a copy conda built (a copy in a conda prefix whose `INSTALLER` says `conda`, or that has none, or whose metadata cannot be found) only as the PyPI release it repackages. **A compiled conda build is not supported yet and is skipped.** A copy holds compiled code when its `WHEEL` says `Root-Is-Purelib: false`. With no `WHEEL` (an `.egg-info` install), it does when the conda package's record in the prefix's `conda-meta` lists a shared library among its files; when no record there lists the copy, when a shared library is named after one of its top-level modules or sits in one of its top-level packages. Nothing is written to such a copy whatever the record and whatever was passed (`--force` included), and the skip never fails a run: `apply` prints `Warning: : conda_build_not_pypi_release: …` once per copy, emits one `skipped` event per record of the release and copy (`errorCode: conda_build_not_pypi_release`; the reason names the copy), counts each such record as `N not supported` in the summary (when no other copy of the package has a result) and leaves the exit status as it is; `apply --check` does not count the copy as drift (the same warning and `skipped` events; `N not supported, skipped` for the records with no other copy; a record another copy verifies is `already_patched` with the reason `every installed copy that can be patched is patched`). The skip is the copy's, over every record of its release: a compiled copy whose files all hold some record's patch already is reported as already patched under that record, with no warning, checks in sync, and is judged for no other record of the release. Only the skip is exempt from failing: a record whose patch content cannot be staged (`--offline` with a missing blob) fails as for any package. A copy that holds no compiled code, or that nothing could be read about, is patched or refused. It is refused, with the per-package error starting `conda_build_not_pypi_release` and ending with the `socket-patch remove ` that drops the record, and nothing written, when the patch's `artifact_id` is a platform wheel (a `…-whl` that is not `…-none-any-whl`), when the copy's metadata was not found and the patch does not name a pure-Python wheel, or when the patch replaces no existing file. A copy whose files all hold the patch already is not refused, compiled or not: nothing is written, and it is reported as already patched. For a conda build a replaced file that hashes to neither side of the patch is an error whatever was passed: `--force` and `--allow-patch-conflicts` act as the default policy (content an earlier Socket patch wrote still gives way), `--force` does not skip a missing file, and `--strict` is unchanged. `scan --mode agent` and `get ` leave a patch out (warning `conda_build_not_pypi_release`, detail `: `, exit status unchanged) when every installed copy of its package is a compiled conda build or refuses it by the rules that need no file hash; `--all-releases` keeps it. `get ` names one patch, so it records it, and the apply it runs then skips or refuses the copy as above. Under `--json`, a `scan` / `get` whose apply skips a compiled copy of a record that run did not select carries that record's `skipped` event too, so the skip is never unsaid. A release can have more than one record (the pure-Python wheel's beside a platform wheel's or the source distribution's). On each copy the records a conda build refuses by those rules are tried after the others, whatever order the manifest holds them in, and such a record is an error only when it is the first one tried on the copy: after another record of the release it is reported as already patched when its files hold the patch, and is otherwise not reported at all (neither as failed nor as `package_not_installed`), since the copy's outcome is the earlier record's. `scan` and `get` leave such a record out without the warning when they keep another record of that release. A copy pip or uv installed into a conda prefix is not a conda build. Files a patch does not replace are not compared. Not covered: the agent-mode blob cache and manifest are checked from `.socket` down, so a `.socket` that is itself a link still redirects those writes (deciding that at lock time is deferred). @@ -2310,6 +2310,7 @@ command's integration tests check its output. | `package_not_installed` | `skipped` | apply: manifest entry has no matching installed package. When the project's lockfiles resolve the purl (a platform-gated optional dependency, a devDependency under `--omit=dev`), the detail says it is lockfile-only and the entry never fails the run, even when no other patch matched; only an all-miss run with an unmatched purl that no lock resolves exits 1 (`partialFailure`). **Cargo is never lockfile-only (v5.0, #616)**: `cargo fetch` unpacks every `Cargo.lock` entry (target-gated ones included), so a locked crate missing from `$CARGO_HOME/registry/src` was simply not fetched yet (a cold CI cache, a pruned `registry/src`) and the next `cargo build` would compile it unpatched; it counts as an unresolved purl (an all-miss run exits 1, as in 4.x) and its detail, the human error and the human warning say to run `cargo fetch` first. A crate `Cargo.lock` takes from a path, git, `[patch]` or `[replace]` source is never looked up in the registry cache (#506): cargo does not build that copy, so the same detail also names that case. | | `apply_failed` | `failed` | apply: hash mismatch, write error, archive read error. Also a manifest key that is not a purl (see `invalid_purl`). The copy is left as it was: every file is staged (its blob read and hash-checked, with the file's final mode and owner) before the first is renamed into place, and a rename that fails puts the files already replaced back. The `error` names the file (`Cannot apply patch: - `); a blob that does not hold its hash's bytes is named with the remedy (`blob is corrupt … Run \`socket-patch repair\``). Only when putting a file back fails too does the `error` end with the files left changed; the original of such a file is kept beside it as `.socket-kept--`, a name no later run removes. A run killed between two renames can still leave some files patched; the next `apply` finishes it. A killed run also leaves `.socket-stage--` / `.socket-orig--` files beside the patch's files (staged content and the second names of the files being replaced, never the package's own content); an `apply` or `rollback` of that package removes them once they are ten minutes old. | | `native_extension_not_rebuilt` | `failed` | apply (gem), and the apply that `get` / `scan --mode agent` run: the patch is incomplete. Its files were written into the installed copy and are left there (unlike `apply_failed`, where the copy is as it was), and the compiled code the copy runs is not the patch's: the build compiled nothing of it, or, on the JRuby build of a gem, the patch changes sources of the gem's jars and does not bring the jars. `error` says what was written and what is not in effect; `files` lists what this run wrote. The run exits 1 (`partialFailure`), the patch stays recorded, `apply --check` is out of sync and `vex` does not attest it; `rollback` restores the files. The same code is a `warnings[]` entry of the run, and the `apply --check` / `vex` tag of such a copy. See "A build that builds nothing of the patch". | +| `conda_build_not_pypi_release` | `skipped` (exit status unchanged; human: `Warning: …`), or the start of a `failed` error | apply, `apply --check`, and the apply that `get` / `scan --mode agent` run (PyPI): `skipped` when the installed copy is a compiled conda build, which is not supported yet: nothing is written and the run does not fail. The start of a `failed` event's error when a conda build without compiled code cannot take the record (a platform wheel's record, or nothing shows the copy is the pure-Python release). Also a top-level `warnings[]` code of `scan --mode agent` / `get` for a patch left out. See "Agent-mode apply to a conda build". | | `unsupported_ecosystem` | `skipped` + run-level `warnings[]`; remove: top-level error | apply (incl. `--check`), rollback, and the nested apply of `get` / `scan --mode agent` (additive): a manifest record whose purl type this CLI has no crawler for — an ecosystem a newer socket-patch recorded, or a known type in another case (`pkg:NPM/…`; the detail then names the lowercase spelling). The record is left alone, named in one `skipped` event each and in one warning (human: one `Warning:` line on stderr), and never changes the exit: a newer CLI's ecosystem in a committed manifest must not fail an older CLI's run (`scan --prune` exempts such records for the same reason). `apply --check` does not count it as checked: its result line reads `N checked patches are in sync; K patches not checked (unsupported ecosystem).` (or `No patches checked: …`) instead of `Patches are in sync`. `rollback` leaves it out of the confirmation prompt and keeps its record. `remove` refuses it before any mutation (exit 1, top-level `error.code`) unless `--skip-rollback` is given: it could not restore what the record patched. Not reported under `--ecosystems`, which scopes the run to ecosystems this CLI knows. | | `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:/` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. | | `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. | diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 1c63e84b9..360a069a4 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2065,12 +2065,19 @@ pub(crate) fn record_apply_outcome( } // The nested apply covers the whole manifest, so its other skips // (`already_patched`, `vendored`, ...) belong to packages this run did - // not select; only a user-patch conflict found after selection is news. + // not select. Two are news all the same: a user-patch conflict found + // after selection, and a copy left unpatched because it is not + // supported yet (a compiled conda build), which would otherwise go + // unsaid, the nested apply being silent under `--json`. for skip in &report.skipped { let Some(key) = skip.purl.as_deref() else { continue; }; - if skip.error_code.as_deref() != Some(super::user_patches::CONFLICT) + let news = matches!( + skip.error_code.as_deref(), + Some(super::user_patches::CONFLICT) | Some(CONDA_BUILD_NOT_PYPI_RELEASE) + ); + if !news || recorded.iter().any(|(purl, _)| apply_key_covers(key, purl)) || report .failures diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index ae643a7ff..1ec5ed77d 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -567,11 +567,42 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { } let mut in_sync: Vec = Vec::new(); let mut not_installed: Vec = Vec::new(); + // Records with a copy `apply` does not support patching yet (a + // compiled conda build that does not hold the patch): their `skipped` + // events, one per record and copy, and how many of the records have + // no other copy. + let mut not_supported: Vec = Vec::new(); + let mut skipped_copies: HashSet = HashSet::new(); + let mut skipped_events: HashSet<(String, String)> = HashSet::new(); + let mut only_skipped_copies = 0usize; if !tree.patches.is_empty() { - let outcome = verify_installed_tree(&args.common, &tree).await; + let (outcome, compiled_conda) = verify_installed_tree(&args.common, &tree).await; + // A copy `apply` skips as not supported yet (a compiled conda + // build) is not drift: a warning, once per copy, as `apply` gives + // it, and a `skipped` event per record under `--json`. + let mut warned = HashSet::new(); + for copy in &compiled_conda.skipped { + let warning = copy.warning(); + if warned.insert(warning) && !args.common.json && !args.common.silent { + eprintln!("Warning: {}", copy.warning()); + } + // One event per record and copy: the reason names the copy. + if skipped_events.insert((copy.purl.clone(), copy.detail.clone())) { + not_supported.push(copy.event()); + } + skipped_copies.insert(copy.purl.clone()); + } in_sync = outcome.applied; for failed in outcome.failed { match failed.reason.as_str() { + // A record whose every copy was skipped that way is not + // supported here, which is not the same as not installed. + "package_not_found" if skipped_copies.contains(&failed.purl) => { + only_skipped_copies += 1; + } + // Its copy holds a sibling record's patch, and `apply` + // reports the copy under that record alone. + "package_not_found" if compiled_conda.passed_over.contains(&failed.purl) => {} "package_not_found" => not_installed.push(failed.purl), // A zero-file record (`no_files`) is drift, not in sync: // nothing was hashed, and `apply` / `get` count such a @@ -605,7 +636,10 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { if drifts.is_empty() { if args.common.json { let mut env = Envelope::new(Command::Apply); - record_check_skips(&mut env, &in_sync, ¬_installed); + record_check_skips(&mut env, &in_sync, ¬_installed, &skipped_copies); + for event in not_supported { + env.record(event); + } for event in unchecked_events { env.record(event); } @@ -614,7 +648,12 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { } else if !args.common.silent { println!( "{}", - format_check_in_sync(checked, not_installed.len(), unchecked_events.len()) + format_check_in_sync( + checked, + not_installed.len(), + only_skipped_copies, + unchecked_events.len() + ) ); } 0 @@ -627,7 +666,10 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { .with_reason(code.clone(), detail.clone()), ); } - record_check_skips(&mut env, &in_sync, ¬_installed); + record_check_skips(&mut env, &in_sync, ¬_installed, &skipped_copies); + for event in not_supported { + env.record(event); + } for event in unchecked_events { env.record(event); } @@ -672,10 +714,15 @@ async fn run_check(args: &ApplyArgs, manifest_path: &Path) -> i32 { /// best-effort once the store copy is patched, and an unpatched store /// copy is drift on its own. Copies under a containment-refused /// `.bundle/config` `BUNDLE_PATH` root are kept: Bundler loads them. +/// * PyPI: a compiled conda build is judged as `apply` treats it, per copy +/// over every record of its release (see [`CompiledCondaCopies`]): a +/// copy that holds no record's patch is dropped — `apply` skips it as +/// not supported yet, so it is not drift — and one that holds some +/// record's patch is in sync for those records and judged for no other. async fn verify_installed_tree( common: &GlobalArgs, tree: &PatchManifest, -) -> socket_patch_core::vex::VerifyOutcome { +) -> (socket_patch_core::vex::VerifyOutcome, CompiledCondaCopies) { use socket_patch_core::crawlers::gradle_cache::expands; use socket_patch_core::patch::apply::select_installed_variants; use socket_patch_core::vex::FailedPatch; @@ -684,6 +731,7 @@ async fn verify_installed_tree( crate::ecosystem_dispatch::find_manifest_package_copies_reusing(&purls, common, true, None) .await; let mut copies = crate::commands::vex::vex_copy_sets(common, tree, &found).await; + let compiled_conda = settle_compiled_conda_copies(tree, &mut copies).await; // Gem copy classes, decided exactly as `apply` decides them. let (gem_stores, refused_root): (Vec, Option) = if !common.global @@ -744,6 +792,14 @@ async fn verify_installed_tree( let mut kept: HashMap<&str, Vec> = HashMap::new(); let mut stray: Vec = Vec::new(); for path in group_copies { + // A compiled conda build is settled already: in sync for the + // records whose patch it holds, and judged for no other. + if let Some(held) = compiled_conda.held.get(&(base.clone(), path.clone())) { + for key in keys.iter().filter(|key| held.contains(*key)) { + kept.entry(key.as_str()).or_default().push(path.clone()); + } + continue; + } let matched = select_installed_variants(&path, &variants).await; if matched.is_empty() { if !expands(&path) { @@ -806,7 +862,116 @@ async fn verify_installed_tree( purl, reason: "not_applied".to_string(), })); - outcome + (outcome, compiled_conda) +} + +/// How `apply --check` judges the compiled conda builds among a tree's +/// copies, which `apply` does not support patching yet. +#[derive(Default)] +struct CompiledCondaCopies { + /// The copies that hold no record's patch: `apply` skips them. One + /// entry per record of the copy's release, in purl order. + skipped: Vec, + /// The copies that already hold the patch of some record of their + /// release (an earlier release wrote it), by release (its base purl) + /// and copy, with those records' keys: `apply` reports them as + /// already patched. A copy's path is its site-packages directory, + /// which every other package of the environment shares, so the + /// release is part of the key. + held: HashMap<(String, PathBuf), Vec>, + /// The other records of such a copy's release. `apply` passes over + /// them on that copy without a report, so they are not drift there + /// and not "not installed" either. + passed_over: HashSet, +} + +/// Takes the compiled conda builds out of `copies` (the copies of each +/// PyPI record of `tree`), leaving one only under the records whose patch +/// it already holds, and says what became of each (see +/// [`CompiledCondaCopies`]). The decision is the copy's, over every record +/// of its release, as `apply` makes it. +async fn settle_compiled_conda_copies( + tree: &PatchManifest, + copies: &mut HashMap>, +) -> CompiledCondaCopies { + use socket_patch_core::patch::conda_copy::conda_build; + let mut settled = CompiledCondaCopies::default(); + let mut releases: BTreeMap> = BTreeMap::new(); + for purl in copies.keys() { + if Ecosystem::from_purl(purl) == Some(Ecosystem::Pypi) && tree.patches.contains_key(purl) { + releases + .entry(strip_purl_qualifiers(purl).to_string()) + .or_default() + .push(purl.clone()); + } + } + for (base, mut keys) in releases { + keys.sort(); + let mut spellings: Vec = keys + .iter() + .flat_map(|key| copies.get(key).cloned().unwrap_or_default()) + .collect(); + spellings.sort(); + spellings.dedup(); + // One install can be found under two spellings of its directory + // (conda's `lib/python3.1 -> python3.13`): it is one copy, as it is + // to `apply`. + let mut real_of: HashMap = HashMap::new(); + for spelling in &spellings { + let real = tokio::fs::canonicalize(spelling) + .await + .unwrap_or_else(|_| spelling.clone()); + real_of.insert(spelling.clone(), real); + } + let is_copy = + |spelling: &PathBuf, path: &PathBuf| real_of.get(spelling) == real_of.get(path); + for path in crate::ecosystem_dispatch::distinct_install_dirs(&spellings).await { + let reason = match conda_build(&base, &path).await { + Some(build) => build.unsupported(&path), + None => None, + }; + let Some(reason) = reason else { + continue; + }; + let mut held: Vec = Vec::new(); + for key in &keys { + let files = &tree.patches[key].files; + let mut holds_patch = !files.is_empty(); + for (file_name, file_info) in files { + if verify_file_patch(&path, file_name, file_info).await.status + != VerifyStatus::AlreadyPatched + { + holds_patch = false; + break; + } + } + if holds_patch { + held.push(key.clone()); + } + } + for key in &keys { + let keeps = held.contains(key); + if let Some(paths) = copies.get_mut(key) { + paths.retain(|spelling| !is_copy(spelling, &path)); + if keeps { + paths.push(path.clone()); + } + } + if held.is_empty() { + settled.skipped.push(UnsupportedCopy { + purl: key.clone(), + detail: reason.clone(), + }); + } else if !keeps { + settled.passed_over.insert(key.clone()); + } + } + if !held.is_empty() { + settled.held.insert((base.clone(), path), held); + } + } + } + settled } /// The `apply --check` drift text for a verifier routing tag. @@ -831,11 +996,22 @@ fn describe_check_failure(reason: &str) -> &'static str { /// The `skipped` events of an `apply --check --json` envelope: in-sync /// patches as `already_patched` (apply's own tag for them) and patches with /// no installed copy as `package_not_installed`. -fn record_check_skips(env: &mut Envelope, in_sync: &[String], not_installed: &[String]) { +fn record_check_skips( + env: &mut Envelope, + in_sync: &[String], + not_installed: &[String], + skipped_copies: &HashSet, +) { for purl in in_sync { + // A copy `apply` skips as not supported yet has its own event. + let detail = if skipped_copies.contains(purl) { + "every installed copy that can be patched is patched" + } else { + "every installed copy is patched" + }; env.record( PatchEvent::new(PatchAction::Skipped, purl.clone()) - .with_reason("already_patched", "every installed copy is patched"), + .with_reason("already_patched", detail), ); } for purl in not_installed { @@ -879,16 +1055,27 @@ fn check_remedy(common: &GlobalArgs, user_patched: bool) -> String { /// uninstalled tree never reads as a vacuous "in sync". With `unchecked` /// records of an ecosystem this CLI does not support, the line claims "in /// sync" only for the patches it did check. -fn format_check_in_sync(checked: usize, not_installed: usize, unchecked: usize) -> String { - let skipped = if not_installed == 0 { - String::new() - } else { - format!( +fn format_check_in_sync( + checked: usize, + not_installed: usize, + not_supported: usize, + unchecked: usize, +) -> String { + let mut skipped = String::new(); + if not_installed > 0 { + skipped.push_str(&format!( "; {} not installed, skipped", plural(not_installed, "patch", "patches") - ) - }; - let nothing_checked = checked == 0 && not_installed == 0; + )); + } + // Installed, and `apply` skips it too (a compiled conda build). + if not_supported > 0 { + skipped.push_str(&format!( + "; {} not supported, skipped", + plural(not_supported, "patch", "patches") + )); + } + let nothing_checked = checked == 0 && not_installed == 0 && not_supported == 0; if unchecked == 0 { return if nothing_checked { "No patches to check.".to_string() @@ -1517,6 +1704,7 @@ fn collect_apply_outcomes( ) -> (Vec, Vec) { let mut applied = Vec::new(); skipped.extend(caveats.not_in_build.iter().map(LeftCopy::event)); + skipped.extend(caveats.unsupported.iter().map(UnsupportedCopy::event)); for result in results { let event = caveats.event_of(result, dry_run); match event.action { @@ -1868,6 +2056,15 @@ pub(crate) async fn run_locked( eprintln!("Note: {}: {}", normalize_purl(&left.purl), left.detail); } } + // A copy skipped as not supported yet (a compiled conda + // build) stays unpatched: a warning, once per copy. + let mut warned = HashSet::new(); + for copy in &caveats.unsupported { + let warning = copy.warning(); + if warned.insert(warning.clone()) { + eprintln!("Warning: {warning}"); + } + } // A package's sidecar advisory (the PyPI `RECORD`, a gem // `--redownload`, `go mod verify`, a signed NuGet package, // a Gradle cache copy) is `sidecars[]` under `--json`; a @@ -2047,6 +2244,15 @@ pub(crate) async fn run_locked( for left in &caveats.not_in_build { env.record(left.event()); } + // Copies skipped as not supported yet (a compiled conda + // build): one Skipped event per record and copy, with the + // reason, which names the copy. + let mut recorded = HashSet::new(); + for copy in &caveats.unsupported { + if recorded.insert((copy.purl.as_str(), copy.detail.as_str())) { + env.record(copy.event()); + } + } // Best-effort gem-env fallback-home copies left unpatched: // one non-fatal Skipped event each, with the copy's path // and reason. Never a Failed event — the bundle-store copy @@ -2425,6 +2631,9 @@ struct ApplyTally { /// patch's ([`gem_ext::GemCaveat::Incomplete`]). The package is not /// patched, and is counted neither as applied nor as already patched. not_in_effect: usize, + /// Every copy was skipped because patching it is not supported yet (a + /// compiled conda build). The package is not patched. + unsupported: usize, } fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { @@ -2456,6 +2665,16 @@ fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { !by_purl.contains_key(purl) && !vendored.contains(purl) && !not_in_effect.contains(purl) }) .collect(); + // A skipped copy counts for its package only when no copy of the + // package says more. + let unsupported: std::collections::BTreeSet<&str> = caveats + .unsupported + .iter() + .map(|copy| copy.purl.as_str()) + .filter(|purl| { + !by_purl.contains_key(purl) && !vendored.contains(purl) && !not_in_effect.contains(purl) + }) + .collect(); let mut tally = ApplyTally { vendored: vendored .iter() @@ -2463,6 +2682,7 @@ fn tally_results(results: &[ApplyResult], caveats: &GemCaveats) -> ApplyTally { .count(), not_applicable: not_applicable.len(), not_in_effect: not_in_effect.len(), + unsupported: unsupported.len(), ..ApplyTally::default() }; for copies in by_purl.values() { @@ -2509,6 +2729,9 @@ fn format_summary_line(tally: &ApplyTally, targeted: usize, not_found: usize) -> if tally.not_in_effect > 0 { parts.push(format!("{} not in effect", tally.not_in_effect)); } + if tally.unsupported > 0 { + parts.push(format!("{} not supported", tally.unsupported)); + } if tally.failed > 0 { parts.push(format!("{} failed", tally.failed)); } @@ -2526,6 +2749,7 @@ fn format_compact_summary(tally: &ApplyTally, targeted: usize, not_found: usize) (tally.vendored, "vendored"), (tally.not_applicable, "not applicable"), (tally.not_in_effect, "not in effect"), + (tally.unsupported, "not supported"), (tally.failed, "failed"), (not_found, "not found on disk"), ] @@ -2572,6 +2796,12 @@ fn format_dry_run_summary(tally: &ApplyTally, not_found: usize) -> Vec { plural(tally.not_in_effect, "package", "packages") )); } + if tally.unsupported > 0 { + lines.push(format!( + " {} not supported", + plural(tally.unsupported, "package", "packages") + )); + } if tally.failed > 0 { lines.push(format!( " {} cannot be patched", @@ -2755,6 +2985,10 @@ struct GemCaveats { not_in_build: Vec, /// Copies whose patch is incomplete. They fail the run. incomplete: Vec, + /// Copies skipped because patching them is not supported yet: a + /// compiled conda build of a Python package (the one entry here that + /// is not a gem's). They have no result and do not fail the run. + unsupported: Vec, } impl GemCaveats { @@ -3233,6 +3467,9 @@ async fn apply_patches_inner( // is not gone over again under another of its manifest keys, // which would run its build a second time), and not applied. let mut any_copy_incomplete = false; + // A copy was skipped as not supported yet (a compiled conda + // build). The package was dealt with, and not applied. + let mut any_copy_unsupported = false; for (pkg_path, is_store_copy) in store_copies .into_iter() .map(|p| (p, true)) @@ -3276,15 +3513,18 @@ async fn apply_patches_inner( // its failure. The engine still sees each record, so one // whose files already hold the patch reads as already // patched, as it does on any other copy. - let conda_never_takes = - Box::pin(conda_refused_variants(&base_purl, pkg_path, &variants)).await; + // + // A compiled conda build is not supported yet: nothing is + // written to it, and the copy is skipped below with a + // warning instead of failing the run. + let conda = Box::pin(conda_copy_view(&base_purl, pkg_path, &variants)).await; let mut ordered_variants: Vec<&String> = variants.iter().collect(); - if !conda_never_takes.is_empty() { + if !conda.never_takes.is_empty() { // By purl within each half, so the run reads the same // whatever order the manifest's map yields. ordered_variants.sort_by(|a, b| { - (conda_never_takes.contains(*a), a.as_str()) - .cmp(&(conda_never_takes.contains(*b), b.as_str())) + (conda.never_takes.contains(*a), a.as_str()) + .cmp(&(conda.never_takes.contains(*b), b.as_str())) }); } @@ -3357,7 +3597,7 @@ async fn apply_patches_inner( // A record this conda build never takes, tried after // another record of the release on the same copy. - let conda_sibling = attempted && conda_never_takes.contains(variant_purl); + let conda_sibling = attempted && conda.never_takes.contains(variant_purl); attempted = true; // A gem patch to native-extension sources rebuilds the // extension (#1996). One it cannot build is refused @@ -3465,7 +3705,9 @@ async fn apply_patches_inner( // not this copy's distribution, and the copy's outcome // is the earlier record's. It did match the copy's // file, so it is not reported as not installed either. - if conda_sibling && is_conda_refusal(&result) { + // On a compiled conda build every record ends here, and + // the copy's outcome is its skip below. + if (conda_sibling || conda.unsupported.is_some()) && is_conda_refusal(&result) { matched_manifest_purls.insert(variant_purl.clone()); continue; } @@ -3535,6 +3777,23 @@ async fn apply_patches_inner( if is_store_copy { any_store_copy_applied = true; } + } else if let Some(reason) = &conda.unsupported { + // A compiled conda build that does not already hold the + // patch: not supported yet, so the copy is skipped. The + // skip accounts for every record of the release, whether + // or not the copy's files match it, and does not fail + // the run. (A record that failed on it for another + // reason was flagged above.) + for variant_purl in &variants { + if manifest.patches.contains_key(variant_purl) { + matched_manifest_purls.insert(variant_purl.clone()); + caveats.unsupported.push(UnsupportedCopy { + purl: variant_purl.clone(), + detail: reason.clone(), + }); + } + } + any_copy_unsupported = true; } else if best_effort { // Nothing applied on a best-effort fallback-home copy. // Attempted-but-failed variants already recorded their @@ -3575,7 +3834,7 @@ async fn apply_patches_inner( } } - if any_copy_applied || any_copy_incomplete { + if any_copy_applied || any_copy_incomplete || any_copy_unsupported { applied_base_purls.insert(base_purl.clone()); } } else { @@ -4432,25 +4691,65 @@ fn format_patch_failure(purl: &str, why: &str) -> String { format!("Error: Failed to patch {purl}: {why}") } -/// The records among `variants` that the copy of `base_purl` at `pkg_path` -/// never takes because conda built it (see -/// `socket_patch_core::patch::conda_copy`): a platform wheel's record -/// always, and every record when the build holds compiled code. Empty for -/// a copy that is not a conda build. -async fn conda_refused_variants( - base_purl: &str, - pkg_path: &Path, - variants: &[String], -) -> HashSet { +/// What the conda rule (`socket_patch_core::patch::conda_copy`) says +/// about one installed copy. Both fields are empty for a copy that is not +/// a conda build. +#[derive(Default)] +struct CondaCopyView { + /// The records the copy never takes: a platform wheel's always, and + /// every record when the build holds compiled code. + never_takes: HashSet, + /// Why the copy is skipped whatever the record: it is a compiled + /// conda build, which is not supported yet. + unsupported: Option, +} + +/// [`CondaCopyView`] of the copy of `base_purl` at `pkg_path`, for the +/// records `variants` of its release. +async fn conda_copy_view(base_purl: &str, pkg_path: &Path, variants: &[String]) -> CondaCopyView { use socket_patch_core::patch::conda_copy::{conda_build, static_refusal_for}; let Some(build) = conda_build(base_purl, pkg_path).await else { - return HashSet::new(); + return CondaCopyView::default(); }; - variants - .iter() - .filter(|variant| static_refusal_for(&build, variant, pkg_path).is_some()) - .cloned() - .collect() + CondaCopyView { + never_takes: variants + .iter() + .filter(|variant| static_refusal_for(&build, variant, pkg_path).is_some()) + .cloned() + .collect(), + unsupported: build.unsupported(pkg_path), + } +} + +/// One copy `apply` skipped because patching it is not supported yet: a +/// compiled conda build of a Python package. It is a `Skipped` event of +/// each record of its release, with the rule's code, and a warning. It is +/// never a failure, and never an apply result. +struct UnsupportedCopy { + /// The manifest key of the patch. + purl: String, + /// The reason, in words; it starts with the rule's code and names the + /// copy. + detail: String, +} + +impl UnsupportedCopy { + fn event(&self) -> PatchEvent { + PatchEvent::new(PatchAction::Skipped, self.purl.clone()).with_reason( + socket_patch_core::patch::conda_copy::REFUSAL_CODE, + self.detail.as_str(), + ) + } + + /// The warning of the copy: `: `, the same for + /// every record of the release. + fn warning(&self) -> String { + format!( + "{}: {}", + normalize_purl(strip_purl_qualifiers(&self.purl)), + self.detail + ) + } } /// Whether the engine refused `result`'s record because conda built the @@ -5078,6 +5377,7 @@ mod tests { vendored: 1, not_applicable: 0, not_in_effect: 0, + unsupported: 0, } ); assert_eq!( @@ -5378,6 +5678,83 @@ mod tests { assert!(!format_results_block(&[other], &caveats, false, Path::new("/p")).is_empty()); } + /// A copy skipped as not supported yet (a compiled conda build) counts + /// for its package once, under its own heading, and only when no other + /// copy of the package has a result. It is a `skipped` event with the + /// rule's code, and one warning per copy however many records the + /// release has. + #[test] + fn a_copy_skipped_as_not_supported_has_its_own_bucket_event_and_warning() { + let code = socket_patch_core::patch::conda_copy::REFUSAL_CODE; + let detail = format!("{code}: conda built the copy in /env with compiled code"); + let pure = "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl"; + let platform = "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let skipped = |purl: &str| UnsupportedCopy { + purl: purl.to_string(), + detail: detail.clone(), + }; + let caveats = GemCaveats { + unsupported: vec![skipped(pure), skipped(platform)], + ..GemCaveats::default() + }; + + let t = tally_results(&[], &caveats); + assert_eq!( + t, + ApplyTally { + unsupported: 2, + ..ApplyTally::default() + } + ); + assert_eq!( + format_summary_line(&t, 2, 0), + "Summary: 0 of 2 targeted patches applied, 0 already patched, 2 not supported, \ + 0 not found on disk" + ); + assert_eq!( + format_compact_summary(&t, 2, 0), + "Applied 0 of 2 patches: 2 not supported." + ); + + // Another copy of the package (a venv's) that took the patch says + // more than the skip. + let applied = ApplyResult { + package_key: platform.to_string(), + package_path: "/venv/site-packages".to_string(), + success: true, + files_verified: Vec::new(), + files_patched: vec!["PIL/TarIO.py".to_string()], + applied_via: HashMap::new(), + error: None, + sidecar: None, + }; + let t = tally_results(&[applied], &caveats); + assert_eq!((t.applied, t.unsupported), (1, 1)); + + let event = serde_json::to_value(caveats.unsupported[0].event()).unwrap(); + assert_eq!(event["action"], "skipped"); + assert_eq!(event["errorCode"], code); + assert_eq!( + caveats.unsupported[0].warning(), + caveats.unsupported[1].warning() + ); + assert!(caveats.unsupported[0] + .warning() + .starts_with(&format!("pkg:pypi/pillow@12.3.0: {code}: "))); + + // `apply --check` names it apart from a package that is not + // installed. + assert_eq!( + format_check_in_sync(1, 1, 2, 0), + "Patches are in sync (1 patch checked; 1 patch not installed, skipped; \ + 2 patches not supported, skipped)." + ); + assert_eq!( + format_check_in_sync(0, 0, 1, 0), + "Patches are in sync (0 patches checked; 1 patch not supported, skipped)." + ); + } + #[test] fn dry_run_summary_lists_every_nonzero_bucket() { let t = ApplyTally { @@ -5388,6 +5765,7 @@ mod tests { vendored: 0, not_applicable: 1, not_in_effect: 2, + unsupported: 1, }; assert_eq!( format_dry_run_summary(&t, 3), @@ -5397,6 +5775,7 @@ mod tests { " 2 packages already patched", " 1 package not applicable", " 2 packages would not take effect", + " 1 package not supported", " 1 package cannot be patched", " 3 packages not found on disk", ] @@ -5509,33 +5888,33 @@ mod tests { #[test] fn check_in_sync_line() { - assert_eq!(format_check_in_sync(0, 0, 0), "No patches to check."); + assert_eq!(format_check_in_sync(0, 0, 0, 0), "No patches to check."); assert_eq!( - format_check_in_sync(1, 0, 0), + format_check_in_sync(1, 0, 0, 0), "Patches are in sync (1 patch checked)." ); assert_eq!( - format_check_in_sync(3, 0, 0), + format_check_in_sync(3, 0, 0, 0), "Patches are in sync (3 patches checked)." ); // A check that skipped uninstalled packages says so, never a bare // vacuous "in sync". assert_eq!( - format_check_in_sync(0, 2, 0), + format_check_in_sync(0, 2, 0, 0), "Patches are in sync (0 patches checked; 2 patches not installed, skipped)." ); // Records of an unsupported ecosystem were not checked: "in sync" // is claimed only for the ones that were. assert_eq!( - format_check_in_sync(0, 0, 3), + format_check_in_sync(0, 0, 0, 3), "No patches checked: 3 patches not checked (unsupported ecosystem)." ); assert_eq!( - format_check_in_sync(1, 0, 1), + format_check_in_sync(1, 0, 0, 1), "1 checked patch is in sync; 1 patch not checked (unsupported ecosystem)." ); assert_eq!( - format_check_in_sync(2, 1, 2), + format_check_in_sync(2, 1, 0, 2), "2 checked patches are in sync; 1 patch not installed, skipped; 2 patches not \ checked (unsupported ecosystem)." ); diff --git a/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs b/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs index 3414e561e..da6b72f5d 100644 --- a/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs +++ b/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs @@ -513,65 +513,130 @@ fn apply_in(cwd: &Path, extra: &[&str]) -> (i32, String, String) { run_with_env(cwd, &args, &[]) } +const CONDA_NOT_SUPPORTED: &str = "compiled conda packages are not supported yet"; + +/// What a run that skipped a compiled conda build says: a warning with +/// the rule's code, and no failure of any kind. +fn assert_skipped_as_not_supported(stderr: &str, at: &str) { + assert!( + stderr.contains(&format!("Warning: pkg:pypi/pillow@12.3.0: {CONDA_REFUSAL}")) + && stderr.contains(CONDA_NOT_SUPPORTED), + "{at}\nstderr:\n{stderr}" + ); + assert_eq!( + stderr.matches(CONDA_REFUSAL).count(), + 1, + "one warning for the copy: {at}\nstderr:\n{stderr}" + ); + assert!( + !stderr.contains("Error:") + && !stderr.contains("no matching installed package") + && !stderr.contains("socket-patch remove"), + "{at}\nstderr:\n{stderr}" + ); +} + /// A compiled conda package is built separately from the PyPI wheel and /// links conda's own libraries. Its Python files are often the wheel's -/// byte for byte, as here, and that is not enough: a patch made from the -/// wheel is not applied to it, with or without `--force`. +/// byte for byte, as here, and that is not enough: compiled conda +/// packages are not supported yet. The copy is skipped with a warning, +/// nothing is written to it, and the run does not fail, with or without +/// `--force`, for a platform wheel's record or a pure-Python wheel's. #[test] -fn a_compiled_conda_build_takes_no_pypi_patch_even_when_the_file_matches() { +fn a_compiled_conda_build_is_skipped_even_when_the_file_matches() { let release = b"# PIL/TarIO.py as PyPI ships it\n"; - for flags in [&[][..], &["--force"][..], &["--allow-patch-conflicts"][..]] { - let tmp = tempfile::tempdir().expect("tempdir"); - let target = stage_conda_copy( - tmp.path(), - &CondaCopy { - name: "pillow", - version: "12.3.0", - purl: "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl", - installer: Some("conda"), - purelib: false, - file: "PIL/TarIO.py", - installed: release, - release, - }, - ); - let (code, stdout, stderr) = apply_in(tmp.path(), flags); - assert_eq!(code, 1, "{flags:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); - assert_eq!(std::fs::read(&target).unwrap(), release, "{flags:?}"); - assert!( - stderr.contains(CONDA_REFUSAL) && stderr.contains("compiled conda package"), - "{flags:?}\nstderr:\n{stderr}" - ); + for purl in [ + "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl", + "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl", + "pkg:pypi/pillow@12.3.0", + ] { + for flags in [ + &[][..], + &["--force"][..], + &["--allow-patch-conflicts"][..], + &["--dry-run"][..], + ] { + let tmp = tempfile::tempdir().expect("tempdir"); + let target = stage_conda_copy( + tmp.path(), + &CondaCopy { + name: "pillow", + version: "12.3.0", + purl, + installer: Some("conda"), + purelib: false, + file: "PIL/TarIO.py", + installed: release, + release, + }, + ); + let at = format!("{purl} {flags:?}"); + let (code, stdout, stderr) = apply_in(tmp.path(), flags); + assert_eq!(code, 0, "{at}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&target).unwrap(), release, "{at}"); + assert_skipped_as_not_supported(&stderr, &at); + assert!(stderr.contains("Root-Is-Purelib: false"), "{at}\n{stderr}"); + assert!( + stdout.contains("not supported") && !stdout.contains("1 not found on disk"), + "{at}\nstdout:\n{stdout}" + ); + } } } -/// The same copy with a patch made from a pure-Python wheel: the copy's -/// own metadata says it holds compiled code, so it is still not the -/// release the patch was made for. +/// The usual compiled conda build is not the wheel file for file either +/// (a recipe patches a source, the wheel's extension modules are not +/// there). It is skipped the same way, not failed as a copy that matches +/// no release, and `apply --check` agrees: a copy `apply` skips is not +/// drift. Under `--json` each record is a `skipped` event with the code. #[test] -fn a_conda_build_that_says_it_is_compiled_takes_no_pure_python_patch() { - let release = b"# PIL/TarIO.py as PyPI ships it\n"; +fn a_compiled_conda_build_that_differs_from_the_wheel_is_skipped_and_checks_clean() { let tmp = tempfile::tempdir().expect("tempdir"); + let conda_build = b"# PIL/TarIO.py as the conda recipe patched it\n"; + let purl = "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; let target = stage_conda_copy( tmp.path(), &CondaCopy { name: "pillow", version: "12.3.0", - purl: "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl", + purl, installer: Some("conda"), purelib: false, file: "PIL/TarIO.py", - installed: release, - release, + installed: conda_build, + release: b"# PIL/TarIO.py as PyPI ships it\n", }, ); - let (code, stdout, stderr) = apply_in(tmp.path(), &[]); - assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); - assert_eq!(std::fs::read(&target).unwrap(), release); - assert!( - stderr.contains(CONDA_REFUSAL) && stderr.contains("Root-Is-Purelib: false"), - "stderr:\n{stderr}" + add_sibling_record( + tmp.path(), + purl, + "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl", ); + + for flags in [&[][..], &["--force"][..], &["--check"][..]] { + let (code, stdout, stderr) = apply_in(tmp.path(), flags); + let at = format!("{flags:?}"); + assert_eq!(code, 0, "{at}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&target).unwrap(), conda_build, "{at}"); + assert_skipped_as_not_supported(&stderr, &at); + assert!( + stdout.contains("2 not supported") || stdout.contains("2 patches not supported"), + "{at}\nstdout:\n{stdout}" + ); + } + + for flags in [&["--json"][..], &["--check", "--json"][..]] { + let (code, stdout, stderr) = apply_in(tmp.path(), flags); + assert_eq!(code, 0, "{flags:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + let envelope: serde_json::Value = serde_json::from_str(&stdout).expect("JSON envelope"); + assert_eq!(envelope["status"], "success", "{flags:?}\n{stdout}"); + let events = envelope["events"].as_array().expect("events"); + assert_eq!(events.len(), 2, "{flags:?}\n{stdout}"); + for event in events { + assert_eq!(event["action"], "skipped", "{flags:?}\n{stdout}"); + assert_eq!(event["errorCode"], CONDA_REFUSAL, "{flags:?}\n{stdout}"); + } + } } /// A pure-Python conda build whose file is not the release's (a recipe @@ -829,8 +894,7 @@ fn a_platform_wheel_record_beside_the_pure_one_does_not_fail_a_pure_python_conda /// A copy that fails is reported once, with its own cause. A pure-Python /// conda build whose file is not the release's fails under the pure /// wheel's record, for that file; the platform wheel's record is not -/// refused on top of it. A compiled conda build, which takes neither -/// record, is refused once. +/// refused on top of it. #[test] fn a_conda_build_two_records_fail_on_is_reported_once() { let release = b"# the PyPI release's file\n"; @@ -855,19 +919,22 @@ fn a_conda_build_two_records_fail_on_is_reported_once() { "stderr:\n{stderr}" ); - for flags in [&[][..], &["--force"][..]] { - let tmp = tempfile::tempdir().expect("tempdir"); - let target = stage_conda_copy(tmp.path(), &sibling_records_copy(false, release, release)); - add_sibling_record(tmp.path(), SIBLING_PURE, SIBLING_PLATFORM); - let (code, stdout, stderr) = apply_in(tmp.path(), flags); - assert_eq!(code, 1, "{flags:?}\nstdout:\n{stdout}\nstderr:\n{stderr}"); - assert_eq!(std::fs::read(&target).unwrap(), release, "{flags:?}"); - assert_eq!(failures(&stderr), 1, "{flags:?}\nstderr:\n{stderr}"); - assert!( - stderr.contains(CONDA_REFUSAL) && !stderr.contains("no matching installed package"), - "{flags:?}\nstderr:\n{stderr}" - ); - } + // The platform wheel's record alone, on the same pure-Python build: + // refused, with how to drop the record. + let tmp = tempfile::tempdir().expect("tempdir"); + let mut alone = sibling_records_copy(true, release, release); + alone.purl = SIBLING_PLATFORM; + stage_conda_copy(tmp.path(), &alone); + let (code, stdout, stderr) = apply_in(tmp.path(), &[]); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(failures(&stderr), 1, "stderr:\n{stderr}"); + assert!( + stderr.contains(CONDA_REFUSAL) + && stderr.contains( + "`socket-patch remove pkg:pypi/charset-normalizer@3.4.4` drops its record" + ), + "stderr:\n{stderr}" + ); } /// `--strict` fails on any file that is not the patch's original. The @@ -901,11 +968,285 @@ fn strict_stays_strict_on_a_conda_build() { assert_eq!(std::fs::read(&target).unwrap(), earlier_patch); } +/// A compiled conda build an earlier release patched, in a release with +/// two records: it holds the pure wheel's patch, and the platform wheel's +/// record also replaces a file the copy holds unpatched. `apply` reports +/// the copy as already patched under the record it holds and passes over +/// the other, and `apply --check` agrees: the copy is judged as a whole, +/// not once per record, so it is in sync. +#[test] +fn a_compiled_conda_build_holding_one_records_patch_is_in_sync() { + let tmp = tempfile::tempdir().expect("tempdir"); + let pure = "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl"; + let platform = "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let target = stage_conda_copy( + tmp.path(), + &CondaCopy { + name: "pillow", + version: "12.3.0", + purl: pure, + installer: Some("conda"), + purelib: false, + file: "PIL/TarIO.py", + installed: CONDA_PATCHED, + release: b"# PIL/TarIO.py as PyPI ships it\n", + }, + ); + add_sibling_record(tmp.path(), pure, platform); + let second = b"# PIL/TiffImagePlugin.py as PyPI ships it\n"; + let second_path = target.parent().unwrap().join("TiffImagePlugin.py"); + std::fs::write(&second_path, second).unwrap(); + let manifest_path = tmp.path().join(".socket").join("manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); + manifest["patches"][platform]["files"]["PIL/TiffImagePlugin.py"] = serde_json::json!({ + "beforeHash": git_sha256(second), + "afterHash": git_sha256(CONDA_PATCHED), + }); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + let (code, stdout, stderr) = apply_in(tmp.path(), &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains(&format!("{pure} (already patched)")), + "stdout:\n{stdout}" + ); + assert!(!stderr.contains(CONDA_REFUSAL), "stderr:\n{stderr}"); + assert_eq!(std::fs::read(&second_path).unwrap(), second); + + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains("Patches are in sync (1 patch checked)."), + "stdout:\n{stdout}" + ); + assert!( + !stderr.contains("OUT OF SYNC") && !stderr.contains(CONDA_REFUSAL), + "stderr:\n{stderr}" + ); +} + +/// A copy's path is its site-packages directory, which every package of +/// the environment shares. A compiled conda build that already holds its +/// patch is in sync, and that says nothing about another package beside +/// it: an unpatched wheel pip installed there is still out of sync, not +/// "not installed". +#[test] +fn a_compiled_conda_build_holding_its_patch_does_not_hide_another_packages_drift() { + let tmp = tempfile::tempdir().expect("tempdir"); + let target = stage_conda_copy( + tmp.path(), + &CondaCopy { + name: "pillow", + version: "12.3.0", + purl: "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl", + installer: Some("conda"), + purelib: false, + file: "PIL/TarIO.py", + installed: CONDA_PATCHED, + release: b"# PIL/TarIO.py as PyPI ships it\n", + }, + ); + // certifi, as pip installed it, in the same site-packages: unpatched. + let site_packages = target.parent().unwrap().parent().unwrap(); + let dist_info = site_packages.join("certifi-2026.7.22.dist-info"); + std::fs::create_dir_all(&dist_info).unwrap(); + std::fs::write( + dist_info.join("METADATA"), + "Metadata-Version: 2.4\nName: certifi\nVersion: 2026.7.22\n", + ) + .unwrap(); + std::fs::write(dist_info.join("INSTALLER"), "pip\n").unwrap(); + std::fs::write( + dist_info.join("WHEEL"), + "Wheel-Version: 1.0\nRoot-Is-Purelib: true\n", + ) + .unwrap(); + let certifi_release = b"# certifi/core.py as PyPI ships it\n"; + std::fs::create_dir_all(site_packages.join("certifi")).unwrap(); + std::fs::write( + site_packages.join("certifi").join("core.py"), + certifi_release, + ) + .unwrap(); + let certifi = "pkg:pypi/certifi@2026.7.22?artifact_id=py3-none-any-whl"; + let manifest_path = tmp.path().join(".socket").join("manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); + manifest["patches"][certifi] = serde_json::json!({ + "uuid": "20000001-0000-4001-8001-000000000091", + "exportedAt": "2026-01-01T00:00:00Z", + "files": { "certifi/core.py": { + "beforeHash": git_sha256(certifi_release), + "afterHash": git_sha256(CONDA_PATCHED), + } }, + "vulnerabilities": {}, + "description": "t", + "license": "MIT", + "tier": "free", + }); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stderr.contains(&format!("{certifi}: patch not applied")) && !stderr.contains("pillow"), + "stderr:\n{stderr}" + ); + assert!(!stdout.contains("not installed"), "stdout:\n{stdout}"); + + // `apply` patches certifi and leaves pillow as it is; then all is in sync. + let (code, stdout, stderr) = apply_in(tmp.path(), &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains("Patches are in sync (2 patches checked)."), + "stdout:\n{stdout}" + ); +} + +/// conda's Python ships `lib/python3.1 -> python3.13`, so an +/// environment's site-packages is found under two spellings. It is one +/// copy: `apply` and `apply --check` each skip a compiled conda build in +/// it once, with one warning. +#[cfg(unix)] +#[test] +fn a_compiled_conda_build_under_two_spellings_of_its_directory_is_skipped_once() { + let release = b"# PIL/TarIO.py as PyPI ships it\n"; + let tmp = tempfile::tempdir().expect("tempdir"); + let target = stage_conda_copy( + tmp.path(), + &CondaCopy { + name: "pillow", + version: "12.3.0", + purl: "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl", + installer: Some("conda"), + purelib: false, + file: "PIL/TarIO.py", + installed: release, + release, + }, + ); + let lib = tmp + .path() + .join(".pixi") + .join("envs") + .join("default") + .join("lib"); + std::os::unix::fs::symlink("python3.13", lib.join("python3.1")).unwrap(); + + for flags in [&[][..], &["--check"][..]] { + let (code, stdout, stderr) = apply_in(tmp.path(), flags); + let at = format!("{flags:?}"); + assert_eq!(code, 0, "{at}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&target).unwrap(), release, "{at}"); + assert_skipped_as_not_supported(&stderr, &at); + } +} + +/// Copies `from` to `to`, files and directories. +fn copy_tree(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } +} + +/// A project with the package in two environments: conda's compiled +/// build in one, the PyPI wheel pip installed in the other. `apply` +/// patches the wheel, skips the conda build with its warning, and +/// succeeds. `apply --check` is then in sync, and under `--json` says both +/// things: the record is patched wherever it can be, and one copy was +/// skipped. +#[test] +fn a_compiled_conda_build_beside_a_pip_installed_wheel_is_skipped_and_the_wheel_patched() { + let release = b"# PIL/TarIO.py as PyPI ships it\n"; + let tmp = tempfile::tempdir().expect("tempdir"); + let purl = "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let conda_copy = stage_conda_copy( + tmp.path(), + &CondaCopy { + name: "pillow", + version: "12.3.0", + purl, + installer: Some("conda"), + purelib: false, + file: "PIL/TarIO.py", + installed: release, + release, + }, + ); + let envs = tmp.path().join(".pixi").join("envs"); + copy_tree(&envs.join("default"), &envs.join("wheels")); + let in_wheels = |path: &Path| { + envs.join("wheels") + .join(path.strip_prefix(envs.join("default")).unwrap()) + }; + let site_packages = conda_copy.parent().unwrap().parent().unwrap(); + std::fs::write( + in_wheels( + &site_packages + .join("pillow-12.3.0.dist-info") + .join("INSTALLER"), + ), + "pip\n", + ) + .unwrap(); + let wheel_copy = in_wheels(&conda_copy); + + let (code, stdout, stderr) = apply_in(tmp.path(), &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&wheel_copy).unwrap(), CONDA_PATCHED); + assert_eq!(std::fs::read(&conda_copy).unwrap(), release); + assert_skipped_as_not_supported(&stderr, "apply"); + assert!( + stdout.contains("1 of 1 targeted patch applied") && !stdout.contains("not supported"), + "the wheel's copy says more than the skip:\n{stdout}" + ); + + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!( + stdout.contains("Patches are in sync (1 patch checked)."), + "stdout:\n{stdout}" + ); + assert_skipped_as_not_supported(&stderr, "apply --check"); + + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check", "--json"]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let envelope: serde_json::Value = serde_json::from_str(&stdout).expect("JSON envelope"); + assert_eq!(envelope["status"], "success", "{stdout}"); + let events = envelope["events"].as_array().expect("events"); + let codes: Vec<&str> = events + .iter() + .map(|event| event["errorCode"].as_str().unwrap_or_default()) + .collect(); + assert_eq!(codes, ["already_patched", CONDA_REFUSAL], "{stdout}"); + assert_eq!( + events[0]["reason"], "every installed copy that can be patched is patched", + "{stdout}" + ); +} + /// An earlier release patched compiled conda builds whose Python file /// matched. Such a copy already holds the patch: nothing is written to it, -/// so there is nothing to refuse, and `apply` reports it as what it is, -/// patched. The same record on an unpatched copy is refused, and the -/// refusal says how to drop the record. +/// so there is nothing to skip, and `apply` reports it as what it is, +/// patched. #[test] fn a_compiled_conda_build_that_already_holds_the_patch_is_reported_as_patched() { let copy = |installed: &'static [u8]| CondaCopy { @@ -926,14 +1267,11 @@ fn a_compiled_conda_build_that_already_holds_the_patch_is_reported_as_patched() assert!(!stderr.contains(CONDA_REFUSAL), "stderr:\n{stderr}"); assert_eq!(std::fs::read(&target).unwrap(), CONDA_PATCHED); - let tmp = tempfile::tempdir().expect("tempdir"); - stage_conda_copy(tmp.path(), ©(b"# PIL/TarIO.py as PyPI ships it\n")); - let (code, _stdout, stderr) = apply_in(tmp.path(), &[]); - assert_eq!(code, 1, "stderr:\n{stderr}"); - assert!( - stderr.contains("`socket-patch remove pkg:pypi/pillow@12.3.0` drops its record"), - "stderr:\n{stderr}" - ); + // `apply --check` agrees: the copy is in sync. + let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("1 patch checked"), "stdout:\n{stdout}"); + assert!(!stderr.contains(CONDA_REFUSAL), "stderr:\n{stderr}"); } // ───────────────────────────────────────────────────────────────────── diff --git a/crates/socket-patch-core/src/patch/apply.rs b/crates/socket-patch-core/src/patch/apply.rs index 7ac3df7d9..6a0a66836 100644 --- a/crates/socket-patch-core/src/patch/apply.rs +++ b/crates/socket-patch-core/src/patch/apply.rs @@ -1656,10 +1656,17 @@ async fn apply_package_patch_at( // patched, which is what its files are. if let Some(refused) = refused { if !every_file_already_patched(pkg_path, files).await { - result.error = Some(format!( - "{refused}; `socket-patch remove {}` drops its record", - crate::utils::purl::strip_purl_qualifiers(package_key) - )); + // A compiled build is one a command skips, with this + // text as its warning. Any other refusal fails the + // copy on every run, so it says how to drop the record. + result.error = Some(if build.unsupported(pkg_path).is_some() { + refused + } else { + format!( + "{refused}; `socket-patch remove {}` drops its record", + crate::utils::purl::strip_purl_qualifiers(package_key) + ) + }); return result; } } diff --git a/crates/socket-patch-core/src/patch/conda_copy.rs b/crates/socket-patch-core/src/patch/conda_copy.rs index 1f79c5cdd..21b5cb917 100644 --- a/crates/socket-patch-core/src/patch/conda_copy.rs +++ b/crates/socket-patch-core/src/patch/conda_copy.rs @@ -18,7 +18,9 @@ //! //! - the patch is not for a platform wheel, and the copy holds no compiled //! code: its `WHEEL` metadata says so, or, for an install without one, -//! no extension module is among its files. A compiled conda package is +//! the conda package's record in `conda-meta` lists no shared library +//! among its files (with no such record, no extension module is among +//! the files of its top-level modules). A compiled conda package is //! never the PyPI wheel, whatever its Python files hash to; //! - every file the patch replaces has the release's bytes (or the bytes a //! Socket patch wrote), and the patch replaces at least one file, so @@ -28,6 +30,11 @@ //! to overwriting local changes to the distribution a patch was made for, //! not to writing one distribution's files into another. //! +//! A compiled conda package is not supported yet. The engine writes +//! nothing to one, and the commands treat it as skipped, not as failed +//! (see [`CondaBuild::unsupported`]): `scan` and `get` leave its patch +//! out, and `apply` passes over the copy, each with a warning. +//! //! What is not compared: the files the patch leaves alone. Their hashes in //! the PyPI release are not in a patch record, so a conda recipe that //! changes another module of an otherwise identical build is not seen. @@ -64,6 +71,25 @@ pub struct CondaBuild { evidence: &'static str, } +impl CondaBuild { + /// Why no patch is applied to this build in `site_packages`, whatever + /// the patch: it holds compiled code, and a compiled conda package is + /// not supported yet. `None` for a build that is, or may be, pure + /// Python. A command reports this as a skip of the copy, with a + /// warning, and never as a failure. + pub fn unsupported(&self, site_packages: &Path) -> Option { + (self.compiled == Some(true)).then(|| { + format!( + "{REFUSAL_CODE}: conda built the copy in {} with compiled code ({}), and \ + compiled conda packages are not supported yet, so it was skipped and is not \ + patched", + site_packages.display(), + self.evidence + ) + }) + } +} + /// The conda build behind the installed copy of `purl` in `site_packages`, /// or `None` when the copy is not one: not a PyPI package, not in a conda /// prefix, or installed by pip or uv (its `INSTALLER` names something @@ -75,7 +101,7 @@ pub async fn conda_build(purl: &str, site_packages: &Path) -> Option if Ecosystem::from_purl(purl) != Some(Ecosystem::Pypi) { return None; } - conda_prefix_of(site_packages)?; + let prefix = conda_prefix_of(site_packages)?; let unknown = Some(CondaBuild { compiled: None, evidence: "its metadata was not found", @@ -102,13 +128,93 @@ pub async fn conda_build(purl: &str, site_packages: &Path) -> Option compiled: Some(!purelib), evidence: "its WHEEL metadata says Root-Is-Purelib: false", }, - None => CondaBuild { - compiled: Some(holds_extension_modules(site_packages, &metadata, &name).await), - evidence: "it holds extension modules", + // No `WHEEL` (an `.egg-info` install). The conda package's own + // file list says what it ships; without one, the files beside the + // metadata are looked at. + None => match conda_record_ships_shared_library(prefix, &metadata).await { + Some(ships) => CondaBuild { + compiled: Some(ships), + evidence: "its conda package ships shared libraries", + }, + None => CondaBuild { + compiled: Some(holds_extension_modules(site_packages, &metadata, &name).await), + evidence: "it holds extension modules", + }, }, }) } +/// Whether the conda package that owns `metadata` (a copy's `.dist-info` +/// or `.egg-info`, a directory or a file) ships a shared library, read +/// from the package's record in `prefix`'s `conda-meta`. conda, mamba and +/// pixi write one record per package they link, with the list of its +/// files, so this says which files are the package's own: a shared +/// library in a namespace package another distribution also installs into +/// is not, and one in a top-level module the metadata does not name is. +/// `None` when no record lists the copy's metadata, or none could be read. +async fn conda_record_ships_shared_library(prefix: &Path, metadata: &Path) -> Option { + // Records list real paths from the prefix. A site-packages reached + // through a link (conda's `lib/python3.1 -> python3.13`) is the same + // directory, so both ends are resolved first. + let real_prefix = tokio::fs::canonicalize(prefix) + .await + .unwrap_or_else(|_| prefix.to_path_buf()); + let real_metadata = tokio::fs::canonicalize(metadata) + .await + .unwrap_or_else(|_| metadata.to_path_buf()); + // conda writes the paths `/`-separated on every platform; a record + // written with the platform's separator (`\`, escaped in JSON) is + // read the same way. + let owned: String = real_metadata + .strip_prefix(&real_prefix) + .ok()? + .components() + .map(|part| part.as_os_str().to_string_lossy()) + .collect::>() + .join("/"); + if owned.is_empty() { + return None; + } + let below = format!("{owned}/"); + let owned_escaped = owned.replace('/', "\\\\"); + for entry in list_dir_entries(&prefix.join("conda-meta")).await { + if !entry.file_name().to_string_lossy().ends_with(".json") { + continue; + } + let Ok(text) = read_regular_to_string(&entry.path()).await else { + continue; + }; + // Most records are another package's: skip them without parsing. + if !text.contains(owned.as_str()) && !text.contains(owned_escaped.as_str()) { + continue; + } + let Ok(record) = serde_json::from_str::(&text) else { + continue; + }; + let files: Vec = record + .get("files") + .and_then(|files| files.as_array()) + .map(|files| { + files + .iter() + .filter_map(|file| file.as_str()) + .map(|file| file.replace('\\', "/")) + .collect() + }) + .unwrap_or_default(); + if files + .iter() + .any(|file| *file == owned || file.starts_with(&below)) + { + return Some(files.iter().any(|file| { + let name = file.rsplit('/').next().unwrap_or(file); + is_shared_library(name) || is_versioned_shared_library(name) + })); + } + } + None +} + /// [`static_refusal_for`] the copy of `purl` in `site_packages`; `None` /// when that copy is not a conda build. pub async fn static_refusal(purl: &str, site_packages: &Path) -> Option { @@ -117,28 +223,28 @@ pub async fn static_refusal(purl: &str, site_packages: &Path) -> Option } /// Why the patch `purl` names is not applied to the conda build `build` -/// in `site_packages`, judged without the patch's files: the patch is for -/// a platform wheel, or the copy holds compiled code, or nothing shows +/// in `site_packages`, judged without the patch's files: the copy holds +/// compiled code ([`CondaBuild::unsupported`]), or the patch is for a +/// platform wheel, or nothing shows /// what the copy holds and the patch does not name a pure-Python wheel. /// `None` when nothing rules the patch out yet (see [`refusal_for`] for /// the file rule). pub fn static_refusal_for(build: &CondaBuild, purl: &str, site_packages: &Path) -> Option { + // A compiled build takes no record, so its reason does not depend on + // which one is asked about. + if let Some(unsupported) = build.unsupported(site_packages) { + return Some(unsupported); + } let where_ = site_packages.display(); let variant = Variant::of(purl); if let Variant::PlatformWheel(wheel) = variant { return Some(format!( "{REFUSAL_CODE}: conda built the copy in {where_}, and this patch is for the \ - platform wheel `{wheel}`: a compiled conda package is built separately from \ - the PyPI wheel, so the patch was not applied to it" + platform wheel `{wheel}`, which a conda build never is, so the patch was not \ + applied to it" )); } match build.compiled { - Some(true) => Some(format!( - "{REFUSAL_CODE}: conda built the copy in {where_} with compiled code ({}), \ - which is not the pure-Python PyPI release the patch was made for, so the \ - patch was not applied to it", - build.evidence - )), // A patch made from a pure-Python wheel says the release is pure // Python; a source distribution's, or a record that names no // artifact, does not, so the copy itself has to show it. @@ -219,7 +325,8 @@ fn root_is_purelib(wheel: &str) -> Option { }) } -/// Whether a distribution with no `WHEEL` metadata holds an extension +/// Whether a distribution with no `WHEEL` metadata, and no conda record +/// that lists its files, holds an extension /// module: a shared library named after one of its top-level modules /// (`_cffi_backend.cpython-313-darwin.so`), or anywhere in one of its /// top-level packages. The top-level names are the metadata's @@ -254,6 +361,17 @@ async fn holds_extension_modules(site_packages: &Path, metadata: &Path, name: &s false } +/// `libfoo.so.1`, `libfoo.so.1.2.3`: a shared library with its version +/// after the extension. +fn is_versioned_shared_library(file_name: &str) -> bool { + file_name.rsplit_once(".so.").is_some_and(|(_, version)| { + !version.is_empty() + && version + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())) + }) +} + fn is_shared_library(file_name: &str) -> bool { [".so", ".pyd", ".dylib"] .iter() @@ -419,28 +537,215 @@ mod tests { } } - /// A compiled conda package is never the PyPI wheel: refused for a - /// platform wheel's patch, and for any other record when the copy - /// itself says it holds compiled code. + /// A compiled conda package is never the PyPI wheel, and is not + /// supported yet: it takes no record, a platform wheel's or any + /// other, and the reason is the copy's, the same for each. #[tokio::test] async fn a_compiled_conda_build_takes_no_pypi_patch() { let tmp = tempfile::tempdir().unwrap(); let site = conda_site(tmp.path()); dist_info(&site, "pillow", "12.3.0", Some("conda"), Some(false)); - let refused = static_refusal(PLATFORM, &site).await.expect("refused"); + let build = conda_build(PLATFORM, &site).await.expect("a conda build"); + let unsupported = build.unsupported(&site).expect("not supported"); assert!( - refused.starts_with(REFUSAL_CODE) && refused.contains("cp313-cp313-manylinux"), - "{refused}" + unsupported.starts_with(REFUSAL_CODE) + && unsupported.contains("Root-Is-Purelib: false") + && unsupported.contains("compiled conda packages are not supported yet"), + "{unsupported}" ); for purl in [ + PLATFORM, "pkg:pypi/pillow@12.3.0?artifact_id=py3-none-any-whl", "pkg:pypi/pillow@12.3.0?artifact_id=tar-gz", "pkg:pypi/pillow@12.3.0", // The names match however the purl or the directory spells them. "pkg:pypi/Pillow@12.3.0?artifact_id=py3-none-any-whl", ] { - let refused = static_refusal(purl, &site).await.expect(purl); - assert!(refused.contains("Root-Is-Purelib: false"), "{refused}"); + assert_eq!( + static_refusal(purl, &site).await.as_deref(), + Some(unsupported.as_str()), + "{purl}" + ); + } + } + + /// A pure-Python conda build is supported. A platform wheel's record + /// is still not its distribution, and the refusal names the wheel. + #[tokio::test] + async fn a_pure_python_conda_build_is_supported_and_takes_no_platform_wheel_record() { + let tmp = tempfile::tempdir().unwrap(); + let site = conda_site(tmp.path()); + dist_info(&site, "certifi", "2026.7.22", Some("conda"), Some(true)); + let build = conda_build(PURE, &site).await.expect("a conda build"); + assert_eq!(build.unsupported(&site), None); + let platform = + "pkg:pypi/certifi@2026.7.22?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let refused = static_refusal(platform, &site).await.expect("refused"); + assert!( + refused.starts_with(REFUSAL_CODE) + && refused.contains("cp313-cp313-manylinux") + && !refused.contains("not supported yet"), + "{refused}" + ); + } + + /// The `conda-meta` record of a conda package: its files, as paths + /// from the prefix. + fn conda_record(prefix: &Path, name: &str, files: &[&str]) { + std::fs::write( + prefix.join("conda-meta").join(format!("{name}.json")), + serde_json::json!({ "name": name, "files": files }).to_string(), + ) + .unwrap(); + } + + /// An install with no `WHEEL` is judged by the conda package's own + /// file list when the prefix has one: a shared library another + /// distribution put into a shared namespace package is not this + /// package's, and one in a module the metadata does not name is. + #[tokio::test] + async fn an_egg_info_conda_build_is_judged_by_its_conda_record() { + let tmp = tempfile::tempdir().unwrap(); + let site = conda_site(tmp.path()); + let sp = "lib/python3.13/site-packages"; + + // Pure Python, in a namespace package (`google`) that also holds + // another distribution's extension module. + egg_info(&site, "googleapis-common-protos", "1.70.0", "google\n"); + std::fs::create_dir_all(site.join("google").join("api")).unwrap(); + std::fs::create_dir_all(site.join("google").join("_upb")).unwrap(); + std::fs::write(site.join("google").join("api").join("annotations.py"), "").unwrap(); + std::fs::write( + site.join("google").join("_upb").join("_message.abi3.so"), + "", + ) + .unwrap(); + let protos = "pkg:pypi/googleapis-common-protos@1.70.0"; + // With no record the files of its top-level names are all there + // is to go by, and they hold a shared library. + assert_eq!(compiled(protos, &site).await, Some(Some(true))); + conda_record( + tmp.path(), + "googleapis-common-protos-1.70.0-pyhd8ed1ab_0", + &[ + &format!("{sp}/google/api/annotations.py"), + &format!("{sp}/googleapis-common-protos-1.70.0-py3.13.egg-info/PKG-INFO"), + ], + ); + // Another package's record, which lists the extension module. + conda_record( + tmp.path(), + "protobuf-6.31.1-py313h_0", + &[ + &format!("{sp}/google/_upb/_message.abi3.so"), + &format!("{sp}/protobuf-6.31.1.dist-info/METADATA"), + ], + ); + assert_eq!(compiled(protos, &site).await, Some(Some(false))); + assert_eq!(static_refusal(protos, &site).await, None); + + // Compiled, with no `top_level.txt` and an import name that is not + // the distribution's: only the record says the library is its own. + let flat = site.join("PyYAML-6.0.2-py3.13.egg-info"); + std::fs::write( + &flat, + "Metadata-Version: 1.1\nName: PyYAML\nVersion: 6.0.2\n", + ) + .unwrap(); + std::fs::create_dir_all(site.join("yaml")).unwrap(); + std::fs::write(site.join("yaml").join("__init__.py"), "").unwrap(); + std::fs::write(site.join("_yaml.cpython-313-darwin.so"), "").unwrap(); + let yaml = "pkg:pypi/pyyaml@6.0.2"; + assert_eq!(compiled(yaml, &site).await, Some(Some(false))); + conda_record( + tmp.path(), + "pyyaml-6.0.2-py313h_0", + &[ + &format!("{sp}/PyYAML-6.0.2-py3.13.egg-info"), + &format!("{sp}/_yaml.cpython-313-darwin.so"), + &format!("{sp}/yaml/__init__.py"), + ], + ); + assert_eq!(compiled(yaml, &site).await, Some(Some(true))); + let unsupported = static_refusal(yaml, &site).await.expect("not supported"); + assert!( + unsupported.contains("its conda package ships shared libraries") + && unsupported.contains("not supported yet"), + "{unsupported}" + ); + + // A record written with the platform's separator reads the same. + egg_info(&site, "six", "1.17.0", "six\n"); + std::fs::write(site.join("six.py"), "").unwrap(); + std::fs::write(site.join("six.cpython-313-darwin.so"), "").unwrap(); + assert_eq!( + compiled("pkg:pypi/six@1.17.0", &site).await, + Some(Some(true)) + ); + conda_record( + tmp.path(), + "six-1.17.0-pyhd8ed1ab_0", + &[ + "lib\\python3.13\\site-packages\\six-1.17.0-py3.13.egg-info\\PKG-INFO", + "lib\\python3.13\\site-packages\\six.py", + ], + ); + assert_eq!( + compiled("pkg:pypi/six@1.17.0", &site).await, + Some(Some(false)) + ); + + // A file whose name only contains `.so.` is not a library. + egg_info(&site, "docopt", "0.6.2", "docopt\n"); + std::fs::write(site.join("docopt.py"), "").unwrap(); + conda_record( + tmp.path(), + "docopt-0.6.2-pyhd8ed1ab_2", + &[ + &format!("{sp}/docopt-0.6.2-py3.13.egg-info/PKG-INFO"), + "share/doc/docopt/libfoo.so.1.md", + "share/doc/docopt/notes.so.txt", + ], + ); + assert_eq!( + compiled("pkg:pypi/docopt@0.6.2", &site).await, + Some(Some(false)) + ); + + // A versioned library counts; an unreadable record is passed over. + egg_info(&site, "munkres", "1.1.4", "munkres\n"); + std::fs::write(site.join("munkres.py"), "").unwrap(); + std::fs::write( + tmp.path().join("conda-meta").join("broken.json"), + "{ munkres", + ) + .unwrap(); + conda_record( + tmp.path(), + "munkres-1.1.4-py313_0", + &[ + &format!("{sp}/munkres-1.1.4-py3.13.egg-info/PKG-INFO"), + "lib/libmunkres.so.1", + ], + ); + assert_eq!( + compiled("pkg:pypi/munkres@1.1.4", &site).await, + Some(Some(true)) + ); + + // conda's Python ships `lib/python3.1 -> python3.13`: the same + // site-packages under another spelling reads the same records. + #[cfg(unix)] + { + std::os::unix::fs::symlink("python3.13", tmp.path().join("lib").join("python3.1")) + .unwrap(); + let alias = tmp + .path() + .join("lib") + .join("python3.1") + .join("site-packages"); + assert_eq!(compiled(protos, &alias).await, Some(Some(false))); + assert_eq!(compiled(yaml, &alias).await, Some(Some(true))); } } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2c11dd3cf..60c7f85bf 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -16,7 +16,7 @@ The backticked slug in each row is the value `-e`/`--ecosystems` accepts (e.g. |-----------|------------------------|------------------------------|--------------------------| | npm (`npm`) — pnpm / yarn / berry / bun / vlt | ✅ any install layout, vlt's `node_modules/.vlt` store included (every store copy, copy-on-write) | ✅ seven lockfile flavors: package-lock, yarn classic, yarn berry (node-modules linker; PnP refused), pnpm v9, pnpm legacy v5.4/v6.0 (`pnpm 7/8` — frozen installs are path-bound because those majors absolutize `file:` override specifiers; moved checkouts run one `pnpm install --offline --no-frozen-lockfile`, surfaced as `vendor_pnpm_legacy_absolute_specifier`), bun text `bun.lock` lockfileVersion 0/1/2/3 and native binary `bun.lockb` revisions 1/2/3 (binary locks stay binary; text workspace vendoring requires lockfileVersion 2 — see [Bun compatibility](testing/bun-compatibility.md)), vlt `vlt-lock.json` lockfileVersion 0/1 (patched package directories for direct dependencies of the root or a workspace member; transitive targets refused — see [vlt notes](#npm-vlt-notes)). Rush monorepos on pnpm 9 and newer are wired through `pnpm-config.json` and each directly-depending project's `package.json` — see [Rush notes](#npm-rush-monorepos) | ✅ package-lock / npm-shrinkwrap, pnpm-lock.yaml and legacy shrinkwrap.yaml (pnpm majors 1–12; block and flow resolutions), yarn classic, yarn berry, bun, vlt (`vlt-lock.json` without `lockfileVersion`, 0 or 1) — pnpm, berry, bun and vlt carry constraints, see [npm hosted-mode notes](#npm-hosted-mode-notes) and [vlt notes](#npm-vlt-notes) | | PyPI (`pypi`) — uv / poetry / pdm / pipenv / pip | ✅ in place | ✅ uv project/script locks, PEP 751 `pylock.toml` / `pylock..toml`, poetry, pdm, pipenv (Pipenv 2018 or later — every `Pipfile.lock` category is rewired, lock-only checkouts included; Pipenv 2023+ does not hash-check local wheels — `vendor_integrity_unverified`; Pipenv 2023.7.9+ exports the vendored wheel without a hash, so `pipenv requirements --hash` output fails pip's hash-checking mode — `pypi_pipenv_hash_export_unsupported`; a venv still holding the upstream release is reported as `pypi_pipenv_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)), and requirements.txt. Native uv vendoring requires uv ≥ 0.2.35 (the `[[package]]` lock grammar); hosted mode covers native `uv.lock` from uv 0.1.45 (the first release whose `uv lock` writes one) and requirements from uv 0.0.5; see [uv compatibility](testing/uv-compatibility.md). | ✅ requirements.txt including hash continuations, uv project/script locks, and PEP 751 locks. Version/source ambiguity is refused; see [uv compatibility](testing/uv-compatibility.md). Poetry 1.x and 2.x locks are supported; Poetry 0.x ignores URL sources and is refused. See [Poetry compatibility](testing/poetry-compatibility.md). Pipenv `Pipfile.lock` (pipfile-spec 6 — Pipenv 7 and later; `path` references for 7–11, `file` from 2018; lock-only checkouts and Pipenv's out-of-tree venv are discovered; a warm venv that Pipenv will not reinstall over warns `redirect_pypi_stale_install`; see [Pipenv compatibility](testing/pipenv-compatibility.md)). `pdm.lock` is supported for the lock formats PDM 0.12–1.4 and 2.8.1+ write (`lock_version` 2 / 4.3–4.5.1); the identity-losing 3.1 / 4.0–4.2 formats (PDM 1.8–2.7) are refused. PDM 2.8.0 writes an indistinguishable `4.3` lock but shares that identity-loss bug, so a rewritten 2.8.0 lock crashes `pdm sync` — upgrade to ≥ 2.8.1. See [PDM compatibility](testing/pdm-compatibility.md). | -| pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs` — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | +| pixi (`pypi`) — the Python packages of a pixi project, from conda channels or PyPI | ✅ in place, in every environment under `.pixi/envs`: PyPI wheels and pure-Python conda packages (compiled conda packages are not supported yet and are skipped) — see [PyPI: pixi projects](#pypi-pixi-projects) | ❌ refused (`pypi_no_requirements` / `pypi_pyproject_only`, which name agent mode) | ❌ nothing rewritten (`redirect_pypi_pixi_project` names agent mode) | | Cargo (`cargo`) | ✅ in-place + `.cargo-checksum.json` rewrite (shared registry-cache caveat — see [Cargo: shared registry cache](#cargo-shared-registry-cache)) | ✅ `[patch.crates-io]` path entry in the root `Cargo.toml` (v5; per-version Socket keys; pre-v5 `.cargo/config*` wiring migrates on re-run) | ✅ per-patch sparse registry (`[registries.socket-patch-]` + Cargo.lock source/checksum); needs cargo 1.68+ (sparse registries) — a project whose `rust-version` or `rust-toolchain[.toml]` declares an older cargo is refused (`redirect_cargo_old_cargo`), use `--mode vendored`; direct dependencies only — a crate another dependency also pulls in is refused, use `--mode vendored`; a crate the user overrides with `[patch]` (path, git or another registry) is refused too, the override is left alone; a `cargo vendor` or `cargo local-registry` project (crates.io replaced by an on-disk source in the project's, a parent directory's or `$CARGO_HOME`'s `.cargo/config*`) is refused, use agent mode; with no `Cargo.lock` the graph is unknown, so only a project whose sole dependency is the patched crate is redirected | | RubyGems (`gem`) | ✅ in place | ✅ Gemfile + Gemfile.lock path pair (a CRLF `Gemfile.lock`, as a `core.autocrlf` checkout leaves it, is edited and reverted in its own line ending, and a lock mixing CRLF and LF fails closed; a gem locked as precompiled platform gems is vendored from prebuilt patched platform gems, see [Ruby gems: native extensions](#ruby-gems-native-extensions); `Gemfile` spelling only — a `gems.rb` twin, which bundler ≥ 2 loads instead, or a `BUNDLE_GEMFILE`-configured manifest makes vendoring refuse with `gemfile_not_loaded` before any write) | ✅ a `source:` option on the gem's own declaration, the lock converged to match (see [Ruby gems: hosted mode](#ruby-gems-hosted-mode)) — edits `gems.rb` + `gems.locked` or `Gemfile` + `Gemfile.lock`, whichever the project holds (a `Gemfile` + `gems.rb` twin is refused with `redirect_gem_twin_manifest_ambiguous`: bundler 1.x loads the `Gemfile`, bundler ≥ 2 loads `gems.rb`, and nothing in the project says which bundler installs it; bundler 4's `BUNDLE_LOCKFILE` (environment, app config or global config) naming any other lock is refused with `redirect_gem_bundle_lockfile_unsupported`, as is vendoring with `gemfile_not_loaded`; spellings that diverge beyond Socket's own edits fail closed with `redirect_gem_gemfile_spellings_diverge`; `BUNDLE_GEMFILE` from `.bundle/config` (which outranks the environment, as in bundler), the environment, or the global `~/.bundle/config` / `$BUNDLE_USER_CONFIG` (lowest, as in bundler) is followed when it names the project's `Gemfile` / `gems.rb`, and any other configured manifest is refused with `redirect_gem_bundle_gemfile_unsupported`); a Bundler all-source, exact-source or hostname mirror in app config or the scan environment can capture the patch registry, so the redirect is refused with `redirect_gem_mirror_overrides_source` without printing mirror URLs (scope mirrors to `mirror.https://rubygems.org`; user-global config and mirrors set only in a later install environment are not inspected); the `CHECKSUMS` pin needs bundler ≥ 2.6 (an older lock is still pinned by source and installs frozen; the run says once, with `redirect_gem_no_checksums_section`, that it cannot record the checksums); a stale pre-redirect materialization that `bundle install` would reuse instead of refetching is replaced with the verified patched gem when it is the project's own, else flagged `redirect_gem_stale_install` with the remedy (see "Ruby gems: gems already installed" below and CLI_CONTRACT.md's "Gem stale-install guard") | | Go (`golang`) | ✅ `go.mod` `replace` → `.socket/go-patches/` — see [Go: directory replaces and go.sum](#go-directory-replaces-and-gosum) | ✅ `replace` → the committed vendor tree | ✅ (free tier) fork-style `replace` → `patch.socket.dev/gopatch/` + committed `go.sum` pin; see [Go notes](#go-directory-replaces-and-gosum). Paid hosted patches are unsupported; `redirect_golang_unsupported` names the vendored remedy | @@ -1003,23 +1003,41 @@ pixi install && socket-patch apply copy conda built (its `INSTALLER` says `conda`, or it has none) takes that patch only when all of this holds, and no flag changes it, `--force` and `--allow-patch-conflicts` included: - - the patch is not for a platform wheel, and the copy holds no compiled code: its - `WHEEL` says `Root-Is-Purelib: true`, or, for an install without one - (`.egg-info`), no extension module is among its files. A compiled conda package - is built separately from the PyPI wheel and links conda's own libraries, so it is - never that release, even when the Python file a patch touches is identical; + - the copy holds no compiled code: its `WHEEL` says `Root-Is-Purelib: true`, or, + for an install without one (`.egg-info`), the conda package's own file list + (its record in the environment's `conda-meta`) holds no shared library. When no + record there lists the copy, the files of its top-level modules are looked at + instead, and a shared library among them counts as its own; + - the patch is not for a platform wheel; - every file the patch replaces has the release's bytes, and the patch replaces at least one file. A file that differs (a recipe that changes the source) is never overwritten, and nothing of the copy is changed. - `scan --mode agent` leaves such a patch out, with the warning - `conda_build_not_pypi_release`, when no installed copy can take it because it is a - compiled conda build; nothing is recorded and the run exits 0. A patch already in - the manifest that a copy cannot take makes `apply` fail for that copy with the same - code (the error names `socket-patch remove`, which drops the record), or with `no - matching variant found` when a replaced file differs. A copy that already holds the - patch, as one an earlier release patched does, has nothing written to it and is - reported as already patched. A release with a platform wheel beside its +- **Compiled conda packages are not supported yet, and are skipped.** A compiled + conda package (`pillow`, `numpy`, `brotli-python`) is built separately from the + PyPI wheel and links conda's own libraries, so it is never that release, even + when the Python file a patch touches is identical. Nothing is written to one, and + it never fails a run: + - `scan --mode agent` and `get ` leave its patch out when every installed + copy of the package is one, with the warning `conda_build_not_pypi_release`; + nothing is recorded and the exit status is unchanged. A package that also has a + copy pip or uv installed keeps its patch, for that copy. (`get ` names one + patch, so it records it; its apply then skips the copy.) + - `apply` skips the copy when its patch is in the manifest already (recorded on + another machine, or for another copy of the package): a `Warning:` line with the + same code, `N not supported` in the summary, a `skipped` event under `--json`, + and the exit status unchanged. `apply --check` does not report the copy as out + of sync. + - The package stays unpatched in that environment, so `vex` does not attest it + as patched there. + + A pure-Python conda build that cannot take a patch already in the manifest still + makes `apply` fail for that copy: with `conda_build_not_pypi_release` for a + platform wheel's record on its own (the error names `socket-patch remove`, which + drops the record), or with `no matching variant found` when a replaced file + differs. A copy that already holds the patch, as one an earlier release patched + does, has nothing written to it and is reported as already patched, compiled or + not. A release with a platform wheel beside its pure-Python one has a record for each: on a pure-Python conda build the pure wheel's record patches the copy, and the platform wheel's is not an error there (it reads as already patched, as its file is). A copy that fails is reported diff --git a/docs/testing/pixi-compatibility.md b/docs/testing/pixi-compatibility.md index 799847297..f5747231e 100644 --- a/docs/testing/pixi-compatibility.md +++ b/docs/testing/pixi-compatibility.md @@ -66,8 +66,9 @@ and no Socket token. POSIX only. - **Conda builds that are not the PyPI release.** A conda build takes a patch only as the pure-Python PyPI release it repackages (see [PyPI: pixi projects](../ecosystems.md#pypi-pixi-projects)). The backtest patches a - pure-Python package; the refusals (a compiled build, a replaced file that differs, - `--force`) are covered without pixi by `patch::conda_copy`'s unit tests, the + pure-Python package; the skip of a compiled build (not supported yet) and the + refusals (a replaced file that differs, a platform wheel's record, `--force`) are + covered without pixi by `patch::conda_copy`'s unit tests, the `apply` suite (`e2e_safety_advisories`) and the `scan` suite (`scan_sync_e2e`). - **conda packages that are not Python distributions** (OpenSSL, libxml2, the `ca-certificates` bundle) are outside what socket-patch patches. From a28184640017714368d5a03dc4afa8dba822ea92 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Fri, 20 Nov 2026 11:05:25 -0500 Subject: [PATCH 2/2] Say each skipped conda copy in nested runs; settle a held copy once Two Bugbot findings on the compiled-conda skip: - The outcomes a nested apply hands to `scan` and `get` dropped the skip of a compiled conda copy when another copy of the same record was patched, and kept one skip per record however many environments hold a copy. A `--json` run then read as fully applied, or named one of several unpatched copies. Each skipped copy now has its event, beside the applied copy's, as `apply --json` reports it. - A compiled conda copy that already holds one record's patch left a sibling record its files do not match reported as not installed, while `apply --check` passes over it. The copy now accounts for every record of its release in `apply` too. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/agent_download.rs | 51 ++++++++++++++++--- crates/socket-patch-cli/src/commands/apply.rs | 48 ++++++++++++++++- crates/socket-patch-cli/src/commands/get.rs | 41 +++++++++++++++ .../tests/apply/e2e_safety_advisories.rs | 18 ++++++- 5 files changed, 148 insertions(+), 12 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index cfa3adfed..314eeb372 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1460,7 +1460,7 @@ socket-patch creates `.socket/` and everything under it itself and never writes - **Inline blobs in `get`**: a patch view's `blobContent` / `beforeBlobContent` must hash (git-sha256) to the `afterHash` / `beforeHash` it is stored under, or the patch fails with `content hash mismatch: content hashes to ` before anything is written, the same rule a downloaded blob is held to. An existing blob that already verifies is never rewritten; every blob is staged and renamed into place, never truncated in place. - **Ledgers**: the vendored ledger (`.socket/vendor/state.json`) and the pre-v5 hosted redirect ledger are refused when `.socket` itself, a directory below it or the ledger file is a link (`vendor_dir_symlink_unsupported` for the vendored flows), so a hosted run that still has to update a pre-v5 redirect ledger fails under a linked `.socket`. - **Agent-mode apply and rollback outside the install tree**: `apply` and `rollback` (dry run included) refuse a package whose written directories resolve outside the install tree they were found in: a Composer path repository (`vendor//` linked to first-party source), a `flit install --symlink` / editable-by-link package, or a package directory a package manager links into `site-packages` from its own prefix (Homebrew's Cellar, a Nix store path). The per-package error carries `outside the install tree`. For `apply` the remedy is to patch that source directly or install the package as a copy; for `rollback` it is to restore that source from version control, since socket-patch does not write into a tree it does not own. -- **Agent-mode apply to a conda build**: a PyPI patch is applied to a copy conda built (a copy in a conda prefix whose `INSTALLER` says `conda`, or that has none, or whose metadata cannot be found) only as the PyPI release it repackages. **A compiled conda build is not supported yet and is skipped.** A copy holds compiled code when its `WHEEL` says `Root-Is-Purelib: false`. With no `WHEEL` (an `.egg-info` install), it does when the conda package's record in the prefix's `conda-meta` lists a shared library among its files; when no record there lists the copy, when a shared library is named after one of its top-level modules or sits in one of its top-level packages. Nothing is written to such a copy whatever the record and whatever was passed (`--force` included), and the skip never fails a run: `apply` prints `Warning: : conda_build_not_pypi_release: …` once per copy, emits one `skipped` event per record of the release and copy (`errorCode: conda_build_not_pypi_release`; the reason names the copy), counts each such record as `N not supported` in the summary (when no other copy of the package has a result) and leaves the exit status as it is; `apply --check` does not count the copy as drift (the same warning and `skipped` events; `N not supported, skipped` for the records with no other copy; a record another copy verifies is `already_patched` with the reason `every installed copy that can be patched is patched`). The skip is the copy's, over every record of its release: a compiled copy whose files all hold some record's patch already is reported as already patched under that record, with no warning, checks in sync, and is judged for no other record of the release. Only the skip is exempt from failing: a record whose patch content cannot be staged (`--offline` with a missing blob) fails as for any package. A copy that holds no compiled code, or that nothing could be read about, is patched or refused. It is refused, with the per-package error starting `conda_build_not_pypi_release` and ending with the `socket-patch remove ` that drops the record, and nothing written, when the patch's `artifact_id` is a platform wheel (a `…-whl` that is not `…-none-any-whl`), when the copy's metadata was not found and the patch does not name a pure-Python wheel, or when the patch replaces no existing file. A copy whose files all hold the patch already is not refused, compiled or not: nothing is written, and it is reported as already patched. For a conda build a replaced file that hashes to neither side of the patch is an error whatever was passed: `--force` and `--allow-patch-conflicts` act as the default policy (content an earlier Socket patch wrote still gives way), `--force` does not skip a missing file, and `--strict` is unchanged. `scan --mode agent` and `get ` leave a patch out (warning `conda_build_not_pypi_release`, detail `: `, exit status unchanged) when every installed copy of its package is a compiled conda build or refuses it by the rules that need no file hash; `--all-releases` keeps it. `get ` names one patch, so it records it, and the apply it runs then skips or refuses the copy as above. Under `--json`, a `scan` / `get` whose apply skips a compiled copy of a record that run did not select carries that record's `skipped` event too, so the skip is never unsaid. A release can have more than one record (the pure-Python wheel's beside a platform wheel's or the source distribution's). On each copy the records a conda build refuses by those rules are tried after the others, whatever order the manifest holds them in, and such a record is an error only when it is the first one tried on the copy: after another record of the release it is reported as already patched when its files hold the patch, and is otherwise not reported at all (neither as failed nor as `package_not_installed`), since the copy's outcome is the earlier record's. `scan` and `get` leave such a record out without the warning when they keep another record of that release. A copy pip or uv installed into a conda prefix is not a conda build. Files a patch does not replace are not compared. +- **Agent-mode apply to a conda build**: a PyPI patch is applied to a copy conda built (a copy in a conda prefix whose `INSTALLER` says `conda`, or that has none, or whose metadata cannot be found) only as the PyPI release it repackages. **A compiled conda build is not supported yet and is skipped.** A copy holds compiled code when its `WHEEL` says `Root-Is-Purelib: false`. With no `WHEEL` (an `.egg-info` install), it does when the conda package's record in the prefix's `conda-meta` lists a shared library among its files; when no record there lists the copy, when a shared library is named after one of its top-level modules or sits in one of its top-level packages. Nothing is written to such a copy whatever the record and whatever was passed (`--force` included), and the skip never fails a run: `apply` prints `Warning: : conda_build_not_pypi_release: …` once per copy, emits one `skipped` event per record of the release and copy (`errorCode: conda_build_not_pypi_release`; the reason names the copy), counts each such record as `N not supported` in the summary (when no other copy of the package has a result) and leaves the exit status as it is; `apply --check` does not count the copy as drift (the same warning and `skipped` events; `N not supported, skipped` for the records with no other copy; a record another copy verifies is `already_patched` with the reason `every installed copy that can be patched is patched`). The skip is the copy's, over every record of its release: a compiled copy whose files all hold some record's patch already is reported as already patched under that record, with no warning, checks in sync, and is judged for no other record of the release. Only the skip is exempt from failing: a record whose patch content cannot be staged (`--offline` with a missing blob) fails as for any package. A copy that holds no compiled code, or that nothing could be read about, is patched or refused. It is refused, with the per-package error starting `conda_build_not_pypi_release` and ending with the `socket-patch remove ` that drops the record, and nothing written, when the patch's `artifact_id` is a platform wheel (a `…-whl` that is not `…-none-any-whl`), when the copy's metadata was not found and the patch does not name a pure-Python wheel, or when the patch replaces no existing file. A copy whose files all hold the patch already is not refused, compiled or not: nothing is written, and it is reported as already patched. For a conda build a replaced file that hashes to neither side of the patch is an error whatever was passed: `--force` and `--allow-patch-conflicts` act as the default policy (content an earlier Socket patch wrote still gives way), `--force` does not skip a missing file, and `--strict` is unchanged. `scan --mode agent` and `get ` leave a patch out (warning `conda_build_not_pypi_release`, detail `: `, exit status unchanged) when every installed copy of its package is a compiled conda build or refuses it by the rules that need no file hash; `--all-releases` keeps it. `get ` names one patch, so it records it, and the apply it runs then skips or refuses the copy as above. Under `--json`, a `scan` / `get` whose apply skips a compiled copy carries a `skipped` event for each such copy: beside the `applied` event of a record another copy took, as the only event of a record whose every copy was skipped, and for a record that run did not select, so the skip is never unsaid. A release can have more than one record (the pure-Python wheel's beside a platform wheel's or the source distribution's). On each copy the records a conda build refuses by those rules are tried after the others, whatever order the manifest holds them in, and such a record is an error only when it is the first one tried on the copy: after another record of the release it is reported as already patched when its files hold the patch, and is otherwise not reported at all (neither as failed nor as `package_not_installed`), since the copy's outcome is the earlier record's. `scan` and `get` leave such a record out without the warning when they keep another record of that release. A copy pip or uv installed into a conda prefix is not a conda build. Files a patch does not replace are not compared. Not covered: the agent-mode blob cache and manifest are checked from `.socket` down, so a `.socket` that is itself a link still redirects those writes (deciding that at lock time is deferred). diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 360a069a4..52efd79eb 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -2026,6 +2026,12 @@ pub(crate) fn record_apply_outcome( env.warnings.push(warning.clone()); } } + // A copy skipped as not supported yet (a compiled conda build) is one + // copy's outcome, not its package's: another copy of the same record + // may have been patched. Its events are recorded on their own below, + // one per copy. + let unsupported_copy = + |skip: &PatchEvent| skip.error_code.as_deref() == Some(CONDA_BUILD_NOT_PYPI_RELEASE); let mut failed_any = false; for (purl, uuid) in recorded { if let Some(failure) = report @@ -2040,9 +2046,11 @@ pub(crate) fn record_apply_outcome( ); failed_any = true; } else if let Some(skip) = report.skipped.iter().find(|skip| { - skip.purl - .as_deref() - .is_some_and(|key| apply_key_covers(key, purl)) + !unsupported_copy(skip) + && skip + .purl + .as_deref() + .is_some_and(|key| apply_key_covers(key, purl)) }) { let mut event = skip.clone().with_uuid(uuid); event.purl = Some(purl.clone()); @@ -2051,6 +2059,14 @@ pub(crate) fn record_apply_outcome( env.record( PatchEvent::new(EventAction::Applied, purl.as_str()).with_uuid(uuid.as_str()), ); + } else if report.skipped.iter().any(|skip| { + unsupported_copy(skip) + && skip + .purl + .as_deref() + .is_some_and(|key| apply_key_covers(key, purl)) + }) { + // Every copy of it was skipped that way: said below. } else if report.code == 0 { record_apply_skip( env, @@ -2073,11 +2089,30 @@ pub(crate) fn record_apply_outcome( let Some(key) = skip.purl.as_deref() else { continue; }; - let news = matches!( - skip.error_code.as_deref(), - Some(super::user_patches::CONFLICT) | Some(CONDA_BUILD_NOT_PYPI_RELEASE) - ); - if !news + if unsupported_copy(skip) { + let mut event = skip.clone(); + if let Some((purl, uuid)) = recorded + .iter() + .find(|(purl, _)| apply_key_covers(key, purl)) + { + event.purl = Some(purl.clone()); + event.uuid = Some(uuid.clone()); + } else if event.uuid.is_none() { + event.uuid = uuid_of(key); + } + // Once per copy: the reason names it. + let said = env.events.iter().any(|existing| { + existing.action == EventAction::Skipped + && existing.error_code == event.error_code + && existing.purl == event.purl + && existing.reason == event.reason + }); + if !said { + env.record(event); + } + continue; + } + if skip.error_code.as_deref() != Some(super::user_patches::CONFLICT) || recorded.iter().any(|(purl, _)| apply_key_covers(key, purl)) || report .failures diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 1ec5ed77d..f67da7c50 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1704,7 +1704,6 @@ fn collect_apply_outcomes( ) -> (Vec, Vec) { let mut applied = Vec::new(); skipped.extend(caveats.not_in_build.iter().map(LeftCopy::event)); - skipped.extend(caveats.unsupported.iter().map(UnsupportedCopy::event)); for result in results { let event = caveats.event_of(result, dry_run); match event.action { @@ -1744,6 +1743,16 @@ fn collect_apply_outcomes( }); skipped.sort_by(|a, b| (&a.purl, &a.error_code).cmp(&(&b.purl, &b.error_code))); skipped.dedup_by(|a, b| a.purl == b.purl && a.error_code == b.error_code); + // A copy skipped as not supported yet (a compiled conda build) stays + // unpatched whatever another copy of its record did, and its reason + // names it: one event per record and copy, kept beside an applied or + // failed copy's outcome. + let mut said = HashSet::new(); + for copy in &caveats.unsupported { + if said.insert((copy.purl.as_str(), copy.detail.as_str())) { + skipped.push(copy.event()); + } + } (applied, skipped) } @@ -3777,6 +3786,18 @@ async fn apply_patches_inner( if is_store_copy { any_store_copy_applied = true; } + // A compiled conda build is judged as a whole (as + // `apply --check` settles it): one that already holds + // a record's patch accounts for every record of its + // release, so a sibling its files do not match is not + // reported as not installed. + if conda.unsupported.is_some() { + for variant_purl in &variants { + if manifest.patches.contains_key(variant_purl) { + matched_manifest_purls.insert(variant_purl.clone()); + } + } + } } else if let Some(reason) = &conda.unsupported { // A compiled conda build that does not already hold the // patch: not supported yet, so the copy is skipped. The @@ -5728,9 +5749,32 @@ mod tests { error: None, sidecar: None, }; - let t = tally_results(&[applied], &caveats); + let t = tally_results(std::slice::from_ref(&applied), &caveats); assert_eq!((t.applied, t.unsupported), (1, 1)); + // The outcomes a nested caller (`scan`, `get`) reads keep each + // skipped copy's event, beside the applied copy of the same + // record and once per copy. + let mut two_envs = GemCaveats { + unsupported: vec![skipped(platform), skipped(platform)], + ..GemCaveats::default() + }; + two_envs.unsupported[1].detail = format!("{code}: conda built the copy in /other-env"); + let (applied_keys, skips) = collect_apply_outcomes( + std::slice::from_ref(&applied), + &two_envs, + &[], + &HashSet::new(), + Vec::new(), + false, + ); + assert_eq!(applied_keys, [platform]); + assert_eq!(skips.len(), 2, "{skips:?}"); + assert!(skips + .iter() + .all(|skip| skip.error_code.as_deref() == Some(code) + && skip.purl.as_deref() == Some(platform))); + let event = serde_json::to_value(caveats.unsupported[0].event()).unwrap(); assert_eq!(event["action"], "skipped"); assert_eq!(event["errorCode"], code); diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 0dbbd5efb..2fc99a809 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -3472,6 +3472,47 @@ mod tests { assert_eq!(json["events"][1]["errorCode"], "user_patch_conflict"); } + /// A copy the nested apply skipped as not supported yet (a compiled + /// conda build) is said for each copy: beside the applied copy of a + /// selected record, as the only outcome of a selected record whose + /// every copy was skipped, and for a record this run did not select. + #[test] + fn record_apply_outcome_says_each_copy_skipped_as_not_supported() { + let code = "conda_build_not_pypi_release"; + let skip = |purl: &str, env_name: &str| { + PatchEvent::new(EventAction::Skipped, purl) + .with_reason(code, format!("{code}: conda built the copy in /{env_name}")) + }; + let mixed = "pkg:pypi/pillow@12.3.0?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let only_conda = "pkg:pypi/pyyaml@6.0.3?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let unselected = "pkg:pypi/numpy@2.4.4?artifact_id=cp313-cp313-manylinux_2_28_x86_64-whl"; + let report = ApplyRunReport { + applied: vec![mixed.into()], + skipped: vec![ + skip(mixed, "default"), + skip(mixed, "test"), + skip(only_conda, "default"), + skip(unselected, "default"), + ], + ..ApplyRunReport::default() + }; + let mut env = Envelope::new(JsonCommand::Get); + let recs = recorded(&[(mixed, "um"), (only_conda, "uo")]); + record_apply_outcome(&mut env, &recs, Some(&report), |_| Some("uu".into())); + assert_eq!( + outcomes(&env), + vec![ + o("applied", mixed, "um", ""), + o("skipped", mixed, "um", code), + o("skipped", mixed, "um", code), + o("skipped", only_conda, "uo", code), + o("skipped", unselected, "uu", code), + ] + ); + assert_eq!(env.status, Status::Success); + assert_ne!(env.events[1].reason, env.events[2].reason); + } + #[test] fn record_apply_outcome_never_infers_a_write_from_exit_zero() { let mut env = Envelope::new(JsonCommand::Get); diff --git a/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs b/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs index da6b72f5d..8dd3b4642 100644 --- a/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs +++ b/crates/socket-patch-cli/tests/apply/e2e_safety_advisories.rs @@ -996,6 +996,13 @@ fn a_compiled_conda_build_holding_one_records_patch_is_in_sync() { let second = b"# PIL/TiffImagePlugin.py as PyPI ships it\n"; let second_path = target.parent().unwrap().join("TiffImagePlugin.py"); std::fs::write(&second_path, second).unwrap(); + // A third record, whose only file the conda recipe changed: it matches + // nothing of the copy. + let sdist = "pkg:pypi/pillow@12.3.0?artifact_id=tar-gz"; + add_sibling_record(tmp.path(), pure, sdist); + let recipe_patched = b"# PIL/ImageFile.py as the conda recipe patched it\n"; + let third_path = target.parent().unwrap().join("ImageFile.py"); + std::fs::write(&third_path, recipe_patched).unwrap(); let manifest_path = tmp.path().join(".socket").join("manifest.json"); let mut manifest: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); @@ -1003,6 +1010,10 @@ fn a_compiled_conda_build_holding_one_records_patch_is_in_sync() { "beforeHash": git_sha256(second), "afterHash": git_sha256(CONDA_PATCHED), }); + manifest["patches"][sdist]["files"] = serde_json::json!({ "PIL/ImageFile.py": { + "beforeHash": git_sha256(b"# PIL/ImageFile.py as PyPI ships it\n"), + "afterHash": git_sha256(CONDA_PATCHED), + } }); std::fs::write( &manifest_path, serde_json::to_vec_pretty(&manifest).unwrap(), @@ -1015,8 +1026,13 @@ fn a_compiled_conda_build_holding_one_records_patch_is_in_sync() { stdout.contains(&format!("{pure} (already patched)")), "stdout:\n{stdout}" ); - assert!(!stderr.contains(CONDA_REFUSAL), "stderr:\n{stderr}"); + assert!( + !stderr.contains(CONDA_REFUSAL) && !stderr.contains("no matching installed package"), + "stderr:\n{stderr}" + ); + assert!(stdout.contains("0 not found on disk"), "stdout:\n{stdout}"); assert_eq!(std::fs::read(&second_path).unwrap(), second); + assert_eq!(std::fs::read(&third_path).unwrap(), recipe_patched); let (code, stdout, stderr) = apply_in(tmp.path(), &["--check"]); assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}");