Skip to content

Commit 0120126

Browse files
Fix agent mode failing on PyPI releases that have a wheel and an sdist record (#2194) (#2409)
* Give an installed PyPI copy the record of its own wheel alone A PyPI release can have one patch record per artifact a patch was made from: a wheel, a wheel per platform, the sdist. Agent mode matched a record to an installed copy by the first file it replaces, which does not tell the artifacts of a release apart. A wheel's install also took the sdist's record. For urllib3 2.2.2 the patch service has a record made from the wheel and one made from the sdist, whose sources are under src/: read against an install, every file of that record is one the patch adds, so it had no file to be matched by and matched any copy. A plain agent-mode scan then exited 1 on every run ("File already exists, but the patch adds it as a new file"), and a vendored scan failed on the same record. The same happens for urllib3 2.3.0, 2.2.3, 1.26.20 and 1.26.19. A platform wheel's install took another platform's record. The platform wheels of a release share their Python files byte for byte, so a record that replaces one of them and the wheel's compiled module matched every install. With two such records in the manifest, a default apply wrote the other platform's extension module over the installed one and exited 0; with one, --force and --allow-patch-conflicts did. An installed copy says which wheel it came from in the Tag lines of its WHEEL metadata, which is what a record's artifact_id spells. So: - the record made from the copy's own wheel, when it matches the copy, is the copy's only record, as a platform gem's copy takes its platform's record. select_installed_variants applies it for apply --check, vex, rollback and the download narrowing of scan and get; apply and vendor ask it at their own gates; - a platform wheel's record that the copy's WHEEL does not name as its own has to match on every file it replaces, under any flag. A release with no record of the installed wheel, and a copy with no WHEEL tags, are matched as before, so a release whose only record was made from the sdist still patches a wheel's install. Fixes #2194. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Leave a platform wheel's record on a conda build to the conda rule A conda build never takes a platform wheel's record, and `apply` has its own account of such a record: it is tried last, refused aloud only when it is the first record tried on the copy, and quiet after another record of the release. The file-by-file check for another wheel's record ran first and skipped the record, so a pure-Python conda build whose file is not the release's reported the platform wheel's record as "no matching installed package" beside the pure wheel's failure. The check now passes over the records a conda build never takes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Ask every file of a PyPI record made from another artifact The first version made the record of the copy's own wheel its only record, while that record matched the copy. Review found what that left open or broke: - when the own record did not match (a file edited after the install, a copy holding an earlier patch), the sdist's record was tried again and failed as before; - a record that says the same as the copy's own (a wheel's and its sdist's replacing one module with the same content) became "not installed", which the conda rule and its contract paragraph do not say; - a record rejected on a file other than its first was reported as not installed, with no file named; - vendor --force skipped the check. One rule replaces it. The record made from the copy's own wheel is matched as any record is. A record made from another artifact is the copy's only when every file it lists is: each file it replaces holds one side of the record, and each file it adds is absent or holds the patch. That is asked of every other record of a release that has a record of the copy's own wheel, and of a platform wheel's record on any copy that does not name that wheel. It does not depend on the own record matching, and no flag relaxes it. - select_installed_variants asks it, so apply --check, vex, rollback and the download narrowing share it; apply asks it at its variant gate. - The download narrowing hands the selector a record's added files too. It dropped them, which is why the sdist's record of a src/ layout had no file to be matched by. - A copy no record matches names the file that says so (no_matching_variant), also when that file is not a record's first. - vendor commits one artifact per package: on a copy that names its wheel it vendors that wheel's record alone, and asks no file, so --force does not skip it. - The conda fixture writes the Tag lines a real WHEEL has. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Keep vendor --force vendoring every recorded release variant The help text of `vendor --force` says it bypasses the installed-variant probe and vendors every recorded release variant. The own-wheel check for a PyPI copy is part of that probe, so it runs where the probe runs and `--force` skips it, as it skips the rest. The previous commit had moved it out from under `--force`. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Name a file the copy lacks, and try the copy's own wheel's record first A second review of the every-file rule found: - A record kept from a copy because one of its files is missing (another platform's extension module, which carries the platform in its name) failed the run as a bare "no matching variant found" with no failed event. `no_variant_reason` now names that file: the copy is installed, and does not hold a file the release the patch was made for does. - Which of two records that replace one file was written depended on the manifest map's order: each record is judged against what the earlier ones left on disk. `apply` now tries the copy's own wheel's record first, then the others by purl. - The message for a copy no record matches named a file of the copy that only differs from what another artifact's record adds. Such a file is named only when no record matched by its own file differs. - The contract and the module docs said `vex` shares the rule. It does not: it reads every PyPI record against every copy and attests the ones in effect, as before. The text says so now. - Two doc comments still said a record's added files never count. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent 3cdb47f commit 0120126

13 files changed

Lines changed: 1458 additions & 57 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1593,6 +1593,7 @@ socket-patch creates `.socket/` and everything under it itself and never writes
15931593
- **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`.
15941594
- **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/<ns>/<name>` 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.
15951595
- **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: <purl>: 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 <purl>` 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 <purl>` leave a patch out (warning `conda_build_not_pypi_release`, detail `<purl>: <reason>`, 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 <uuid>` 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.
1596+
- **Agent-mode apply to a PyPI release with several records**: a PyPI release has one patch record for each of its artifacts a patch was made from, and the record's purl names the artifact (`?artifact_id=py3-none-any-whl`, `cp313-cp313-manylinux_2_28_x86_64-whl`, `tar-gz` for the sdist). An installed copy names the wheel it came from in the `Tag:` lines (and the `Build:` line, when there is one) of its `<name>-<version>.dist-info/WHEEL`; the record made from that wheel is the copy's own, and is matched as any record is, by the first file it replaces. **A record made from another artifact is the copy's only when every file it lists is**: each file it replaces holds the record's original or patched content, and each file it adds is absent or holds the patched content. That is asked of every other record of a release that has a record of the copy's own wheel (the sdist's, another wheel's), and of a platform wheel's record (an `artifact_id` ending `-whl` and not `-none-any-whl`) on any copy that does not name that wheel. A wheel and its sdist hold the same modules under paths that can differ (a `src/` layout makes every file of the sdist's record one it adds), and the platform wheels of a release share their Python files byte for byte, so one file does not tell these artifacts apart. No flag relaxes this (`--force` and `--allow-patch-conflicts` included): nothing of such a record is written to the copy. `apply`, `apply --check`, `rollback` and the download narrowing of `scan` and `get` (without `--all-releases`) share the rule; `apply` tries the copy's own wheel's record first, so which of two records that replace one file is written does not depend on the manifest's order. `vex` reads every record of the release against the copy and attests the ones in effect, as before. A record it keeps from a copy is reported as any record with no matching copy is: `skipped` / `package_not_installed` when another record was tried on the copy, and when none was, the copy fails as `no_matching_variant`, naming the file that holds neither side or that the copy does not hold. What does not change: a record that says the same as the copy's own (a wheel's and its sdist's that replace the same module with the same content) is still applied or read as already patched; a release with no record of the installed wheel, and a copy with no readable `WHEEL` tags (an `.egg-info` install), are matched by the first replaced file, so a release whose only record was made from the sdist still patches a wheel's install; a conda build's own rule above decides for a platform wheel's record. **`vendor` commits one artifact per package**, so its installed-variant probe takes, on a copy that names its wheel, that wheel's record and no other record of the release (`--force` bypasses the probe and vendors every record, as before).
15961597

15971598
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).
15981599

‎crates/socket-patch-cli/src/commands/agent_download.rs‎

Lines changed: 7 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -286,29 +286,6 @@ pub(crate) async fn unwind_new_blobs(blobs_dir: &Path, hashes: &[String]) {
286286
}
287287
}
288288

289-
/// Build a file map keyed by path, keeping only files that carry BOTH
290-
/// hashes — the rule used ONLY for installed-distribution matching in
291-
/// [`filter_to_installed_releases`]. New files (no `beforeHash`) can
292-
/// neither identify nor disqualify an installed variant, so they are
293-
/// excluded here; [`select_installed_variants`] then discriminates on a
294-
/// non-empty `beforeHash`. Do NOT use this to build manifest records —
295-
/// see [`files_for_manifest`], which retains patch-added files.
296-
pub(crate) fn files_with_both_hashes(patch: &PatchResponse) -> HashMap<String, PatchFileInfo> {
297-
let mut files = HashMap::new();
298-
for (file_path, file_info) in &patch.files {
299-
if let (Some(before), Some(after)) = (&file_info.before_hash, &file_info.after_hash) {
300-
files.insert(
301-
file_path.clone(),
302-
PatchFileInfo {
303-
before_hash: before.clone(),
304-
after_hash: after.clone(),
305-
},
306-
);
307-
}
308-
}
309-
files
310-
}
311-
312289
/// The result line of a download that applies nothing after the save
313290
/// (`--save-only`): `Saved 2 patches to .socket/manifest.json (1 updated,
314291
/// 1 skipped).` A run that changed nothing says so instead of claiming the
@@ -602,6 +579,12 @@ pub(crate) async fn filter_to_installed_releases(
602579
// Fetch each variant's file hashes (the view carries them) so we
603580
// can hash-match against the installed distribution. The view is
604581
// kept for the download loop — it is the same GET it would issue.
582+
//
583+
// The files are the record's as the manifest will hold them, the
584+
// ones a patch adds included: `select_installed_variants` picks
585+
// its one file among those a record replaces, and a PyPI record
586+
// made from another artifact than the installed one is judged by
587+
// every file it lists, as `apply` will judge it.
605588
let mut candidates: Vec<(String, HashMap<String, PatchFileInfo>)> = Vec::new();
606589
for s in &variants {
607590
let view = match variant_views.next().await {
@@ -621,7 +604,7 @@ pub(crate) async fn filter_to_installed_releases(
621604
};
622605
match view {
623606
Ok(Some(patch)) => {
624-
candidates.push((s.purl.clone(), files_with_both_hashes(&patch)));
607+
candidates.push((s.purl.clone(), files_for_manifest(&patch)));
625608
views.insert(s.uuid.clone(), patch);
626609
}
627610
// On a fetch error/miss, keep the variant so the main

‎crates/socket-patch-cli/src/commands/apply.rs‎

Lines changed: 85 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3797,14 +3797,30 @@ async fn apply_patches_inner(
37973797
// written to it, and the copy is skipped below with a
37983798
// warning instead of failing the run.
37993799
let conda = Box::pin(conda_copy_view(&base_purl, pkg_path, &variants)).await;
3800+
// A PyPI copy's own wheel's record is tried first. A record
3801+
// made from another artifact of the release is judged by
3802+
// what the copy holds when its turn comes (`pypi_wheel`),
3803+
// so the order decides which of two records that replace
3804+
// one file is written.
3805+
let own_wheel =
3806+
if variants.len() > 1 && Ecosystem::from_purl(purl) == Some(Ecosystem::Pypi) {
3807+
let keys = variants.iter().map(String::as_str);
3808+
socket_patch_core::patch::pypi_wheel::own_wheel_record(pkg_path, keys).await
3809+
} else {
3810+
None
3811+
};
38003812
let mut ordered_variants: Vec<&String> = variants.iter().collect();
3801-
if !conda.never_takes.is_empty() {
3802-
// By purl within each half, so the run reads the same
3813+
if !conda.never_takes.is_empty() || own_wheel.is_some() {
3814+
// By purl within each group, so the run reads the same
38033815
// whatever order the manifest's map yields.
3804-
ordered_variants.sort_by(|a, b| {
3805-
(conda.never_takes.contains(*a), a.as_str())
3806-
.cmp(&(conda.never_takes.contains(*b), b.as_str()))
3807-
});
3816+
let rank = |variant: &String| {
3817+
(
3818+
conda.never_takes.contains(variant),
3819+
own_wheel != Some(variant.as_str()),
3820+
)
3821+
};
3822+
ordered_variants
3823+
.sort_by(|a, b| (rank(a), a.as_str()).cmp(&(rank(b), b.as_str())));
38083824
}
38093825

38103826
for variant_purl in ordered_variants {
@@ -3815,6 +3831,24 @@ async fn apply_patches_inner(
38153831
Some(p) => p,
38163832
None => continue,
38173833
};
3834+
// A PyPI record made from another artifact of the
3835+
// release than the one this copy was installed from
3836+
// is the copy's only when every file it lists is,
3837+
// under any flag (see core's `pypi_wheel`). A conda
3838+
// build never takes a platform wheel's record at all,
3839+
// and has its own account of it below.
3840+
if !conda.never_takes.contains(variant_purl)
3841+
&& socket_patch_core::patch::pypi_wheel::anothers_record(
3842+
pkg_path,
3843+
variant_purl,
3844+
variants.iter().map(String::as_str),
3845+
&patch.files,
3846+
)
3847+
.await
3848+
.is_some()
3849+
{
3850+
continue;
3851+
}
38183852

38193853
// Check the representative file's status (skip when
38203854
// --force). A mismatch *or* a missing file means this
@@ -5145,7 +5179,25 @@ async fn no_variant_reason(
51455179
// The file each record is matched by, as the apply loop judged it,
51465180
// where the copy holds it with other content.
51475181
let mut differs: std::collections::BTreeSet<&str> = Default::default();
5182+
// The file that says a PyPI record was made from another artifact
5183+
// than the copy's (`pypi_wheel`): one the copy holds with other
5184+
// content, or does not hold. Named only when no record matched by its
5185+
// own file differs: beside a record of the copy's own wheel, the
5186+
// other artifact's file is not what is wrong with the copy.
5187+
let mut anothers_differs: std::collections::BTreeSet<&str> = Default::default();
5188+
let mut anothers_lacks: std::collections::BTreeSet<&str> = Default::default();
51485189
for (key, files) in records {
5190+
let release = records.iter().map(|(key, _)| *key);
5191+
let anothers =
5192+
socket_patch_core::patch::pypi_wheel::anothers_record(pkg_path, key, release, files);
5193+
if let Some((name, status)) = anothers.await {
5194+
let name = name.strip_prefix("package/").unwrap_or(name);
5195+
match status {
5196+
VerifyStatus::NotFound => anothers_lacks.insert(name),
5197+
_ => anothers_differs.insert(name),
5198+
};
5199+
continue;
5200+
}
51495201
let telling = gem_ext::discriminating_files(pkg_path, key, files).await;
51505202
let Some((name, info)) = representative_file(&telling) else {
51515203
continue;
@@ -5157,7 +5209,17 @@ async fn no_variant_reason(
51575209
}
51585210
}
51595211
}
5160-
let other_content = !differs.is_empty();
5212+
// A PyPI copy is found by its metadata, so it is installed whichever
5213+
// file of another artifact's record it differs in or lacks.
5214+
let lacks = if differs.is_empty() && anothers_differs.is_empty() {
5215+
anothers_lacks
5216+
} else {
5217+
Default::default()
5218+
};
5219+
if differs.is_empty() {
5220+
differs = anothers_differs;
5221+
}
5222+
let other_content = !differs.is_empty() || !lacks.is_empty();
51615223
let python_copy_in_conda = Ecosystem::from_purl(purl) == Some(Ecosystem::Pypi)
51625224
&& socket_patch_core::crawlers::pixi_env::conda_prefix_of(pkg_path).is_some();
51635225
if python_copy_in_conda {
@@ -5177,6 +5239,17 @@ async fn no_variant_reason(
51775239
other_content,
51785240
};
51795241
}
5242+
if differs.is_empty() {
5243+
return NoVariant {
5244+
reason: format!(
5245+
"no matching variant found: the copy in {} is installed, but it does not hold \
5246+
{}, which the release the patch was made for does, so it was left as it is",
5247+
pkg_path.display(),
5248+
lacks.into_iter().collect::<Vec<_>>().join(", ")
5249+
),
5250+
other_content,
5251+
};
5252+
}
51805253
let mut reason = format!(
51815254
"no matching variant found: the copy in {} is installed, but {} there holds neither \
51825255
the original nor the patched content of a release the patch was made for, so it \
@@ -5203,9 +5276,11 @@ struct NoVariant {
52035276
reason: String,
52045277
/// The copy holds a file of the patch whose content is neither side of
52055278
/// any record: the package is installed there, edited or as another
5206-
/// build. `false` when the copy holds none of the files the records
5207-
/// are matched by (a qualified record cannot be told to belong to
5208-
/// such a copy, so it stays `package_not_installed`).
5279+
/// build. Also a PyPI copy that lacks a file of a record made from
5280+
/// another artifact of its release. `false` when the copy holds none
5281+
/// of the files the records are matched by (a qualified record cannot
5282+
/// be told to belong to such a copy, so it stays
5283+
/// `package_not_installed`).
52095284
other_content: bool,
52105285
}
52115286

‎crates/socket-patch-cli/src/commands/get.rs‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2762,8 +2762,8 @@ async fn run_get_vendored(
27622762
mod tests {
27632763
use super::*;
27642764
use crate::commands::agent_download::{
2765-
base64_decode, files_with_both_hashes, format_record_skip, format_save_line,
2766-
nested_apply_args_from_params, severity_rank, write_blob_entry, APPLY_FAILED,
2765+
base64_decode, format_record_skip, format_save_line, nested_apply_args_from_params,
2766+
severity_rank, write_blob_entry, APPLY_FAILED,
27672767
};
27682768
use socket_patch_core::crawlers::CrawlerOptions;
27692769
use socket_patch_core::manifest::records::record_from_patch_response;
@@ -4108,7 +4108,7 @@ mod tests {
41084108
assert_eq!(base64_decode("cGF0Y2hlZAo").unwrap(), b"patched\n");
41094109
}
41104110

4111-
// --- files_for_manifest / files_with_both_hashes ---------------------
4111+
// --- files_for_manifest ----------------------------------------------
41124112
// The download/scan/vendor record builder: a net-new file (afterHash, NO
41134113
// beforeHash) that the patch ADDS must be retained in the manifest
41144114
// record, not silently dropped. E.g. the whole-crate cargo export for
@@ -4163,12 +4163,6 @@ mod tests {
41634163
// New files record an empty-string beforeHash sentinel.
41644164
assert_eq!(added.before_hash, "");
41654165
assert_eq!(added.after_hash, "a".repeat(64));
4166-
4167-
// The both-hashes rule (used only for installed-variant matching)
4168-
// drops the added file.
4169-
let strict = files_with_both_hashes(&patch);
4170-
assert_eq!(strict.len(), 1);
4171-
assert!(!strict.contains_key("lib/rubygems_plugin.rb"));
41724166
}
41734167

41744168
#[test]
@@ -4187,9 +4181,6 @@ mod tests {
41874181
let kept = files_for_manifest(&patch);
41884182
assert_eq!(kept.len(), 9, "all whole-crate-export files must be kept");
41894183
assert!(kept.values().all(|f| f.before_hash.is_empty()));
4190-
4191-
// Guardrail precondition: the both-hashes rule yields an empty map.
4192-
assert!(files_with_both_hashes(&patch).is_empty());
41934184
}
41944185

41954186
#[test]

0 commit comments

Comments
 (0)