From 81f35b0e0a14ddf4cc7d206540de78d0d9df1b90 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 10:45:11 -0500 Subject: [PATCH 01/28] Vendor a gem locked as platform gems once one locked platform has a patched build A gem `Gemfile.lock` names as precompiled platform gems was vendored only when every locked platform had a patched build. Bundler's default lock names eight platforms, so such a gem stayed unpatched in vendored mode until all eight had one. It is now vendored when the fix's list names a patched build for at least one locked platform. Each of the others gets the tree of the gem the patch registry lists for it: upstream's own gem, unchanged. That gem is downloaded from the patch server, checked against the sha256 the list names, and its tree carries the gemspec the gem itself holds (its `metadata.gz`, which Bundler reads like a Ruby gemspec). Hosted mode installs the same gem for such a platform. - The ledger records such a tree as a `gemBuilds` entry with no `uuid` and the sha256 of its gem. It records no files: the copy's file inventory vouches for every byte of the tree, as it does for the files of a patched tree that the patch does not name, and the digest is what a restore fetches the gem again by. - A copy that is intact asks for the fix's list (one request) and is vendored again when the list names another build for a locked platform: a patched build that was published since, or upstream's gem where the patched build was withdrawn. - A newer fix that has no patched build for a platform the vendored copy of an earlier patch holds one for is a skip: the earlier copy stays in force. - Unchanged: a lock none of whose platforms has a patched build, a platform the registry does not list, and a build the list names whose patch is not served are the skips they were. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 17 +- .../src/patch/gem_refresh.rs | 10 +- crates/socket-patch-core/src/vendor/gem.rs | 1026 +++++++++++++++-- crates/socket-patch-core/src/vendor/mod.rs | 15 +- .../src/vendor/redownload.rs | 1 + .../src/vendor/service_fetch.rs | 4 + crates/socket-patch-core/src/vendor/state.rs | 38 +- 7 files changed, 970 insertions(+), 141 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 2216a04e83..11869b4c91 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -2632,6 +2632,10 @@ pub(crate) struct VendorReference { /// serves them (`registryOverride.identifiers.gemBuilds`); `None` when /// the reference carries no list. pub gem_builds: Option>, + /// gem: the index URL of that registry (`registryOverride.indexUrl`, + /// its host rewritten like every artifact URL): where the registry + /// serves the gem file of each platform it lists, `gems/`. + pub gem_index_url: Option, } /// Outcome of [`ApiClient::fetch_vendor_package`], and, with the @@ -2682,14 +2686,19 @@ fn vendor_reference( if let Some(miss) = reference_miss(&result.status) { return miss; } - let gem_builds = result - .registry_override - .as_ref() - .and_then(|registry| registry.identifiers.gem_builds.clone()); + let registry = result.registry_override.as_ref(); + let gem_builds = registry.and_then(|registry| registry.identifiers.gem_builds.clone()); + let gem_index_url = registry + .filter(|registry| registry.kind == "rubygems-compact-index") + .and_then(|registry| match patch_server_url { + Some(base) => rewrite_url_host(®istry.index_url, base).ok(), + None => Some(registry.index_url.clone()), + }); VendorServiceOutcome::Ready(VendorReference { archive: served_artifacts(result, patch_server_url, true).pop(), secondary: served_secondary_artifacts(result, patch_server_url), gem_builds, + gem_index_url, }) } diff --git a/crates/socket-patch-core/src/patch/gem_refresh.rs b/crates/socket-patch-core/src/patch/gem_refresh.rs index fb70463a44..20a15de886 100644 --- a/crates/socket-patch-core/src/patch/gem_refresh.rs +++ b/crates/socket-patch-core/src/patch/gem_refresh.rs @@ -213,7 +213,7 @@ fn inspect(bytes: Vec, wanted: &Wanted) -> Result { } /// A `.gem`'s `metadata.gz` member, gunzipped: the gemspec as YAML. -fn gem_metadata(gem_bytes: &[u8]) -> Option> { +pub(crate) fn gem_metadata(gem_bytes: &[u8]) -> Option> { use std::io::Read as _; let mut archive = tar::Archive::new(gem_bytes); for entry in archive.entries().ok()? { @@ -233,11 +233,11 @@ fn gem_metadata(gem_bytes: &[u8]) -> Option> { /// What a gemspec's YAML says that the refresh acts on. #[derive(Debug, PartialEq, Eq)] -struct SpecFacts { +pub(crate) struct SpecFacts { /// `-`, plus `-` for a platform gem. - full_name: String, + pub(crate) full_name: String, /// `extensions` lists at least one build script. - native: bool, + pub(crate) native: bool, } /// A top-level `key:` line of a gemspec's YAML and the rest of that line. @@ -265,7 +265,7 @@ fn unquote(value: &str) -> &str { /// top-level keys of one mapping, each followed by its indented block or /// its sequence items. `None` when the name or version cannot be read, or /// the platform is not a plain string. -fn parse_metadata(yaml: &str) -> Option { +pub(crate) fn parse_metadata(yaml: &str) -> Option { let lines: Vec<&str> = yaml.lines().collect(); let (mut name, mut version, mut platform, mut native) = (None, None, None, false); let mut i = 0; diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index d44df1cc7b..595521e629 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -61,7 +61,8 @@ //! as its ruby-platform tree (the extensions would never be built), so it is //! vendored as the patch service's PATCHED PLATFORM GEMS, one unpacked tree //! per locked platform, each with the stub gemspec the service serves for -//! it (verified against real bundler 4.0.15). The gem's fix is the patch +//! it (verified against real bundler 4.0.15), and upstream's own gem for a +//! platform that has no patched build yet. The gem's fix is the patch //! of its ruby gem (`` below, whatever the platforms); each patched //! platform gem has a patch of its own, which the fix's package reference //! names (`gemBuilds[].patchUuid`) and whose `tarball` and stub gemspec @@ -96,12 +97,21 @@ //! emptied in the copy. A tree git would still not commit in full is //! refused: wired without its binary, the gem would install everywhere //! and fail to load; -//! * every locked platform needs a patched build. While the fix's -//! reference names none for one of them (the patch registry serves -//! upstream's own gem for it, does not list it, or lists no platform gem -//! at all), or the patch it names for one is not served (it is still -//! being built, or the service does not grant it), the gem is left as it -//! is and reported as a skip +//! * every locked platform gets a tree, and at least one of them a +//! patched build. A platform the fix's reference names no patched build +//! for (`patchUuid: null`: the patch registry serves upstream's own gem +//! for it) gets that gem's tree, unchanged: the `.gem` the registry +//! serves for the platform, downloaded from the patch server and checked +//! against the sha256 the reference lists, with the gemspec the gem +//! itself carries (its `metadata.gz`, which bundler reads as it reads a +//! Ruby gemspec). Hosted mode installs the same gem for such a platform. +//! A later run follows the list: the tree becomes the patched build's +//! once one is published, and a tree whose patched build was withdrawn +//! goes back to upstream's gem ([`listing_moved`]). While no locked +//! platform has a patched build, the registry does not list one of them +//! or lists no platform gem at all, or the patch it names for one is not +//! served (it is still being built, or the service does not grant it), +//! the gem is left as it is and reported as a skip //! ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): a build is named and //! served only once published, so the next run may find it. A plain //! ` ()` entry beside the platform ones (the ruby platform, @@ -895,11 +905,87 @@ pub(super) fn is_platform_dir_name(platform: &str) -> bool { /// bundler requires of one. async fn stub_gemspec_valid(tree: &Path, name: &str) -> bool { match read_regular_to_string(&tree.join(format!("{name}.gemspec"))).await { + // The gemspec a gem carries (a tree of upstream's own gem): it has + // to be the one of the gem this tree is named after. + Ok(text) if text.starts_with("---") => { + let dir = |path: Option<&Path>| { + let name = path.and_then(Path::file_name); + name.and_then(|name| name.to_str()).map(str::to_string) + }; + let leaf = dir(tree.parent()) + .zip(dir(Some(tree))) + .map(|(gem, platform)| format!("{gem}-{platform}")); + let facts = crate::patch::gem_refresh::parse_metadata(&text); + facts.is_some_and(|facts| !facts.native && Some(facts.full_name) == leaf) + } Ok(text) => gemspec_missing_required_attrs(&text).is_empty(), Err(_) => false, } } +/// Whether the list of the gem's fix names another build for a locked +/// platform than the tree the ledger records for it: a patched build +/// where the copy holds upstream's gem (the build was published since), +/// upstream's gem where it holds a patched one (the build was withdrawn), +/// or the build of another patch. Only a list that names a gem for every +/// locked platform says so: with no list (the service has not read the +/// version's gems, or is building one again), a platform the list leaves +/// out, a request that fails or no service to ask, the copy stands as it +/// is and nothing is said. ONE request, the fix's reference. +async fn listing_moved( + project_root: &Path, + service: Option<&VendorServiceConfig>, + record: &PatchRecord, + name: &str, + copy_rel: &str, + trees: &PlatformTrees<'_>, +) -> bool { + let Some(cfg) = service.filter(|cfg| cfg.service_enabled()) else { + return false; + }; + if service_offline_conflict(service).is_some() { + return false; + } + let BuildsFrom::Locked(platforms) = &trees.from else { + return false; + }; + let Some(entry) = recorded_copy(project_root, &record.uuid, copy_rel).await else { + return false; + }; + let Ok(sources) = locked_build_sources(cfg, &record.uuid, name, trees, platforms).await else { + return false; + }; + sources.iter().any(|source| { + let recorded = entry + .gem_builds + .iter() + .find(|b| b.platform == source.platform); + !recorded.is_some_and(|built| built.uuid.eq_ignore_ascii_case(&source.uuid)) + }) +} + +/// The platforms whose patched build the vendored copy of ANOTHER patch +/// of the gem `name`@`version` holds, as the ledger records it. +async fn held_patched_platforms( + project_root: &Path, + name: &str, + version: &str, + uuid: &str, +) -> Vec { + let Ok(state) = super::state::load_state_shared(project_root).await else { + return Vec::new(); + }; + let base_purl = build_gem_purl(name, version); + let earlier = state.entries.values().filter(|entry| { + entry.ecosystem == "gem" && entry.base_purl == base_purl && entry.uuid != uuid + }); + earlier + .flat_map(|entry| entry.gem_builds.iter()) + .filter(|built| !built.is_upstream()) + .map(|built| built.platform.clone()) + .collect() +} + /// The vendor ledger's entry for the copy at `copy_rel` of the patch /// `uuid`: its file inventory is what vouches for the bytes of the /// platform trees once they are vendored (see [`verify_platform_tree`]), @@ -1199,10 +1285,19 @@ pub async fn vendor_gem_previewing<'a>( let (lock_wired, copy_ok) = (*lock_wired, *copy_ok); // What is vendored for each locked platform, once the service names it. let label = format!("{name}@{version}"); + // The patched builds a copy of another patch of the gem holds. + let held = match platforms.is_empty() { + true => Vec::new(), + false => held_patched_platforms(project_root, name, version, &record.uuid).await, + }; let locked = |standing: Standing| PlatformTrees { gem: &label, from: BuildsFrom::Locked(platforms), standing, + held: match standing { + Standing::EarlierPatch => held.clone(), + _ => Vec::new(), + }, }; // ── idempotent hot path ────────────────────────────────────────────── @@ -1210,8 +1305,23 @@ pub async fn vendor_gem_previewing<'a>( // already reference the uuid path → touch nothing. `entry` stays `None`: // the first run's ledger entry holds the only copy of the pre-vendor // originals. + // An intact copy vendored as platform gems still follows the fix's + // list: a locked platform that gained a patched build, or lost one to + // a withdrawal, is vendored again as the list has it now. + let moved = lock_wired + && copy_ok + && !platforms.is_empty() + && listing_moved( + project_root, + service, + record, + name, + copy_rel, + &locked(Standing::Wired), + ) + .await; if lock_wired { - if copy_ok { + if copy_ok && !moved { // The uuid dir's `.gitignore` / `.gitattributes` are not part // of the copy: one that was deleted (or never written) is put // back, or a project `*.so` rule drops the binaries from the @@ -1271,10 +1381,17 @@ pub async fn vendor_gem_previewing<'a>( } warnings.push(VendorWarning::new( "vendor_artifact_rebuilt", - format!( - "the committed vendored copy for {name}@{version} was missing or stale; \ - rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" - ), + match moved { + true => format!( + "the patch registry lists other builds for {name}@{version} than the \ + vendored copy holds; vendored again at {copy_rel} (Gemfile and \ + Gemfile.lock untouched)" + ), + false => format!( + "the committed vendored copy for {name}@{version} was missing or \ + stale; rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" + ), + }, )); // The rebuilt tree may differ from the one the ledger // inventoried (a service ↔ local flip swaps the stub gemspec): @@ -1819,14 +1936,24 @@ pub(super) struct PlatformTrees<'a> { pub(super) gem: &'a str, pub(super) from: BuildsFrom<'a>, pub(super) standing: Standing, + /// The platforms whose patched build the copy in force of another + /// patch of the gem holds ([`Standing::EarlierPatch`]): the gem does + /// not move to a fix whose list patches fewer of them, as a hosted + /// lock does not. Empty where no such copy stands. + pub(super) held: Vec, } /// One platform tree to stage: the patch it is unpacked from, and what its /// downloads must match beyond the digests that patch's own reference -/// states for them. +/// states for them. Or, for a platform the fix's list names no patched +/// build for, upstream's own gem as the patch registry serves it. struct BuildSource { platform: String, + /// The patch of the platform's patched build; empty for upstream's gem. uuid: String, + /// Upstream's gem for the platform: the file the fix's registry serves + /// for it (`gems/`), with the sha256 its list names. + upstream: Option, pinned: BuildPin, } @@ -1952,6 +2079,56 @@ fn no_patched_build_detail( format!("{gem} {lead}: {none}{have}. Vendored mode needs every locked platform{tail}") } +/// The skip of a gem none of whose locked platforms (`upstream`) has a +/// patched build in the fix's list: there is nothing to vendor it for, +/// and the registry would serve upstream's own gem for each. The gem +/// moves on a later run, once a build of one of them is published. +fn none_patched_skip(trees: &PlatformTrees<'_>, upstream: &[&str]) -> Box { + let (lead, tail) = match trees.standing { + Standing::NotVendored | Standing::Hosted => ("is not vendored", "."), + Standing::Wired => ("was not brought up to date", ""), + Standing::EarlierPatch => ( + "was not brought up to date", + "; its vendored copy of an earlier patch stays in force as it is.", + ), + }; + Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + format!( + "{} {lead}: no patched build yet for {}{tail}", + trees.gem, + listed(upstream) + ), + )) +} + +/// The skip of a gem whose copy of an earlier patch holds the patched +/// build of platforms (`lost`) that the newer fix has none for: the copy +/// stays in force, as a hosted lock stays on the patch it is on +/// ([`GEM_NEWER_FIX_WAITS`](crate::hosted::engine::GEM_NEWER_FIX_WAITS)). +fn newer_fix_waits(trees: &PlatformTrees<'_>, lost: &[&str]) -> Box { + Box::new(refused( + super::VENDOR_PREBUILT_PLATFORM_PENDING, + format!( + "{} was not brought up to date: the newer fix has no patched build for {} yet; its \ + vendored copy of an earlier patch stays in force as it is.", + trees.gem, + listed(lost) + ), + )) +} + +/// `sha256-` of a sha256 given in hex, as the patch registry +/// lists a gem's; `None` for anything else. +fn sha256_sri(hex_digest: &str) -> Option { + use base64::Engine as _; + let bytes = hex::decode(hex_digest).ok().filter(|b| b.len() == 32)?; + Some(format!( + "sha256-{}", + base64::engine::general_purpose::STANDARD.encode(bytes) + )) +} + /// What a gem's fix says when it names no builds to vendor from right /// now: its reference carries no list of the version's gems (the service /// has not read them, or is building one of them again), or the service @@ -2030,6 +2207,10 @@ async fn locked_build_sources( let Some(builds) = served.gem_builds.as_deref() else { return Err(no_builds_listed_skip(trees)); }; + let version = trees + .gem + .rsplit_once('@') + .map_or("", |(_, version)| version); let mut sources: Vec = Vec::with_capacity(platforms.len()); let mut missing = NoPatchedBuild::default(); for platform in platforms { @@ -2037,20 +2218,65 @@ async fn locked_build_sources( missing.unlisted.push(platform); continue; }; - match build.patch_uuid.as_deref() { - Some(uuid) => sources.push(BuildSource { - platform: platform.clone(), - uuid: uuid.to_string(), - pinned: BuildPin::Registry(build.gem_checksum_sha256.clone()), - }), - None => missing.yet.push(platform), - } + let pinned = BuildPin::Registry(build.gem_checksum_sha256.clone()); + let upstream = match build.patch_uuid { + Some(_) => None, + // Upstream's own gem, from the registry that lists it. + None => { + let listed = served + .gem_index_url + .as_deref() + .zip(sha256_sri(&build.gem_checksum_sha256)); + let Some((index, integrity_sri)) = listed else { + return Err(policy.miss(format!( + "the patch service names no registry or no sha256 for upstream's \ + gem of {name} ({platform})" + ))); + }; + Some(crate::api::client::SecondaryArtifact { + kind: "gem".to_string(), + url: format!( + "{}/gems/{name}-{version}-{platform}.gem", + index.trim_end_matches('/') + ), + integrity_sri, + prefetched: None, + }) + } + }; + sources.push(BuildSource { + platform: platform.clone(), + uuid: build.patch_uuid.clone().unwrap_or_default(), + upstream, + pinned, + }); } - if missing.is_empty() { - return Ok(sources); + // A platform the list leaves out has no gem to vendor at all. + if !missing.is_empty() { + return Err(no_patched_build(trees, &missing, &[])); } - let patched: Vec<&str> = sources.iter().map(|s| s.platform.as_str()).collect(); - Err(no_patched_build(trees, &missing, &patched)) + let of = |upstream: bool| -> Vec<&str> { + let kept = sources.iter().filter(|s| s.upstream.is_some() == upstream); + kept.map(|s| s.platform.as_str()).collect() + }; + let patched = of(false); + // With no patched build among the locked platforms there is nothing + // to vendor the gem for. A copy the lock is already wired to follows + // the list all the same, as a hosted lock does: its builds were + // withdrawn, and its trees go back to upstream's gems. + if patched.is_empty() && trees.standing != Standing::Wired { + return Err(none_patched_skip(trees, &of(true))); + } + let lost: Vec<&str> = trees + .held + .iter() + .map(String::as_str) + .filter(|held| platforms.iter().any(|p| p == held) && !patched.contains(held)) + .collect(); + if !lost.is_empty() { + return Err(newer_fix_waits(trees, &lost)); + } + Ok(sources) } /// A restore found that the build a ledger entry records for a platform is @@ -2123,6 +2349,63 @@ async fn recorded_build_sources( ) }; let now = listed.iter().find(|gem| gem.platform == built.platform); + // A tree of upstream's own gem is restored from the gem the + // registry lists for the platform today, which must be the one the + // entry pins. + if built.is_upstream() { + let upstream = now.filter(|gem| gem.patch_uuid.is_none()).and_then(|gem| { + let index = served.gem_index_url.as_deref()?; + Some((gem, index, sha256_sri(&gem.gem_checksum_sha256)?)) + }); + let Some((gem, index, integrity_sri)) = upstream else { + return Err(policy.hard( + VENDOR_PREBUILT_REPLACED, + format!( + "the copy of upstream's gem for {subject} cannot be restored as it \ + was vendored: the gem's fix {} for that platform now. Nothing was \ + restored. Run `socket-patch scan --mode vendored`, which vendors \ + what the patch service serves now", + match now.and_then(|gem| gem.patch_uuid.as_deref()) { + Some(uuid) => format!("names the patched build of patch {uuid}"), + None => "lists no gem".to_string(), + } + ), + )); + }; + if built.gem_integrity.is_empty() { + return Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "the vendor ledger's entry for upstream's gem for {subject} pins no \ + digest for the gem it was vendored from; refusing to restore it" + ), + )); + } + let version = trees + .gem + .rsplit_once('@') + .map_or("", |(_, version)| version); + sources.push(BuildSource { + platform: built.platform.clone(), + uuid: String::new(), + upstream: Some(crate::api::client::SecondaryArtifact { + kind: "gem".to_string(), + url: format!( + "{}/gems/{name}-{version}-{}.gem", + index.trim_end_matches('/'), + built.platform + ), + integrity_sri, + prefetched: None, + }), + pinned: BuildPin::Restored { + sha256: gem.gem_checksum_sha256.clone(), + gem: built.gem_integrity.clone(), + gemspec: String::new(), + }, + }); + continue; + } let Some((gem, uuid)) = now.and_then(|gem| Some((gem, gem.patch_uuid.as_deref()?))) else { return Err(replaced( "names no patched build for that platform now (it was withdrawn)", @@ -2147,6 +2430,7 @@ async fn recorded_build_sources( sources.push(BuildSource { platform: built.platform.clone(), uuid: uuid.to_string(), + upstream: None, pinned: BuildPin::Restored { sha256: gem.gem_checksum_sha256.clone(), gem: built.gem_integrity.clone(), @@ -2193,14 +2477,15 @@ fn refuse_foreign_stub( } } -/// One platform tree whose patch the service serves: its source, how -/// messages name it (` ()`), and the gem and the stub -/// gemspec that patch's reference lists. +/// One platform tree to download: its source, how messages name it +/// (` ()`), its gem, and the stub gemspec its patch's +/// reference lists. A tree of upstream's own gem has no stub: its gemspec +/// is the one the gem carries. type ServedBuild<'a> = ( &'a BuildSource, String, crate::api::client::SecondaryArtifact, - crate::api::client::SecondaryArtifact, + Option, ); /// What the patch of each of `sources` serves, asked for in ONE request @@ -2221,13 +2506,27 @@ async fn served_builds<'a>( sources: &'a [BuildSource], ) -> Result>, Box> { let policy = ServicePolicy::Refused; - let uuids: Vec = sources.iter().map(|source| source.uuid.clone()).collect(); - let references = fetch_served_references(cfg, &uuids) + // Only a patched build has a patch to ask about. + let patched = sources.iter().filter(|source| source.upstream.is_none()); + let uuids: Vec = patched.map(|source| source.uuid.clone()).collect(); + let mut references = fetch_served_references(cfg, &uuids) .await - .map_err(|reason| policy.miss(format!("patch service request failed ({reason})")))?; + .map_err(|reason| policy.miss(format!("patch service request failed ({reason})")))? + .into_iter(); let mut builds = Vec::with_capacity(sources.len()); let mut missing = NoPatchedBuild::default(); - for (source, (reference, unserved)) in sources.iter().zip(references) { + for source in sources { + if let Some(gem) = &source.upstream { + let subject = format!("{name} ({})", source.platform); + builds.push((source, subject, gem.clone(), None)); + continue; + } + let Some((reference, unserved)) = references.next() else { + return Err(policy.miss(format!( + "the patch service did not answer for the patch of {name} ({})", + source.platform + ))); + }; if let (BuildsFrom::Locked(_), Some(unserved)) = (&trees.from, unserved) { match unserved { Unserved::Building => missing.yet.push(&source.platform), @@ -2251,11 +2550,12 @@ async fn served_builds<'a>( "the patch service served no stub gemspec for {subject}" ))); }; - builds.push((source, subject, gem, stub)); + builds.push((source, subject, gem, Some(stub))); } if !missing.is_empty() { let patched: Vec<&str> = builds .iter() + .filter(|(source, ..)| source.upstream.is_none()) .map(|(source, ..)| source.platform.as_str()) .collect(); return Err(no_patched_build(trees, &missing, &patched)); @@ -2344,12 +2644,24 @@ async fn stage_platform_builds( }; let builds = served_builds(cfg, name, trees, &sources).await?; + let version = trees + .gem + .rsplit_once('@') + .map_or("", |(_, version)| version); // The gems, a few platforms at a time and taken in lock order. let mut downloads = std::pin::pin!(futures_util::stream::iter(&builds) .map(|(source, subject, gem, stub)| async move { - let gem_bytes = build_artifact(cfg, gem, "patched platform gem", subject).await?; - source.pinned.check_gem(&gem_bytes, subject)?; + let what = gem_noun(source); + let gem_bytes = build_artifact(cfg, gem, what, subject).await?; + source.pinned.check_gem(&gem_bytes, what, subject)?; + let Some(stub) = stub else { + // Upstream's own gem: its gemspec is the one it carries, + // and no patch names files of it. + let leaf = format!("{name}-{version}-{}", source.platform); + let gemspec = upstream_gemspec(&gem_bytes, &leaf, subject)?; + return Ok((gem_bytes, gemspec, BTreeMap::new())); + }; let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject).await?; source.pinned.check_stub(&stub_bytes, subject)?; let files = build_files(cfg, source, subject).await?; @@ -2366,10 +2678,13 @@ async fn stage_platform_builds( let (gem_bytes, stub_bytes, files) = downloaded?; let own: HashMap = files.clone().into_iter().collect(); let platform = source.platform.as_str(); - let stub_text = String::from_utf8_lossy(&stub_bytes); - refuse_unusable_stub(policy, name, subject, &stub_text)?; - if matches!(trees.from, BuildsFrom::Recorded(_)) { - refuse_foreign_stub(policy, trees.gem, platform, subject, &stub_text)?; + let what = gem_noun(source); + if stub.is_some() { + let stub_text = String::from_utf8_lossy(&stub_bytes); + refuse_unusable_stub(policy, name, subject, &stub_text)?; + if matches!(trees.from, BuildsFrom::Recorded(_)) { + refuse_foreign_stub(policy, trees.gem, platform, subject, &stub_text)?; + } } let tree = stage.join(platform); @@ -2382,7 +2697,7 @@ async fn stage_platform_builds( if let Err(e) = extract_on_blocking_pool(gem_bytes, &tree, extract_gem_data).await { return Err(policy.hard( "vendor_prebuilt_extract_failed", - format!("cannot extract the patched platform gem for {subject}: {e}"), + format!("cannot extract the {what} for {subject}: {e}"), )); } match empty_shipped_gitignores(&tree, &own).await { @@ -2390,14 +2705,14 @@ async fn stage_platform_builds( Err(e) => { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot empty a `.gitignore` the patched platform gem for {subject} ships: {e}"), + format!("cannot empty a `.gitignore` the {what} for {subject} ships: {e}"), )); } } if let Err(e) = tokio::fs::write(tree.join(format!("{name}.gemspec")), &stub_bytes).await { return Err(policy.hard( "vendor_prebuilt_write_failed", - format!("cannot write the stub gemspec for {subject} into the vendored dir: {e}"), + format!("cannot write the gemspec for {subject} into the vendored dir: {e}"), )); } // The gem passed the digests stated for this platform above, which @@ -2417,19 +2732,33 @@ async fn stage_platform_builds( platform: platform.to_string(), uuid: source.uuid.clone(), gem_integrity: gem.integrity_sri.clone(), - gemspec_integrity: stub.integrity_sri.clone(), + gemspec_integrity: stub + .as_ref() + .map_or_else(String::new, |s| s.integrity_sri.clone()), files, }); } let source_url = builds - .first() + .iter() + .find(|(source, ..)| source.upstream.is_none()) .map(|(_, _, gem, _)| gem.url.as_str()) .unwrap_or_default(); - let mut warnings = vec![downloaded_warning( - format_args!("{name} as patched platform gems ({})", platforms.join(", ")), - source_url, - )]; + let of = |upstream: bool| -> Vec<&str> { + let kept = builds + .iter() + .filter(|(source, ..)| source.upstream.is_some() == upstream); + kept.map(|(source, ..)| source.platform.as_str()).collect() + }; + let subject = match of(true).as_slice() { + [] => format!("{name} as patched platform gems ({})", platforms.join(", ")), + upstream => format!( + "{name} as platform gems (patched: {}; upstream's own: {})", + of(false).join(", "), + upstream.join(", ") + ), + }; + let mut warnings = vec![downloaded_warning(subject, source_url)]; if !emptied.is_empty() { warnings.push(VendorWarning::new( GITIGNORE_NEUTRALIZED, @@ -2444,14 +2773,66 @@ async fn stage_platform_builds( Ok((warnings, built)) } +/// How messages name the gem of `source`. +fn gem_noun(source: &BuildSource) -> &'static str { + match source.upstream { + Some(_) => "upstream platform gem", + None => "patched platform gem", + } +} + +/// The gemspec of a tree of upstream's own gem: the one the gem carries +/// (`metadata.gz`, a gemspec as YAML, which Bundler reads from a +/// `.gemspec` file as it reads the Ruby form). It must be the gemspec of +/// the gem `leaf` (`--`) and declare no +/// extension: Bundler builds none for a path gem. +fn upstream_gemspec( + gem_bytes: &[u8], + leaf: &str, + subject: &str, +) -> Result, Box> { + use crate::patch::gem_refresh::{gem_metadata, parse_metadata}; + let policy = ServicePolicy::Refused; + let metadata = gem_metadata(gem_bytes); + let facts = metadata + .as_deref() + .and_then(|yaml| std::str::from_utf8(yaml).ok()) + .and_then(parse_metadata); + let (Some(metadata), Some(facts)) = (metadata, facts) else { + return Err(policy.hard( + "vendor_prebuilt_extract_failed", + format!("upstream's gem for {subject} carries no gemspec that can be read"), + )); + }; + if facts.full_name != leaf { + return Err(policy.hard( + "vendor_prebuilt_integrity_mismatch", + format!( + "upstream's gem for {subject} is {}, not {leaf}; refusing to vendor it", + facts.full_name + ), + )); + } + if facts.native { + return Err(policy.hard( + "native_extensions_unsupported", + format!( + "upstream's gem for {subject} builds a native extension; bundler does not \ + build extensions for path-sourced gems" + ), + )); + } + Ok(metadata) +} + impl BuildPin { /// Whether the downloaded platform gem is the one this tree is pinned /// to; a mismatch is never vendored. - fn check_gem(&self, gem: &[u8], subject: &str) -> Result<(), Box> { + fn check_gem(&self, gem: &[u8], what: &str, subject: &str) -> Result<(), Box> { let mismatch = |why: String| { ServicePolicy::Refused.hard( "vendor_prebuilt_integrity_mismatch", - format!("patched platform gem for {subject} {why}; refusing to vendor it"), + format!("{what} for {subject} {why}; refusing to vendor it"), ) }; let (Self::Registry(listed) | Self::Restored { sha256: listed, .. }) = self; @@ -2783,10 +3164,17 @@ pub async fn preview_locked_builds( return refusal(super::service_fetch::required()); }; let label = format!("{}@{}", prelude.name, prelude.version); + let held = match standing { + Standing::EarlierPatch => { + held_patched_platforms(project_root, &prelude.name, &prelude.version, uuid).await + } + _ => Vec::new(), + }; let trees = PlatformTrees { gem: &label, from: BuildsFrom::Locked(&prelude.platforms), standing, + held, }; let named = locked_build_sources(cfg, uuid, &prelude.name, &trees, &prelude.platforms).await; let sources = match named { @@ -8535,6 +8923,16 @@ mod tests { /// `metadata.gz`). `data_files` are the inner data.tar.gz entries at the /// root (no prefix dir), as a real `.gem` carries them. pub(super) fn make_gem(data_files: &[(&str, &[u8])]) -> Vec { + // A token metadata.gz: the CLI service path never reads it (it uses the + // served stub), but a real `.gem` always carries one. + make_gem_with_metadata( + b"--- !ruby/object:Gem::Specification\nname: rack\n", + data_files, + ) + } + + /// [`make_gem`] with the gemspec `metadata` (YAML) the gem carries. + pub(super) fn make_gem_with_metadata(metadata: &[u8], data_files: &[(&str, &[u8])]) -> Vec { use std::io::Write as _; let mut data_tar = tar::Builder::new(Vec::new()); for (rel, content) in data_files { @@ -8548,11 +8946,8 @@ mod tests { let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); enc.write_all(&data_tar).unwrap(); let data_gz = enc.finish().unwrap(); - // A token metadata.gz: the CLI service path never reads it (it uses the - // served stub), but a real `.gem` always carries one. let mut menc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); - menc.write_all(b"--- !ruby/object:Gem::Specification\nname: rack\n") - .unwrap(); + menc.write_all(metadata).unwrap(); let metadata_gz = menc.finish().unwrap(); let mut outer = tar::Builder::new(Vec::new()); for (name, bytes) in [ @@ -12807,6 +13202,53 @@ mod tests { } } + /// The gemspec upstream's gem for `platform` carries, as YAML. + fn upstream_gemspec_yaml(platform: &str) -> String { + format!( + "--- !ruby/object:Gem::Specification\nname: nokogiri\nversion: \ + !ruby/object:Gem::Version\n version: 1.18.10\nplatform: {platform}\nauthors:\n- \ + Nokogiri\nextensions: []\nsummary: upstream\n" + ) + } + + /// Upstream's own gem for `platform`, which has no patched build: + /// the registry lists it as it is (`patchUuid: null`) and serves + /// its file. + fn upstream(platform: &'static str) -> Served { + Served { + platform, + listed: Listed::PassThrough, + own: Own::Granted, + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(platform).as_bytes(), + &[(RB, RB_PRISTINE), (SO, b"upstream's binary")], + )), + stub: None, + gem_sha512: None, + listed_sha256: None, + files: BTreeMap::new(), + } + } + + /// What the ledger records of `platform`'s tree of [`upstream`]'s + /// gem. + fn kept(platform: &'static str) -> GemBuildEntry { + use base64::Engine as _; + use sha2::Digest as _; + let gem = upstream(platform).gem.unwrap_or_default(); + let digest = sha2::Sha256::digest(&gem); + GemBuildEntry { + platform: platform.to_string(), + uuid: String::new(), + gem_integrity: format!( + "sha256-{}", + base64::engine::general_purpose::STANDARD.encode(digest) + ), + gemspec_integrity: String::new(), + files: BTreeMap::new(), + } + } + /// The patch of `platform`'s patched build of the fix `uuid`. fn build_uuid(uuid: &str, platform: &str) -> String { let tag = &crate::utils::digest::sha256_hex_of(platform.as_bytes())[..8]; @@ -12858,6 +13300,13 @@ mod tests { "platform": platform, "gemChecksumSha256": listed_sha256, "patchUuid": null })); + // The registry serves the file of a gem it lists. + if let Some(gem) = build.gem.as_deref().filter(|_| list) { + let route = format!( + "/patch-registry/gem/tok/{uuid}/s/4/gems/nokogiri-1.18.10-{platform}.gem" + ); + artifact("gem", route, gem, None); + } continue; } Listed::Patched => gem_builds.push(serde_json::json!({ @@ -13241,7 +13690,9 @@ mod tests { ); assert!(found.diagnostics.is_empty(), "{:?}", found.diagnostics); - // A second run changes nothing and asks the service nothing. + // A second run changes nothing. It asks the service one + // thing, the list of the gem's fix, which names the builds + // the copy holds. let requests = ts::request_count(&server).await; let snapshot = ts::tree_snapshot(&root); let (again, entry, warnings) = @@ -13249,7 +13700,7 @@ mod tests { assert!(again.success, "{:?}", again.error); assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); assert_eq!(ts::tree_snapshot(&root), snapshot); - assert_eq!(ts::request_count(&server).await, requests); + assert_eq!(ts::request_count(&server).await, requests + 1); // Revert: both files byte for byte, the trees gone. let reverted = revert_gem(&saved, &root, false).await; @@ -13261,12 +13712,377 @@ mod tests { } } - /// Every locked platform needs a patched build. While the gem - /// patch's reference names none for one of them (the registry - /// serves upstream's own gem for it, does not list it, or lists no - /// platform gem at all), a dry run and a wet run both leave the gem - /// alone under the benign pending code: one line that names the gem - /// and the platforms, one request (the gem patch's reference), no + /// A lock whose platforms are not all patched is vendored when the + /// fix's list names a patched build for at least one of them. The + /// patched platform gets the tree of its patched build, the other + /// the gem the patch registry lists for it: upstream's own, + /// unchanged, with the gemspec that gem carries. That gem comes + /// from the patch server and is checked against the sha256 of the + /// list. The ledger records the tree with no patch, the copy + /// verifies and a change to the tree is found, a second run asks + /// for the fix's list alone, and revert restores both files byte + /// for byte. + #[tokio::test] + async fn a_platform_without_a_patched_build_is_vendored_as_upstreams_gem() { + let lock_before = lock(None); + let (_tmp, root, record) = project(&lock_before).await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("a ledger entry"); + + let rel = rel(UUID); + let read = |platform: &str, file: &str| { + std::fs::read(root.join(&rel).join(platform).join(file)).unwrap() + }; + assert_eq!(read(DARWIN, RB), stamped(DARWIN)); + assert_eq!(read(DARWIN, "nokogiri.gemspec"), stub(DARWIN)); + assert_eq!(read(LINUX, RB), RB_PRISTINE, "upstream's file, unchanged"); + assert_eq!(read(LINUX, SO), b"upstream's binary"); + assert_eq!( + read(LINUX, "nokogiri.gemspec"), + upstream_gemspec_yaml(LINUX).as_bytes(), + "the gemspec upstream's gem carries, as it is" + ); + // Both platforms are in the one PATH section, as when both are + // patched. + assert_eq!(text(root.join(GEMFILE_LOCK)).await, vendored(&rel, None)); + + // The requests: the fix's list, the reference of the one + // patched build, that build's gem and stub, and upstream's gem + // from the fix's registry on the patch server. + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + let own = build_uuid(UUID, DARWIN); + let mut fetched = downloads(&server).await; + fetched.sort(); + let mut expected = vec![ + format!("/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{DARWIN}.gem"), + format!("/patch/gem/nokogiri/1.18.10/tok/{own}/nokogiri-1.18.10-{DARWIN}.gemspec"), + format!("/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem"), + ]; + expected.sort(); + assert_eq!(fetched, expected); + let downloaded: Vec<&str> = warnings + .iter() + .filter(|w| w.code == "vendor_prebuilt_downloaded") + .map(|w| w.detail.as_str()) + .collect(); + assert!( + matches!(downloaded.as_slice(), [said] if said.contains( + "nokogiri as platform gems (patched: arm64-darwin; upstream's own: \ + x86_64-linux-gnu)" + )), + "{warnings:?}" + ); + + // The ledger: the tree of upstream's gem names no patch, no + // gemspec digest and no files, only the gem it is. + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), kept(LINUX)]); + ts::persist(&root, NOKO, entry.clone()).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!(saved, entry); + let ledger: Value = + serde_json::from_str(&text(root.join(".socket/vendor/state.json")).await).unwrap(); + assert_eq!( + ledger["entries"][NOKO]["gemBuilds"][1], + serde_json::json!({ + "platform": LINUX, + "gemIntegrity": kept(LINUX).gem_integrity, + }) + ); + assert!(saved.gem_builds[1].is_upstream() && !saved.gem_builds[0].is_upstream()); + assert!(saved.gem_tree_files(LINUX, &record.files).is_empty()); + + // The copy verifies, and its inventory vouches for every file + // of the tree no patch names a file of. + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + let binary = root.join(&rel).join(LINUX).join(SO); + tokio::fs::write(&binary, b"another binary").await.unwrap(); + assert!(matches!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Corrupt { .. } + )); + tokio::fs::write(&binary, b"upstream's binary") + .await + .unwrap(); + + // A second run changes nothing: one request, the fix's list. + let requests = ts::request_count(&server).await; + let snapshot = ts::tree_snapshot(&root); + let (again, rerun_entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::tree_snapshot(&root), snapshot); + assert_eq!(ts::request_count(&server).await, requests + 1); + + let reverted = revert_gem(&saved, &root, false).await; + assert!(reverted.success, "{:?}", reverted.error); + assert!(reverted.warnings.is_empty(), "{:?}", reverted.warnings); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert!(!root.join(".socket/vendor/gem").exists()); + } + + /// The copy follows the fix's list. A locked platform that gains a + /// patched build gets that build's tree in place of upstream's + /// gem; one whose patched build is withdrawn goes back to + /// upstream's gem, the last one included. The Gemfile and the lock + /// are not touched, and the copy verifies after each step. + #[tokio::test] + async fn a_vendored_copy_follows_a_gained_and_a_withdrawn_build() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let lock_wired = text(root.join(GEMFILE_LOCK)).await; + let gemfile_wired = text(root.join(GEMFILE)).await; + let rel = rel(UUID); + let linux_rb = root.join(&rel).join(LINUX).join(RB); + let darwin_rb = root.join(&rel).join(DARWIN).join(RB); + + let steps: [(Vec, Vec); 3] = [ + // The linux build is published. + ( + vec![served(DARWIN), served(LINUX)], + vec![built(UUID, DARWIN), built(UUID, LINUX)], + ), + // The darwin build is withdrawn. + ( + vec![upstream(DARWIN), served(LINUX)], + vec![kept(DARWIN), built(UUID, LINUX)], + ), + // And the linux one: the copy holds upstream's gems alone. + ( + vec![upstream(DARWIN), upstream(LINUX)], + vec![kept(DARWIN), kept(LINUX)], + ), + ]; + for (list, expected) in steps { + let (server, cfg) = service(UUID, &list).await; + // A dry run says the same and writes nothing. + let snapshot = ts::tree_snapshot(&root); + let mut previewed = Vec::new(); + let preview = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &PatchSources::blobs_only(&root.join("no-blobs")), + "2026-06-09T00:00:00Z", + true, + false, + Some(&cfg), + false, + &mut previewed, + ) + .await; + let (preview, ..) = unwrap_done(preview); + assert!(preview.success, "{:?}", preview.error); + let named = |builds: &[GemBuildEntry]| -> Vec<(String, String)> { + let pair = |b: &GemBuildEntry| (b.platform.clone(), b.uuid.clone()); + builds.iter().map(pair).collect() + }; + assert_eq!(named(&previewed), named(&expected)); + assert_eq!( + ts::tree_snapshot(&root), + snapshot, + "a dry run writes nothing" + ); + + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let entry = entry.expect("the copy's new ledger entry"); + assert_eq!(entry.gem_builds, expected); + assert!( + warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt" + && w.detail.contains("lists other builds for nokogiri@1.18.10")), + "{warnings:?}" + ); + ts::persist(&root, NOKO, entry).await; + let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + assert_eq!( + check_vendored_artifact(&root, &saved, &record).await, + ArtifactHealth::Healthy + ); + for (path, platform) in [(&darwin_rb, DARWIN), (&linux_rb, LINUX)] { + let patched = !saved + .gem_builds + .iter() + .any(|b| b.platform == platform && b.is_upstream()); + let expected = if patched { + stamped(platform) + } else { + RB_PRISTINE.to_vec() + }; + assert_eq!(tokio::fs::read(path).await.unwrap(), expected, "{platform}"); + } + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_wired); + assert_eq!(text(root.join(GEMFILE)).await, gemfile_wired); + + // In step with the list again: the fix's list, nothing else. + let requests = ts::request_count(&server).await; + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, requests + 1); + } + } + + /// A fresh vendor of a gem none of whose locked platforms has a + /// patched build is the skip it was, whatever the list names for + /// them, and an upstream gem that is not the one the list names + /// (another sha256, another gem's gemspec, one with extensions to + /// build) is refused with nothing left behind. + #[tokio::test] + async fn an_upstream_gem_that_is_not_the_listed_one_is_refused() { + let another = |metadata: String| Served { + gem: Some(make_gem_with_metadata( + metadata.as_bytes(), + &[(RB, RB_PRISTINE)], + )), + ..upstream(LINUX) + }; + let cases = [ + ( + Served { + listed_sha256: Some("0".repeat(64)), + ..upstream(LINUX) + }, + "integrity", + ), + ( + another(upstream_gemspec_yaml(DARWIN)), + "vendor_prebuilt_integrity_mismatch", + ), + ( + another( + upstream_gemspec_yaml(LINUX) + .replace("extensions: []", "extensions:\n- ext/nokogiri/extconf.rb"), + ), + "native_extensions_unsupported", + ), + ]; + for (linux, says) in cases { + let lock_before = lock(None); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), linux]).await; + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, false).await; + let said = match outcome { + VendorOutcome::Refused { code, detail } => format!("{code}: {detail}"), + VendorOutcome::Done { result, .. } => { + assert!(!result.success, "{says}: vendored"); + result.error.unwrap_or_default() + } + }; + assert!(said.contains(says), "{says}: {said}"); + assert!(said.contains("x86_64-linux-gnu"), "{said}"); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before, "{says}"); + assert!(!root.join(".socket/vendor/gem").exists(), "{says}"); + } + } + + /// `repair` (a restore) of a copy with a tree of upstream's gem + /// fetches that gem again from the fix's registry, by the digest + /// the ledger recorded with the tree, and refuses, with nothing + /// unpacked, when the list names a patched build for the platform + /// now, when it lists another gem, and when the ledger entry pins + /// no digest for the tree. + #[tokio::test] + async fn a_lost_tree_of_upstreams_gem_is_restored_from_the_fixs_registry() { + let (_tmp, root, record) = project(&lock(None)).await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let tree = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&tree).await.unwrap(); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Corrupt { + reason: "file_not_found".to_string() + } + ); + + // The refusals. + let before = ts::tree_snapshot(&root); + let mut no_pin = entry.clone(); + no_pin.gem_builds[1].gem_integrity.clear(); + let refused = crate::vendor::redownload::restore(&root, &no_pin, &record, &cfg) + .await + .expect_err("an entry with no digest for the tree"); + assert!(refused.contains("pins no digest"), "{refused}"); + let another_gem = Served { + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(LINUX).as_bytes(), + &[(RB, RB_PRISTINE), (SO, b"another release")], + )), + ..upstream(LINUX) + }; + for (now, code, says) in [ + ( + served(LINUX), + VENDOR_PREBUILT_REPLACED, + "names the patched build of patch", + ), + ( + another_gem, + "vendor_prebuilt_integrity_mismatch", + "is not the gem this copy was vendored from", + ), + ] { + let (_server, cfg) = service(UUID, &[served(DARWIN), now]).await; + let refused = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect_err("a list that moved"); + assert!(refused.starts_with(code), "{refused}"); + assert!(refused.contains(says), "{refused}"); + assert!(refused.contains("nokogiri (x86_64-linux-gnu)"), "{refused}"); + assert_eq!(ts::tree_snapshot(&root), before, "{says}"); + } + + // The restore: the fix's list, the patched build's reference, + // and both gems again. + let asked = reference_requests(&server).await.len(); + let fetched = downloads(&server).await.len(); + crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect("restore"); + assert_eq!( + reference_requests(&server).await[asked..], + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + let again = downloads(&server).await[fetched..].to_vec(); + assert!( + again.contains(&format!( + "/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem" + )), + "{again:?}" + ); + assert_eq!( + check_vendored_artifact(&root, &entry, &record).await, + ArtifactHealth::Healthy + ); + assert_eq!( + tokio::fs::read(tree.join("nokogiri.gemspec")) + .await + .unwrap(), + upstream_gemspec_yaml(LINUX).as_bytes() + ); + } + + /// The gem needs a gem for every locked platform and a patched + /// build of one at least. While the list of the gem's fix leaves a + /// locked platform out, names a patched build for none, or is not + /// there at all, a dry run and a wet run both leave the gem alone + /// under the benign pending code: one line that names the gem and + /// the platforms, one request (the gem patch's reference), no /// download and nothing written. #[tokio::test] async fn a_locked_platform_without_a_patched_build_is_a_skip_that_downloads_nothing() { @@ -13274,14 +14090,7 @@ mod tests { listed, ..served(platform) }; - let cases: [(Vec, bool, &str); 6] = [ - ( - vec![served(DARWIN), listed(LINUX, Listed::PassThrough)], - true, - "nokogiri@1.18.10 is not vendored: no patched build yet for x86_64-linux-gnu \ - (arm64-darwin has one). Vendored mode needs every locked platform; `scan \ - --mode hosted` can patch the others now.", - ), + let cases: [(Vec, bool, &str); 5] = [ // A platform the list leaves out is one upstream does not // publish: not one to wait for, and hosted mode leaves // such a gem alone too. @@ -13301,11 +14110,10 @@ mod tests { ], true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin, and there is no patched build yet for x86_64-linux-gnu. \ - Vendored mode needs every locked platform, and a re-run does not change \ - what the registry lists: this is settled once the lockfile no longer names \ - arm64-darwin (`bundle lock --remove-platform arm64-darwin`), or the \ - registry lists a gem for every locked platform.", + arm64-darwin. Vendored mode needs every locked platform, and a re-run does \ + not change what the registry lists: this is settled once the lockfile no \ + longer names arm64-darwin (`bundle lock --remove-platform arm64-darwin`), \ + or the registry lists a gem for every locked platform.", ), ( vec![ @@ -13314,7 +14122,7 @@ mod tests { ], true, "nokogiri@1.18.10 is not vendored: no patched build yet for arm64-darwin and \ - x86_64-linux-gnu. Vendored mode needs every locked platform.", + x86_64-linux-gnu.", ), ( Vec::new(), @@ -13415,10 +14223,11 @@ mod tests { ); } - /// A platform the lock gains after the gem was vendored, with no - /// patched build: the vendored copy stays in force exactly as it - /// is, dry run or not, under the same benign code and one line - /// that says why it was not brought up to date. + /// A platform the lock gains after the gem was vendored, whose + /// patched build is named and not served yet: the vendored copy + /// stays in force exactly as it is, dry run or not, under the same + /// benign code and one line that says why it was not brought up to + /// date. #[tokio::test] async fn a_vendored_gem_whose_lock_gains_an_unpatched_platform_stays_as_it_is() { const JAVA: &str = "java"; @@ -13433,11 +14242,8 @@ mod tests { ); tokio::fs::write(&lock_path, &gained).await.unwrap(); let before = ts::tree_snapshot(&root); - let pass_through = Served { - listed: Listed::PassThrough, - ..served(JAVA) - }; - let (server, cfg) = service(UUID, &[served(DARWIN), pass_through, served(LINUX)]).await; + let building = unserved(JAVA, "pending_build"); + let (server, cfg) = service(UUID, &[served(DARWIN), building, served(LINUX)]).await; for dry_run in [true, false] { let (code, detail) = unwrap_refused( vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, @@ -13854,11 +14660,7 @@ mod tests { let (_tmp, root, record) = project(&lock(None)).await; let before = ts::tree_snapshot(&root); - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; - for not_vendorable in [pass_through, unserved(LINUX, "pending_build")] { + for not_vendorable in [unserved(LINUX, "pending_build")] { let (_server, cfg) = service(UUID, &[served(DARWIN), not_vendorable]).await; let mut previewed = Vec::new(); let outcome = run(&root, &record, &cfg, true, &mut previewed).await; @@ -13922,16 +14724,10 @@ mod tests { assert_eq!(reference_requests(&server).await, both_requests(UUID)); assert_eq!(downloads(&server).await, Vec::::new()); - // A locked platform with no patched build, which the gem - // patch's reference says (one request), or whose patch is not - // served, which that patch's own reference says (the second): - // the wet run's skip, word for word. - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; + // A locked platform whose patch is not served, which that + // patch's own reference says (the second request): the wet + // run's skip, word for word. for (not_vendorable, requests) in [ - (pass_through, vec![vec![UUID.to_string()]]), ( unserved(LINUX, "pending_build"), both_requests(UUID).to_vec(), @@ -14155,6 +14951,7 @@ mod tests { gem: "nokogiri@1.18.10", from: BuildsFrom::Locked(&platforms), standing, + held: Vec::new(), }; let (code, detail) = unwrap_refused(*no_builds_listed_skip(&trees)); assert_eq!(code, "vendor_prebuilt_platform_pending"); @@ -14215,13 +15012,9 @@ mod tests { unwrap_refused(outcome) } const NEEDS: &str = "Vendored mode needs every locked platform"; - let pass_through = Served { - listed: Listed::PassThrough, - ..served(LINUX) - }; let cases: [(Vec, String); 3] = [ ( - vec![served(DARWIN), pass_through], + vec![served(DARWIN), unserved(LINUX, "pending_build")], format!( "nokogiri@1.18.10 is not vendored: no patched build yet for \ x86_64-linux-gnu (arm64-darwin has one). {NEEDS}; the gem stays hosted." @@ -14774,13 +15567,13 @@ mod tests { check_vendored_artifact(&root, &entry, &record).await, ArtifactHealth::Healthy ); - // A second run is in sync and asks the service nothing. + // A second run is in sync and asks for the fix's list alone. let requests = ts::request_count(&server).await; let (again, rerun_entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); - assert_eq!(ts::request_count(&server).await, requests); + assert_eq!(ts::request_count(&server).await, requests + 1); // Without the inventory the files of each tree's own patch // vouch for it: the binary that patch built is in the tree. @@ -14983,7 +15776,8 @@ mod tests { } // An in-sync re-run puts back metadata that went missing, asks - // the service nothing, and leaves a dry run's tree alone. + // the service for the fix's list alone (the dry run and the + // wet run once each), and leaves a dry run's tree alone. let requests = ts::request_count(&server).await; for (file, _) in metadata { tokio::fs::remove_file(uuid_dir.join(file)).await.unwrap(); @@ -15000,7 +15794,7 @@ mod tests { for (file, text_of) in metadata { assert_eq!(text(uuid_dir.join(file)).await, text_of, "re-run: {file}"); } - assert_eq!(ts::request_count(&server).await, requests); + assert_eq!(ts::request_count(&server).await, requests + 2); } /// A restore checks each download against the digest the ledger @@ -15158,9 +15952,11 @@ mod tests { assert!(!root.join(format!(".socket/vendor/gem/{UUID_B}")).exists()); } - /// A newer patch of a gem already vendored, with a locked platform - /// that has no patched build yet: the copy of the earlier patch - /// stays wired and untouched, and the skip's one line says so. + /// A newer patch of a gem already vendored, which has no patched + /// build yet for a platform the vendored copy holds one for: the + /// gem does not move to a fix that patches fewer of its locked + /// builds. The copy of the earlier patch stays wired and + /// untouched, and the skip's one line says so. #[tokio::test] async fn a_newer_patch_with_an_unpatched_platform_keeps_the_earlier_copy() { let (_tmp, root, record_a) = project(&lock(None)).await; @@ -15183,9 +15979,9 @@ mod tests { assert_eq!(code, "vendor_prebuilt_platform_pending", "{detail}"); assert_eq!( detail, - "nokogiri@1.18.10 was not brought up to date: no patched build yet for \ - x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every locked \ - platform; its vendored copy of an earlier patch stays in force as it is." + "nokogiri@1.18.10 was not brought up to date: the newer fix has no patched \ + build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays \ + in force as it is." ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 29e3026531..d3c3ec8f2b 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -728,16 +728,19 @@ pub const VENDOR_PREBUILT_UNAVAILABLE: &str = "vendor_prebuilt_unavailable"; /// no older vendored patch to keep. pub const VENDOR_PREBUILT_REQUIRED: &str = "vendor_prebuilt_required"; -/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and at -/// least one of the locked platforms has no patched build: the gem -/// patch's registry serves upstream's own gem for it or does not list it, -/// or the patch it names for that build is not served (still being built, -/// or not granted). A patched build is named and served only once it is +/// gem: `Gemfile.lock` pins the gem as precompiled platform gems and the +/// gem cannot be vendored for them yet: no locked platform has a patched +/// build (the gem patch's registry serves upstream's own gem for each), +/// the registry does not list one of them, the patch it names for a build +/// is not served (still being built, or not granted), or a newer fix has +/// no patched build for a platform the vendored copy of an earlier patch +/// holds one for. A patched build is named and served only once it is /// published, so "not yet" and "never" look the same from here: the /// package is left as it is and the /// run does not fail because of it, whether or not an earlier vendored /// copy stays in force (the detail says which). A re-run vendors it once -/// every locked platform has one. +/// the registry lists a gem for every locked platform, a patched build +/// for at least one of them, and serves each build it names. pub const VENDOR_PREBUILT_PLATFORM_PENDING: &str = "vendor_prebuilt_platform_pending"; /// Whether `code` marks a patch the service does not serve (yet): diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index f35b366e5b..7ea9e8e259 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -274,6 +274,7 @@ pub async fn restore( gem: &format!("{name}@{version}"), from: super::gem::BuildsFrom::Recorded(builds), standing: super::gem::Standing::Wired, + held: Vec::new(), }; super::gem::gem_platform_service_copy( Some(service), diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index 0a72fe5464..54e672eb85 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -126,6 +126,9 @@ pub(crate) struct ServedReference { /// serves them, each with the patch of its patched build if it has /// one; `None` when the reference carries no list. pub gem_builds: Option>, + /// gem: the index URL of that registry, which serves the gem file of + /// each platform it lists at `gems/`. + pub gem_index_url: Option, } impl ServedReference { @@ -141,6 +144,7 @@ impl From for ServedReference { archive: reference.archive, secondary: reference.secondary, gem_builds: reference.gem_builds, + gem_index_url: reference.gem_index_url, } } } diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index d0a237202f..4d602fb719 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -360,10 +360,21 @@ pub struct GemBuildEntry { /// `Gem::Platform#to_s` as `Gemfile.lock` spells it. pub platform: String, /// The patch of this platform gem: the one the tree was unpacked from. + /// Absent for a tree of upstream's own gem ([`Self::is_upstream`]): a + /// locked platform that had no patched build when the gem was + /// vendored. Such a tree is the gem the patch registry lists for the + /// platform, unchanged, with the gemspec that gem carries. It records + /// no patch, no gemspec digest and no files: nothing in it is patched, + /// the copy's file inventory vouches for every byte of it as it does + /// for a patched tree, and its gem digest is what a restore fetches + /// it again by. A reader that requires a patch of every tree fails on + /// the entry, and so never attests the tree as patched. + #[serde(default, skip_serializing_if = "String::is_empty")] pub uuid: String, - /// The sha512 (SRI) of the patched platform `.gem` the tree was - /// unpacked from, as the patch service stated it and the download was - /// verified against. + /// The digest (SRI) of the platform `.gem` the tree was unpacked + /// from, which the download was verified against: the sha512 the + /// patch service states for a patched build, the sha256 the patch + /// registry lists for upstream's gem. #[serde(default, skip_serializing_if = "String::is_empty")] pub gem_integrity: String, /// The sha512 (SRI) of the stub gemspec the tree holds, likewise. @@ -381,6 +392,12 @@ pub struct GemBuildEntry { } impl GemBuildEntry { + /// Whether this is a tree of upstream's own gem, which no patch + /// stands behind ([`Self::uuid`]). + pub fn is_upstream(&self) -> bool { + self.uuid.is_empty() + } + /// The purl of this platform gem of the gem `base_purl`: /// `pkg:gem/@?platform=`. pub fn purl(&self, base_purl: &str) -> String { @@ -404,19 +421,18 @@ impl VendorEntry { /// gem: the files the tree of `platform` is verified against: those of /// that platform's own patch where the ledger records them - /// ([`GemBuildEntry::files`]), else `fallback`, the gem patch's. + /// ([`GemBuildEntry::files`]), else `fallback`, the gem patch's. None + /// for a tree of upstream's own gem, which holds no patched file. pub fn gem_tree_files( &self, platform: &str, fallback: &HashMap, ) -> HashMap { - self.gem_builds - .iter() - .find(|built| built.platform == platform && !built.files.is_empty()) - .map_or_else( - || fallback.clone(), - |built| built.files.clone().into_iter().collect(), - ) + match self.gem_builds.iter().find(|b| b.platform == platform) { + Some(built) if built.is_upstream() => HashMap::new(), + Some(built) if !built.files.is_empty() => built.files.clone().into_iter().collect(), + _ => fallback.clone(), + } } /// gem: the platforms of a copy vendored as precompiled platform gems From e23d017bd71974912774b5434ae7db4623b7a67d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 10:53:34 -0500 Subject: [PATCH 02/28] Report a vendored tree of upstream's gem as hosted mode reports such a build A gem vendored as platform gems is reported per tree. A tree of upstream's own gem (a locked platform with no patched build) now gets what hosted mode gives a locked build the patch registry serves as upstream's gem: - the advisory `skipped` event `gem_upstream_build_kept`, with no `uuid`, which `summary` does not count; `withdrawn: true` and the matching reason where the run put the tree in place of a patched build, and `newlyPatched: true` on a patched build the run put in place of upstream's gem; - one line per such gem under the summary line, in hosted mode's words (`nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)`). A gem whose every tree is a patched build prints no line, as before; - in `vex`, the `affected` statement of that platform gem with what changes it, read from the ledger with no request. The patched trees are attested as before. `vendor --check` fails every tree of a copy that does not verify, the one of upstream's gem included, so a copy that holds upstream's gems alone still fails its check. Telemetry takes such a tree as about no patch. A dry run of `scan --mode vendored` asks the fix's list for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/hosted.rs | 6 +- .../src/commands/scan/vendor_flow.rs | 59 ++- .../socket-patch-cli/src/commands/vendor.rs | 390 ++++++++++++++++-- .../src/commands/vex_sources.rs | 136 ++++-- crates/socket-patch-core/src/vendor/gem.rs | 103 +++-- 5 files changed, 591 insertions(+), 103 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index d384e69b6c..d8d3f6fbb3 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -3945,8 +3945,10 @@ fn format_gem_manifest_edits( /// (`would also be patched for`) of the builds a wet run would put in /// place, and `upstream gem would be back for` of those it would put back. /// `reports` are the run's pins per locked build (`engine::pin_reports`), -/// `skipped` its skips. -fn format_gem_build_lines( +/// `skipped` its skips. Vendored mode says the same of a gem it vendors +/// as platform gems, with a tree in place of a locked build +/// (`crate::commands::vendor::format_vendored_gem_build_lines`). +pub(crate) fn format_gem_build_lines( reports: &[socket_patch_core::hosted::engine::PinReport], skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 83ba3ded8b..50348e138d 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -121,6 +121,24 @@ pub(crate) struct PreviewRow { /// rows, which are then reported once per platform gem, as the wet /// run reports them. pub(crate) gem_builds: Vec, + /// gem: the trees the ledger records for the gem, which say which of + /// [`Self::gem_builds`] the wet run would put in place of another. + pub(crate) gem_recorded: Option>, +} + +impl PreviewRow { + /// What the wet run would report of each tree of [`Self::gem_builds`] + /// (`crate::commands::vendor::gem_build_reports`). `gem_recorded` is + /// what the ledger holds for the gem. + fn gem_reports(&self) -> Vec { + crate::commands::vendor::gem_build_reports( + &self.purl, + &self.uuid, + &self.gem_builds, + self.gem_recorded.as_deref(), + true, + ) + } } /// The vendored dry-run preview, purl-sorted (see [`classify_vendor`]). @@ -202,14 +220,13 @@ impl VendorPreview { } }; let event = event.with_uuid(row.uuid.as_str()); - let events = match row.gem_builds.as_slice() { + let events = match row.gem_reports().as_slice() { [] => vec![event], - builds => { - crate::commands::vendor::gem_build_events(&event, &row.purl, &row.uuid, builds) - } + reports => crate::commands::vendor::gem_build_events(&event, reports), }; for event in events { - env.record(tag_mode(event, Some("vendored"))); + let event = tag_mode(event, Some("vendored")); + crate::commands::vendor::record_gem_build_event(env, event); } env.warnings.extend( row.warnings.iter().map(|w| { @@ -258,10 +275,13 @@ impl VendorPreview { PreviewVerdict::WouldVendor | PreviewVerdict::WouldRevendor { .. } ) }; + // A gem already vendored for its patch is asked about too: its + // copy follows the builds the patch registry lists. + let in_sync = |row: &PreviewRow| matches!(row.verdict, PreviewVerdict::AlreadyVendored); let candidates: Vec<&str> = self .rows .iter() - .filter(|row| would_vendor(row)) + .filter(|row| would_vendor(row) || in_sync(row)) .map(|row| row.purl.as_str()) .collect(); let platform_gems: HashSet = @@ -276,9 +296,13 @@ impl VendorPreview { let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); let state = load_state(&common.cwd).await.unwrap_or_default(); for row in &mut self.rows { - if !would_vendor(row) || !platform_gems.contains(&row.purl) { + let vendored = in_sync(row); + if !(would_vendor(row) || vendored) || !platform_gems.contains(&row.purl) { continue; } + row.gem_recorded = lookup_entry(&state.entries, &row.purl) + .filter(|entry| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .map(|entry| entry.gem_builds.clone()); let asked = socket_patch_core::vendor::gem::preview_locked_builds( &common.cwd, &row.purl, @@ -290,9 +314,16 @@ impl VendorPreview { let (code, detail) = match asked { None => continue, Some(LockedBuildsPreview::Vendor(builds)) => { + // The wet run vendors the copy again with these. + if vendored { + row.verdict = PreviewVerdict::WouldVendor; + } row.gem_builds = builds; continue; } + // What the wet run leaves a vendored copy with is the + // copy as it is. + Some(LockedBuildsPreview::Refused { .. }) if vendored => continue, Some(LockedBuildsPreview::Refused { code, detail }) => (code, detail), }; // As the vendor loop settles the backend's refusal: an older @@ -317,6 +348,14 @@ impl VendorPreview { } } + /// The lines of the gems the wet run would vendor as platform gems + /// with upstream's own gem for a locked platform, as its vendor step + /// prints them (`format_vendored_gem_build_lines`). + fn gem_build_lines(&self) -> Vec { + let reports: Vec<_> = self.rows.iter().flat_map(PreviewRow::gem_reports).collect(); + crate::commands::vendor::format_vendored_gem_build_lines(&reports, true) + } + /// The uuids of the rows the wet run would vendor or already holds: /// every row it would not refuse. pub(crate) fn landing_uuids(&self) -> HashSet<&str> { @@ -357,6 +396,11 @@ impl VendorPreview { /// --dry-run` so the two cannot drift. Callers gate it on `--silent`. pub(crate) fn print_human(&self) { println!("{}", self.dry_run_line()); + let stdout_width = + crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in self.gem_build_lines() { + println!("{}", crate::ui::wrap_line(&line, stdout_width)); + } for row in &self.rows { if matches!(row.verdict, PreviewVerdict::AlreadyVendored) { eprintln!( @@ -532,6 +576,7 @@ async fn preview_vendor_with( warnings, hosted: false, gem_builds: Vec::new(), + gem_recorded: None, } }) .collect(); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index f643abb22d..056fd052b7 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -25,6 +25,9 @@ use futures_util::StreamExt; use socket_patch_core::api::client::get_api_client_with_overrides; use socket_patch_core::constants::SOCKET_DIR; use socket_patch_core::crawlers::{CrawlerOptions, Ecosystem}; +use socket_patch_core::hosted::engine::{ + gem_upstream_build_kept_detail, PinReport, GEM_UPSTREAM_BUILD_KEPT, +}; use socket_patch_core::manifest::operations::{manifest_exists, read_manifest, write_manifest}; use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use socket_patch_core::patch::apply::{verify_file_patch, PatchSources}; @@ -819,35 +822,158 @@ const GEM_FIX_DETAIL: &str = "gemFix"; /// `details` key of those events: the platform of the event's gem. const GEM_PLATFORM_DETAIL: &str = "platform"; -/// `event`, the outcome of a gem vendored as platform gems, once per tree -/// of `builds`: each names that platform gem -/// (`pkg:gem/@?platform=`) and its own patch, -/// and `details` ties it to the gem's patch `fix`. -pub(crate) fn gem_build_events( - event: &PatchEvent, +/// What a run reports of each tree of a gem vendored as platform gems +/// (`builds`, of the gem `base_purl` under the gem's patch `fix`), as +/// hosted mode reports the locked builds of a pin ([`PinReport`]): a +/// patched build under its own patch, a tree of upstream's own gem under +/// none. `wrote`: the run put `builds` in place (or is a dry run of one +/// that would), over the trees the ledger recorded for the gem before +/// (`prior`). A patched build the ledger did not hold is then +/// `newly_patched`, and a tree of upstream's gem where it held a patched +/// build is `withdrawn`. +pub(crate) fn gem_build_reports( base_purl: &str, fix: &str, builds: &[vendor::GemBuildEntry], -) -> Vec { + prior: Option<&[vendor::GemBuildEntry]>, + wrote: bool, +) -> Vec { builds .iter() .map(|built| { - let mut event = event.clone(); - event.purl = Some(built.purl(base_purl)); - event.uuid = Some(built.uuid.clone()); - let mut details = event + let before = + prior.and_then(|prior| prior.iter().find(|b| b.platform == built.platform)); + let was_patched = before.is_some_and(|before| !before.is_upstream()); + PinReport { + purl: built.purl(base_purl), + uuid: (!built.is_upstream()).then(|| built.uuid.clone()), + gem_fix: Some(fix.to_string()), + platform: Some(built.platform.clone()), + newly_patched: wrote && !built.is_upstream() && !was_patched, + withdrawn: wrote && built.is_upstream() && was_patched, + } + }) + .collect() +} + +/// `event`, the outcome of a gem vendored as platform gems, once per tree +/// of the gem (`reports`, see [`gem_build_reports`]), as hosted mode +/// reports a pin's locked builds. A patched build is the gem's event under +/// that platform gem (`pkg:gem/@?platform=`) and +/// its own patch, with `newlyPatched: true` where this run put it in place +/// of upstream's gem. A tree of upstream's own gem is the advisory +/// `skipped` event hosted mode records for such a build +/// ([`GEM_UPSTREAM_BUILD_KEPT`]), with no `uuid` and `withdrawn: true` +/// where this run put it in place of a patched build: `summary` does not +/// count it ([`record_gem_build_event`]). Only where the gem's event is a +/// failure (the copy did not verify) does such a tree share it. `details` +/// ties each event to the gem's patch. +pub(crate) fn gem_build_events(event: &PatchEvent, reports: &[PinReport]) -> Vec { + reports + .iter() + .map(|report| { + let platform = report.platform.as_deref().unwrap_or_default(); + let mut built = match &report.uuid { + Some(_) => event.clone(), + None if event.action == PatchAction::Failed => event.clone(), + None => PatchEvent::new(PatchAction::Skipped, report.purl.as_str()).with_reason( + GEM_UPSTREAM_BUILD_KEPT, + gem_upstream_build_kept_detail(platform, report.withdrawn), + ), + }; + built.purl = Some(report.purl.clone()); + built.uuid = report.uuid.clone(); + let mut details = built .details .take() .filter(serde_json::Value::is_object) .unwrap_or_else(|| serde_json::json!({})); - details[GEM_FIX_DETAIL] = serde_json::json!(fix); - details[GEM_PLATFORM_DETAIL] = serde_json::json!(built.platform); - event.details = Some(details); - event + details[GEM_FIX_DETAIL] = serde_json::json!(report.gem_fix); + details[GEM_PLATFORM_DETAIL] = serde_json::json!(platform); + if report.newly_patched { + details["newlyPatched"] = serde_json::json!(true); + } + if report.withdrawn { + details["withdrawn"] = serde_json::json!(true); + } + built.details = Some(details); + built }) .collect() } +/// Record one event of [`gem_build_events`]: `summary` counts each but +/// the advisory one of a tree of upstream's gem, where nothing was +/// skipped (as hosted mode records it). +pub(crate) fn record_gem_build_event(env: &mut Envelope, event: PatchEvent) { + if event.error_code.as_deref() == Some(GEM_UPSTREAM_BUILD_KEPT) { + env.events.push(event); + } else { + env.record(event); + } +} + +/// The run's reports of the gems it vendored as platform gems, read back +/// from the events of [`gem_build_events`] in `env`: one per tree a run +/// holds in place (or a dry run would). +fn gem_build_reports_of(env: &Envelope) -> Vec { + let flag = |details: &serde_json::Value, key: &str| details[key].as_bool() == Some(true); + env.events + .iter() + .filter(|event| { + matches!(event.action, PatchAction::Applied | PatchAction::Verified) + || matches!( + event.error_code.as_deref(), + Some("already_vendored" | GEM_UPSTREAM_BUILD_KEPT) + ) + }) + .filter_map(|event| { + let details = event.details.as_ref()?; + Some(PinReport { + purl: event.purl.clone()?, + uuid: event.uuid.clone(), + gem_fix: Some(details.get(GEM_FIX_DETAIL)?.as_str()?.to_string()), + platform: Some(details.get(GEM_PLATFORM_DETAIL)?.as_str()?.to_string()), + newly_patched: flag(details, "newlyPatched"), + withdrawn: flag(details, "withdrawn"), + }) + }) + .collect() +} + +/// Which trees are patched of each gem vendored as platform gems that +/// holds upstream's own gem for a locked platform, or that this run +/// brought in step with the builds the patch registry lists: hosted +/// mode's line for such a gem, one per gem +/// (`crate::commands::scan::hosted::format_gem_build_lines`). A gem whose +/// every tree is a patched build says nothing here, as before. +pub(crate) fn format_vendored_gem_build_lines(reports: &[PinReport], dry_run: bool) -> Vec { + let mut fixes: Vec<&str> = Vec::new(); + for report in reports { + if let Some(fix) = report.gem_fix.as_deref().filter(|fix| !fixes.contains(fix)) { + fixes.push(fix); + } + } + let mut said: Vec = Vec::new(); + for fix in fixes { + let of_gem = |report: &&PinReport| report.gem_fix.as_deref() == Some(fix); + let builds: Vec<&PinReport> = reports.iter().filter(of_gem).collect(); + let patched = |build: &&&PinReport| build.uuid.is_some(); + let gained = builds + .iter() + .filter(patched) + .any(|build| build.newly_patched) + && builds + .iter() + .filter(patched) + .any(|build| !build.newly_patched); + if gained || builds.iter().any(|build| build.uuid.is_none()) { + said.extend(builds.into_iter().cloned()); + } + } + crate::commands::scan::hosted::format_gem_build_lines(&said, &[], dry_run) +} + /// How many of the events `counted` picks stand for a gem that an earlier /// one of them already stands for ([`GEM_FIX_DETAIL`]): what a count of /// events is over a count of packages. @@ -1664,9 +1790,15 @@ async fn run_check(args: &VendorArgs) -> i32 { // A gem vendored as platform gems: the verdict of its directory, // once per platform gem and under that gem's own patch. if entry.ecosystem == "gem" && !entry.gem_builds.is_empty() { - for event in gem_build_events(&event, &entry.base_purl, &entry.uuid, &entry.gem_builds) - { - env.record(event); + let reports = gem_build_reports( + &entry.base_purl, + &entry.uuid, + &entry.gem_builds, + None, + false, + ); + for event in gem_build_events(&event, &reports) { + record_gem_build_event(&mut env, event); } } else { env.record(event); @@ -2918,7 +3050,9 @@ fn vendor_outcomes( crate::telemetry_outcomes::patch_outcomes( env.events .iter() - .filter(|event| event.error_code.as_deref() != Some("vendor_orphan_removed")), + .filter(|event| event.error_code.as_deref() != Some("vendor_orphan_removed")) + // A tree of upstream's own gem is about no patch. + .filter(|event| event.error_code.as_deref() != Some(GEM_UPSTREAM_BUILD_KEPT)), MODE_VENDORED, crate::telemetry_outcomes::uuid_lookup(uuids), ) @@ -4497,16 +4631,39 @@ pub(crate) async fn vendor_records_reusing( // below: the ones this run wrote, or a dry run found the wet // run would write, else the ones the ledger records for this // patch (an in-sync re-run writes none). - let gem_builds: Vec = match &outcome { + // What the ledger held for the gem before this run says which + // of them the run put in place. + let gem_recorded: Option> = + lookup_entry(&state.entries, candidate) + .filter(|entry| entry.ecosystem == "gem" && !entry.gem_builds.is_empty()) + .map(|entry| entry.gem_builds.clone()); + let (gem_builds, gem_wrote): (Vec, bool) = match &outcome { Some(VendorOutcome::Done { entry: Some(entry), .. - }) => entry.gem_builds.clone(), - _ if !gem_preview.is_empty() => gem_preview, - _ => lookup_entry(&state.entries, candidate) - .filter(|entry| entry.ecosystem == "gem" && entry.uuid == record.uuid) - .map(|entry| entry.gem_builds.clone()) - .unwrap_or_default(), + }) => (entry.gem_builds.clone(), true), + _ if !gem_preview.is_empty() => (gem_preview, true), + _ => { + let recorded = lookup_entry(&state.entries, candidate) + .filter(|entry| entry.ecosystem == "gem" && entry.uuid == record.uuid) + .map(|entry| entry.gem_builds.clone()); + (recorded.unwrap_or_default(), false) + } }; + let gem_reports = gem_build_reports( + candidate, + &record.uuid, + &gem_builds, + gem_recorded.as_deref(), + gem_wrote, + ); + // The run puts other trees in place than the ledger records: + // the list of the gem's fix names another build for a locked + // platform (a patched build published since, or upstream's + // gem where the patched build was withdrawn). + let gem_moved = gem_reports + .iter() + .any(|report| report.newly_patched || report.withdrawn) + && gem_recorded.is_some(); match outcome { None => { env.record( @@ -4591,6 +4748,7 @@ pub(crate) async fn vendor_records_reusing( // ledger recording this exact patch is the tell. let dry_previewed_in_sync = common.dry_run && event.action == PatchAction::Verified + && !gem_moved && lookup_entry(&state.entries, candidate) .is_some_and(|e| e.uuid == record.uuid); if dry_previewed_in_sync { @@ -4615,10 +4773,9 @@ pub(crate) async fn vendor_records_reusing( let per_build = matches!(event.action, PatchAction::Applied | PatchAction::Verified) || in_sync; - if per_build && !gem_builds.is_empty() { - for event in gem_build_events(&event, candidate, &record.uuid, &gem_builds) - { - env.record(event); + if per_build && !gem_reports.is_empty() { + for event in gem_build_events(&event, &gem_reports) { + record_gem_build_event(env, event); } } else { env.record(event); @@ -4630,7 +4787,13 @@ pub(crate) async fn vendor_records_reusing( // "vendored X from the patch service" on a package // this run left untouched would contradict the // "already vendored" count: JSON only. - if in_sync && w.code == "vendor_prebuilt_downloaded" { + // And a copy vendored again because the fix's list + // names other builds is said by the gem's own line + // (`format_vendored_gem_build_lines`), not as a + // warning: nothing was wrong with the copy. + let quiet = (in_sync && w.code == "vendor_prebuilt_downloaded") + || (gem_moved && w.code == "vendor_artifact_rebuilt"); + if quiet { push_advisory_event(env, candidate, w); } else { record_warning(env, candidate, w, common); @@ -5005,6 +5168,12 @@ fn print_vendor_closing( } let tally = VendorTally::from_envelope(env, common.dry_run, dry_in_sync); println!("{}", format_vendor_summary(common.dry_run, &tally)); + // For a gem vendored as platform gems that holds upstream's own gem + // for a locked platform: which of its platforms are patched. + let stdout_width = crate::ui::attended(crate::ui::Stream::Stdout).then(crate::ui::stdout_width); + for line in format_vendored_gem_build_lines(&gem_build_reports_of(env), common.dry_run) { + println!("{}", crate::ui::wrap_line(&line, stdout_width)); + } if let Some(lines) = closing_lines { let vendored: Vec<&str> = env .events @@ -8925,6 +9094,157 @@ mod ui_format_tests { .collect() } + /// [`gem_build_events`] of trees the ledger records, as a run that + /// wrote none of them reports them. + fn build_events( + event: &PatchEvent, + purl: &str, + fix: &str, + builds: &[vendor::GemBuildEntry], + ) -> Vec { + gem_build_events(event, &gem_build_reports(purl, fix, builds, None, false)) + } + + /// A copy that holds upstream's own gem for a locked platform is + /// reported as hosted mode reports such a pin. The patched build is + /// the gem's event under its own patch, and the only one `summary` + /// counts. The tree of upstream's gem is the advisory event with no + /// patch, which says why it is there. The run's one line names both, + /// and telemetry takes the tree of upstream's gem as about no patch. + #[test] + fn a_tree_of_upstreams_gem_is_an_uncounted_event_and_a_line() { + const GEM: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut mixed = nokogiri_builds(); + mixed[1].uuid.clear(); + let record = |event: PatchEvent, reports: &[PinReport]| { + let mut env = Envelope::new(Command::Vendor); + for event in gem_build_events(&event, reports) { + record_gem_build_event(&mut env, event); + } + env + }; + let lines = |env: &Envelope, dry_run: bool| { + format_vendored_gem_build_lines(&gem_build_reports_of(env), dry_run) + }; + + // A first vendor. + let fresh = gem_build_reports(GEM, "source", &mixed, None, true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &fresh); + assert_eq!( + serde_json::to_value(&env.events).unwrap(), + serde_json::json!([ + { + "action": "applied", + "purl": "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin", + "uuid": "darwin", + "details": { + "gemFix": "source", "platform": "arm64-darwin", "newlyPatched": true + } + }, + { + "action": "skipped", + "purl": "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu", + "reason": "the patch registry serves upstream's own gem for \ + x86_64-linux-gnu: no patched build yet", + "errorCode": "gem_upstream_build_kept", + "details": { "gemFix": "source", "platform": "x86_64-linux-gnu" } + } + ]) + ); + assert_eq!((env.summary.applied, env.summary.skipped), (1, 0)); + assert_eq!(vendored_packages(&env), 1); + const KEPT: &str = "nokogiri 1.18.10: patched for arm64-darwin; upstream gem kept for \ + x86_64-linux-gnu (no patched build yet)"; + assert_eq!(lines(&env, false), [KEPT]); + let uuids = HashMap::from([(GEM.to_string(), "source".to_string())]); + let told: Vec = vendor_outcomes(&env, &uuids) + .into_iter() + .map(|outcome| outcome.uuid) + .collect(); + assert_eq!( + told, + ["darwin"], + "the tree of upstream's gem names no patch" + ); + + // A dry run of it, and a later run that finds the copy in step. + let env = record(PatchEvent::new(PatchAction::Verified, GEM), &fresh); + assert_eq!( + lines(&env, true), + [ + "nokogiri 1.18.10: would be patched for arm64-darwin; upstream gem kept for \ + x86_64-linux-gnu (no patched build yet)" + ] + ); + let in_step = gem_build_reports(GEM, "source", &mixed, Some(&mixed), false); + let already = + PatchEvent::new(PatchAction::Skipped, GEM).with_reason("already_vendored", "in sync"); + let env = record(already.clone(), &in_step); + assert_eq!((env.summary.applied, env.summary.skipped), (0, 1)); + assert_eq!(lines(&env, false), [KEPT]); + + // The linux build is published: the run that takes it says so. + let both = nokogiri_builds(); + let gained = gem_build_reports(GEM, "source", &both, Some(&mixed), true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &gained); + assert_eq!(env.summary.applied, 2); + assert_eq!( + env.events[1].details, + Some(serde_json::json!({ + "gemFix": "source", "platform": "x86_64-linux-gnu", "newlyPatched": true + })) + ); + assert_eq!( + env.events[0].details.as_ref().unwrap().get("newlyPatched"), + None + ); + assert_eq!( + lines(&env, false), + [ + "nokogiri 1.18.10: now also patched for x86_64-linux-gnu; already patched for \ + arm64-darwin" + ] + ); + // And it is withdrawn again. + let withdrawn = gem_build_reports(GEM, "source", &mixed, Some(&both), true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &withdrawn); + assert_eq!(env.summary.applied, 1); + assert_eq!( + env.events[1].reason.as_deref(), + Some( + "the patch registry serves upstream's own gem for x86_64-linux-gnu: its patched \ + build was withdrawn" + ) + ); + assert_eq!( + lines(&env, false), + [ + "nokogiri 1.18.10: patched for arm64-darwin; upstream gem back for \ + x86_64-linux-gnu (its patched build was withdrawn)" + ] + ); + + // A gem whose every tree is a patched build says no line, as + // before, in step or freshly vendored. + let all = gem_build_reports(GEM, "source", &both, Some(&both), false); + assert!(lines(&record(already, &all), false).is_empty()); + let all = gem_build_reports(GEM, "source", &both, None, true); + let env = record(PatchEvent::new(PatchAction::Applied, GEM), &all); + assert!(lines(&env, false).is_empty()); + + // `vendor --check`: a copy that fails its check fails for every + // tree, the one of upstream's gem included. + let checked = gem_build_reports(GEM, "source", &mixed, None, false); + let failed = + PatchEvent::new(PatchAction::Failed, GEM).with_error("vendor_check_failed", "x"); + let env = record(failed, &checked); + assert_eq!(env.summary.failed, 2); + assert_eq!(env.events[1].uuid, None); + let verified = PatchEvent::new(PatchAction::Verified, GEM); + let env = record(verified, &checked); + assert_eq!((env.summary.verified, env.events.len()), (1, 2)); + } + /// The outcome of a gem vendored as platform gems becomes one event /// per platform gem: that gem's purl, its own patch, and details that /// name the gem's patch and the platform beside whatever the outcome @@ -8937,7 +9257,7 @@ mod ui_format_tests { ) .with_reason("already_vendored", "in sync") .with_details(serde_json::json!({ "kept": true })); - let events = gem_build_events( + let events = build_events( &outcome, "pkg:gem/nokogiri@1.18.10?platform=ruby", "source", @@ -8975,7 +9295,7 @@ mod ui_format_tests { fn tally_counts_a_gem_vendored_as_platform_gems_once() { let builds = |env: &mut Envelope, event: &PatchEvent| { let purl = "pkg:gem/nokogiri@1.18.10?platform=ruby"; - for event in gem_build_events(event, purl, "source", &nokogiri_builds()) { + for event in build_events(event, purl, "source", &nokogiri_builds()) { env.record(event); } }; @@ -9019,7 +9339,7 @@ mod ui_format_tests { // Two gems vendored as platform gems are two packages. let mut two = Envelope::new(Command::Vendor); builds(&mut two, &event(PatchAction::Applied)); - for event in gem_build_events( + for event in build_events( &PatchEvent::new(PatchAction::Applied, "pkg:gem/ffi@1.17.0"), "pkg:gem/ffi@1.17.0", "another", @@ -9095,7 +9415,7 @@ mod ui_format_tests { .with_reason("already_vendored", "in sync"), ); let since = env.events.len(); - for event in gem_build_events( + for event in build_events( &PatchEvent::new(PatchAction::Applied, gem), gem, "source", diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index a8d392eb6a..37eb3ce881 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -518,7 +518,11 @@ fn gate_unattested( /// with the vulnerabilities of the gem patch's record: the fix is the same /// in every one of them. Read from the plan alone, with no request: the /// ledger is what says which patch built which tree. An entry that names -/// no patch for its trees is attested as the gem itself. +/// no patch for its trees is attested as the gem itself. A tree the +/// ledger records as upstream's own gem (a locked platform that had no +/// patched build when the gem was vendored) is stated `affected`, like a +/// hosted build on upstream's gem, with what changes that +/// ([`upstream_tree_action`]). /// /// A gem a lock takes from its patch registry as platform builds is one /// hosted pin, judged as one. The registry serves a patched build for some @@ -561,6 +565,21 @@ pub(crate) struct GemBuildInfo { pub unshown: Option, } +/// The action statement of a tree of upstream's own gem in a copy +/// vendored as platform gems +/// ([`socket_patch_core::vendor::GemBuildEntry::is_upstream`]): why an +/// install on `platform` is without the gem's patch `gem_fix`, and what +/// changes that. The ledger says what was vendored, not what the patch +/// registry lists today. +fn upstream_tree_action(platform: &str, gem_fix: &str) -> String { + format!( + "The vendored copy holds upstream's own gem for {platform}: the patch registry had no \ + patched build of this gem for it when the copy was vendored, so an install on that \ + platform is without Socket patch {gem_fix}. Run `socket-patch scan --mode vendored` \ + again later: the copy takes the patched build once it is published." + ) +} + /// The action statement of a hosted gem build on upstream's gem /// ([`GemBuildState::Upstream`]): why the lock installs it without the /// gem's patch `gem_fix`, and what changes that. @@ -618,32 +637,42 @@ impl GemBuildView { let mut builds = BTreeMap::new(); for (key, entry, record) in vendored { view.patches.remove(key); - let purls: Vec = entry - .gem_builds - .iter() - .map(|built| { - let purl = built.purl(&entry.base_purl); - // A purl the view already attests keeps its own record. - view.patches - .entry(purl.clone()) - .or_insert_with(|| PatchRecord { + let mut patched = Vec::new(); + for built in &entry.gem_builds { + let purl = built.purl(&entry.base_purl); + let upstream = built.is_upstream(); + // A purl the view already attests keeps its own record. + view.patches + .entry(purl.clone()) + .or_insert_with(|| match upstream { + // A tree of upstream's own gem, named for the + // document alone: what it is affected by, as the + // record of the gem's patch states it. No copy is + // checked against this record. + true => record.clone(), + false => PatchRecord { uuid: built.uuid.clone(), files: entry.gem_tree_files(&built.platform, &record.files), ..record.clone() - }); - builds.insert( - purl.clone(), - GemBuildInfo { - gem_fix: entry.uuid.clone(), - platform: Some(built.platform.clone()), - kept_upstream: false, - unshown: None, }, - ); - purl - }) - .collect(); - platform_gems.insert(key.clone(), purls); + }); + builds.insert( + purl.clone(), + GemBuildInfo { + gem_fix: entry.uuid.clone(), + platform: Some(built.platform.clone()), + kept_upstream: upstream, + unshown: None, + }, + ); + match upstream { + true => { + not_patched.push((purl, upstream_tree_action(&built.platform, &entry.uuid))) + } + false => patched.push(purl), + } + } + platform_gems.insert(key.clone(), patched); } for (key, gem, record) in hosted { view.patches.remove(key); @@ -2465,6 +2494,67 @@ mod tests { ); } + /// A tree of upstream's own gem in a vendored copy is never among the + /// gem's patched builds. The document names it, under the gem's patch + /// and with its vulnerabilities, as a build to state `affected`, with + /// what changes that; the patched tree is attested as before. + #[test] + fn a_vendored_tree_of_upstreams_gem_is_stated_affected() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + let view = builds.view(); + assert_eq!(view.patches[darwin].uuid, DARWIN); + assert_eq!( + view.patches[linux], + record(U1), + "named under the gem's patch" + ); + assert!(!view.patches.contains_key(key)); + + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert_eq!(vendored, [darwin], "only the patched tree is attested"); + assert_eq!( + builds.not_patched(), + [( + linux.to_string(), + format!( + "The vendored copy holds upstream's own gem for x86_64-linux-gnu: the patch \ + registry had no patched build of this gem for it when the copy was \ + vendored, so an install on that platform is without Socket patch {U1}. Run \ + `socket-patch scan --mode vendored` again later: the copy takes the patched \ + build once it is published." + ) + )] + ); + let info = &builds.builds()[linux]; + assert!(info.kept_upstream && info.unshown.is_none()); + assert_eq!(info.gem_fix, U1); + assert!(!builds.builds()[darwin].kept_upstream); + + // A copy that holds upstream's gems alone attests no build. + let none = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", ""), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + let builds = GemBuildView::of(&none).expect("a gem vendored as platform gems"); + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert!(vendored.is_empty()); + assert_eq!(builds.not_patched().len(), 2); + } + /// The gem itself stays the attested package where the ledger does not /// say which patch built which tree: an entry that names no tree, one /// whose trees are another patch's than the view's record, and one diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 595521e629..f5cec68d4c 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -940,28 +940,41 @@ async fn listing_moved( copy_rel: &str, trees: &PlatformTrees<'_>, ) -> bool { - let Some(cfg) = service.filter(|cfg| cfg.service_enabled()) else { - return false; - }; + moved_sources(project_root, service, &record.uuid, name, copy_rel, trees) + .await + .is_some() +} + +/// [`listing_moved`] for the copy of the patch `uuid`: what the list +/// names for each locked platform now, where that is not what the ledger +/// records. +async fn moved_sources( + project_root: &Path, + service: Option<&VendorServiceConfig>, + uuid: &str, + name: &str, + copy_rel: &str, + trees: &PlatformTrees<'_>, +) -> Option> { + let cfg = service.filter(|cfg| cfg.service_enabled())?; if service_offline_conflict(service).is_some() { - return false; + return None; } let BuildsFrom::Locked(platforms) = &trees.from else { - return false; - }; - let Some(entry) = recorded_copy(project_root, &record.uuid, copy_rel).await else { - return false; - }; - let Ok(sources) = locked_build_sources(cfg, &record.uuid, name, trees, platforms).await else { - return false; + return None; }; - sources.iter().any(|source| { + let entry = recorded_copy(project_root, uuid, copy_rel).await?; + let sources = locked_build_sources(cfg, uuid, name, trees, platforms) + .await + .ok()?; + let moved = sources.iter().any(|source| { let recorded = entry .gem_builds .iter() .find(|b| b.platform == source.platform); !recorded.is_some_and(|built| built.uuid.eq_ignore_ascii_case(&source.uuid)) - }) + }); + moved.then_some(sources) } /// The platforms whose patched build the vendored copy of ANOTHER patch @@ -3091,10 +3104,11 @@ async fn preview_platform_builds( /// ([`preview_locked_builds`]). #[derive(Debug)] pub enum LockedBuildsPreview { - /// Every locked platform has a patched build, and the service serves - /// the patch of each: the tree of each, in lock order, with the patch - /// it is vendored from. Nothing was downloaded, so the entries carry - /// no digest. + /// The registry lists a gem for every locked platform and a patched + /// build for at least one, and the service serves the patch of each + /// patched build: the tree of each platform, in lock order, with the + /// patch it is vendored from (none for a tree of upstream's own gem). + /// Nothing was downloaded, so the entries carry no digest. Vendor(Vec), /// What the backend refuses the gem with before it downloads /// anything: the skip of a gem with a locked platform that has no @@ -3120,11 +3134,18 @@ pub enum LockedBuildsPreview { /// the skip of a locked platform with no patched build says that the gem /// stays hosted, as the wet run's does ([`vendor_gem_previewing`]). /// +/// A lock already wired to this patch's copy is judged by the list +/// alone: where it names another build for a locked platform than the +/// tree the ledger records (a patched build published since, upstream's +/// gem where the patched build was withdrawn), and serves each patched +/// build it names, the wet run vendors the copy again with those +/// ([`listing_moved`]). +/// /// `None` for a gem this does not judge, so the caller's own verdict /// stands: one the lock does not name as platform gems, one whose lock is -/// already wired to this patch's copy (only the copy tells what a run -/// does with it), one a hub of a Bazel workspace takes, and a lock the -/// edit fails on. +/// already wired to this patch's copy and holds what the list names (only +/// the copy tells what a run does with it), one a hub of a Bazel +/// workspace takes, and a lock the edit fails on. pub async fn preview_locked_builds( project_root: &Path, purl: &str, @@ -3144,12 +3165,33 @@ pub async fn preview_locked_builds( Ok(prelude) => prelude, Err(outcome) => return refusal(outcome), }; - if prelude.platforms.is_empty() - || prelude.lock_wired - || bazel::takes(&prelude, project_root, uuid).await - { + if prelude.platforms.is_empty() || bazel::takes(&prelude, project_root, uuid).await { return None; } + let builds_of = |sources: Vec| { + let build = |source: BuildSource| GemBuildEntry { + platform: source.platform, + uuid: source.uuid, + gem_integrity: String::new(), + gemspec_integrity: String::new(), + files: BTreeMap::new(), + }; + LockedBuildsPreview::Vendor(sources.into_iter().map(build).collect()) + }; + if prelude.lock_wired { + let label = format!("{}@{}", prelude.name, prelude.version); + let trees = PlatformTrees { + gem: &label, + from: BuildsFrom::Locked(&prelude.platforms), + standing: Standing::Wired, + held: Vec::new(), + }; + let (name, copy_rel) = (prelude.name.as_str(), prelude.copy_rel.as_str()); + let sources = moved_sources(project_root, service, uuid, name, copy_rel, &trees).await?; + let cfg = service.filter(|cfg| cfg.service_enabled())?; + let served = served_builds(cfg, name, &trees, &sources).await; + return served.is_ok().then(|| builds_of(sources)); + } let standing = match hosted { true => Standing::Hosted, false => match gem_edits(purl, &prelude) { @@ -3185,18 +3227,7 @@ pub async fn preview_locked_builds( if let Err(outcome) = served_builds(cfg, &prelude.name, &trees, &sources).await { return refusal(*outcome); } - Some(LockedBuildsPreview::Vendor( - sources - .into_iter() - .map(|source| GemBuildEntry { - platform: source.platform, - uuid: source.uuid, - gem_integrity: String::new(), - gemspec_integrity: String::new(), - files: BTreeMap::new(), - }) - .collect(), - )) + Some(builds_of(sources)) } /// Acquire a verified service copy without replacing the prior copy on From 09da5fb877ae5e30d1495e9ff25b9fd93b7658d9 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 10:59:33 -0500 Subject: [PATCH 03/28] Cover a gem vendored with upstream's gem for a platform at the CLI level The stand-in patch service of the platform-gem tests now serves upstream's own gem for a platform it lists with no patched build, from the gem patch's registry and with the sha256 the list names. - A lock with one patched platform and one that has none: vendored, the one line, the counted and the advisory event, the ledger, a later run in step (one request), `vendor --check` and a change to the upstream tree, an offline `vex` (the patched build attested, the other stated `affected`), and revert byte for byte. - A later run that takes a published build and one that follows a withdrawal, each with its dry run first. - Every dry run (`vendor`, `scan`, `get`) says what the wet run does. - A takeover of a hosted gem with upstream's gem for a platform, by a scan and by an eject. - The tests of a gem that is left alone or stays hosted because of one platform now use a build whose patch is still being built, and a lock none of whose platforms has a patched build keeps the one-line skip. Co-Authored-By: Claude Fable 5.2 --- .../vendor/vendor_gem_platform_builds_e2e.rs | 661 ++++++++++++++++-- 1 file changed, 617 insertions(+), 44 deletions(-) diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index dd5ab18312..2aa6fdeeaf 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -94,6 +94,52 @@ fn platform_gem(platform: &str) -> Vec { ]) } +/// The gemspec upstream's gem for `platform` carries (its `metadata.gz`, +/// as YAML). +fn upstream_gemspec(platform: &str) -> String { + format!( + "--- !ruby/object:Gem::Specification\nname: {NAME}\nversion: \ + !ruby/object:Gem::Version\n version: {VERSION}\nplatform: {platform}\nauthors:\n- \ + Socket\nextensions: []\nrequire_paths:\n- lib\nsummary: a synthetic fixture gem\n" + ) +} + +/// Upstream's own gem of `platform`, which has no patched build: the +/// pristine Ruby file, upstream's binary, and its gemspec. +fn upstream_gem(platform: &str) -> Vec { + let gz = |bytes: &[u8]| { + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + std::io::Write::write_all(&mut gz, bytes).unwrap(); + gz.finish().unwrap() + }; + let binary = format!("upstream's {platform}"); + let data = make_gem(&[(LIB, PRISTINE), (SO, binary.as_bytes())]); + // `make_gem` wraps the data archive alone: take it out and put the + // gemspec beside it, as a gem holds them. + let mut inner = tar::Archive::new(data.as_slice()); + let mut data_tar_gz = Vec::new(); + for entry in inner.entries().unwrap() { + std::io::Read::read_to_end(&mut entry.unwrap(), &mut data_tar_gz).unwrap(); + } + let mut gem = tar::Builder::new(Vec::new()); + let metadata = gz(upstream_gemspec(platform).as_bytes()); + for (name, bytes) in [("metadata.gz", &metadata), ("data.tar.gz", &data_tar_gz)] { + let mut header = tar::Header::new_gnu(); + header.set_size(bytes.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + gem.append_data(&mut header, name, bytes.as_slice()) + .unwrap(); + } + gem.into_inner().unwrap() +} + +/// Where the registry of the gem patch `uuid` serves upstream's gem of +/// `platform`. +fn upstream_route(uuid: &str, platform: &str) -> String { + format!("/patch-registry/gem/tok/{uuid}/s/4/gems/{NAME}-{VERSION}-{platform}.gem") +} + fn stub(platform: &str) -> Vec { format!( "Gem::Specification.new do |s|\n s.name = \"{NAME}\"\n s.version = \"{VERSION}\"\n \ @@ -168,8 +214,15 @@ fn build_files(platform: &str) -> serde_json::Value { }) } +/// A patch service where `linux` has a patched build and the patch of +/// darwin's build, which the gem patch's list names, is still being built. +async fn service_still_building_darwin() -> MockServer { + service_of(UUID, &[(DARWIN, Some("pending_build")), (LINUX, None)], &[]).await +} + /// A patch service where the platforms of `patched` have a patched build -/// and those of `pass_through` are listed as upstream's own gem. +/// and those of `pass_through` are listed as upstream's own gem, which the +/// gem patch's registry serves. async fn service(patched: &[&'static str], pass_through: &[&'static str]) -> MockServer { let granted: Vec<(&'static str, Option<&'static str>)> = patched.iter().map(|platform| (*platform, None)).collect(); @@ -250,9 +303,15 @@ async fn service_of( } } for platform in pass_through { + let gem = upstream_gem(platform); gem_builds.push(serde_json::json!({ - "platform": platform, "gemChecksumSha256": "ab".repeat(32), "patchUuid": null + "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": null })); + Mock::given(method("GET")) + .and(wm_path(upstream_route(uuid, platform))) + .respond_with(ResponseTemplate::new(200).set_body_bytes(gem)) + .mount(&server) + .await; } gem_builds.sort_by_key(|build| build["platform"].as_str().map(str::to_string)); let ruby_gem = make_gem(&[(LIB, &stamped(uuid))]); @@ -345,7 +404,7 @@ async fn downloads(server: &MockServer) -> Vec { let mut paths: Vec = requests .iter() .map(|request| request.url.path().to_string()) - .filter(|path| path.starts_with("/patch/gem/")) + .filter(|path| path.starts_with("/patch/gem/") || path.contains("/gems/")) .collect(); paths.sort(); paths @@ -591,7 +650,11 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { stdout.contains("1 package is already vendored; nothing to do."), "the gem is one package:\n{stdout}\n{stderr}" ); - assert_eq!(server.received_requests().await.unwrap().len(), asked); + assert_eq!( + server.received_requests().await.unwrap().len(), + asked + 2, + "each run asks for the gem patch's list, which names the builds the copy holds" + ); // 3. `vendor --check`: one verdict per platform gem. let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); @@ -670,14 +733,15 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { ); assert_eq!( server.received_requests().await.unwrap().len(), - asked, - "offline" + asked + 2, + "`vendor --check` and an offline `vex` ask nothing" ); // 5. A damaged tree: the check fails per platform gem, and the next // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then - // those patches are asked for in one request. + // those patches are asked for in one request. The run then finds + // the rebuilt copy in step with the gem patch's list. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -692,7 +756,8 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { reference_requests(&server).await[before..], [ vec![UUID.to_string()], - vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()] + vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + vec![UUID.to_string()], ] ); assert_eq!( @@ -760,19 +825,369 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { assert!(!root.join(".socket/vendor").exists()); } -/// A locked platform with no patched build: the gem is not vendored, the -/// run exits 0 with nothing written and nothing downloaded, and says so in -/// one plain line (a counted benign skip in `--json`). +/// A locked platform with no patched build, beside one that has one: the +/// gem is vendored. The patched platform gets its patched build's tree, +/// the other the tree of upstream's own gem, which the gem patch's +/// registry serves, with the gemspec that gem carries. The run counts the +/// patched build alone, reports the other as hosted mode does (the +/// advisory `gem_upstream_build_kept`, with no patch), and says which is +/// which in one line. A later run finds the copy in step, `vendor --check` +/// verifies it and finds a change to the upstream tree, `vex` attests the +/// patched build and states the other `affected`, and revert restores +/// both files byte for byte. #[tokio::test] -async fn a_locked_platform_without_a_patched_build_is_one_line_and_no_failure() { +async fn a_locked_platform_without_a_patched_build_gets_upstreams_gem() { let server = service(&[LINUX], &[DARWIN]).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); write_project(root); let line = format!( - "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now." + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched build \ + yet)" + ); + let kept = + format!("the patch registry serves upstream's own gem for {DARWIN}: no patched build yet"); + let darwin_purl = format!("{PURL}?platform={DARWIN}"); + let linux_purl = format!("{PURL}?platform={LINUX}"); + // The events of the gem's trees: the patched build, counted, and the + // advisory one of upstream's gem, which `summary` leaves out. + let assert_trees = |env: &serde_json::Value, action: &str, code: &str| { + let trees: Vec<&serde_json::Value> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["gemFix"] == UUID) + .filter(|event| event["errorCode"] != "vendor_prebuilt_downloaded") + .collect(); + assert_eq!(trees.len(), 2, "{env:#}"); + let (upstream, patched) = (trees[0], trees[1]); + assert_eq!(upstream["action"], "skipped", "{env:#}"); + assert_eq!(upstream["purl"], darwin_purl.as_str(), "{env:#}"); + assert_eq!(upstream["errorCode"], "gem_upstream_build_kept", "{env:#}"); + assert_eq!(upstream["reason"], kept.as_str(), "{env:#}"); + assert!(upstream.get("uuid").is_none(), "no patch: {upstream:#}"); + assert_eq!(upstream["details"]["platform"], DARWIN, "{env:#}"); + assert_eq!(patched["action"], action, "{env:#}"); + assert_eq!(patched["purl"], linux_purl.as_str(), "{env:#}"); + assert_eq!(patched["uuid"], LINUX_UUID, "{env:#}"); + let coded = patched["errorCode"].as_str().unwrap_or_default(); + assert_eq!(coded, code, "{env:#}"); + }; + + // 1. A dry run says what the wet run does and writes nothing. + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Would vendor 1 package."), "{stdout}"); + assert!( + stdout.contains(&line.replace("patched for", "would be patched for")), + "{stdout}" + ); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + assert_nothing_vendored(root); + + // 2. The wet run. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{env:#}"); + assert_eq!(env["summary"]["applied"], 1, "{env:#}"); + assert_eq!(env["summary"]["skipped"], 0, "{env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_trees(&env, "applied", ""); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "{env:#}" + ); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(SO)).unwrap(), + format!("upstream's {DARWIN}").as_bytes() + ); + assert_eq!( + std::fs::read_to_string(tree(root, DARWIN).join(format!("{NAME}.gemspec"))).unwrap(), + upstream_gemspec(DARWIN), + "the gemspec upstream's gem carries" + ); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + for platform in [DARWIN, LINUX] { + let block = format!("PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n"); + assert!(lock_wired.contains(&block), "{lock_wired}"); + assert!( + lock_wired.contains(&format!(" {NAME} ({VERSION}-{platform})\n")), + "{lock_wired}" + ); + } + // The requests: the gem patch's list, the reference of the one + // patched build, its gem and stub, and upstream's gem from the gem + // patch's registry. Nothing else is downloaded. + assert_eq!( + reference_requests(&server).await[2..], + [vec![UUID.to_string()], vec![LINUX_UUID.to_string()]] + ); + let base = format!("/patch/gem/{NAME}/{VERSION}/tok-{LINUX}/{LINUX_UUID}/{NAME}-{VERSION}"); + let wet = [ + format!("{base}.gem"), + format!("{base}.gemspec"), + upstream_route(UUID, DARWIN), + ]; + // (The dry run of `vendor` downloads and verifies the same three.) + let mut expected = [wet.clone(), wet].concat(); + expected.sort(); + assert_eq!(downloads(&server).await, expected); + // The ledger: the tree of upstream's gem names no patch. + let ledger: serde_json::Value = + serde_json::from_slice(&std::fs::read(root.join(".socket/vendor/state.json")).unwrap()) + .unwrap(); + let builds = &ledger["entries"][PURL]["gemBuilds"]; + assert_eq!(builds[0]["platform"], DARWIN, "{builds:#}"); + assert!(builds[0].get("uuid").is_none(), "{builds:#}"); + assert!(builds[0].get("files").is_none(), "{builds:#}"); + let sha256 = base64::engine::general_purpose::STANDARD + .encode(sha2::Sha256::digest(upstream_gem(DARWIN))); + assert_eq!( + builds[0]["gemIntegrity"], + format!("sha256-{sha256}").as_str() ); + assert_eq!(builds[1]["uuid"], LINUX_UUID, "{builds:#}"); + + // 3. A later run: in step, one request (the list), the same line. + let asked = server.received_requests().await.unwrap().len(); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_eq!(env["summary"]["skipped"], 1, "{env:#}"); + assert_trees(&env, "skipped", "already_vendored"); + assert_eq!(server.received_requests().await.unwrap().len(), asked + 1); + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!(stdout.contains(&line), "{stdout}"); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + + // 4. `vendor --check`: the patched tree verifies, the tree of + // upstream's gem is reported as such, and a change to it is found. + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["verified"], 1, "{env:#}"); + assert_trees(&env, "verified", "vendor_check_ok"); + let binary = tree(root, DARWIN).join(SO); + std::fs::write(&binary, b"not upstream's").unwrap(); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_eq!( + env["summary"]["failed"], 2, + "every tree of the copy: {env:#}" + ); + std::fs::write(&binary, format!("upstream's {DARWIN}")).unwrap(); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 5. `vex`, offline from the ledger: the patched build is attested + // under its own patch, and the build on upstream's gem is stated + // affected, with what changes that. + let out = root.join("vex.json"); + let vex = [ + "vex", + "--offline", + "--json", + "--product", + "pkg:gem/app@1.0.0", + "--output", + out.to_str().unwrap(), + ]; + let (code, env, stderr) = run_json(root, &vex, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let doc: serde_json::Value = serde_json::from_slice(&std::fs::read(&out).unwrap()).unwrap(); + let status_of = |purl: &str| -> Vec<(String, String)> { + let statements = doc["statements"].as_array().unwrap().iter(); + statements + .filter(|statement| statement.to_string().contains(purl)) + .map(|statement| { + let text = |key: &str| statement[key].as_str().unwrap_or_default().to_string(); + (text("status"), text("action_statement")) + }) + .collect() + }; + assert_eq!( + status_of(&linux_purl), + [("not_affected".to_string(), String::new())], + "{doc:#}" + ); + let affected = status_of(&darwin_purl); + assert_eq!(affected.len(), 1, "{doc:#}"); + assert_eq!(affected[0].0, "affected", "{doc:#}"); + assert_eq!( + affected[0].1, + format!( + "The vendored copy holds upstream's own gem for {DARWIN}: the patch registry had no \ + patched build of this gem for it when the copy was vendored, so an install on that \ + platform is without Socket patch {UUID}. Run `socket-patch scan --mode vendored` \ + again later: the copy takes the patched build once it is published." + ), + "{doc:#}" + ); + let kept_events: Vec<&serde_json::Value> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["errorCode"] == "gem_upstream_build_kept") + .collect(); + assert_eq!(kept_events.len(), 1, "{env:#}"); + assert_eq!(kept_events[0]["purl"], darwin_purl.as_str(), "{env:#}"); + + // 6. Revert. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile")).unwrap(), + GEMFILE + ); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// The copy follows the builds the gem patch's registry lists. A later +/// run takes a patched build that was published since in place of +/// upstream's gem, and puts upstream's gem back where a patched build was +/// withdrawn: one line each, counted as hosted mode counts them, with no +/// warning, and a dry run says the same first. The Gemfile and the lock +/// stay as the first run left them. +#[tokio::test] +async fn a_later_run_follows_a_published_and_a_withdrawn_build() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + let darwin_lib = tree(root, DARWIN).join(LIB); + let linux_lib = tree(root, LINUX).join(LIB); + + let steps: [(&[&'static str], &[&'static str], String); 2] = [ + // The darwin build is published. + ( + &[DARWIN, LINUX], + &[], + format!("{NAME} {VERSION}: now also patched for {DARWIN}; already patched for {LINUX}"), + ), + // The linux build is withdrawn. + ( + &[DARWIN], + &[LINUX], + format!( + "{NAME} {VERSION}: patched for {DARWIN}; upstream gem back for {LINUX} (its \ + patched build was withdrawn)" + ), + ), + ]; + for (patched, pass_through, line) in steps { + let server = service(patched, pass_through).await; + let before = std::fs::read(&linux_lib).unwrap(); + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + let would = line + .replace("now also patched", "would also be patched") + .replace("gem back for", "gem would be back for"); + assert!(stdout.contains(&would), "{would}\n{stdout}"); + assert!(stdout.contains("Would vendor 1 package."), "{stdout}"); + assert_eq!( + std::fs::read(&linux_lib).unwrap(), + before, + "a dry run writes nothing" + ); + + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{line}\n{stdout}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + // Nothing on stderr but the note about this test's stand-in token. + let said: Vec<&str> = stderr + .lines() + .filter(|l| !l.contains("--api-token") && !l.contains("fake-token")) + .filter(|l| !l.trim().is_empty()) + .collect(); + assert_eq!(said, Vec::<&str>::new(), "no warning: {stderr}"); + let is_patched = |platform: &str| patched.contains(&platform); + for (lib, platform) in [(&darwin_lib, DARWIN), (&linux_lib, LINUX)] { + let expected = match is_patched(platform) { + true => stamped(build_uuid(platform)), + false => PRISTINE.to_vec(), + }; + assert_eq!(std::fs::read(lib).unwrap(), expected, "{platform}"); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_wired + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // In step again: each patched build the copy holds, already + // vendored. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + assert_eq!(env["summary"]["skipped"], patched.len(), "{env:#}"); + } + + // The JSON of a run that takes a published build: `applied` per + // patched build, `newlyPatched` on the one it put in place. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 2, "{env:#}"); + assert_per_platform_gem(&env, "applied", ""); + let newly: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["newlyPatched"] == true) + .filter_map(|event| event["details"]["platform"].as_str()) + .collect(); + assert_eq!(newly, [LINUX], "{env:#}"); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "{env:#}" + ); + + // Revert: both files as they were before the first run. + let (code, env, stderr) = run_json(root, &["vendor", "--revert", "--json"], &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock() + ); + assert!(!root.join(".socket/vendor").exists()); +} + +/// No locked platform has a patched build: the gem is not vendored, the +/// run exits 0 with nothing written and nothing downloaded, and says so in +/// one plain line (a counted benign skip in `--json`). +#[tokio::test] +async fn a_gem_with_no_patched_build_for_any_locked_platform_is_one_line_and_no_failure() { + let server = service(&[], &[DARWIN, LINUX]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let line = + format!("{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} and {LINUX}."); let (code, stdout, stderr) = run( root, @@ -918,13 +1333,13 @@ fn write_hosted_project(root: &Path) -> (String, String) { (gemfile, lock) } -/// An eject (`vendor` over a hosted lock) of a gem whose registry serves -/// upstream's own gem for one locked platform cannot vendor it: the eject -/// is refused whole, the reason names the platform, and the lock stays -/// hosted, byte for byte. +/// An eject (`vendor` over a hosted lock) of a gem while the patch of one +/// locked platform's build is still being built cannot vendor it: the +/// eject is refused whole, the reason names the platform, and the lock +/// stays hosted, byte for byte. #[tokio::test] -async fn an_eject_of_a_gem_with_a_pass_through_platform_is_refused_whole() { - let server = service(&[LINUX], &[DARWIN]).await; +async fn an_eject_of_a_gem_with_a_build_still_being_built_is_refused_whole() { + let server = service_still_building_darwin().await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); let (gemfile, lock) = write_hosted_project(root); @@ -1148,11 +1563,72 @@ async fn a_vendored_scan_takes_over_a_hosted_platform_gem() { } /// The same takeover while the registry serves upstream's own gem for one -/// locked platform: the gem is not vendored and stays hosted, byte for +/// locked platform: the gem is vendored all the same, with the patched +/// build's tree for the one platform and upstream's gem for the other, as +/// the hosted lock installed them. The scan's dry run says so first, and +/// an eject (`vendor` over the hosted lock) vendors the same. +#[tokio::test] +async fn a_takeover_of_a_hosted_gem_with_upstreams_gem_for_a_platform_vendors_both() { + for command in [SCAN_IT, VENDOR_IT] { + let server = service(&[LINUX], &[DARWIN]).await; + mount_search(&server).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let (_, hosted_lock) = write_hosted_project(root); + if command[0] == "scan" { + install_darwin_gem(root); + } + let line = format!( + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched \ + build yet)" + ); + + let dry = with(command, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{dry:?}\n{stdout}\n{stderr}"); + // (An eject's dry run names the packages it would eject and asks + // the patch service nothing.) + if command[0] == "scan" { + let would = line.replace("patched for", "would be patched for"); + assert!(stdout.contains(&would), "{dry:?}\n{stdout}\n{stderr}"); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + hosted_lock + ); + assert!(!root.join(".socket/vendor/gem").exists()); + + let (code, stdout, stderr) = run(root, command, &server.uri()); + assert_eq!(code, 0, "{command:?}\n{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{command:?}\n{stdout}\n{stderr}"); + let lock = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: .socket/vendor/gem/{UUID}/{NAME}-{VERSION}\n" + )), + "{lock}" + ); + assert!(!lock.contains("patch-registry"), "{lock}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + } +} + +/// The same takeover while the patch of one locked platform's build is +/// still being built: the gem is not vendored and stays hosted, byte for /// byte, the run does not fail, and its one line says the pin stays. #[tokio::test] -async fn a_vendored_scan_leaves_a_hosted_gem_with_a_pass_through_platform_hosted() { - let server = service(&[LINUX], &[DARWIN]).await; +async fn a_vendored_scan_leaves_a_hosted_gem_with_a_build_still_being_built_hosted() { + let server = service_still_building_darwin().await; mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1530,21 +2006,121 @@ async fn a_vendored_get_dry_run_follows_the_runs_fallback_to_the_public_proxy() } } -/// Every dry run of a gem with a locked platform that has no patched build -/// says what the wet run says, and neither claims to vendor it: the gem -/// patch's reference lists upstream's own gem for the platform, so that -/// one request is all a run makes. +/// Every dry run of a gem none of whose locked platforms has a patched +/// build says what the wet run says, and neither claims to vendor it: the +/// gem patch's reference lists upstream's own gem for each platform, so +/// that one request is all a run makes. +#[tokio::test] +async fn every_dry_run_says_the_wet_runs_line_for_a_gem_with_no_patched_build() { + let line = + format!("{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} and {LINUX}."); + for command in [VENDOR_IT, SCAN_IT, GET_IT] { + let server = service(&[], &[DARWIN, LINUX]).await; + mount_search(&server).await; + assert_dry_and_wet_runs_skip_alike(&server, command, &line, &[vec![UUID.to_string()]]) + .await; + } +} + +/// Every dry run of a gem with a patched build for one locked platform and +/// upstream's own gem for the other says what the wet run does: it would +/// vendor the gem, with the one line that says which platform is patched, +/// the patched build `verified` where the wet run reports `applied`, and +/// the advisory event of the build on upstream's gem in both. `scan` and +/// `get` ask for the references the wet run asks for and download nothing. #[tokio::test] -async fn every_dry_run_says_the_wet_runs_line_for_a_platform_with_no_patched_build() { +async fn every_dry_run_previews_a_gem_with_upstreams_gem_for_a_platform() { let line = format!( - "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now." + "{NAME} {VERSION}: would be patched for {LINUX}; upstream gem kept for {DARWIN} (no \ + patched build yet)" ); for command in [VENDOR_IT, SCAN_IT, GET_IT] { let server = service(&[LINUX], &[DARWIN]).await; mount_search(&server).await; - assert_dry_and_wet_runs_skip_alike(&server, command, &line, &[vec![UUID.to_string()]]) - .await; + let project = fresh_project(command); + let root = project.path(); + let trees = |env: &serde_json::Value| -> Vec<(String, String, String)> { + let events = env["events"].as_array().unwrap().iter(); + events + .filter(|event| event["details"]["gemFix"] == UUID) + .filter(|event| event["errorCode"] != "vendor_prebuilt_downloaded") + .map(|event| { + let text = |key: &str| event[key].as_str().unwrap_or_default().to_string(); + (text("purl"), text("uuid"), text("errorCode")) + }) + .collect() + }; + let expected = [ + ( + format!("{PURL}?platform={DARWIN}"), + String::new(), + "gem_upstream_build_kept".to_string(), + ), + ( + format!("{PURL}?platform={LINUX}"), + LINUX_UUID.to_string(), + String::new(), + ), + ]; + + let args = with(command, &["--dry-run", "--json"]); + let (code, dry, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{dry:#}\n{stderr}"); + assert_eq!(dry["status"], "success", "{dry:#}"); + assert_eq!(trees(&dry), expected, "{args:?}\n{dry:#}"); + for (count, n) in [ + ("verified", 1), + ("applied", 0), + ("skipped", 0), + ("failed", 0), + ] { + assert_eq!(dry["summary"][count], n, "summary.{count}: {dry:#}"); + } + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], vec![LINUX_UUID.to_string()]], + "{command:?}: the wet run's reference requests" + ); + let downloaded = downloads(&server).await.len(); + match command[0] { + "vendor" => assert_eq!(downloaded, 3, "the gems and the stub, verified"), + _ => assert_eq!(downloaded, 0, "{command:?} downloads nothing"), + } + assert_nothing_vendored(root); + + let args = with(command, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{stdout}\n{stderr}"); + assert!(stdout.contains(&line), "{args:?}\n{stdout}"); + assert_eq!(said_of_the_gem(&stderr), Vec::<&str>::new(), "{stderr}"); + assert_nothing_vendored(root); + + let args = with(command, &["--json"]); + let (code, wet, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{wet:#}\n{stderr}"); + assert_eq!(wet["summary"]["applied"], 1, "{wet:#}"); + assert_eq!(trees(&wet), expected, "{args:?}\n{wet:#}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(LIB)).unwrap(), + stamped(LINUX_UUID) + ); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); + + // Vendored: a dry run of a later scan asks for the gem patch's + // list, as the wet run does, and promises nothing more. + let asked = reference_requests(&server).await.len(); + let args = with(command, &["--dry-run", "--json"]); + let (code, dry, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{dry:#}\n{stderr}"); + assert_eq!(dry["summary"]["verified"], 0, "{args:?}\n{dry:#}"); + assert_eq!( + reference_requests(&server).await[asked..], + [vec![UUID.to_string()]], + "{args:?}" + ); } } @@ -1689,20 +2265,17 @@ async fn an_unserved_platform_patch_still_fails_a_damaged_wired_copy_and_an_ejec } } -/// `scan --mode vendored` over a lock that pins the gem hosted, while a -/// locked platform has no patched build (the registry serves upstream's -/// own gem for it, or the patch of its build is still being built): the -/// dry run and the wet run both say the gem stays hosted, and it does, -/// byte for byte. +/// `scan --mode vendored` over a lock that pins the gem hosted, while the +/// patch of one locked platform's build is still being built: the dry run +/// and the wet run both say the gem stays hosted, and it does, byte for +/// byte. #[tokio::test] -async fn a_takeover_of_a_hosted_gem_with_an_unpatched_platform_stays_hosted_dry_or_wet() { +async fn a_takeover_of_a_hosted_gem_with_a_build_still_being_built_stays_hosted_dry_or_wet() { let line = format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ Vendored mode needs every locked platform; the gem stays hosted." ); - let pass_through = service(&[LINUX], &[DARWIN]).await; - let building = service_of(UUID, &[(DARWIN, Some("pending_build")), (LINUX, None)], &[]).await; - for server in [pass_through, building] { + for server in [service_still_building_darwin().await] { mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1732,7 +2305,7 @@ async fn a_takeover_of_a_hosted_gem_with_an_unpatched_platform_stays_hosted_dry_ } /// No run tells a gem that stays hosted to run hosted mode. A hosted gem -/// with a locked platform that has no patched build reaches the vendored +/// with a locked platform whose patched build is still being built reaches the vendored /// backend three ways: `scan` and `get` take it over (their dry runs ask /// the patch service with no record of the patch), and `vendor` ejects it, /// which is all or nothing and so fails. Each of them, dry or wet, for a @@ -1746,7 +2319,7 @@ async fn no_run_tells_a_gem_that_stays_hosted_to_run_hosted_mode() { Vendored mode needs every locked platform; the gem stays hosted." ); for command in [SCAN_IT, GET_IT, VENDOR_IT] { - let server = service(&[LINUX], &[DARWIN]).await; + let server = service_still_building_darwin().await; mount_search(&server).await; let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); @@ -1782,7 +2355,7 @@ async fn no_run_tells_a_gem_that_stays_hosted_to_run_hosted_mode() { // The same platforms for a gem with no hosted pin: hosted mode is what // patches the others. - let server = service(&[LINUX], &[DARWIN]).await; + let server = service_still_building_darwin().await; let project = fresh_project(VENDOR_IT); let (code, stdout, stderr) = run(project.path(), VENDOR_IT, &server.uri()); assert_eq!(code, 0, "{stdout}\n{stderr}"); From fc5c5b1f2fc740a83a5135703e85b43329495263 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:02:54 -0500 Subject: [PATCH 04/28] Run a gem vendored with upstream's gem for a platform on real Bundler The platform-gem capstone of the real-Bundler suite gains the mixed case: two locked platforms with a patched build (this machine's among them) and one the registry serves as upstream's own gem. The stand-in registry now serves that gem's file. The gem is vendored: two counted `applied` events and the advisory one, upstream's gem downloaded from the patch server, its tree with the YAML gemspec the gem carries. A fresh checkout installs frozen with no request to the patch service, Ruby loads the patched build of the running platform, `bundle install` and `bundle lock` regenerate the lock byte for byte, `vendor --check` passes and revert restores both files. A platform the list leaves out and a build whose patch is still being built stay the skips they were. An in-sync re-run now makes one request, and a newer patch that lacks a build the vendored copy holds is worded as hosted mode words it. Co-Authored-By: Claude Fable 5.2 --- .../tests/e2e_vendor_gem_build.rs | 263 ++++++++++++++++-- 1 file changed, 240 insertions(+), 23 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 9bbf8a1ee1..92151786e1 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2867,7 +2867,8 @@ fn platform_purl(platform: &str) -> String { /// (`registryOverride.identifiers.gemBuilds`): the ruby gem, each platform /// of `patched` with the patch of its patched build ([`build_uuid`]), and /// each of `upstream` with none (the registry hands on upstream's own gem -/// for it); a platform in neither is one the list leaves out, as for a +/// for it, and serves its file); a platform in neither is one the list +/// leaves out, as for a /// platform upstream does not publish. Each of those patches serves that /// platform's gem (`tarball`) /// and stub gemspec, and one request answers for every uuid it names. A @@ -2969,11 +2970,13 @@ async fn platform_patch_service( }), ); } + let mut upstream_gems = Vec::new(); for platform in upstream { let gem = read("repo/gems", format!("{}.gem", file_of(Some(platform)))); builds.push(serde_json::json!({ "platform": platform, "gemChecksumSha256": sha256_hex(&gem), "patchUuid": null, })); + upstream_gems.push((format!("{}.gem", file_of(Some(platform))), gem)); } for platform in building { let own = build_uuid(uuid, platform); @@ -2993,6 +2996,12 @@ async fn platform_patch_service( )[..12]; let registry = format!("https://patch.socket.dev/patch-registry/gem/grant-token/{uuid}/"); let artifacts = artifacts(uuid, None); + // The registry serves upstream's own gem of a platform it lists with + // no patched build, under the snapshot the list goes by. + for (file, gem) in upstream_gems { + let route = format!("/patch-registry/gem/grant-token/{uuid}/s/{key}/gems/{file}"); + mounts.push((route, gem)); + } let reference = |listed: bool| { let mut identifiers = serde_json::json!({ "name": PLAT, "version": PLAT_VERSION, "gemChecksumSha256": ruby_sha, @@ -3078,7 +3087,12 @@ async fn service_requests(server: &MockServer) -> usize { .await .unwrap_or_default() .iter() - .filter(|r| r.url.path().ends_with("/package") || r.url.path().starts_with("/patch/gem/")) + .filter(|r| { + let path = r.url.path(); + path.ends_with("/package") + || path.starts_with("/patch/gem/") + || path.starts_with("/patch-registry/") + }) .count() } @@ -3340,15 +3354,16 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) let unvendored = base.join("unvendored"); common::fs_tree::copy_tree(&proj, &unvendored); - // 2. One locked platform has no patched build yet: the gem is not + // 2. One locked platform has no gem to vendor: the gem is not // vendored, in one line, the run does not fail, no gem is - // downloaded and nothing is written. The same whether the service - // lists upstream's own gem for that platform or names a patch for - // it whose own reference says it is still being built (which a run - // learns from its second request, for the platform patches). A - // platform the list leaves out is not one to wait for: the line - // says that the registry does not list it, and what settles that. - // A dry run says what the wet run says. + // downloaded and nothing is written. Either the service names a + // patch for that platform whose own reference says it is still + // being built (which a run learns from its second request, for the + // platform patches), or the list leaves the platform out, which is + // not one to wait for: the line says that the registry does not + // list it, and what settles that. A dry run says what the wet run + // says. (A platform the registry lists as upstream's own gem is + // vendored as that gem: step 2b.) let mut own_patches: Vec = platforms.iter().map(|p| build_uuid(UUID, p)).collect(); own_patches.sort(); let (with_build, without_build) = platforms.split_at(2); @@ -3367,13 +3382,13 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) --remove-platform {0}`), or the registry lists a gem for every locked platform.", without_build[0] ); - for (listed, building) in [(without_build, none), (none, none), (none, without_build)] { - let not_vendored = match listed.is_empty() && building.is_empty() { + for building in [none, without_build] { + let not_vendored = match building.is_empty() { true => ¬_listed, false => ¬_vendored, }; let partial = - platform_patch_service(&fixture, &purl, UUID, with_build, listed, building).await; + platform_patch_service(&fixture, &purl, UUID, with_build, none, building).await; let mut asked = vec![vec![UUID.to_string()]]; if !building.is_empty() { asked.push(own_patches.clone()); @@ -3445,6 +3460,208 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert!(!unvendored.join(".socket/vendor").exists()); } + // 2b. One locked platform has no patched build, and the registry + // serves upstream's own gem for it: the gem is vendored, with the + // patched build's tree for the platforms that have one (this + // machine's among them) and upstream's gem for the other. A fresh + // checkout installs frozen with no request to the patch service, + // Ruby loads the patched build, and revert restores both files. + { + let mixed = base.join("mixed"); + common::fs_tree::copy_tree(&proj, &mixed); + let server = + platform_patch_service(&fixture, &purl, UUID, with_build, without_build, none).await; + let unpatched = &without_build[0]; + let (code, stdout, stderr) = vendor_in(&mixed, &server, true); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let env = parse_json_envelope(&stdout); + assert_eq!(env["status"], "success", "{env}"); + assert_eq!(env["summary"]["applied"], 2, "the patched builds: {env}"); + assert_eq!(env["summary"]["skipped"], 0, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + assert_eq!( + platform_gem_events(&env, "applied"), + per_platform_gem(&have, ""), + "{env}" + ); + let kept: Vec<_> = platform_gem_events(&env, "skipped") + .into_iter() + .filter(|event| event.4 == "gem_upstream_build_kept") + .collect(); + assert_eq!( + kept, + [( + platform_purl(unpatched), + String::new(), + UUID.to_string(), + unpatched.clone(), + "gem_upstream_build_kept".to_string() + )], + "the tree of upstream's gem is reported with no patch: {env}" + ); + assert!( + env["warnings"].as_array().is_none_or(Vec::is_empty), + "no warning: {env}" + ); + // The requests: the gem patch's list, the patched builds' + // references in one request, their gems and stubs, and upstream's + // gem from the gem patch's registry. + let mut patched_patches: Vec = + with_build.iter().map(|p| build_uuid(UUID, p)).collect(); + patched_patches.sort(); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string()], patched_patches] + ); + let registry_gems: Vec = server + .received_requests() + .await + .unwrap_or_default() + .iter() + .filter(|r| r.url.path().starts_with("/patch-registry/")) + .filter_map(|r| r.url.path().rsplit('/').next().map(str::to_string)) + .collect(); + assert_eq!( + registry_gems, + [format!("{PLAT}-{PLAT_VERSION}-{unpatched}.gem")], + "upstream's gem comes from the patch server" + ); + assert_eq!(artifact_downloads(&server).await.len(), 4); + + let copy_rel = format!(".socket/vendor/gem/{UUID}/{PLAT}-{PLAT_VERSION}"); + for platform in &platforms { + let tree = mixed.join(©_rel).join(platform); + let expected = match platform == unpatched { + true => PLAT_PRISTINE, + false => patched.as_str(), + }; + assert_eq!( + std::fs::read_to_string(tree.join("lib/sockplat.rb")).unwrap(), + expected, + "{platform}" + ); + assert_eq!( + &std::fs::read_to_string(tree.join("lib/sockplat/build")).unwrap(), + platform, + "{platform}: the tree is that platform's own gem" + ); + } + let gemspec = mixed + .join(©_rel) + .join(unpatched) + .join(format!("{PLAT}.gemspec")); + let gemspec = std::fs::read_to_string(gemspec).unwrap(); + assert!( + gemspec.starts_with("--- !ruby/object:Gem::Specification"), + "the gemspec upstream's gem carries:\n{gemspec}" + ); + let lock = std::fs::read_to_string(mixed.join("Gemfile.lock")).unwrap(); + assert!( + lock.starts_with(&format!( + "PATH\n remote: {copy_rel}\n specs:\n{blocks}\nGEM\n" + )), + "every platform block sits in the one PATH section:\n{lock}" + ); + // For a person: one package, and the line that says which + // platforms are patched. + let person = base.join("mixed-person"); + common::fs_tree::copy_tree(&unvendored, &person); + let (code, stdout, stderr) = vendor_in(&person, &server, false); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + let line = format!( + "{PLAT} {PLAT_VERSION}: patched for {}, {}; upstream gem kept for {unpatched} (no \ + patched build yet)", + have[0], have[1] + ); + let flat = stdout.replace("\n ", " "); + assert!(flat.contains(&line), "{line}\n{stdout}"); + let said: Vec<&str> = stderr + .lines() + .filter(|line| !line.contains("SOCKET_API_TOKEN")) + .collect(); + assert_eq!(said, Vec::<&str>::new(), "no warning:\n{stderr}"); + + // A fresh checkout: only the committable files. + let fresh = base.join("mixed-fresh"); + std::fs::create_dir_all(&fresh).unwrap(); + std::fs::copy(mixed.join("Gemfile"), fresh.join("Gemfile")).unwrap(); + std::fs::copy(mixed.join("Gemfile.lock"), fresh.join("Gemfile.lock")).unwrap(); + common::fs_tree::copy_tree(&mixed.join(".socket"), &fresh.join(".socket")); + common::fs_tree::copy_tree(&mixed.join(".bundle"), &fresh.join(".bundle")); + let lock_wired = std::fs::read(mixed.join("Gemfile.lock")).unwrap(); + let served_before = service_requests(&server).await; + let ci = bundle(&fresh, &["install"], true); + assert!( + ci.status.success(), + "a frozen `bundle install` over a copy with upstream's gem for a platform.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&ci.stdout), + String::from_utf8_lossy(&ci.stderr), + ); + assert_eq!( + std::fs::read(fresh.join("Gemfile.lock")).unwrap(), + lock_wired + ); + let script = format!( + "require \"{declared}\"\n\ + abort \"probe constant missing after require\" unless defined?(Sockplat::SOCKET_PATCH_VENDOR_E2E)\n\ + loaded = $LOADED_FEATURES.grep(%r{{/sockplat\\.rb\\z}})\n\ + puts loaded\n\ + puts \"build=\" + File.read(File.join(File.dirname(loaded.first), \"sockplat/build\"))" + ); + let probe = bundle(&fresh, &["exec", "ruby", "-e", script.as_str()], false); + let probe_out = String::from_utf8_lossy(&probe.stdout).into_owned(); + assert!( + probe.status.success(), + "the runtime probe failed.\nstdout:\n{probe_out}\nstderr:\n{}", + String::from_utf8_lossy(&probe.stderr), + ); + assert!( + probe_out.contains(&format!("{copy_rel}/{own}/lib/sockplat.rb")) + && probe_out.contains(&format!("build={own}")), + "Ruby loads the patched build of the running platform:\n{probe_out}" + ); + for args in [&["install"][..], &["lock"][..]] { + let regen = bundle(&fresh, args, false); + assert!( + regen.status.success(), + "`bundle {}` over the vendored pair failed:\n{}", + args.join(" "), + String::from_utf8_lossy(®en.stderr) + ); + assert_eq!( + std::fs::read(fresh.join("Gemfile.lock")).unwrap(), + lock_wired, + "`bundle {}` regenerates the committed lock byte for byte", + args.join(" ") + ); + } + assert_eq!( + service_requests(&server).await, + served_before, + "the fresh checkout installs with no request to the patch service" + ); + + // `vendor --check` verifies the copy, and revert restores both + // files byte for byte. + let root = mixed.to_str().unwrap(); + let (code, stdout, stderr) = + run_socket(&mixed, &["vendor", "--check", "--json", "--cwd", root]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let (code, stdout, stderr) = + run_socket(&mixed, &["vendor", "--revert", "--json", "--cwd", root]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(mixed.join("Gemfile")).unwrap(), + gemfile_before + ); + assert_eq!( + std::fs::read(mixed.join("Gemfile.lock")).unwrap(), + lock_before + ); + assert!(!mixed.join(".socket/vendor").exists()); + } + // 3. A patched build of every platform: a dry run names the platform // gems the wet run vendors and writes nothing; then vendor. let preview = platform_patch_service(&fixture, &purl, UUID, &platforms, none, none).await; @@ -3796,7 +4013,8 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) }); }); - // 6. A second run changes nothing and asks the service nothing. + // 6. A second run changes nothing. It asks the service for the gem + // patch's list, which names the builds the copy holds. let gemfile_wired = std::fs::read(&gemfile_path).unwrap(); let state_wired = std::fs::read(&state_path).unwrap(); let (code, stdout, stderr) = vendor(&server); @@ -3816,13 +4034,13 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!(std::fs::read(&state_path).unwrap(), state_wired); assert_eq!( service_requests(&server).await, - served_before, - "an in-sync re-run downloads nothing" + served_before + 1, + "an in-sync re-run asks for the gem patch's list and downloads nothing" ); - // A newer patch of the gem that lacks one platform's patched build: - // the vendored patch stays in force, and the run says so in one line - // and does not fail. + // A newer patch of the gem that lacks the patched build of a platform + // the vendored copy holds one for: the vendored patch stays in force, + // and the run says so in one line and does not fail. let manifest_path = proj.join(".socket/manifest.json"); let manifest = std::fs::read_to_string(&manifest_path).unwrap(); std::fs::write(&manifest_path, manifest.replace(UUID, UUID_NEXT)).unwrap(); @@ -3845,10 +4063,9 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) assert_eq!( kept["reason"], format!( - "{PLAT}@{PLAT_VERSION} was not brought up to date: no patched build yet for {} ({} \ - and {} have one). Vendored mode needs every locked platform; its vendored copy of \ - an earlier patch stays in force as it is.", - without_build[0], have[0], have[1] + "{PLAT}@{PLAT_VERSION} was not brought up to date: the newer fix has no patched \ + build for {} yet; its vendored copy of an earlier patch stays in force as it is.", + without_build[0] ) .as_str(), "{kept}" From 662c9268c2d88aebbe8a1030e26957af94d55303 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:02:54 -0500 Subject: [PATCH 05/28] Document vendoring a platform-locked gem with upstream's gem for a platform `CLI_CONTRACT.md`: the gem row of the vendored layouts (the tree of upstream's gem, where it comes from, the gem's line, how a later run follows the list, the ledger entry of such a tree, its events and its `vex` statement, the dry runs), and the rows of `vendor_prebuilt_platform_pending`, `vendor_prebuilt_replaced` and `gem_upstream_build_kept`. `docs/ecosystems.md`: the vendored row of the native-extensions table and the support matrix cell. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 ++++---- docs/ecosystems.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 7f87bc353b..a9f588bded 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked patched platform gem per locked platform, `-//`, each from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. Every locked platform needs a patched build: while one has none the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same): the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event each (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; human lines and totals count the gem as one package. `vex` attests each vendored platform gem under its own patch, from the committed ledger alone. A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per platform gem and a gem with a platform that has no patched build as the same one line and `skipped` event as the wet run, never as "would vendor". A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: a run over a copy that is in sync asks ONE request, the gem patch's reference, and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_artifact_rebuilt` in `--json` and prints no warning. A list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2522,8 +2522,8 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | -| `vendor_prebuilt_replaced` | `failed` | repair, and a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged (gem): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | -| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem patch's reference has no patched build for at least one locked platform: the platform is served as upstream's gem (`gemBuilds[].patchUuid` is null), or the list leaves it out; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). Vendored mode is all-or-nothing for such a gem. Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem): `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` (with no platform patched: `… no patched build yet for arm64-darwin and x86_64-linux-gnu. Vendored mode needs every locked platform.`). A platform whose patch is listed but not served yet (still being built) counts the same way, and one whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once every locked platform has a patched build. Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | +| `vendor_prebuilt_replaced` | `failed` | repair, and a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged (gem): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | +| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | | `vendor_ledger_missing` | `failed` (artifact-level: `uuid` + `details.{ecosystem,path}`, no purl) | repair (v5.0) and `vendor --check`: a lockfile references `.socket/vendor///` but the vendor ledger has no entry for it; repair no longer rebuilds ledger entries from lockfiles. Recovery: restore `.socket/vendor/state.json` from version control and re-run `repair`, or `git checkout -- ` and re-vendor. | @@ -2663,7 +2663,7 @@ command's integration tests check its output. | `redirect_gem_dependency_not_locked` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the manifest declares the gem but the lock's `DEPENDENCIES` does not list it (an out-of-date lock, or a conditional declaration). The gem is skipped, nothing written for it; run `bundle lock` and re-run. | | `redirect_gem_lock_unconvergeable` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock cannot be edited into the one Bundler writes for the redirected manifest (no `BUNDLED WITH` section, or a merged Bundler < 2.2 `GEM` section whose remotes the manifest's sources do not explain), and Bundler refuses a manifest whose sources its lock does not record under frozen / deployment mode. The gem is refused whole: neither file changes for it. The detail names the lock shape and the way out (`bundle lock` with the current Bundler, then re-run; or `--mode vendored` / `--mode agent`). For a manifest with more than one top-level `source` line, which Bundler 2.2 to 2.7 lock into one `GEM` section naming every source and `bundle lock` does not change, the detail names that cause instead, and the way out is to keep the source that serves the gem as the one top-level `source`, move each other one into a `source "" do … end` block, run `bundle lock` (with Bundler 2.2.25 or later, which the detail says when the lock was written by an earlier 2.2 release, since those keep the one section) and re-run, or `--mode agent`; it does not print the source URLs. The gate counts block-less `source` calls outside every other construct, a computed URL included; a `source` inside a conditional is not counted and keeps the generic detail. | | `redirect_gem_platform_unsupported` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock holds precompiled platform builds of the gem (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem patch's reference carries no list of the version's gems (`gemBuilds`: the patch service names no platform gem of the version right now, which is also its answer to a project that is not on the patch yet while a gem of the patch is being built again), or the lock is the merged layout of Bundler < 2.2. The detail names the locked builds and which of the two it is. The gem is skipped and the manifest and lock stay byte-identical for it. A platform with no patched build, or one the list does not name, is not this warning: see `gem_upstream_build_kept`, `redirect_gem_no_patched_build` and `redirect_gem_platform_unlisted`. | -| `gem_upstream_build_kept` | `events[]` (`skipped`, NOT counted in `summary`, no `uuid`) | scan/get `--mode hosted` (gem): one platform build the lock names of a gem that was moved to (or is on) the patch registry, which the registry serves as upstream's own gem: that platform has no patched build yet, and installs what it installed before, or its patched build was withdrawn and this run put its lock entry back on upstream's gem. `details.gemFix` is the gem's patch and `details.platform` the platform; `details.withdrawn: true` marks the second case, on the run that puts the entry back (told from the lock's `CHECKSUMS` entry, or, for a build with none, from the listing of the registry the lock is on where the run read it). `details.gemFix` is the patch whose registry the lock is on after the run, which is an earlier patch than the selected one where the lock stays on it (`redirect_gem_newer_fix_waits`, `redirect_gem_platform_unlisted`). The human line of the gem names the build (`upstream gem kept for arm64-darwin (no patched build yet)`, or `upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`). Never a warning, never attested as patched. | +| `gem_upstream_build_kept` | `events[]` (`skipped`, NOT counted in `summary`, no `uuid`) | scan/get `--mode hosted` (gem): one platform build the lock names of a gem that was moved to (or is on) the patch registry, which the registry serves as upstream's own gem: that platform has no patched build yet, and installs what it installed before, or its patched build was withdrawn and this run put its lock entry back on upstream's gem. `details.gemFix` is the gem's patch and `details.platform` the platform; `details.withdrawn: true` marks the second case, on the run that puts the entry back (told from the lock's `CHECKSUMS` entry, or, for a build with none, from the listing of the registry the lock is on where the run read it). `details.gemFix` is the patch whose registry the lock is on after the run, which is an earlier patch than the selected one where the lock stays on it (`redirect_gem_newer_fix_waits`, `redirect_gem_platform_unlisted`). The human line of the gem names the build (`upstream gem kept for arm64-darwin (no patched build yet)`, or `upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`). Never a warning, never attested as patched. Also vendor / scan / get `--mode vendored`, `vendor --check` and `vex` (gem): one tree of a gem vendored as platform gems that is upstream's own gem, for a locked platform that had no patched build when the gem was vendored, with the same `details` (`details.withdrawn: true` on the run that puts the tree in place of a patched build that was withdrawn). | | `platform_gem_patch_not_taken` | `warnings[]` (warning) | get `` `--mode hosted` (gem): the uuid is the patch of one platform gem (`pkg:gem/@?platform=`) and its package reference names no gem patch it was built from, so there is nothing to take in its place: hosted mode patches a gem through the gem's own patch. The patch is skipped, exit 0, and the detail names the command to run (`socket-patch get pkg:gem/@ --mode hosted`). With such a patch named on the reference the run takes that one instead and says so (`platformGemPatch`). | | `redirect_gem_no_patched_build` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock holds the gem as precompiled platform builds and none of the builds it names has a patched build yet, so moving the gem would gain nothing: it is left on its upstream registry, byte-identical. Only for a lock that takes the gem from its upstream registry: one that is on a patch registry of the gem already follows the selected patch's list, so that it is never left on a registry that refuses a build it pins (a lock on ANOTHER patch's registry under the rule of `redirect_gem_newer_fix_waits`). One plain line on stdout (`nokogiri 1.18.10: no patched build yet for arm64-darwin, x86_64-linux-gnu; left on its upstream registry`), no warning, exit 0. A later run moves the gem once the patch service lists a patched build for a platform the lock names. | | `redirect_gem_platform_unlisted` | `events[]` (`skipped`) | scan/get `--mode hosted` (gem): the lock names a platform the gem patch's list (`gemBuilds`) leaves out. The patch service lists every platform gem upstream publishes for the version, whether or not a patched build of it exists or is being made, so a platform it leaves out is one upstream does not publish (a private build, a yanked platform gem), and the run says only that it is not listed. The gem is not moved to that patch. This holds for a lock that is already on the patch too (the known limit above): nothing is written, and no string of the lock reaches the Gemfile. One plain line on stdout (`nokogiri 1.18.10: the patch registry does not list arm64-darwin, so the gem is left as it is`; for a lock on the registry of another patch of the gem, `nokogiri 1.18.10: the newer fix's registry does not list arm64-darwin; the lock stays on the patch it is on`), no warning, exit 0. A lock on its upstream registry is byte-identical. A lock on another patch's registry stays on that patch: byte-identical too, unless that patch has withdrawn a build the lock pins, in which case the run brings the lock to that patch's current listing (one `info/` request to the lock's registry on each such run; see `redirect_gem_newer_fix_waits`). A later run moves the gem once the list has the platform. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 1a7811451a..cf997eea65 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -22,7 +22,7 @@ below is about what a package manager installs and builds. | 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). Declined where a rules_python hub of a Bazel workspace reads the file, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ 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`: 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; in a Bazel workspace a crate is not pinned while a rules_rust hub reads the project's Cargo files without its cargo config (`redirect_cargo_bazel_config_unread`), see [Bazel workspaces: Cargo](#bazel-workspaces-cargo) | -| 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 the 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); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ 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"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | +| 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 the patched platform gems, with upstream's own gem for a platform that has no patched build yet, 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); declined where a rules_ruby hub of a Bazel workspace reads the pair, see [Bazel workspaces: PyPI and RubyGems vendored mode](#bazel-workspaces-pypi-and-rubygems-vendored-mode) | ✅ 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"). In a Bazel workspace whose rules_ruby call holds the gem to another sha256 in `gem_checksums`, or has a `gem_checksums` that is not written out in the call, nothing is written for it (`redirect_bazel_gem_checksums_pinned`); see [Bazel workspaces: RubyGems](#bazel-workspaces-rubygems) | | 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 | | Maven (`maven`) — Maven and Gradle | ✅ in place in every copy the build consumes: each `~/.m2` copy it reads and each Gradle `files-2.1` copy; `~/.m2` `.sha1`/`.md5` sidecars are rewritten, Gradle copies get advisories; jar-member records swap in the patch service's whole jar — prefer vendored / hosted, see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | ✅ suffixed Maven repository (`-socket.` pin + `.mvn/maven.config` + fallback file repository) for every pom root, single-module or reactor, or Gradle 6.8+ same-GAV repository with settings wiring and SHA-256 checks (a root with both `pom.xml` and a Gradle build wires both); see [JVM vendoring](design/maven-vendoring.md) and [Gradle](#gradle) | ✅ fail-closed by a Socket-only `-socket.` suffix: pom projects get a pinned `` (`${property}` versions are refused); Gradle 6.8+ builds get an owned settings script, lock-entry rewrites and a resolution tripwire — see [Maven & NuGet caveats](#maven--nuget-caveats) and [Gradle](#gradle) | | sbt / Mill / scala-cli (`maven`) | ✅ Coursier caches (sbt 1.3+, sbt 2, Mill, scala-cli) and Ivy caches (sbt 0.13–1.2, `useCoursier := false`) patched in place, Coursier checksum sidecars resynced — see [Scala build tools](#scala-build-tools-sbt-mill-scala-cli) | ✅ sbt 0.13.18+: generated `socket-patch-vendor.sbt` over the committed suffixed `.socket/vendor/maven2` tree; scala-cli directory builds: owned `socket-patch.scala` + same-GAV `.socket/vendor/coursier` tree (Linux / macOS); Mill: not wired (agent or hosted guidance) | ✅ sbt 0.13.18+: one generated `socket-patch.sbt`, gated on sbt's own `sbt update` records; Mill / scala-cli: paste-able snippets only (`redirect_mill_manual_snippet`, `redirect_scala_cli_manual_snippet`) | @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs a patched build. While one has none the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) names the platforms without a patched build and says that hosted mode can patch the others now. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once every platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 0a2f4b70267f0368bbb0ccbcfc51bfd6bbdd1623 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:09:21 -0500 Subject: [PATCH 06/28] Vendor real nokogiri with upstream's gem for a platform in the e2e script The vendored scenario of `tests/nokogiri/nokogiri_e2e.rb` no longer waits for every platform. With `--pass-through` naming some of the locked platforms, the scan vendors nokogiri with the patched build of the others and upstream's own gem, served by the stand-in's registry, for those. The script checks the events, the trees and their gemspecs, where upstream's gem was asked for, the line of a later scan, the `vex` statements, and a frozen install of a fresh checkout with the service unreachable: Ruby loads the patched nokogiri where this machine's platform has a patched build, and upstream's nokogiri from the committed tree where it has none (`--pass-through own`). The next scan then takes the builds the stand-in publishes. With no patched build at all nothing is vendored, as before. The compatibility workflow runs the vendored scenario with the runner's own platform passed through as well. Co-Authored-By: Claude Fable 5.2 --- .github/workflows/nokogiri-compatibility.yml | 10 +- tests/nokogiri/nokogiri_e2e.rb | 103 +++++++++++++++++-- 2 files changed, 102 insertions(+), 11 deletions(-) diff --git a/.github/workflows/nokogiri-compatibility.yml b/.github/workflows/nokogiri-compatibility.yml index 90f2c56bd4..6bf6256524 100644 --- a/.github/workflows/nokogiri-compatibility.yml +++ b/.github/workflows/nokogiri-compatibility.yml @@ -213,8 +213,14 @@ jobs: - {os: macos-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, cli: build, args: '--scenarios vendored', note: vendored} - {os: ubuntu-latest, ruby: 'jruby-9.4', nokogiri: '1.18.10', install: java, args: '--scenarios vendored', note: vendored} # The same with a locked platform that has no patched build at - # first: nothing is vendored until the service has it. - - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through others', note: 'vendored, a platform passed through'} + # first: the scan commits upstream's own gem for it, which the + # stand-in's registry serves, beside the patched build of the + # other, and the next scan takes the patched build once the + # service has it. `own` is the runner's platform: the frozen + # install loads upstream's nokogiri from the committed tree, then + # the patched one. + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through others', note: 'vendored, another platform passed through'} + - {os: ubuntu-latest, ruby: '3.4', nokogiri: '1.18.10', install: precompiled, args: '--scenarios vendored --add-platform aarch64-linux-gnu --pass-through own', note: 'vendored, own platform passed through'} needs: static-cli runs-on: ${{ vars.DISABLE_DEPOT_RUNNERS != 'true' && matrix.os == 'ubuntu-latest' && 'depot-ubuntu-24.04-4' || matrix.os }} timeout-minutes: 60 diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index f2d9ca1b2b..e7f60e625c 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -533,11 +533,17 @@ def scenario(name) # patched nothing moves. Once the service has the builds that # were missing, the next scan moves the lock to the newer # registry snapshot and the install is the patched gem. - # vendored The scan commits the patched platform gem of every locked - # platform, each from its own patch, and a fresh checkout - # installs from that tree with the service unreachable. While - # a locked platform has no patched build nothing is vendored: - # the run says so and exits 0. + # vendored The scan commits one tree per locked platform: the patched + # platform gem, from its own patch, where the platform has a + # patched build, and upstream's own gem, which the patch + # registry serves, where it has none yet. A fresh checkout + # installs from those trees with the service unreachable, and + # Ruby there loads the patched gem where this machine's + # platform has one and upstream's own where it has none. Once + # the service has the builds that were missing, the next scan + # puts their trees in place. While no locked platform has a + # patched build nothing is vendored: the run says so and + # exits 0. # # Either way the scenario ends with `vex` and a `rollback` to the lock as # it was. @@ -797,8 +803,12 @@ def redirect_warnings(stdout) # The vendored scans, up to the lock that takes nokogiri from the # committed tree. Returns that lock. def vendored(service, platforms, waiting, lock, gemfile) - unless waiting.empty? - # A locked platform with no patched build: nothing is vendored. + have = platforms - waiting + if !waiting.empty? && !have.empty? + vendored_with_upstream(service, platforms, waiting, have) + waiting.each { |platform| service.publish(platform) } + elsif !waiting.empty? + # No locked platform has a patched build: nothing is vendored. code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") pending = events(stdout).find { |e| e["errorCode"] == "vendor_prebuilt_platform_pending" } || {} check(code.zero? && pending["action"] == "skipped", @@ -818,6 +828,14 @@ def vendored(service, platforms, waiting, lock, gemfile) code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") said = tail(stdout) + tail(stderr) check(code.zero?, "`scan --mode vendored` succeeds (#{secs.round}s)", "exit #{code}\n#{said}") + unless waiting.empty? || have.empty? + # The copy held upstream's gem for these: the scan puts the patched + # builds in their place, and says so with no warning. + gained = events(stdout).select { |e| e["details"].is_a?(Hash) && e["details"]["newlyPatched"] } + .map { |e| e["details"]["platform"] } + check(gained.sort == waiting.sort && warning_codes(stdout).empty?, + "it takes the builds published since in place of upstream's gem", "#{gained.inspect}\n#{said}") + end rewritten = File.read(lock_path) check(rewritten != lock, "it rewires the lock", said) vendored = Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "**", "*.gemspec")) @@ -843,9 +861,74 @@ def vendored(service, platforms, waiting, lock, gemfile) rewritten end + # A lock with a patched build for some platforms (`have`) and none yet for + # the others (`waiting`): the scan vendors the gem, with upstream's own + # gem for the latter, and a fresh checkout installs from the trees with + # the service unreachable. + def vendored_with_upstream(service, platforms, waiting, have) + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + said = tail(stdout) + tail(stderr) + builds = events(stdout).select { |e| e["details"].is_a?(Hash) && e["details"]["gemFix"] == UUID } + kept = builds.select { |e| e["errorCode"] == "gem_upstream_build_kept" } + applied = builds.select { |e| e["action"] == "applied" } + platforms_of = lambda { |list| list.map { |e| e["details"]["platform"] }.sort } + check(code.zero? && platforms_of.call(applied) == have.sort && platforms_of.call(kept) == waiting.sort, + "`scan --mode vendored` vendors the gem: patched for #{have.join(', ')}, upstream's own gem for " \ + "#{waiting.join(', ')} (#{secs.round}s)", "exit #{code}\n#{said}") + check(kept.all? { |e| e["uuid"].nil? } && applied.all? { |e| e["uuid"] == service.uuid_of(e["details"]["platform"]) }, + "each patched build under its own patch, the others under none", builds.inspect) + check(warning_codes(stdout).empty?, "with no warning", said) + mixed = File.read(lock_path) + check(mixed =~ /^PATH\n remote: \.socket\/vendor\/gem\//, "the lock takes nokogiri from the vendored path", mixed) + gemspec = lambda do |platform| + Dir.glob(File.join(@proj, ".socket", "vendor", "gem", "*", "nokogiri-#{@version}", platform, "nokogiri.gemspec")).first + end + check(platforms.all? { |p| gemspec.call(p) }, "with a tree for each of #{platforms.size} platforms") + check(waiting.all? { |p| File.read(gemspec.call(p).to_s).start_with?("---") } && + have.none? { |p| File.read(gemspec.call(p).to_s).start_with?("---") }, + "a tree of upstream's gem carries the gemspec that gem holds") + # Upstream's gem comes from the patch registry, as its list names it. + files = waiting.map { |p| "nokogiri-#{@version}-#{p}.gem" }.sort + fetched = service.requests.select { |_, path, _| path.include?("/gems/") } + .map { |_, path, status| [File.basename(path), status] }.sort + check(fetched == files.map { |f| [f, @opts[:redirect] ? 302 : 200] }, + "upstream's gem is asked of the patch registry", fetched.inspect) + unless @opts[:redirect] + check(service.upstream_requests.empty?, "and of nothing else", service.upstream_requests.inspect) + end + # A later scan finds the copy in step and says which platforms are + # patched. + code, stdout, stderr, = sp_service("scan", "--mode", "vendored", "--yes") + line = stdout.gsub(/\n\s+/, " ") + check(code.zero? && line.include?("nokogiri #{@version}: patched for") && line.include?("upstream gem kept for") && + waiting.all? { |p| line.include?(p) } && File.read(lock_path) == mixed, + "a later scan changes nothing and says which platforms are patched", "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + # `vex`: a patched build is attested, a build on upstream's gem is not. + code, stdout, stderr, = sp_service("vex", "--offline", "--product", PRODUCT, "--output", File.join(@proj, "vex.json")) + statements = begin + JSON.parse(File.read(File.join(@proj, "vex.json"))).fetch("statements", []) + rescue StandardError + [] + end + status_of = lambda do |platform| + purl = "pkg:gem/nokogiri@#{@version}?platform=#{platform}" + statements.select { |st| st.to_s.include?(purl) }.map { |st| st["status"] }.uniq + end + check(code.zero? && have.all? { |p| status_of.call(p) == ["not_affected"] } && + waiting.all? { |p| status_of.call(p) == ["affected"] }, + "`vex` attests the patched builds and states the builds on upstream's gem affected", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + # A fresh checkout, with the patch service unreachable. + service.take_down + installs_frozen(service, "vendored", mixed, have.include?(own_platform)) + service.bring_up + end + # A fresh checkout of what the scan left to commit installs with the lock # frozen, and Ruby there loads nokogiri: the patched gem when `patched`, - # else upstream's own, which the patch registry hands on. + # else upstream's own, which the patch registry hands on (hosted) or the + # vendored tree holds (vendored). def installs_frozen(service, mode, rewritten, patched) checkout = fresh_checkout(mode == "vendored" ? [".socket"] : []) service.forget_requests @@ -861,7 +944,9 @@ def installs_frozen(service, mode, rewritten, patched) JSON.pretty_generate(now)) file = "nokogiri-#{@version}-#{own_platform}.gem" answers = service.requests.select { |_, path, _| path.end_with?("/gems/#{file}") }.map(&:last).uniq - if @opts[:redirect] + if mode == "vendored" + check(answers.empty?, "from the tree of upstream's gem the scan committed", answers.inspect) + elsif @opts[:redirect] check(answers == [302] && service.upstream_requests.include?(["GET", "/gems/#{file}", 200]), "which the patch registry answers with a redirect to the upstream registry", (service.requests + service.upstream_requests).inspect) From 445f752cbf5fb1dd531d3f1a39340dcb8c9b5b2e Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:22:02 -0500 Subject: [PATCH 07/28] Keep the gem's line in a helper module, and preview a wired lock by the list The line that says which platform builds of a gem are patched is printed by hosted mode and now by vendored mode. It moves, with the filter vendored mode applies to it, into the helper module `commands/gem_build_lines.rs`, so that `vendor` does not import `scan` (the command modules' layering test). The core test of the request-less preview covers a lock already wired to the patch's copy: one request (the fix's list) while the copy holds what the list names, the trees the wet run would put in place when the list names another build, and no promise when a patched build it names is not served. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/gem_build_lines.rs | 148 ++++++++++++++++++ crates/socket-patch-cli/src/commands/mod.rs | 1 + .../src/commands/scan/hosted.rs | 110 +------------ .../src/commands/scan/vendor_flow.rs | 2 +- .../socket-patch-cli/src/commands/vendor.rs | 34 +--- crates/socket-patch-core/src/vendor/gem.rs | 36 ++++- 6 files changed, 187 insertions(+), 144 deletions(-) create mode 100644 crates/socket-patch-cli/src/commands/gem_build_lines.rs diff --git a/crates/socket-patch-cli/src/commands/gem_build_lines.rs b/crates/socket-patch-cli/src/commands/gem_build_lines.rs new file mode 100644 index 0000000000..a021ff5bc4 --- /dev/null +++ b/crates/socket-patch-cli/src/commands/gem_build_lines.rs @@ -0,0 +1,148 @@ +//! The line a run prints for a gem a Bundler lock names as precompiled +//! platform builds: which of them are patched. Hosted mode says it of the +//! locked builds of a pin, vendored mode of the trees of a vendored copy. + +use socket_patch_core::hosted::engine::PinReport; +use socket_patch_core::utils::purl::purl_parts; + +/// Which builds are patched of each gem the Bundler lock names as +/// precompiled platform builds, one line per gem. Such a gem takes its +/// patch registry as the one source of every locked build, and the +/// registry serves a patched build for some platforms and upstream's own +/// gem for the rest, so the summary's "1 package" does not say which +/// machines run patched code. Not a warning: nothing here needs doing. +/// +/// - `nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu` +/// - a platform with no patched build yet: `…: patched for +/// x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched +/// build yet)` +/// - a patched build that this run found for a platform of a lock already +/// on the registry: `…: now also patched for arm64-darwin; already +/// patched for x86_64-linux-gnu` +/// - a build this run put back on upstream's gem, because the patched +/// build its lock entry pinned was withdrawn: `…: patched for +/// arm64-darwin; upstream gem back for x86_64-linux-gnu (its patched +/// build was withdrawn)`, before the builds that never had one +/// - a gem left where it is under one of the quiet skips +/// (`engine::is_quiet_gem_skip`), in the skip's own sentence: `…: no +/// patched build yet for arm64-darwin, x86_64-linux-gnu; left on its +/// upstream registry` +/// +/// The ruby-platform gem, where the lock names it beside the platform +/// builds, is the platform `ruby`. A dry run says `would be patched for` +/// (`would also be patched for`) of the builds a wet run would put in +/// place, and `upstream gem would be back for` of those it would put back. +/// `reports` are the run's pins per locked build (`engine::pin_reports`), +/// `skipped` its skips. Vendored mode says the same of a gem it vendors +/// as platform gems, with a tree in place of a locked build +/// ([`format_vendored_gem_build_lines`]). +pub(crate) fn format_gem_build_lines( + reports: &[socket_patch_core::hosted::engine::PinReport], + skipped: &[socket_patch_core::hosted::engine::SkippedPatch], + dry_run: bool, +) -> Vec { + use socket_patch_core::hosted::engine::{is_quiet_gem_skip, PinReport}; + // Per gem patch, in report order: its locked builds. + let mut gems: Vec<(&str, Vec<&PinReport>)> = Vec::new(); + for report in reports { + let Some(gem_fix) = report.gem_fix.as_deref() else { + continue; + }; + match gems.iter_mut().find(|(fix, _)| *fix == gem_fix) { + Some((_, builds)) => builds.push(report), + None => gems.push((gem_fix, vec![report])), + } + } + let mut lines: Vec = Vec::new(); + for (_, builds) in gems { + let Some((_, name, version)) = builds.first().and_then(|build| purl_parts(&build.purl)) + else { + continue; + }; + let platforms = |keep: &dyn Fn(&PinReport) -> bool| -> String { + let named: Vec<&str> = builds + .iter() + .filter(|build| keep(build)) + .map(|build| build.platform.as_deref().unwrap_or("ruby")) + .collect(); + named.join(", ") + }; + let now = platforms(&|build| build.uuid.is_some() && build.newly_patched); + let before = platforms(&|build| build.uuid.is_some() && !build.newly_patched); + let is_back = |build: &PinReport| build.uuid.is_none() && build.withdrawn; + let back = platforms(&is_back); + let kept = platforms(&|build| build.uuid.is_none() && !build.withdrawn); + let (first, also) = if dry_run { + ("would be patched for", "would also be patched for") + } else { + ("patched for", "now also patched for") + }; + let mut parts: Vec = Vec::new(); + match (now.is_empty(), before.is_empty()) { + (false, true) => parts.push(format!("{first} {now}")), + (false, false) => { + parts.push(format!("{also} {now}")); + parts.push(format!("already patched for {before}")); + } + (true, false) => parts.push(format!("patched for {before}")), + // No locked build is patched: the lock followed a withdrawn + // build back to upstream's gem. + (true, true) => {} + } + if !back.is_empty() { + let is = if dry_run { "would be back" } else { "back" }; + let why = match builds.iter().filter(|build| is_back(build)).count() { + 1 => "its patched build was withdrawn", + _ => "their patched builds were withdrawn", + }; + parts.push(format!("upstream gem {is} for {back} ({why})")); + } + if !kept.is_empty() { + parts.push(format!( + "upstream gem kept for {kept} (no patched build yet)" + )); + } + lines.push(format!("{name} {version}: {}", parts.join("; "))); + } + lines.extend( + skipped + .iter() + .filter(|skip| is_quiet_gem_skip(&skip.reason)) + .filter_map(|skip| skip.detail.clone()), + ); + lines +} + +/// Which trees are patched of each gem vendored as platform gems that +/// holds upstream's own gem for a locked platform, or that this run +/// brought in step with the builds the patch registry lists: hosted +/// mode's line for such a gem, one per gem ([`format_gem_build_lines`]). +/// A gem whose every tree is a patched build says nothing here, as before. +/// `reports` are the run's reports per tree +/// (`crate::commands::vendor::gem_build_reports`). +pub(crate) fn format_vendored_gem_build_lines(reports: &[PinReport], dry_run: bool) -> Vec { + let mut fixes: Vec<&str> = Vec::new(); + for report in reports { + if let Some(fix) = report.gem_fix.as_deref().filter(|fix| !fixes.contains(fix)) { + fixes.push(fix); + } + } + let mut said: Vec = Vec::new(); + for fix in fixes { + let of_gem = |report: &&PinReport| report.gem_fix.as_deref() == Some(fix); + let builds: Vec<&PinReport> = reports.iter().filter(of_gem).collect(); + let patched = |build: &&&PinReport| build.uuid.is_some(); + let gained = builds + .iter() + .filter(patched) + .any(|build| build.newly_patched) + && builds + .iter() + .filter(patched) + .any(|build| !build.newly_patched); + if gained || builds.iter().any(|build| build.uuid.is_none()) { + said.extend(builds.into_iter().cloned()); + } + } + format_gem_build_lines(&said, &[], dry_run) +} diff --git a/crates/socket-patch-cli/src/commands/mod.rs b/crates/socket-patch-cli/src/commands/mod.rs index c7975f2ce6..9d096e6603 100644 --- a/crates/socket-patch-cli/src/commands/mod.rs +++ b/crates/socket-patch-cli/src/commands/mod.rs @@ -3,6 +3,7 @@ pub mod apply; pub(crate) mod composer_hints; pub(crate) mod context; pub(crate) mod fetch_stage; +pub(crate) mod gem_build_lines; pub(crate) mod gem_refresh; pub mod get; pub mod hosted_bundle; diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index d8d3f6fbb3..5cced1283d 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -13,6 +13,8 @@ use socket_patch_core::patch::redirect::DepOverride; use socket_patch_core::utils::concurrent::api_concurrency; use socket_patch_core::utils::purl::purl_parts; +use crate::commands::gem_build_lines::format_gem_build_lines; + use crate::commands::agent_download::tag_mode; use crate::commands::gem_refresh::{self, StaleGem}; use crate::commands::vex::generate_vex_from_manifest_path; @@ -3917,114 +3919,6 @@ fn format_gem_manifest_edits( .collect() } -/// Which builds are patched of each gem the Bundler lock names as -/// precompiled platform builds, one line per gem. Such a gem takes its -/// patch registry as the one source of every locked build, and the -/// registry serves a patched build for some platforms and upstream's own -/// gem for the rest, so the summary's "1 package" does not say which -/// machines run patched code. Not a warning: nothing here needs doing. -/// -/// - `nokogiri 1.19.3: patched for arm64-darwin, x86_64-linux-gnu` -/// - a platform with no patched build yet: `…: patched for -/// x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched -/// build yet)` -/// - a patched build that this run found for a platform of a lock already -/// on the registry: `…: now also patched for arm64-darwin; already -/// patched for x86_64-linux-gnu` -/// - a build this run put back on upstream's gem, because the patched -/// build its lock entry pinned was withdrawn: `…: patched for -/// arm64-darwin; upstream gem back for x86_64-linux-gnu (its patched -/// build was withdrawn)`, before the builds that never had one -/// - a gem left where it is under one of the quiet skips -/// (`engine::is_quiet_gem_skip`), in the skip's own sentence: `…: no -/// patched build yet for arm64-darwin, x86_64-linux-gnu; left on its -/// upstream registry` -/// -/// The ruby-platform gem, where the lock names it beside the platform -/// builds, is the platform `ruby`. A dry run says `would be patched for` -/// (`would also be patched for`) of the builds a wet run would put in -/// place, and `upstream gem would be back for` of those it would put back. -/// `reports` are the run's pins per locked build (`engine::pin_reports`), -/// `skipped` its skips. Vendored mode says the same of a gem it vendors -/// as platform gems, with a tree in place of a locked build -/// (`crate::commands::vendor::format_vendored_gem_build_lines`). -pub(crate) fn format_gem_build_lines( - reports: &[socket_patch_core::hosted::engine::PinReport], - skipped: &[socket_patch_core::hosted::engine::SkippedPatch], - dry_run: bool, -) -> Vec { - use socket_patch_core::hosted::engine::{is_quiet_gem_skip, PinReport}; - // Per gem patch, in report order: its locked builds. - let mut gems: Vec<(&str, Vec<&PinReport>)> = Vec::new(); - for report in reports { - let Some(gem_fix) = report.gem_fix.as_deref() else { - continue; - }; - match gems.iter_mut().find(|(fix, _)| *fix == gem_fix) { - Some((_, builds)) => builds.push(report), - None => gems.push((gem_fix, vec![report])), - } - } - let mut lines: Vec = Vec::new(); - for (_, builds) in gems { - let Some((_, name, version)) = builds.first().and_then(|build| purl_parts(&build.purl)) - else { - continue; - }; - let platforms = |keep: &dyn Fn(&PinReport) -> bool| -> String { - let named: Vec<&str> = builds - .iter() - .filter(|build| keep(build)) - .map(|build| build.platform.as_deref().unwrap_or("ruby")) - .collect(); - named.join(", ") - }; - let now = platforms(&|build| build.uuid.is_some() && build.newly_patched); - let before = platforms(&|build| build.uuid.is_some() && !build.newly_patched); - let is_back = |build: &PinReport| build.uuid.is_none() && build.withdrawn; - let back = platforms(&is_back); - let kept = platforms(&|build| build.uuid.is_none() && !build.withdrawn); - let (first, also) = if dry_run { - ("would be patched for", "would also be patched for") - } else { - ("patched for", "now also patched for") - }; - let mut parts: Vec = Vec::new(); - match (now.is_empty(), before.is_empty()) { - (false, true) => parts.push(format!("{first} {now}")), - (false, false) => { - parts.push(format!("{also} {now}")); - parts.push(format!("already patched for {before}")); - } - (true, false) => parts.push(format!("patched for {before}")), - // No locked build is patched: the lock followed a withdrawn - // build back to upstream's gem. - (true, true) => {} - } - if !back.is_empty() { - let is = if dry_run { "would be back" } else { "back" }; - let why = match builds.iter().filter(|build| is_back(build)).count() { - 1 => "its patched build was withdrawn", - _ => "their patched builds were withdrawn", - }; - parts.push(format!("upstream gem {is} for {back} ({why})")); - } - if !kept.is_empty() { - parts.push(format!( - "upstream gem kept for {kept} (no patched build yet)" - )); - } - lines.push(format!("{name} {version}: {}", parts.join("; "))); - } - lines.extend( - skipped - .iter() - .filter(|skip| is_quiet_gem_skip(&skip.reason)) - .filter_map(|skip| skip.detail.clone()), - ); - lines -} - /// What wiring a gem to its patch source costs the project's update /// workflow, said once per run under [`format_gem_manifest_edits`]' lines. /// diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 50348e138d..f45fcf1db7 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -353,7 +353,7 @@ impl VendorPreview { /// prints them (`format_vendored_gem_build_lines`). fn gem_build_lines(&self) -> Vec { let reports: Vec<_> = self.rows.iter().flat_map(PreviewRow::gem_reports).collect(); - crate::commands::vendor::format_vendored_gem_build_lines(&reports, true) + crate::commands::gem_build_lines::format_vendored_gem_build_lines(&reports, true) } /// The uuids of the rows the wet run would vendor or already holds: diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 056fd052b7..1d33384c67 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -54,6 +54,7 @@ use std::time::Duration; use crate::args::{apply_env_toggles, GlobalArgs}; use crate::commands::apply::{representative_file, result_to_event, variant_matches_installed}; +use crate::commands::gem_build_lines::format_vendored_gem_build_lines; use crate::commands::lock_cli::acquire_or_emit; use crate::commands::vendor_orphans::{ orphan_label, orphan_removal_failed, orphan_removed_event, orphan_still_wired, @@ -941,39 +942,6 @@ fn gem_build_reports_of(env: &Envelope) -> Vec { .collect() } -/// Which trees are patched of each gem vendored as platform gems that -/// holds upstream's own gem for a locked platform, or that this run -/// brought in step with the builds the patch registry lists: hosted -/// mode's line for such a gem, one per gem -/// (`crate::commands::scan::hosted::format_gem_build_lines`). A gem whose -/// every tree is a patched build says nothing here, as before. -pub(crate) fn format_vendored_gem_build_lines(reports: &[PinReport], dry_run: bool) -> Vec { - let mut fixes: Vec<&str> = Vec::new(); - for report in reports { - if let Some(fix) = report.gem_fix.as_deref().filter(|fix| !fixes.contains(fix)) { - fixes.push(fix); - } - } - let mut said: Vec = Vec::new(); - for fix in fixes { - let of_gem = |report: &&PinReport| report.gem_fix.as_deref() == Some(fix); - let builds: Vec<&PinReport> = reports.iter().filter(of_gem).collect(); - let patched = |build: &&&PinReport| build.uuid.is_some(); - let gained = builds - .iter() - .filter(patched) - .any(|build| build.newly_patched) - && builds - .iter() - .filter(patched) - .any(|build| !build.newly_patched); - if gained || builds.iter().any(|build| build.uuid.is_none()) { - said.extend(builds.into_iter().cloned()); - } - } - crate::commands::scan::hosted::format_gem_build_lines(&said, &[], dry_run) -} - /// How many of the events `counted` picks stand for a gem that an earlier /// one of them already stands for ([`GEM_FIX_DETAIL`]): what a count of /// events is over a count of packages. diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index f5cec68d4c..e13a6deb96 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -14833,7 +14833,9 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), before); // Not judged: a gem the lock names for the ruby platform, and - // a lock already wired to the patch's copy. + // a lock already wired to the patch's copy while that copy + // holds the builds the list names. The list is all the latter + // asks for: one request. let ruby_gem = "pkg:gem/puma@6.4.2"; assert!( preview_locked_builds(&root, ruby_gem, UUID, false, Some(&cfg)) @@ -14843,7 +14845,37 @@ mod tests { vendor_and_persist(&root, &record, &cfg).await; let asked = ts::request_count(&server).await; assert!(preview(&root, &cfg).await.is_none()); - assert_eq!(ts::request_count(&server).await, asked); + assert_eq!(ts::request_count(&server).await, asked + 1); + + // A wired lock whose copy holds another build than the list + // names now is judged by the list: the trees the wet run puts + // in place, for a published build and for a withdrawn one. + // Each patched build must be served, as for a fresh vendor. + let (withdrawn, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + match preview(&root, &cfg).await { + Some(LockedBuildsPreview::Vendor(builds)) => assert_eq!( + builds, + [ + named(DARWIN), + GemBuildEntry { + uuid: String::new(), + ..named(LINUX) + } + ] + ), + other => panic!("{other:?}"), + } + assert_eq!( + reference_requests(&withdrawn).await, + [vec![UUID.to_string()], vec![build_uuid(UUID, DARWIN)]] + ); + assert_eq!(downloads(&withdrawn).await, Vec::::new()); + let (_unserved, cfg) = + service(UUID, &[unserved(DARWIN, "pending_build"), upstream(LINUX)]).await; + assert!( + preview(&root, &cfg).await.is_none(), + "the copy stays as it is, as in the wet run" + ); } /// The preview words a skip as the wet run does when the Gemfile From 986a9631ab5a7cf9e907631f73da502254af3b2c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:54:28 -0500 Subject: [PATCH 08/28] Never make an intact vendored gem worse when its fix's list moves Review findings on the gem backend, with the rule that an intact committed copy is never made worse and a run never fails because of something it could have left alone. - An intact copy whose list moved went through the rebuild of a missing or stale copy, where any failure but the pending skip ended the run. When the list cannot be followed (a request that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) the copy now stays in force: the run ends as it does for a copy in step, with one line (`vendor_gem_list_not_followed`). A build the list names that is not served yet keeps its skip. A dry run says the same. The advisory of a copy that did follow its list has a code of its own (`vendor_gem_list_followed`). - A ledger entry that names no build of its trees says nothing of a moved list: no request is made for it and the copy stands. - The package references of several patches can be asked for in one request and remembered by the client: a later read of one of them makes no request, and a request that brought no answer is not made again per patch. A run asks for the lists of the gems it finds vendored this way, and the fix's reference is read once whether or not the list moved. - Upstream's own gem is downloaded with a client that follows no redirect: a redirect the registry answers is the gem not being served. - The skips of `locked_build_sources` (a platform the list leaves out, no patched build at all, a newer fix with fewer builds) are judged before an upstream gem the list does not pin fails the gem. - The download advisory names a copy of upstream's gems alone as such and says where it came from, the `.gitignore` advisory names the gems as they are, and the registry URL of an upstream gem is built in one place. - The ledger's doc comment says what each older reader does with a tree of upstream's gem. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 235 ++++++- crates/socket-patch-core/src/vendor/gem.rs | 603 +++++++++++++++--- crates/socket-patch-core/src/vendor/mod.rs | 20 + .../src/vendor/service_fetch.rs | 20 + crates/socket-patch-core/src/vendor/state.rs | 12 +- 5 files changed, 786 insertions(+), 104 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 11869b4c91..333682ed34 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -336,6 +336,15 @@ pub struct ApiClient { /// here so every blob/tarball download shares one connection pool /// instead of paying a fresh TLS-config build + handshake per request. plain: reqwest::Client, + /// `plain` that follows no redirect: for a download that must come + /// from the host it is asked of ([`Self::download_registry_gem`]). + plain_no_redirect: reqwest::Client, + /// The package references this client was told to remember + /// ([`Self::remember_vendor_references`]), by patch uuid: the answer, + /// or `None` for a patch that request brought no answer for. Shared by + /// clones. + remembered_references: + Arc>>>, api_url: String, /// Bearer token; always `None` on an [`ApiRoute::Proxy`] client. api_token: Option, @@ -629,7 +638,9 @@ impl ApiClient { }; Self { client: api_client(api_token.as_deref(), &timeouts), - plain: plain_client(&timeouts), + plain: plain_client(&timeouts, true), + plain_no_redirect: plain_client(&timeouts, false), + remembered_references: Arc::default(), api_url, api_token, route: options.route, @@ -715,7 +726,8 @@ impl ApiClient { /// cloning the client. pub fn with_api_timeouts(mut self, timeouts: ApiTimeouts) -> Self { self.client = api_client(self.api_token.as_deref(), &timeouts); - self.plain = plain_client(&timeouts); + self.plain = plain_client(&timeouts, true); + self.plain_no_redirect = plain_client(&timeouts, false); self } @@ -1866,6 +1878,55 @@ impl ApiClient { .collect()) } + /// Ask for the package references of `uuids` in ONE request (per + /// [`MAX_REFERENCE_BATCH`]) and remember what came back: a later + /// [`Self::fetch_vendor_reference`] of one of them, by this client or + /// a clone, is answered from here and makes no request. A patch the + /// request brought no answer for (it failed, or the response left the + /// patch out) is remembered as such, and a later ask of it fails at + /// once: a service that cannot be reached is asked once for all of + /// them, not once per patch. For a run that reads the references of + /// several patches one after another, over seconds. + pub async fn remember_vendor_references( + &self, + uuids: &[String], + free_only: bool, + vendor_url: Option<&str>, + ) { + let mut answers: std::collections::HashMap> = + uuids.iter().map(|uuid| (uuid.clone(), None)).collect(); + let refused = uuids + .iter() + .any(|uuid| self.vendor_request_refused(uuid).is_some()); + if !refused { + for chunk in uuids.chunks(MAX_REFERENCE_BATCH) { + match self + .request_vendor_references(chunk, free_only, vendor_url) + .await + { + Ok(answered) => { + self.vendor_outage.store(0, Ordering::Relaxed); + answers.extend( + answered + .into_iter() + .map(|(uuid, result)| (uuid, Some(result))), + ); + } + // As `note_vendor_outcome` counts one failed request. + Err((_, retryable)) => { + if retryable { + self.vendor_outage.fetch_add(1, Ordering::Relaxed); + } + break; + } + } + } + } + if let Ok(mut held) = self.remembered_references.lock() { + held.extend(answers); + } + } + /// Attach a download plan: `uuids` are the packages the vendor loop is /// expected to download from the service, in loop order, with these /// request parameters. Until the guard drops, the loop's @@ -2077,6 +2138,25 @@ impl ApiClient { free_only: bool, vendor_url: Option<&str>, ) -> Result { + let remembered = self + .remembered_references + .lock() + .ok() + .and_then(|held| held.get(uuid).cloned()); + match remembered { + Some(Some(result)) => return Ok(result), + // Asked moments ago, in this run, and not answered: not asked + // again. The failed request was counted when it was made. + Some(None) => { + return Err(( + ApiError::Network(format!( + "the patch service did not answer for {uuid} earlier in this run" + )), + false, + )) + } + None => {} + } let plan = self .vendor_prefetch .lock() @@ -2278,6 +2358,20 @@ impl ApiClient { url: &str, max_bytes: u64, noun: &str, + ) -> Result { + self.serve_get_once_with(&self.plain, url, max_bytes, noun) + .await + } + + /// [`Self::serve_get_once`] with `client`, which is `plain` or its + /// twin that follows no redirect: a redirect that one is answered is + /// a terminal miss, like a 404. + async fn serve_get_once_with( + &self, + client: &reqwest::Client, + url: &str, + max_bytes: u64, + noun: &str, ) -> Result { if !(url.starts_with("https://") || url.starts_with("http://")) { return Err(( @@ -2293,7 +2387,7 @@ impl ApiClient { // below gets its own (larger) bound — archives can be big. let sent = tokio::time::timeout( self.vendor_retry.attempt_timeout, - self.plain + client .get(url) .header(header::ACCEPT, "application/octet-stream") .send(), @@ -2327,6 +2421,8 @@ impl ApiClient { // 404 (build_failed / not stored) and 410 (withdrawn) are terminal // misses; the caller decides build-fallback vs hard-fail. StatusCode::NOT_FOUND | StatusCode::GONE => return Ok(ServeDownload::NotFound), + // Only the client that follows none is answered a redirect. + status if status.is_redirection() => return Ok(ServeDownload::NotFound), // 408 = the archive is still building (Retry-After) — the // caller's pending policy, never retried here. StatusCode::REQUEST_TIMEOUT => return Ok(ServeDownload::Pending), @@ -2382,6 +2478,25 @@ impl ApiClient { artifact_download_result(self.download_vendor_archive(url, None).await, url) } + /// [`Self::download_artifact`] for a gem file a patch registry lists + /// as upstream's own (`/gems/`), which a vendored copy + /// takes from the patch service and from nowhere else: no redirect is + /// followed, and one the registry answers is the gem not being served + /// ("artifact not found"). + pub(crate) async fn download_registry_gem(&self, url: &str) -> Result, ApiError> { + let outcome = self + .retry_vendor(url, "vendor package download", None, || { + self.serve_get_once_with( + &self.plain_no_redirect, + url, + MAX_VENDOR_PACKAGE_BYTES, + "vendor package", + ) + }) + .await; + artifact_download_result(outcome, url) + } + /// The first attempt of [`Self::download_artifact`] alone: `Ok` with /// exactly the result `download_artifact` would return when that attempt /// settles it (success, or a failure it would not retry), `Err` with the @@ -2794,18 +2909,21 @@ fn api_client(api_token: Option<&str>, timeouts: &ApiTimeouts) -> reqwest::Clien /// A serve URL holds its grant token in the path, and a serve route can /// answer with a redirect to another host, which the client follows. No /// `Referer` is set on the way: it would hand that URL to the next host. -fn plain_client(timeouts: &ApiTimeouts) -> reqwest::Client { +fn plain_client(timeouts: &ApiTimeouts, follow_redirects: bool) -> reqwest::Client { let mut headers = HeaderMap::new(); headers.insert( header::USER_AGENT, HeaderValue::from_static(USER_AGENT_VALUE), ); + let builder = crate::utils::http::client_builder() + .default_headers(headers) + .referer(false); + let builder = match follow_redirects { + true => builder, + false => builder.redirect(reqwest::redirect::Policy::none()), + }; timeouts - .apply( - crate::utils::http::client_builder() - .default_headers(headers) - .referer(false), - ) + .apply(builder) .build() .expect("failed to build plain reqwest client") } @@ -6236,6 +6354,105 @@ mod vendor_package_tests { assert!(!sent.contains(GRANT), "the grant token: {sent}"); } + /// Upstream's own gem of a patch registry is taken from that registry + /// alone: a redirect it answers is not followed, and is the gem not + /// being served. The file itself downloads as any artifact does. + #[tokio::test] + async fn download_registry_gem_follows_no_redirect() { + let registry = MockServer::start().await; + let elsewhere = MockServer::start().await; + let redirected = "/patch-registry/gem/tok/u/s/4f/gems/a-1.0.0-java.gem"; + let relayed = "/patch-registry/gem/tok/u/s/4f/gems/a-1.0.0-x86_64-linux.gem"; + Mock::given(method("GET")) + .and(path(redirected)) + .respond_with(ResponseTemplate::new(302).insert_header( + "Location", + format!("{}/gems/a.gem", elsewhere.uri()).as_str(), + )) + .mount(®istry) + .await; + Mock::given(method("GET")) + .and(path(relayed)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"upstream".to_vec())) + .mount(®istry) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"elsewhere".to_vec())) + .mount(&elsewhere) + .await; + let client = auth_client(registry.uri()); + let err = client + .download_registry_gem(&format!("{}{redirected}", registry.uri())) + .await + .expect_err("a redirect is the gem not being served"); + assert!(err.to_string().contains("artifact not found"), "{err}"); + let asked = elsewhere.received_requests().await.unwrap_or_default(); + assert!(asked.is_empty(), "the redirect was followed: {asked:?}"); + let bytes = client + .download_registry_gem(&format!("{}{relayed}", registry.uri())) + .await + .expect("the registry's own file"); + assert_eq!(bytes, b"upstream"); + } + + /// References asked for at once are remembered: a later read of one + /// of them, by the client or a clone, makes no request, whatever the + /// answer was. A patch the response leaves out, and every patch of a + /// request that failed, fails at once on a later read, with no request. + #[tokio::test] + async fn remembered_references_answer_later_reads_without_a_request() { + const SERVED: &str = "22222222-2222-4222-8222-222222222222"; + const BUILDING: &str = "33333333-3333-4333-8333-333333333333"; + const LEFT_OUT: &str = "44444444-4444-4444-8444-444444444444"; + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0/orgs/acme/patches/package")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "results": { + SERVED: { + "status": "granted", + "url": format!("{}/patch/gem/a.gem", server.uri()), + "artifacts": [ + { "kind": "tarball", "integrity": { "sha512": "sha512-GEM==" } } + ] + }, + BUILDING: { "status": "pending_build", "url": null, "artifacts": [] } + } + }))) + .expect(1) + .mount(&server) + .await; + let client = auth_client(server.uri()); + let uuids = [SERVED, BUILDING, LEFT_OUT].map(str::to_string); + client.remember_vendor_references(&uuids, false, None).await; + for _ in 0..2 { + let clone = client.clone(); + let served = clone.fetch_vendor_reference(SERVED, false, None, None); + assert!(matches!(served.await, VendorServiceOutcome::Ready(_))); + } + let building = client.fetch_vendor_reference(BUILDING, false, None, None); + assert!(matches!(building.await, VendorServiceOutcome::Pending)); + let left_out = client.fetch_vendor_reference(LEFT_OUT, false, None, None); + assert!(matches!(left_out.await, VendorServiceOutcome::Failed(_))); + assert_eq!( + server.received_requests().await.unwrap_or_default().len(), + 1 + ); + + // A request that fails is made once for all of its patches. + let down = MockServer::start().await; + let client = auth_client(down.uri()).with_vendor_retry(VendorRetryPolicy::none()); + client.remember_vendor_references(&uuids, false, None).await; + for uuid in &uuids { + let read = client.fetch_vendor_reference(uuid, false, None, None); + assert!( + matches!(read.await, VendorServiceOutcome::Failed(_)), + "{uuid}" + ); + } + assert_eq!(down.received_requests().await.unwrap_or_default().len(), 1); + } + /// A promised secondary that 404s must ERROR ("artifact not found"), /// and a still-building 408 maps to "artifact still building" — the /// arms encoding the no-soft-skip policy for promised artifacts. diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index e13a6deb96..b89debc2e9 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -964,6 +964,11 @@ async fn moved_sources( return None; }; let entry = recorded_copy(project_root, uuid, copy_rel).await?; + // An entry that names no build of its trees (a development build's + // ledger) cannot say that the list names another one: the copy stands. + if entry.gem_builds.is_empty() { + return None; + } let sources = locked_build_sources(cfg, uuid, name, trees, platforms) .await .ok()?; @@ -1371,7 +1376,7 @@ pub async fn vendor_gem_previewing<'a>( return refusal; } let mut warnings: Vec = Vec::new(); - let (result, builds) = match materialise_patched_copy( + let materialised = materialise_patched_copy( purl, copy_dir, uuid_dir, @@ -1382,30 +1387,37 @@ pub async fn vendor_gem_previewing<'a>( service, &mut warnings, ) - .await - { - Ok(materialised) => materialised, + .await; + let (result, builds) = match materialised { + Ok((result, builds)) if result.success => (result, builds), + // The copy was intact, and only the list said to vendor it + // again: it stays in force, whatever went wrong. + failed if moved => { + let failed = failed.map(|(result, _)| result); + return list_not_followed(failed, project_root, record, &prelude).await; + } + Ok((result, _)) => return done(result, None, warnings), Err(outcome) => { return wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await } }; - if !result.success { - return done(result, None, warnings); - } - warnings.push(VendorWarning::new( - "vendor_artifact_rebuilt", - match moved { - true => format!( + warnings.push(match moved { + true => VendorWarning::new( + GEM_LIST_FOLLOWED, + format!( "the patch registry lists other builds for {name}@{version} than the \ - vendored copy holds; vendored again at {copy_rel} (Gemfile and \ + vendored copy held; vendored again at {copy_rel} (Gemfile and \ Gemfile.lock untouched)" ), - false => format!( + ), + false => VendorWarning::new( + "vendor_artifact_rebuilt", + format!( "the committed vendored copy for {name}@{version} was missing or \ stale; rebuilt at {copy_rel} (Gemfile and Gemfile.lock untouched)" ), - }, - )); + ), + }); // The rebuilt tree may differ from the one the ledger // inventoried (a service ↔ local flip swaps the stub gemspec): // hand back a refreshed entry. Its wiring is empty ON PURPOSE — @@ -1445,6 +1457,10 @@ pub async fn vendor_gem_previewing<'a>( }; match checked { Ok(builds) => *previewed = builds, + // As the wet run settles it: an intact copy stays in force. + Err(outcome) if moved => { + return list_not_followed(Err(outcome), project_root, record, &prelude).await + } Err(outcome) => { return match lock_wired { true => wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await, @@ -1673,6 +1689,66 @@ pub async fn vendor_gem_previewing<'a>( done(result, Some(entry), warnings) } +/// Advisory of a run that vendored an intact copy again because the list +/// of the gem's fix names another build for a locked platform than the +/// copy held: a patched build published since, or upstream's gem where +/// the patched build was withdrawn. The entry it comes with replaces the +/// copy's own, as an artifact rebuild's does. +pub const GEM_LIST_FOLLOWED: &str = "vendor_gem_list_followed"; + +/// Advisory of a run that found the same and could not vendor the copy +/// again (a request that failed, a build that is not served or fails its +/// digest, a gem that does not unpack): the copy is intact and stays in +/// force as it is, and the run ends as it does for a copy in step. +pub const GEM_LIST_NOT_FOLLOWED: &str = "vendor_gem_list_not_followed"; + +/// The outcome of an INTACT copy the lock is wired to that this run tried +/// to vendor again, because the list of the gem's fix names another build +/// for a locked platform, and could not (`failed`: the refusal, or the +/// result that did not succeed). The copy is never made worse and the run +/// never fails over it: nothing of the copy was touched (the new one is +/// staged beside it), so it stays in force and the run reports it as it +/// reports a copy in step, with one line that says why it was not brought +/// in step ([`GEM_LIST_NOT_FOLLOWED`]). A build the list names that is not +/// served yet keeps the skip of [`wired_copy_not_rebuilt`]. +async fn list_not_followed( + failed: Result>, + project_root: &Path, + record: &PatchRecord, + prelude: &GemPrelude, +) -> VendorOutcome { + let why = match failed { + Err(outcome) => match *outcome { + VendorOutcome::Refused { code, detail } + if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => + { + let pending = refused(code, detail); + return wired_copy_not_rebuilt(pending, project_root, record, prelude).await; + } + VendorOutcome::Refused { detail, .. } => detail, + VendorOutcome::Done { result, .. } => result.error.unwrap_or_default(), + }, + Ok(result) => result.error.unwrap_or_default(), + }; + let why = match why.trim().trim_end_matches('.') { + "" => String::new(), + why => format!(" ({why})"), + }; + let purl = build_gem_purl(&prelude.name, &prelude.version); + done( + already_patched_result(&purl, &prelude.copy_dir, &record.files), + None, + vec![VendorWarning::new( + GEM_LIST_NOT_FOLLOWED, + format!( + "{}@{} could not be brought in step with the builds the patch registry lists{why}; \ + its vendored copy stays in force as it is.", + prelude.name, prelude.version + ), + )], + ) +} + /// The outcome of a copy the lock is ALREADY wired to that this run could /// not rebuild because a locked platform has no patched build /// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). While the copy the @@ -2220,65 +2296,33 @@ async fn locked_build_sources( let Some(builds) = served.gem_builds.as_deref() else { return Err(no_builds_listed_skip(trees)); }; - let version = trees - .gem - .rsplit_once('@') - .map_or("", |(_, version)| version); - let mut sources: Vec = Vec::with_capacity(platforms.len()); + let mut listed = Vec::with_capacity(platforms.len()); let mut missing = NoPatchedBuild::default(); for platform in platforms { - let Some(build) = builds.iter().find(|build| build.platform == *platform) else { - missing.unlisted.push(platform); - continue; - }; - let pinned = BuildPin::Registry(build.gem_checksum_sha256.clone()); - let upstream = match build.patch_uuid { - Some(_) => None, - // Upstream's own gem, from the registry that lists it. - None => { - let listed = served - .gem_index_url - .as_deref() - .zip(sha256_sri(&build.gem_checksum_sha256)); - let Some((index, integrity_sri)) = listed else { - return Err(policy.miss(format!( - "the patch service names no registry or no sha256 for upstream's \ - gem of {name} ({platform})" - ))); - }; - Some(crate::api::client::SecondaryArtifact { - kind: "gem".to_string(), - url: format!( - "{}/gems/{name}-{version}-{platform}.gem", - index.trim_end_matches('/') - ), - integrity_sri, - prefetched: None, - }) - } - }; - sources.push(BuildSource { - platform: platform.clone(), - uuid: build.patch_uuid.clone().unwrap_or_default(), - upstream, - pinned, - }); + match builds.iter().find(|build| build.platform == *platform) { + Some(build) => listed.push((platform, build)), + None => missing.unlisted.push(platform), + } } - // A platform the list leaves out has no gem to vendor at all. + // The skips first: a gem that is left as it is whatever its gems are + // is never failed over one of them. A platform the list leaves out + // has no gem to vendor at all. if !missing.is_empty() { return Err(no_patched_build(trees, &missing, &[])); } - let of = |upstream: bool| -> Vec<&str> { - let kept = sources.iter().filter(|s| s.upstream.is_some() == upstream); - kept.map(|s| s.platform.as_str()).collect() + let of = |patched: bool| -> Vec<&str> { + let kept = listed + .iter() + .filter(|(_, build)| build.patch_uuid.is_some() == patched); + kept.map(|(platform, _)| platform.as_str()).collect() }; - let patched = of(false); + let patched = of(true); // With no patched build among the locked platforms there is nothing // to vendor the gem for. A copy the lock is already wired to follows // the list all the same, as a hosted lock does: its builds were // withdrawn, and its trees go back to upstream's gems. if patched.is_empty() && trees.standing != Standing::Wired { - return Err(none_patched_skip(trees, &of(true))); + return Err(none_patched_skip(trees, &of(false))); } let lost: Vec<&str> = trees .held @@ -2289,16 +2333,68 @@ async fn locked_build_sources( if !lost.is_empty() { return Err(newer_fix_waits(trees, &lost)); } + let mut sources: Vec = Vec::with_capacity(listed.len()); + for (platform, build) in listed { + let upstream = match build.patch_uuid { + Some(_) => None, + // Upstream's own gem, from the registry that lists it. + None => { + let index = served.gem_index_url.as_deref(); + let gem = upstream_gem_artifact(index, trees.gem, platform, build); + Some(gem.ok_or_else(|| { + policy.miss(format!( + "the patch service names no registry or no sha256 for upstream's \ + gem of {name} ({platform})" + )) + })?) + } + }; + sources.push(BuildSource { + platform: platform.clone(), + uuid: build.patch_uuid.clone().unwrap_or_default(), + upstream, + pinned: BuildPin::Registry(build.gem_checksum_sha256.clone()), + }); + } Ok(sources) } +/// The version of `gem` (`@`, as [`PlatformTrees::gem`] +/// names it). +fn gem_version(gem: &str) -> &str { + gem.rsplit_once('@').map_or("", |(_, version)| version) +} + +/// Upstream's own gem of `platform` as the registry at `index` (the +/// gem patch's `indexUrl`) serves it and `listed` pins it: the file +/// `/gems/--.gem`, with the sha256 of the +/// list. `None` when the reference names no registry, or no sha256 that +/// is one. `gem` is `@`. +fn upstream_gem_artifact( + index: Option<&str>, + gem: &str, + platform: &str, + listed: &crate::patch::redirect::GemPlatformChecksum, +) -> Option { + let (name, version) = gem.rsplit_once('@')?; + Some(crate::api::client::SecondaryArtifact { + kind: "gem".to_string(), + url: format!( + "{}/gems/{name}-{version}-{platform}.gem", + index?.trim_end_matches('/') + ), + integrity_sri: sha256_sri(&listed.gem_checksum_sha256)?, + prefetched: None, + }) +} + /// A restore found that the build a ledger entry records for a platform is /// no longer the one the list of the gem's fix names for it: it was rebuilt /// under another patch or with other bytes, or withdrawn. A fix that /// carries no list says neither ([`no_builds_listed`]). /// Nothing is unpacked. Not an integrity failure: the same state follows /// an edited ledger, and neither is told from the other here. -pub(crate) const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; +pub const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; /// The sources of the trees a ledger entry records, for a restore. /// @@ -2367,10 +2463,13 @@ async fn recorded_build_sources( // entry pins. if built.is_upstream() { let upstream = now.filter(|gem| gem.patch_uuid.is_none()).and_then(|gem| { - let index = served.gem_index_url.as_deref()?; - Some((gem, index, sha256_sri(&gem.gem_checksum_sha256)?)) + let index = served.gem_index_url.as_deref(); + Some(( + gem, + upstream_gem_artifact(index, trees.gem, &built.platform, gem)?, + )) }); - let Some((gem, index, integrity_sri)) = upstream else { + let Some((gem, artifact)) = upstream else { return Err(policy.hard( VENDOR_PREBUILT_REPLACED, format!( @@ -2394,23 +2493,10 @@ async fn recorded_build_sources( ), )); } - let version = trees - .gem - .rsplit_once('@') - .map_or("", |(_, version)| version); sources.push(BuildSource { platform: built.platform.clone(), uuid: String::new(), - upstream: Some(crate::api::client::SecondaryArtifact { - kind: "gem".to_string(), - url: format!( - "{}/gems/{name}-{version}-{}.gem", - index.trim_end_matches('/'), - built.platform - ), - integrity_sri, - prefetched: None, - }), + upstream: Some(artifact), pinned: BuildPin::Restored { sha256: gem.gem_checksum_sha256.clone(), gem: built.gem_integrity.clone(), @@ -2657,16 +2743,16 @@ async fn stage_platform_builds( }; let builds = served_builds(cfg, name, trees, &sources).await?; - let version = trees - .gem - .rsplit_once('@') - .map_or("", |(_, version)| version); + let version = gem_version(trees.gem); // The gems, a few platforms at a time and taken in lock order. let mut downloads = std::pin::pin!(futures_util::stream::iter(&builds) .map(|(source, subject, gem, stub)| async move { let what = gem_noun(source); - let gem_bytes = build_artifact(cfg, gem, what, subject).await?; + // Upstream's own gem comes from the patch registry and from + // nowhere it might point to. + let from_registry = source.upstream.is_some(); + let gem_bytes = build_artifact(cfg, gem, what, subject, from_registry).await?; source.pinned.check_gem(&gem_bytes, what, subject)?; let Some(stub) = stub else { // Upstream's own gem: its gemspec is the one it carries, @@ -2675,7 +2761,7 @@ async fn stage_platform_builds( let gemspec = upstream_gemspec(&gem_bytes, &leaf, subject)?; return Ok((gem_bytes, gemspec, BTreeMap::new())); }; - let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject).await?; + let stub_bytes = build_artifact(cfg, stub, "stub gemspec", subject, false).await?; source.pinned.check_stub(&stub_bytes, subject)?; let files = build_files(cfg, source, subject).await?; Ok::<_, Box>((gem_bytes, stub_bytes, files)) @@ -2752,9 +2838,12 @@ async fn stage_platform_builds( }); } + // Where the copy came from: a patched build's gem, else (a copy of + // upstream's gems alone, after a withdrawal) the first gem of it. let source_url = builds .iter() .find(|(source, ..)| source.upstream.is_none()) + .or(builds.first()) .map(|(_, _, gem, _)| gem.url.as_str()) .unwrap_or_default(); let of = |upstream: bool| -> Vec<&str> { @@ -2763,20 +2852,30 @@ async fn stage_platform_builds( .filter(|(source, ..)| source.upstream.is_some() == upstream); kept.map(|(source, ..)| source.platform.as_str()).collect() }; - let subject = match of(true).as_slice() { - [] => format!("{name} as patched platform gems ({})", platforms.join(", ")), - upstream => format!( + let (patched, upstream) = (of(false), of(true)); + let subject = match (patched.as_slice(), upstream.as_slice()) { + (_, []) => format!("{name} as patched platform gems ({})", platforms.join(", ")), + ([], upstream) => format!( + "{name} as upstream's own platform gems ({})", + upstream.join(", ") + ), + (patched, upstream) => format!( "{name} as platform gems (patched: {}; upstream's own: {})", - of(false).join(", "), + patched.join(", "), upstream.join(", ") ), }; let mut warnings = vec![downloaded_warning(subject, source_url)]; if !emptied.is_empty() { + // Whose `.gitignore` it is: the gems of the copy, patched or not. + let gems = match upstream.is_empty() { + true => "the patched platform gems", + false => "the platform gems", + }; warnings.push(VendorWarning::new( GITIGNORE_NEUTRALIZED, format!( - "{name}: the patched platform gems ship their own `.gitignore` ({}), whose \ + "{name}: {gems} ship their own `.gitignore` ({}), whose \ rules would keep git from committing files of the vendored trees; emptied in \ the vendored copy (commit it)", super::npm_dir::summarize_rules(&emptied) @@ -2958,9 +3057,14 @@ async fn build_artifact( artifact: &crate::api::client::SecondaryArtifact, what: &str, subject: &str, + from_registry: bool, ) -> Result, Box> { let policy = ServicePolicy::Refused; - match fetch_verified_artifact(cfg, Some(artifact)).await { + let fetched = match from_registry { + true => super::service_fetch::fetch_verified_registry_gem(cfg, artifact).await, + false => fetch_verified_artifact(cfg, Some(artifact)).await, + }; + match fetched { SecondaryArtifactResult::Ready(bytes) => Ok(bytes), SecondaryArtifactResult::Absent => { Err(policy.miss(format!("the patch service served no {what} for {subject}"))) @@ -13933,10 +14037,34 @@ mod tests { let entry = entry.expect("the copy's new ledger entry"); assert_eq!(entry.gem_builds, expected); assert!( - warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt" + warnings.iter().any(|w| w.code == GEM_LIST_FOLLOWED && w.detail.contains("lists other builds for nokogiri@1.18.10")), "{warnings:?}" ); + // The download advisory names the gems as they are: the + // patched ones, upstream's, or both, and where they came + // from. + let all_upstream = expected.iter().all(GemBuildEntry::is_upstream); + let downloaded: Vec<&str> = warnings + .iter() + .filter(|w| w.code == "vendor_prebuilt_downloaded") + .map(|w| w.detail.as_str()) + .collect(); + let [downloaded] = downloaded.as_slice() else { + panic!("one download advisory: {warnings:?}"); + }; + assert!( + !downloaded.contains("patched: ;") && downloaded.contains(" (http"), + "{downloaded}" + ); + assert_eq!( + downloaded.contains( + "vendored nokogiri as upstream's own platform gems (arm64-darwin, \ + x86_64-linux-gnu) from the patch service (http" + ), + all_upstream, + "{downloaded}" + ); ts::persist(&root, NOKO, entry).await; let saved = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); assert_eq!( @@ -13968,6 +14096,295 @@ mod tests { } } + /// An intact copy is never made worse, and a run never fails over + /// something it could have left alone. When the list names another + /// build for a locked platform and that build cannot be vendored + /// (its gem fails the digest, its stub is not served, upstream's + /// gem does not unpack), nothing of the copy is touched: the run + /// ends as it does for a copy in step, with the one line that says + /// the copy stays in force. A build the list names that is not + /// served yet keeps its skip. A dry run says the same. An entry + /// that names no build of its trees says nothing of the list: no + /// request is made for it. + #[tokio::test] + async fn an_intact_copy_stays_in_force_when_the_list_cannot_be_followed() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let before = ts::tree_snapshot(&root); + let another = make_gem(&[(RB, &stamped(LINUX)), (SO, &b"another"[..])]); + let failing: [(Vec, &str); 3] = [ + ( + vec![ + served(DARWIN), + Served { + gem_sha512: Some(sri_sha512(&another)), + ..served(LINUX) + }, + ], + "failed integrity verification", + ), + ( + vec![ + served(DARWIN), + Served { + stub: None, + ..served(LINUX) + }, + ], + "stub gemspec", + ), + ( + vec![ + Served { + gem: Some(b"not a gem".to_vec()), + ..upstream(DARWIN) + }, + upstream(LINUX), + ], + "arm64-darwin", + ), + ]; + for (list, why) in failing { + let (_server, cfg) = service(UUID, &list).await; + for dry_run in [true, false] { + let (result, rerun_entry, warnings) = unwrap_done( + vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, + ); + assert!(result.success, "{why}: {:?}", result.error); + assert!(rerun_entry.is_none(), "{why}: the ledger entry stands"); + let [said] = warnings.as_slice() else { + panic!("{why}: one line: {warnings:?}"); + }; + assert_eq!(said.code, GEM_LIST_NOT_FOLLOWED, "{why}"); + assert!( + said.detail.starts_with( + "nokogiri@1.18.10 could not be brought in step with the builds the \ + patch registry lists (" + ) && said + .detail + .ends_with("); its vendored copy stays in force as it is.") + && said.detail.contains(why), + "{why}: {}", + said.detail + ); + assert_eq!(ts::tree_snapshot(&root), before, "{why}: byte for byte"); + } + } + + // A build the list names that is not served yet: the skip. + let (_server, cfg) = + service(UUID, &[served(DARWIN), unserved(LINUX, "pending_build")]).await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!( + detail.ends_with("; its vendored copy stays in force as it is."), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + + // An entry that names no build of its trees (a development + // build's ledger), over trees that hold the files of the gem's + // own patch, which is what such an entry is checked against. + let plain = |platform: &'static str| Served { + gem: Some(make_gem(&[(RB, RB_PATCHED), (SO, platform.as_bytes())])), + files: BTreeMap::from([( + RB.to_string(), + PatchFileInfo { + before_hash: compute_git_sha256_from_bytes(RB_PRISTINE), + after_hash: compute_git_sha256_from_bytes(RB_PATCHED), + }, + )]), + ..served(platform) + }; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[plain(DARWIN), plain(LINUX)]).await; + let mut no_builds = vendor_and_persist(&root, &record, &cfg).await; + no_builds.gem_builds.clear(); + ts::persist(&root, NOKO, no_builds).await; + let ledgered = ts::tree_snapshot(&root); + let (server, cfg) = service(UUID, &[plain(DARWIN), upstream(LINUX)]).await; + let (result, rerun_entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!(rerun_entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, 0); + assert_eq!(ts::tree_snapshot(&root), ledgered); + } + + /// The lists of the gems a run finds already vendored are asked + /// for in one request, ahead of the gems + /// ([`VendorServiceConfig::remember_references`]). A copy in step + /// then asks nothing more, a copy whose list moved reads the fix's + /// reference from that answer (it is asked for once in all), and a + /// service that does not answer is asked once: the copy stands. + #[tokio::test] + async fn the_lists_asked_for_at_once_serve_the_gems_that_follow_them() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let fixes = [UUID.to_string()]; + + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + cfg.remember_references(&fixes).await; + assert_eq!(ts::request_count(&server).await, 1); + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&server).await, 1, "read from the answer"); + + // No answer: one request (this client retries nothing), and the + // copy stands with nothing said. + let down = wiremock::MockServer::start().await; + let cfg = ts::service_cfg(&down.uri(), crate::vendor::VendorSource::Service, false); + let before = ts::tree_snapshot(&root); + cfg.remember_references(&fixes).await; + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&down).await, 1); + assert_eq!(ts::tree_snapshot(&root), before); + + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + cfg.remember_references(&fixes).await; + let (result, entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert_eq!( + entry.expect("the copy's new entry").gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)] + ); + assert_eq!( + reference_requests(&server).await, + [ + vec![UUID.to_string()], + vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)] + ], + "the fix's reference once, then the builds' in one request" + ); + } + + /// A gem that is left as it is whatever its gems are is never + /// failed over one of them: the skips are judged before an + /// upstream gem the list does not pin. Beside a patched build that + /// gem is the miss it was. Upstream's gem is taken from the patch + /// registry alone: a redirect it answers is the gem not being + /// served, and is not followed. + #[tokio::test] + async fn a_skip_is_judged_before_an_upstream_gem_that_cannot_be_fetched() { + use wiremock::matchers::{method, path}; + use wiremock::{Mock, ResponseTemplate}; + let unpinned = |platform| Served { + listed_sha256: Some("not a sha256".to_string()), + ..upstream(platform) + }; + let unlisted = Served { + listed: Listed::Unlisted, + ..served(LINUX) + }; + let skips = [ + ( + vec![unpinned(DARWIN), unlisted], + "the patch registry does not list x86_64-linux-gnu", + ), + ( + vec![unpinned(DARWIN), upstream(LINUX)], + "is not vendored: no patched build yet for arm64-darwin and \ + x86_64-linux-gnu.", + ), + ]; + for (list, says) in skips { + let (_tmp, root, record) = project(&lock(None)).await; + let (server, cfg) = service(UUID, &list).await; + let (code, detail) = unwrap_refused( + vendor(&root, ¬_installed(&root), &record, &cfg, false).await, + ); + assert_eq!( + code, + crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, + "{detail}" + ); + assert!(detail.contains(says), "{detail}"); + assert_eq!(downloads(&server).await, Vec::::new()); + } + + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[unpinned(DARWIN), served(LINUX)]).await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_REQUIRED, "{detail}"); + assert!( + detail.contains("no sha256 for upstream's gem of nokogiri (arm64-darwin)"), + "{detail}" + ); + assert!(!root.join(".socket/vendor/gem").exists()); + + // The registry answers the gem's file with a redirect. + let elsewhere = wiremock::MockServer::start().await; + let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let file = + format!("/patch-registry/gem/tok/{UUID}/s/4/gems/nokogiri-1.18.10-{LINUX}.gem"); + Mock::given(method("GET")) + .and(path(file.as_str())) + .respond_with(ResponseTemplate::new(302).insert_header( + "Location", + format!("{}/gems/nokogiri-1.18.10-{LINUX}.gem", elsewhere.uri()).as_str(), + )) + .with_priority(1) + .mount(&server) + .await; + let (code, detail) = + unwrap_refused(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_REQUIRED, "{detail}"); + assert!( + detail.contains( + "could not fetch the upstream platform gem for nokogiri (x86_64-linux-gnu) \ + (artifact not found" + ), + "{detail}" + ); + assert_eq!( + ts::request_count(&elsewhere).await, + 0, + "no redirect is followed" + ); + assert!(!root.join(".socket/vendor/gem").exists()); + } + + /// A `.gitignore` a gem of the copy ships is emptied whichever gem + /// it is, and the advisory names the gems as they are. + #[tokio::test] + async fn a_gitignore_upstreams_gem_ships_is_emptied_and_named_as_such() { + let (_tmp, root, record) = project(&lock(None)).await; + let shipping = Served { + gem: Some(make_gem_with_metadata( + upstream_gemspec_yaml(LINUX).as_bytes(), + &[(RB, RB_PRISTINE), (".gitignore", &b"*.so\n"[..])], + )), + ..upstream(LINUX) + }; + let (_server, cfg) = service(UUID, &[served(DARWIN), shipping]).await; + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let said: Vec<&str> = warnings + .iter() + .filter(|w| w.code == GITIGNORE_NEUTRALIZED) + .map(|w| w.detail.as_str()) + .collect(); + assert!( + matches!(said.as_slice(), [said] if said.starts_with( + "nokogiri: the platform gems ship their own `.gitignore` (" + )), + "{warnings:?}" + ); + let emptied = root.join(rel(UUID)).join(LINUX).join(".gitignore"); + assert_eq!(tokio::fs::read(emptied).await.unwrap(), b""); + } + /// A fresh vendor of a gem none of whose locked platforms has a /// patched build is the skip it was, whatever the list names for /// them, and an upstream gem that is not the one the list names diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index d3c3ec8f2b..df8c9d7aec 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -390,6 +390,26 @@ impl VendorServiceConfig { && crate::utils::concurrent::api_concurrency(self.use_public_proxy) > 1 } + /// Ask the service, in ONE request, for the package references of + /// `uuids` and keep the answers for this run's later reads of them + /// (see + /// [`crate::api::client::ApiClient::remember_vendor_references`]). + /// Nothing is asked offline or with no client. + pub async fn remember_references(&self, uuids: &[String]) { + if uuids.is_empty() || !self.service_enabled() { + return; + } + if let Some(client) = self.client.as_ref() { + client + .remember_vendor_references( + uuids, + self.use_public_proxy, + self.vendor_url.as_deref(), + ) + .await; + } + } + /// Attach a download plan to this config's client: `downloads` are the /// records the vendor loop is expected to download from the service, /// in loop order, each with the secondary artifact its backend fetches diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index 54e672eb85..608f13ad48 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -462,6 +462,25 @@ pub(crate) async fn fetch_verified_secondary( pub(crate) async fn fetch_verified_artifact( cfg: &VendorServiceConfig, artifact: Option<&SecondaryArtifact>, +) -> SecondaryArtifactResult { + fetch_verified(cfg, artifact, false).await +} + +/// [`fetch_verified_artifact`] for a gem file a patch registry lists as +/// upstream's own: it is taken from the patch service alone, so no +/// redirect is followed +/// ([`crate::api::client::ApiClient::download_registry_gem`]). +pub(crate) async fn fetch_verified_registry_gem( + cfg: &VendorServiceConfig, + artifact: &SecondaryArtifact, +) -> SecondaryArtifactResult { + fetch_verified(cfg, Some(artifact), true).await +} + +async fn fetch_verified( + cfg: &VendorServiceConfig, + artifact: Option<&SecondaryArtifact>, + registry_gem: bool, ) -> SecondaryArtifactResult { let Some(client) = cfg.client.as_ref() else { return SecondaryArtifactResult::Failed("vendor service not configured".to_string()); @@ -474,6 +493,7 @@ pub(crate) async fn fetch_verified_artifact( // live request (its debug lines print here, where this call's would). let downloaded = match artifact.prefetched.as_ref().and_then(|p| p.take()) { Some(held) => held.release(), + None if registry_gem => client.download_registry_gem(&artifact.url).await, None => client.download_artifact(&artifact.url).await, }; let bytes = match downloaded { diff --git a/crates/socket-patch-core/src/vendor/state.rs b/crates/socket-patch-core/src/vendor/state.rs index 4d602fb719..1c946c8642 100644 --- a/crates/socket-patch-core/src/vendor/state.rs +++ b/crates/socket-patch-core/src/vendor/state.rs @@ -367,8 +367,16 @@ pub struct GemBuildEntry { /// no patch, no gemspec digest and no files: nothing in it is patched, /// the copy's file inventory vouches for every byte of it as it does /// for a patched tree, and its gem digest is what a restore fetches - /// it again by. A reader that requires a patch of every tree fails on - /// the entry, and so never attests the tree as patched. + /// it again by. + /// + /// Older readers: one that requires a patch of every tree (the first + /// to record `gemBuilds`) fails on the entry. One that knows no + /// `gemBuilds` ignores the key and judges the trees it finds on disk + /// by the files of the gem's patch and the copy's inventory, under + /// which a tree that ships none of the patched files passes: it + /// would take a tree of upstream's gem for a patched one whenever that + /// gem ships none of them. A project vendored this way must not be + /// attested by a CLI that does not read this entry. #[serde(default, skip_serializing_if = "String::is_empty")] pub uuid: String, /// The digest (SRI) of the platform `.gem` the tree was unpacked From f218b631c798e1e4d8519cf5eca75002d26b5d5f Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:54:28 -0500 Subject: [PATCH 09/28] Vendor a damaged gem copy from the list once the list moved, and count real skips Review findings on the CLI side of a gem vendored as platform gems. - The vendor loop restores a damaged copy before it reaches the backend and stopped at a restore error. A restore that is refused only because the list of the gem's fix names other builds now (`vendor_prebuilt_replaced`) goes on to the backend, which vendors the copy again from that list, as it does for an intact copy. `repair` still refuses and names the scan. A ledger edited to name another patch for a tree looks the same and is settled the same way: the list chooses what is unpacked. - The lists of the gems already vendored as platform gems are asked for in one request before the loop, and by the dry-run preview of a scan. - `VendorTally` no longer subtracts the uncounted advisory event of a tree of upstream's gem, so a package skipped beside such a gem is said. - `vex`: a tree of upstream's gem under a purl the view already attests leaves that purl alone, as a hosted build does. - The dry-run preview of a scan reports an in-step copy per tree, with the gem's line, as the real run does. - The line of a copy that could not follow its list prints as a note. Tests: a damaged copy after the list moved (either tree), an intact copy whose rebuild fails with every file compared byte for byte (dry and wet), the dry run of an in-step copy, the tally, the vex view, and the edited ledger settled by the list. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/vendor_flow.rs | 22 +- .../socket-patch-cli/src/commands/vendor.rs | 71 +++++- .../src/commands/vex_sources.rs | 32 +++ .../vendor/vendor_gem_platform_builds_e2e.rs | 228 +++++++++++++++++- 4 files changed, 340 insertions(+), 13 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index f45fcf1db7..e628b3208d 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -131,12 +131,19 @@ impl PreviewRow { /// (`crate::commands::vendor::gem_build_reports`). `gem_recorded` is /// what the ledger holds for the gem. fn gem_reports(&self) -> Vec { + // A copy in step holds the trees the ledger records: the wet run + // writes none of them. + let in_step = matches!(self.verdict, PreviewVerdict::AlreadyVendored); + let builds = match (in_step, self.gem_recorded.as_deref()) { + (true, Some(recorded)) => recorded, + _ => self.gem_builds.as_slice(), + }; crate::commands::vendor::gem_build_reports( &self.purl, &self.uuid, - &self.gem_builds, + builds, self.gem_recorded.as_deref(), - true, + !in_step, ) } } @@ -295,6 +302,17 @@ impl VendorPreview { // Offline, the backend refuses before it would ask. let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); let state = load_state(&common.cwd).await.unwrap_or_default(); + // The lists of the gems already vendored, in one request, as the + // wet run's vendor step asks for them. + let mut fixes: Vec = self + .rows + .iter() + .filter(|row| in_sync(row) && platform_gems.contains(&row.purl)) + .map(|row| row.uuid.clone()) + .collect(); + fixes.sort(); + fixes.dedup(); + service.remember_references(&fixes).await; for row in &mut self.rows { let vendored = in_sync(row); if !(would_vendor(row) || vendored) || !platform_gems.contains(&row.purl) { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 1d33384c67..ddd5991037 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -738,6 +738,9 @@ fn advisory_tier(code: &str) -> AdvisoryTier { "vendor_prebuilt_downloaded" | "vendor_artifact_reused" => AdvisoryTier::Verbose, // The run did what was asked; these explain how. "vendor_fetched_missing" + // An intact copy that could not follow its fix's list stays in + // force: nothing is wrong with the project. + | vendor::gem::GEM_LIST_NOT_FOLLOWED | "vendor_would_revert_redirect" | "vendor_takeover_reverted_redirect" | "cargo_wiring_migrated" @@ -950,6 +953,9 @@ fn gem_fix_repeats(env: &Envelope, counted: impl Fn(&PatchEvent) -> bool) -> u32 env.events .iter() .filter(|event| counted(event)) + // The advisory event of a tree of upstream's gem is in no count + // of `summary`, so it is no repeat of one either. + .filter(|event| event.error_code.as_deref() != Some(GEM_UPSTREAM_BUILD_KEPT)) .filter_map(|event| event.details.as_ref()?.get(GEM_FIX_DETAIL)?.as_str()) .filter(|fix| !gems.insert(fix)) .count() as u32 @@ -4099,6 +4105,27 @@ pub(crate) async fn vendor_records_reusing( .await .into_iter() .collect(); + // A gem already vendored as platform gems follows the list of its + // fix. The lists of all of them are asked for in ONE request, here, + // and each gem's backend reads its own from the answer: a service + // that cannot be reached is asked once, and every copy then stands + // as it is. + if let Some(cfg) = service { + let mut fixes: Vec = platform_gems + .iter() + .filter_map(|purl| { + let record = records.get(purl)?; + let entry = lookup_entry(&state.entries, purl)?; + let vendored = entry.ecosystem == "gem" + && entry.uuid == record.uuid + && !entry.gem_builds.is_empty(); + vendored.then(|| record.uuid.clone()) + }) + .collect(); + fixes.sort(); + fixes.dedup(); + cfg.remember_references(&fixes).await; + } let gates = CandidateGates { cwd: &common.cwd, force, @@ -4535,6 +4562,15 @@ pub(crate) async fn vendor_records_reusing( } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); } + // A copy vendored as platform gems that cannot be + // restored as it was only because the list of the + // gem's fix names other builds now: the backend + // below vendors it again from that list, as it + // does for an intact copy. + Err(detail) + if entry.ecosystem == "gem" + && !entry.gem_builds.is_empty() + && detail.starts_with(vendor::gem::VENDOR_PREBUILT_REPLACED) => {} Err(detail) => { has_errors = true; env.record( @@ -4760,7 +4796,7 @@ pub(crate) async fn vendor_records_reusing( // (`format_vendored_gem_build_lines`), not as a // warning: nothing was wrong with the copy. let quiet = (in_sync && w.code == "vendor_prebuilt_downloaded") - || (gem_moved && w.code == "vendor_artifact_rebuilt"); + || w.code == vendor::gem::GEM_LIST_FOLLOWED; if quiet { push_advisory_event(env, candidate, w); } else { @@ -4776,7 +4812,10 @@ pub(crate) async fn vendor_records_reusing( // recording it would give `--revert` an entry that // deletes the artifact yet cannot unwire the project — // leave the ledger as is. - let rebuilt = warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"); + let rebuilt = warnings.iter().any(|w| { + w.code == "vendor_artifact_rebuilt" + || w.code == vendor::gem::GEM_LIST_FOLLOWED + }); let entry = entry.filter(|e| { !rebuilt || state @@ -9213,6 +9252,34 @@ mod ui_format_tests { assert_eq!((env.summary.verified, env.events.len()), (1, 2)); } + /// The advisory event of a tree of upstream's gem is in no count of + /// `summary`, so it takes nothing out of the tally: a package that was + /// skipped beside a gem in step that holds such a tree is still said. + #[test] + fn tally_keeps_a_real_skip_beside_a_gem_with_a_tree_of_upstreams_gem() { + const GEM: &str = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let mut mixed = nokogiri_builds(); + mixed[1].uuid.clear(); + let mut env = Envelope::new(Command::Vendor); + let already = + PatchEvent::new(PatchAction::Skipped, GEM).with_reason("already_vendored", "in sync"); + let in_step = gem_build_reports(GEM, "source", &mixed, Some(&mixed), false); + for event in gem_build_events(&already, &in_step) { + record_gem_build_event(&mut env, event); + } + env.record( + PatchEvent::new(PatchAction::Skipped, "pkg:gem/rack@3.1.8") + .with_reason("vendor_prebuilt_platform_pending", "left as it is"), + ); + assert_eq!(env.summary.skipped, 2, "{:?}", env.events); + let counted = VendorTally::from_envelope(&env, false, 0); + assert_eq!(counted, tally(0, 1, 0, 1, 0)); + assert_eq!( + format_vendor_summary(false, &counted), + "Vendored 0 packages; 1 already vendored; 1 skipped." + ); + } + /// The outcome of a gem vendored as platform gems becomes one event /// per platform gem: that gem's purl, its own patch, and details that /// name the gem's patch and the platform beside whatever the outcome diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 37eb3ce881..aee50eb596 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -641,6 +641,12 @@ impl GemBuildView { for built in &entry.gem_builds { let purl = built.purl(&entry.base_purl); let upstream = built.is_upstream(); + // A purl the view already attests keeps its own record, + // and the outcome of its own check: a tree of upstream's + // gem says nothing of it, as for a hosted build. + if upstream && view.patches.contains_key(&purl) { + continue; + } // A purl the view already attests keeps its own record. view.patches .entry(purl.clone()) @@ -2555,6 +2561,32 @@ mod tests { assert_eq!(builds.not_patched().len(), 2); } + /// A purl the view already attests keeps its own record and the + /// outcome of its own check: a tree of upstream's gem under that purl + /// says nothing of it, so the document never states the one product + /// both ways. As for a hosted build. + #[test] + fn a_vendored_tree_of_upstreams_gem_leaves_an_attested_purl_alone() { + const DARWIN: &str = "11111111-1111-4111-8111-111111111111"; + let key = "pkg:gem/nokogiri@1.18.10?platform=ruby"; + let linux = "pkg:gem/nokogiri@1.18.10?platform=x86_64-linux-gnu"; + let mut plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", ""), + ]; + }); + plan.view.patches.insert(linux.to_string(), record(U2)); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + assert_eq!(builds.view().patches[linux], record(U2), "its own record"); + assert!( + builds.not_patched().is_empty(), + "{:?}", + builds.not_patched() + ); + assert!(!builds.builds().contains_key(linux)); + } + /// The gem itself stays the attested package where the ledger does not /// say which patch built which tree: an entry that names no tree, one /// whose trees are another patch's than the view's record, and one diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 2aa6fdeeaf..09af25151e 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -740,8 +740,9 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // 5. A damaged tree: the check fails per platform gem, and the next // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then - // those patches are asked for in one request. The run then finds - // the rebuilt copy in step with the gem patch's list. + // those patches are asked for in one request. The run asks for the + // gem patch's reference once, ahead of its gems, and reads it there + // both for the restore and to find the rebuilt copy in step. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -757,7 +758,6 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { [ vec![UUID.to_string()], vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], - vec![UUID.to_string()], ] ); assert_eq!( @@ -767,14 +767,19 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // 5b. The ledger is committed data, and it does not choose what is // unpacked: with the patch of the linux tree edited to another - // served patch, the damaged tree is not rebuilt from it. The run - // fails, downloads nothing and leaves the tree as it was. + // served patch, the damaged tree is not restored from it. `repair`, + // which restores a copy as it was vendored, refuses, downloads + // nothing and names the command that vendors the current build. + // That command does: a vendor run takes the copy from the list of + // the gem's fix, as for a list that moved, so the tree is the + // build the list names and the ledger names its patch again. let state_path = root.join(".socket/vendor/state.json"); let honest = std::fs::read_to_string(&state_path).unwrap(); std::fs::write(&state_path, honest.replace(LINUX_UUID, DARWIN_UUID)).unwrap(); std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let fetched = downloads(&server).await.len(); - let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + let repair = ["repair", "--download-only", "--json"]; + let (code, env, stderr) = run_json(root, &repair, &server.uri()); assert_ne!(code, 0, "{env:#}\n{stderr}"); // Said as what it is, a build that is no longer the one the fix // names, under its own code and with the commands that vendor the @@ -801,12 +806,19 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { b"another binary", "nothing is unpacked" ); - std::fs::write(&state_path, honest).unwrap(); let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); assert_eq!( std::fs::read(tree(root, LINUX).join(SO)).unwrap(), - LINUX.as_bytes() + LINUX.as_bytes(), + "the build the list names" + ); + let ledger: serde_json::Value = + serde_json::from_slice(&std::fs::read(&state_path).unwrap()).unwrap(); + assert_eq!( + ledger["entries"][PURL]["gemBuilds"][1]["uuid"], LINUX_UUID, + "the ledger names the patch the tree came from: {ledger:#}" ); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 0, "{env:#}\n{stderr}"); @@ -1177,6 +1189,183 @@ async fn a_later_run_follows_a_published_and_a_withdrawn_build() { assert!(!root.join(".socket/vendor").exists()); } +/// Every regular file under `root`, by relative path. +fn snapshot(root: &Path) -> std::collections::BTreeMap> { + fn walk(base: &Path, dir: &Path, out: &mut std::collections::BTreeMap>) { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + walk(base, &path, out); + } else { + let rel = path + .strip_prefix(base) + .unwrap() + .to_string_lossy() + .into_owned(); + out.insert(rel, std::fs::read(&path).unwrap()); + } + } + } + let mut out = std::collections::BTreeMap::new(); + walk(root, root, &mut out); + out +} + +/// A copy that is damaged after the list of its fix moved is vendored +/// again from that list. The exact restore of the copy as it was vendored +/// is refused (the list names another build for a platform), and the run +/// goes on to what it does for an intact copy whose list moved, instead of +/// failing on every re-run until a rollback. Whichever tree is damaged: +/// the one of upstream's gem, or the patched one. +#[tokio::test] +async fn a_damaged_copy_is_vendored_from_the_list_once_the_list_moved() { + for damaged in [DARWIN, LINUX] { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let lock_wired = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + + // The darwin build is published, and a tree of the copy is damaged. + let server = service(&[DARWIN, LINUX], &[]).await; + std::fs::write(tree(root, damaged).join(SO), b"damaged").unwrap(); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{damaged}: {env:#}\n{stderr}"); + + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{damaged}: {env:#}"); + assert_eq!(env["summary"]["failed"], 0, "{damaged}: {env:#}"); + assert_eq!(env["summary"]["applied"], 2, "{damaged}: {env:#}"); + assert_per_platform_gem(&env, "applied", ""); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{damaged}: {platform} is the build the list names" + ); + assert_eq!( + std::fs::read(tree(root, platform).join(SO)).unwrap(), + platform.as_bytes(), + "{damaged}: {platform}" + ); + } + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_wired, + "{damaged}" + ); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + } +} + +/// An intact copy is never made worse, and a run never fails because of +/// something it could have left alone. The list of the gem's fix names a +/// patched build for a platform the copy holds upstream's gem for, and +/// that build cannot be vendored (its gem is not the one its patch +/// states). Every file of the project stays byte for byte what it was, the +/// run exits 0 and counts the copy as it counts one in step, and one line +/// says that the copy could not be brought in step and stays in force. A +/// dry run says the same. +#[tokio::test] +async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let before = snapshot(root); + + let server = service(&[DARWIN, LINUX], &[]).await; + let gem = + format!("/patch/gem/{NAME}/{VERSION}/tok-{DARWIN}/{DARWIN_UUID}/{NAME}-{VERSION}.gem"); + Mock::given(method("GET")) + .and(wm_path(gem)) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"not the gem".to_vec())) + .with_priority(1) + .mount(&server) + .await; + let note = format!( + "{NAME}@{VERSION} could not be brought in step with the builds the patch registry lists (" + ); + for flags in [&["--dry-run"][..], &[]] { + let args = with(VENDOR, flags); + let (code, env, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{env:#}\n{stderr}"); + assert_eq!(env["status"], "success", "{args:?}\n{env:#}"); + for (count, n) in [ + ("failed", 0), + ("applied", 0), + ("verified", 0), + ("skipped", 1), + ] { + assert_eq!( + env["summary"][count], n, + "{args:?} summary.{count}: {env:#}" + ); + } + let events = env["events"].as_array().unwrap(); + let of = |code: &str| -> Vec<&serde_json::Value> { + let coded = events.iter().filter(|event| event["errorCode"] == code); + coded.collect() + }; + let notes = of("vendor_gem_list_not_followed"); + let [said] = notes.as_slice() else { + panic!("{args:?}: one line: {env:#}"); + }; + let reason = said["reason"].as_str().unwrap_or_default(); + assert!( + reason.starts_with(¬e) + && reason.ends_with("); its vendored copy stays in force as it is."), + "{args:?}: {reason}" + ); + assert_eq!(of("already_vendored").len(), 1, "{args:?}: {env:#}"); + assert_eq!(of("gem_upstream_build_kept").len(), 1, "{args:?}: {env:#}"); + assert_eq!( + snapshot(root), + before, + "{args:?}: every file, byte for byte" + ); + } + + // For a person: the copy is already vendored, the line of the gem as + // the copy holds it, and the note. No error and no warning. + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!( + stdout.contains(&format!( + "{NAME} {VERSION}: patched for {LINUX}; upstream gem kept for {DARWIN} (no patched \ + build yet)" + )), + "{stdout}" + ); + let said: Vec<&str> = stderr + .lines() + .filter(|l| !l.contains("--api-token") && !l.contains("fake-token")) + .filter(|l| !l.trim().is_empty()) + .collect(); + assert!( + matches!(said.as_slice(), [line] if line.starts_with(&format!("Note: {note}"))), + "one note, no error and no warning:\n{stderr}" + ); + assert_eq!(snapshot(root), before); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + /// No locked platform has a patched build: the gem is not vendored, the /// run exits 0 with nothing written and nothing downloaded, and says so in /// one plain line (a counted benign skip in `--json`). @@ -2110,7 +2299,8 @@ async fn every_dry_run_previews_a_gem_with_upstreams_gem_for_a_platform() { ); // Vendored: a dry run of a later scan asks for the gem patch's - // list, as the wet run does, and promises nothing more. + // list, as the wet run does, and says what that run says: each + // tree as the copy holds it, and the gem's line. let asked = reference_requests(&server).await.len(); let args = with(command, &["--dry-run", "--json"]); let (code, dry, stderr) = run_json(root, &args, &server.uri()); @@ -2121,6 +2311,26 @@ async fn every_dry_run_previews_a_gem_with_upstreams_gem_for_a_platform() { [vec![UUID.to_string()]], "{args:?}" ); + let in_step = [ + expected[0].clone(), + ( + expected[1].0.clone(), + expected[1].1.clone(), + "already_vendored".to_string(), + ), + ]; + assert_eq!(trees(&dry), in_step, "{args:?}\n{dry:#}"); + let args = with(command, &["--json"]); + let (code, wet, stderr) = run_json(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{wet:#}\n{stderr}"); + assert_eq!(trees(&wet), in_step, "{args:?}: the real run\n{wet:#}"); + for flags in [&["--dry-run"][..], &[]] { + let args = with(command, flags); + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "{args:?}\n{stdout}\n{stderr}"); + let kept = line.replace("would be patched for", "patched for"); + assert!(stdout.contains(&kept), "{args:?}\n{stdout}\n{stderr}"); + } } } From e3ea8def8e5ca513bd575a1832ed72ae0ffc05a2 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 11:56:05 -0500 Subject: [PATCH 10/28] Document how a vendored gem follows its list without being made worse `CLI_CONTRACT.md`: the one request for the lists of all the gems vendored as platform gems, the download of upstream's gem that follows no redirect, what a run does when the list cannot be read or cannot be followed (`vendor_gem_list_not_followed`, a note, exit 0, the copy untouched), the advisory of a copy that followed its list (`vendor_gem_list_followed`), and that a vendor run whose exact restore is refused because the list moved vendors the copy again from the list while `repair` still refuses. `docs/ecosystems.md`: the same in the vendored row of the native-extensions table. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 ++++-- docs/ecosystems.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index a9f588bded..2264fcad83 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: a run over a copy that is in sync asks ONE request, the gem patch's reference, and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_artifact_rebuilt` in `--json` and prints no warning. A list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: a run asks for the references of all the gems it finds vendored this way in ONE request, ahead of its packages (so a run over a copy that is in sync makes that one request for it, and a patch service that does not answer is asked once, not once per gem), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2522,7 +2522,9 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | -| `vendor_prebuilt_replaced` | `failed` | repair, and a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged (gem): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | +| `vendor_prebuilt_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | +| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, or an upstream gem did not unpack. Nothing of the copy was touched and it stays in force; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | +| `vendor_gem_list_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): the run vendored an intact copy again because its fix lists another build for a locked platform. JSON only: the gem's line says which platforms changed (`now also patched for …`, `upstream gem back for …`), and the builds' events carry `details.newlyPatched` / `details.withdrawn`. | | `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index cf997eea65..9f0ae3bab5 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (one request for all the gems vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 373ce9dcd7597a67ea0d4e91ac50c1a91f1f5aa3 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 12:05:35 -0500 Subject: [PATCH 11/28] Say in the nokogiri script that vendored mode follows no redirect With `--pass-through-redirect` the stand-in registry answers the file of upstream's gem with a redirect to its upstream stand-in. Vendored mode takes that gem from the patch service alone, so the vendored scenario now checks that the scan does not vendor the gem, asks nothing of the upstream stand-in and writes nothing, and then goes on once the stand-in publishes the builds. Co-Authored-By: Claude Fable 5.2 --- tests/nokogiri/nokogiri_e2e.rb | 34 +++++++++++++++++++++++++++------- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/tests/nokogiri/nokogiri_e2e.rb b/tests/nokogiri/nokogiri_e2e.rb index e7f60e625c..2269797183 100644 --- a/tests/nokogiri/nokogiri_e2e.rb +++ b/tests/nokogiri/nokogiri_e2e.rb @@ -804,7 +804,10 @@ def redirect_warnings(stdout) # committed tree. Returns that lock. def vendored(service, platforms, waiting, lock, gemfile) have = platforms - waiting - if !waiting.empty? && !have.empty? + if !waiting.empty? && !have.empty? && @opts[:redirect] + vendored_redirect_not_followed(service, lock, gemfile) + waiting.each { |platform| service.publish(platform) } + elsif !waiting.empty? && !have.empty? vendored_with_upstream(service, platforms, waiting, have) waiting.each { |platform| service.publish(platform) } elsif !waiting.empty? @@ -828,7 +831,7 @@ def vendored(service, platforms, waiting, lock, gemfile) code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") said = tail(stdout) + tail(stderr) check(code.zero?, "`scan --mode vendored` succeeds (#{secs.round}s)", "exit #{code}\n#{said}") - unless waiting.empty? || have.empty? + unless waiting.empty? || have.empty? || @opts[:redirect] # The copy held upstream's gem for these: the scan puts the patched # builds in their place, and says so with no warning. gained = events(stdout).select { |e| e["details"].is_a?(Hash) && e["details"]["newlyPatched"] } @@ -861,6 +864,26 @@ def vendored(service, platforms, waiting, lock, gemfile) rewritten end + # The same lock against a registry that answers the file of upstream's + # gem with a redirect to the upstream registry (`--pass-through-redirect`). + # Vendored mode takes that gem from the patch service alone: the + # redirect is not followed, the gem is not served as far as the scan is + # concerned, and nothing is vendored or written. + def vendored_redirect_not_followed(service, lock, gemfile) + service.forget_requests + code, stdout, stderr, secs = sp_service("scan", "--mode", "vendored", "--yes", "--json") + said = stdout + stderr + check(!code.zero? && said.include?("could not fetch the upstream platform gem"), + "`scan --mode vendored` does not vendor the gem while the registry redirects upstream's gem (#{secs.round}s)", + "exit #{code}\n#{tail(stdout)}#{tail(stderr)}") + answers = service.requests.select { |_, path, _| path.include?("/gems/") }.map(&:last).uniq + check(answers == [302] && service.upstream_requests.empty?, + "the redirect is not followed: nothing is asked of the upstream registry", + (service.requests + service.upstream_requests).inspect) + check(File.read(lock_path) == lock && File.read(File.join(@proj, "Gemfile")) == gemfile && + !File.exist?(File.join(@proj, ".socket", "vendor", "gem")), "nothing is written") + end + # A lock with a patched build for some platforms (`have`) and none yet for # the others (`waiting`): the scan vendors the gem, with upstream's own # gem for the latter, and a fresh checkout installs from the trees with @@ -892,11 +915,8 @@ def vendored_with_upstream(service, platforms, waiting, have) files = waiting.map { |p| "nokogiri-#{@version}-#{p}.gem" }.sort fetched = service.requests.select { |_, path, _| path.include?("/gems/") } .map { |_, path, status| [File.basename(path), status] }.sort - check(fetched == files.map { |f| [f, @opts[:redirect] ? 302 : 200] }, - "upstream's gem is asked of the patch registry", fetched.inspect) - unless @opts[:redirect] - check(service.upstream_requests.empty?, "and of nothing else", service.upstream_requests.inspect) - end + check(fetched == files.map { |f| [f, 200] }, "upstream's gem is asked of the patch registry", fetched.inspect) + check(service.upstream_requests.empty?, "and of nothing else", service.upstream_requests.inspect) # A later scan finds the copy in step and says which platforms are # patched. code, stdout, stderr, = sp_service("scan", "--mode", "vendored", "--yes") From 73a2a0d1be940023a04a4ccc50be1a138eff03da Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 12:32:44 -0500 Subject: [PATCH 12/28] Say a vendored gem stays in force only when it still stands, and drop the client memo Review findings on the gem backend and the API client. - A run that could not vendor an intact copy again said the copy "stays in force as it is" without looking at it. Two failures happen after the copy was changed: the new trees are in place and the uuid dir's git metadata cannot be written, or the swap of the stage fails and cannot be undone. One function, `copy_in_force`, now answers whether the recorded copy stands with its metadata in place. The in-step path and every outcome that says the copy stays in force go through it (`wired_copy_failed`); a copy that no longer stands is the failure it is for any damaged copy. A copy left in force gets its `.gitignore` and `.gitattributes` put back, as a copy in step does. - The client-wide memo of batched references is gone, and with it the remembered "no answer" that failed later reads of the same patch. The batch goes through the vendor prefetch plan: a planned download can be a position whose reference alone is read (`PlannedDownload::reference`), which shares the plan's one reference request and is never fetched ahead. - The rebuild of a copy whose list moved takes the gems that list was read to name (`BuildsFrom::Listed`), so the fix's reference is asked for once with or without a plan. - A redirect is "not found" only for the client that follows none. The client that follows redirects answers one it cannot follow as it did. - `restore` returns a structured reason (`RestoreError::list_moved`), true only when the list of the gem's fix names another build than the entry records; a reference that does not pin upstream's gem is a miss. `restore_follows_list` asks the same without downloading, for a dry run. - `follows_list` is the one rule for which copies follow a list. - Failure points for the stage swap, its undo and the uuid dir's metadata, for the tests of the two failures above (debug builds only). Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 192 ++----- .../src/api/vendor_prefetch.rs | 80 ++- crates/socket-patch-core/src/vendor/common.rs | 8 +- crates/socket-patch-core/src/vendor/gem.rs | 520 +++++++++++------- crates/socket-patch-core/src/vendor/mod.rs | 23 +- .../src/vendor/redownload.rs | 67 ++- 6 files changed, 521 insertions(+), 369 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index 333682ed34..c357a10b8b 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -339,12 +339,6 @@ pub struct ApiClient { /// `plain` that follows no redirect: for a download that must come /// from the host it is asked of ([`Self::download_registry_gem`]). plain_no_redirect: reqwest::Client, - /// The package references this client was told to remember - /// ([`Self::remember_vendor_references`]), by patch uuid: the answer, - /// or `None` for a patch that request brought no answer for. Shared by - /// clones. - remembered_references: - Arc>>>, api_url: String, /// Bearer token; always `None` on an [`ApiRoute::Proxy`] client. api_token: Option, @@ -640,7 +634,6 @@ impl ApiClient { client: api_client(api_token.as_deref(), &timeouts), plain: plain_client(&timeouts, true), plain_no_redirect: plain_client(&timeouts, false), - remembered_references: Arc::default(), api_url, api_token, route: options.route, @@ -1878,55 +1871,6 @@ impl ApiClient { .collect()) } - /// Ask for the package references of `uuids` in ONE request (per - /// [`MAX_REFERENCE_BATCH`]) and remember what came back: a later - /// [`Self::fetch_vendor_reference`] of one of them, by this client or - /// a clone, is answered from here and makes no request. A patch the - /// request brought no answer for (it failed, or the response left the - /// patch out) is remembered as such, and a later ask of it fails at - /// once: a service that cannot be reached is asked once for all of - /// them, not once per patch. For a run that reads the references of - /// several patches one after another, over seconds. - pub async fn remember_vendor_references( - &self, - uuids: &[String], - free_only: bool, - vendor_url: Option<&str>, - ) { - let mut answers: std::collections::HashMap> = - uuids.iter().map(|uuid| (uuid.clone(), None)).collect(); - let refused = uuids - .iter() - .any(|uuid| self.vendor_request_refused(uuid).is_some()); - if !refused { - for chunk in uuids.chunks(MAX_REFERENCE_BATCH) { - match self - .request_vendor_references(chunk, free_only, vendor_url) - .await - { - Ok(answered) => { - self.vendor_outage.store(0, Ordering::Relaxed); - answers.extend( - answered - .into_iter() - .map(|(uuid, result)| (uuid, Some(result))), - ); - } - // As `note_vendor_outcome` counts one failed request. - Err((_, retryable)) => { - if retryable { - self.vendor_outage.fetch_add(1, Ordering::Relaxed); - } - break; - } - } - } - } - if let Ok(mut held) = self.remembered_references.lock() { - held.extend(answers); - } - } - /// Attach a download plan: `uuids` are the packages the vendor loop is /// expected to download from the service, in loop order, with these /// request parameters. Until the guard drops, the loop's @@ -2138,25 +2082,6 @@ impl ApiClient { free_only: bool, vendor_url: Option<&str>, ) -> Result { - let remembered = self - .remembered_references - .lock() - .ok() - .and_then(|held| held.get(uuid).cloned()); - match remembered { - Some(Some(result)) => return Ok(result), - // Asked moments ago, in this run, and not answered: not asked - // again. The failed request was counted when it was made. - Some(None) => { - return Err(( - ApiError::Network(format!( - "the patch service did not answer for {uuid} earlier in this run" - )), - false, - )) - } - None => {} - } let plan = self .vendor_prefetch .lock() @@ -2359,20 +2284,24 @@ impl ApiClient { max_bytes: u64, noun: &str, ) -> Result { - self.serve_get_once_with(&self.plain, url, max_bytes, noun) - .await + self.serve_get_once_with(true, url, max_bytes, noun).await } - /// [`Self::serve_get_once`] with `client`, which is `plain` or its - /// twin that follows no redirect: a redirect that one is answered is - /// a terminal miss, like a 404. + /// [`Self::serve_get_once`] with the plain client (`follow_redirects`) + /// or its twin that follows no redirect. Only for that twin is a + /// redirect an answer of its own: a terminal miss, like a 404. The + /// client that follows redirects answers as it always did. async fn serve_get_once_with( &self, - client: &reqwest::Client, + follow_redirects: bool, url: &str, max_bytes: u64, noun: &str, ) -> Result { + let client = match follow_redirects { + true => &self.plain, + false => &self.plain_no_redirect, + }; if !(url.starts_with("https://") || url.starts_with("http://")) { return Err(( ApiError::Other(format!( @@ -2421,8 +2350,11 @@ impl ApiClient { // 404 (build_failed / not stored) and 410 (withdrawn) are terminal // misses; the caller decides build-fallback vs hard-fail. StatusCode::NOT_FOUND | StatusCode::GONE => return Ok(ServeDownload::NotFound), - // Only the client that follows none is answered a redirect. - status if status.is_redirection() => return Ok(ServeDownload::NotFound), + // The gem's registry answered a redirect to the client that + // follows none: the gem is not served here. + status if !follow_redirects && status.is_redirection() => { + return Ok(ServeDownload::NotFound) + } // 408 = the archive is still building (Retry-After) — the // caller's pending policy, never retried here. StatusCode::REQUEST_TIMEOUT => return Ok(ServeDownload::Pending), @@ -2486,12 +2418,7 @@ impl ApiClient { pub(crate) async fn download_registry_gem(&self, url: &str) -> Result, ApiError> { let outcome = self .retry_vendor(url, "vendor package download", None, || { - self.serve_get_once_with( - &self.plain_no_redirect, - url, - MAX_VENDOR_PACKAGE_BYTES, - "vendor package", - ) + self.serve_get_once_with(false, url, MAX_VENDOR_PACKAGE_BYTES, "vendor package") }) .await; artifact_download_result(outcome, url) @@ -2695,6 +2622,12 @@ pub struct PlannedDownload { /// backend's stage, or run its afterHash check (see /// [`crate::vendor::prestage`]). Built by the backends' plan gates. pub stage: Option, + /// The loop reads this patch's package reference and downloads nothing + /// of it (a gem vendored as platform gems, whose backend reads the + /// list of its fix and takes its gems from other patches). The + /// position takes part in the plan's one reference request and is + /// never fetched ahead. + pub reference_only: bool, } impl PlannedDownload { @@ -2704,6 +2637,16 @@ impl PlannedDownload { uuid, secondary: None, stage: None, + reference_only: false, + } + } + + /// A patch whose package reference alone the loop reads + /// ([`Self::reference_only`]). + pub fn reference(uuid: String) -> Self { + Self { + reference_only: true, + ..Self::archive(uuid) } } } @@ -6393,64 +6336,25 @@ mod vendor_package_tests { .await .expect("the registry's own file"); assert_eq!(bytes, b"upstream"); - } - /// References asked for at once are remembered: a later read of one - /// of them, by the client or a clone, makes no request, whatever the - /// answer was. A patch the response leaves out, and every patch of a - /// request that failed, fails at once on a later read, with no request. - #[tokio::test] - async fn remembered_references_answer_later_reads_without_a_request() { - const SERVED: &str = "22222222-2222-4222-8222-222222222222"; - const BUILDING: &str = "33333333-3333-4333-8333-333333333333"; - const LEFT_OUT: &str = "44444444-4444-4444-8444-444444444444"; - let server = MockServer::start().await; - Mock::given(method("POST")) - .and(path("/v0/orgs/acme/patches/package")) - .respond_with(ResponseTemplate::new(200).set_body_json(json!({ - "results": { - SERVED: { - "status": "granted", - "url": format!("{}/patch/gem/a.gem", server.uri()), - "artifacts": [ - { "kind": "tarball", "integrity": { "sha512": "sha512-GEM==" } } - ] - }, - BUILDING: { "status": "pending_build", "url": null, "artifacts": [] } - } - }))) - .expect(1) - .mount(&server) + // The client that follows redirects answers a redirect it cannot + // follow (no `Location`) as it always did: a failed download, with + // its status, and not a file that is not served. + let odd = MockServer::start().await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(302)) + .mount(&odd) .await; - let client = auth_client(server.uri()); - let uuids = [SERVED, BUILDING, LEFT_OUT].map(str::to_string); - client.remember_vendor_references(&uuids, false, None).await; - for _ in 0..2 { - let clone = client.clone(); - let served = clone.fetch_vendor_reference(SERVED, false, None, None); - assert!(matches!(served.await, VendorServiceOutcome::Ready(_))); - } - let building = client.fetch_vendor_reference(BUILDING, false, None, None); - assert!(matches!(building.await, VendorServiceOutcome::Pending)); - let left_out = client.fetch_vendor_reference(LEFT_OUT, false, None, None); - assert!(matches!(left_out.await, VendorServiceOutcome::Failed(_))); - assert_eq!( - server.received_requests().await.unwrap_or_default().len(), - 1 + let client = auth_client(odd.uri()).with_vendor_retry(VendorRetryPolicy::none()); + let err = client + .download_artifact(&format!("{}/patch/gem/a.gem", odd.uri())) + .await + .expect_err("a redirect with nowhere to go"); + let said = err.to_string(); + assert!( + said.contains("download failed with status") && !said.contains("artifact not found"), + "{said}" ); - - // A request that fails is made once for all of its patches. - let down = MockServer::start().await; - let client = auth_client(down.uri()).with_vendor_retry(VendorRetryPolicy::none()); - client.remember_vendor_references(&uuids, false, None).await; - for uuid in &uuids { - let read = client.fetch_vendor_reference(uuid, false, None, None); - assert!( - matches!(read.await, VendorServiceOutcome::Failed(_)), - "{uuid}" - ); - } - assert_eq!(down.received_requests().await.unwrap_or_default().len(), 1); } /// A promised secondary that 404s must ERROR ("artifact not found"), diff --git a/crates/socket-patch-core/src/api/vendor_prefetch.rs b/crates/socket-patch-core/src/api/vendor_prefetch.rs index 259669d942..81fa693c66 100644 --- a/crates/socket-patch-core/src/api/vendor_prefetch.rs +++ b/crates/socket-patch-core/src/api/vendor_prefetch.rs @@ -366,6 +366,7 @@ impl VendorPrefetch { Riders { secondary: d.secondary, stage: d.stage, + reference_only: d.reference_only, }, ) }) @@ -559,7 +560,9 @@ impl VendorPrefetch { .map( move |(offset, (uuid, riders)): (usize, (String, Riders))| async move { let index = from + offset; - if !look.admits(index).await { + // Its reference is the plan's batch's to + // answer; nothing of it is downloaded. + if riders.reference_only || !look.admits(index).await { return None; } let mut held = hold_back_debug(client.fetch_vendor_package_once( @@ -629,6 +632,10 @@ fn archive_bytes(fetched: &Fetched) -> usize { struct Riders { secondary: Option, stage: Option, + /// The loop reads this position's reference and never its archive + /// ([`PlannedDownload::reference_only`]): the task fetches nothing + /// for it. + reference_only: bool, } /// Do what rides a planned download — exactly when the loop's backend @@ -642,7 +649,9 @@ struct Riders { /// * The stage recipe runs on the bytes (see [`crate::vendor::prestage`]); /// what it produced rides the archive to the backend. async fn ride_along(client: &ApiClient, held: &mut Fetched, riders: Riders) { - let Riders { secondary, stage } = riders; + let Riders { + secondary, stage, .. + } = riders; if secondary.is_none() && stage.is_none() { return; } @@ -729,6 +738,73 @@ mod tests { NotFound, } + /// A position whose reference alone is read shares the plan's one + /// reference request and is never fetched ahead: once the loop takes + /// the archive before it and the task runs, nothing of that position + /// is downloaded, and its reference is answered from the batch. + #[tokio::test] + async fn a_reference_only_position_is_batched_and_never_downloaded() { + let server = MockServer::start().await; + let (archive, listed) = (uuid(1), uuid(2)); + let sri = |bytes: &[u8]| { + let digest = base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)); + format!("sha512-{digest}") + }; + let url = |u: &str| format!("{}/serve/{u}.gem", server.uri()); + let granted = |u: &str| { + serde_json::json!({ "status": "granted", "url": url(u), "artifacts": [ + { "kind": "tarball", "url": url(u), "integrity": { "sha512": sri(b"bytes") } } + ] }) + }; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { archive.clone(): granted(&archive), listed.clone(): granted(&listed) } + }))) + .mount(&server) + .await; + Mock::given(method("GET")) + .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bytes".to_vec())) + .mount(&server) + .await; + let client = client(&server.uri()); + let _guard = client.prefetch_vendor_downloads( + vec![ + PlannedDownload::archive(archive.clone()), + PlannedDownload::reference(listed.clone()), + ], + false, + None, + None, + 4, + usize::MAX, + ); + let fetched = client + .fetch_vendor_package(&archive, false, None, None) + .await; + assert!( + matches!(fetched, VendorServiceOutcome::Ready(_)), + "{fetched:?}" + ); + // The task has had every chance to run ahead of the loop. + tokio::time::sleep(Duration::from_millis(100)).await; + let read = client + .fetch_vendor_reference(&listed, false, None, None) + .await; + assert!(matches!(read, VendorServiceOutcome::Ready(_))); + let requests = server.received_requests().await.unwrap_or_default(); + let asked = |verb: &str| -> Vec { + let of_verb = requests.iter().filter(|r| r.method.as_str() == verb); + of_verb.map(|r| r.url.path().to_string()).collect() + }; + assert_eq!(asked("POST"), [POST_PATH], "one reference request for both"); + assert_eq!( + asked("GET"), + [format!("/serve/{archive}.gem")], + "one download" + ); + } + fn uuid(i: usize) -> String { format!("{i:08x}-0000-4000-8000-{i:012x}") } diff --git a/crates/socket-patch-core/src/vendor/common.rs b/crates/socket-patch-core/src/vendor/common.rs index 8f1cce2275..2fbbba64db 100644 --- a/crates/socket-patch-core/src/vendor/common.rs +++ b/crates/socket-patch-core/src/vendor/common.rs @@ -375,7 +375,11 @@ pub(crate) async fn swap_stage_into_place(stage: &Path, copy_dir: &Path) -> std: Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, Err(e) => return Err(e), }; - match tokio::fs::rename(stage, copy_dir).await { + let renamed = match crate::utils::failpoint::hit_or_error("vendor_swap_stage") { + Ok(()) => tokio::fs::rename(stage, copy_dir).await, + Err(e) => Err(e), + }; + match renamed { Ok(()) => { crate::utils::durability::moved(stage, copy_dir); if had_old { @@ -384,7 +388,7 @@ pub(crate) async fn swap_stage_into_place(stage: &Path, copy_dir: &Path) -> std: Ok(()) } Err(e) => { - if had_old { + if had_old && !crate::utils::failpoint::fails("vendor_swap_restore") { let _ = tokio::fs::rename(&backup, copy_dir).await; } Err(e) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index b89debc2e9..bce4855535 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -107,7 +107,7 @@ //! Ruby gemspec). Hosted mode installs the same gem for such a platform. //! A later run follows the list: the tree becomes the patched build's //! once one is published, and a tree whose patched build was withdrawn -//! goes back to upstream's gem ([`listing_moved`]). While no locked +//! goes back to upstream's gem ([`moved_sources`]). While no locked //! platform has a patched build, the registry does not list one of them //! or lists no platform gem at all, or the patch it names for one is not //! served (it is still being built, or the service does not grant it), @@ -923,31 +923,27 @@ async fn stub_gemspec_valid(tree: &Path, name: &str) -> bool { } } -/// Whether the list of the gem's fix names another build for a locked -/// platform than the tree the ledger records for it: a patched build -/// where the copy holds upstream's gem (the build was published since), -/// upstream's gem where it holds a patched one (the build was withdrawn), -/// or the build of another patch. Only a list that names a gem for every -/// locked platform says so: with no list (the service has not read the -/// version's gems, or is building one again), a platform the list leaves -/// out, a request that fails or no service to ask, the copy stands as it -/// is and nothing is said. ONE request, the fix's reference. -async fn listing_moved( - project_root: &Path, - service: Option<&VendorServiceConfig>, - record: &PatchRecord, - name: &str, - copy_rel: &str, - trees: &PlatformTrees<'_>, -) -> bool { - moved_sources(project_root, service, &record.uuid, name, copy_rel, trees) - .await - .is_some() +/// Whether a ledger entry is one that follows the list of its gem's fix: +/// a gem copy of the patch `uuid` vendored as platform gems, whose entry +/// names the build of each tree. The one rule for the copies a run asks +/// the patch service about: an entry that names no build of its trees (a +/// development build's ledger) cannot say that the list names another +/// one, and is left alone. +pub fn follows_list(entry: &VendorEntry, uuid: &str) -> bool { + entry.ecosystem == "gem" && entry.uuid == uuid && !entry.gem_builds.is_empty() } -/// [`listing_moved`] for the copy of the patch `uuid`: what the list -/// names for each locked platform now, where that is not what the ledger -/// records. +/// What the list of the gem's fix `uuid` names for each locked platform +/// now, where that is not what the ledger records for the copy: a patched +/// build where the copy holds upstream's gem (the build was published +/// since), upstream's gem where it holds a patched one (the build was +/// withdrawn), or the build of another patch. `None` while the list names +/// what the copy holds. Only a list that names a gem for every locked +/// platform says that it moved: with no list (the service has not read +/// the version's gems, or is building one again), a platform the list +/// leaves out, a request that fails or no service to ask, the copy stands +/// as it is and nothing is said. ONE request, the fix's reference (the +/// one request of a run's download plan, where the copy is planned). async fn moved_sources( project_root: &Path, service: Option<&VendorServiceConfig>, @@ -964,9 +960,7 @@ async fn moved_sources( return None; }; let entry = recorded_copy(project_root, uuid, copy_rel).await?; - // An entry that names no build of its trees (a development build's - // ledger) cannot say that the list names another one: the copy stands. - if entry.gem_builds.is_empty() { + if !follows_list(&entry, uuid) { return None; } let sources = locked_build_sources(cfg, uuid, name, trees, platforms) @@ -1326,36 +1320,29 @@ pub async fn vendor_gem_previewing<'a>( // An intact copy vendored as platform gems still follows the fix's // list: a locked platform that gained a patched build, or lost one to // a withdrawal, is vendored again as the list has it now. - let moved = lock_wired - && copy_ok - && !platforms.is_empty() - && listing_moved( - project_root, - service, - record, - name, - copy_rel, - &locked(Standing::Wired), - ) - .await; + let moved = match lock_wired && copy_ok && !platforms.is_empty() { + true => { + let wired = locked(Standing::Wired); + moved_sources(project_root, service, &record.uuid, name, copy_rel, &wired).await + } + false => None, + }; + // The trees of the wired copy: the ones the list was just read to + // name, where it moved (it is not read again), else the locked ones. + let wired = match &moved { + Some(sources) => PlatformTrees { + gem: &label, + from: BuildsFrom::Listed(sources), + standing: Standing::Wired, + held: Vec::new(), + }, + None => locked(Standing::Wired), + }; if lock_wired { - if copy_ok && !moved { - // The uuid dir's `.gitignore` / `.gitattributes` are not part - // of the copy: one that was deleted (or never written) is put - // back, or a project `*.so` rule drops the binaries from the - // next commit. - let mut warnings: Vec = Vec::new(); - if !platforms.is_empty() && !dry_run { - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail( - copy_rel, - &format!("cannot write the vendored dir's git metadata: {e}"), - ), - )); - } - } + if copy_ok && moved.is_none() { + let warnings = copy_in_force(project_root, record, &prelude, true, dry_run) + .await + .unwrap_or_default(); return done( already_patched_result(purl, copy_dir, &record.files), None, @@ -1381,7 +1368,7 @@ pub async fn vendor_gem_previewing<'a>( copy_dir, uuid_dir, name, - &locked(Standing::Wired), + &wired, record, false, // live-wired: never unwind the uuid dir on failure service, @@ -1390,18 +1377,23 @@ pub async fn vendor_gem_previewing<'a>( .await; let (result, builds) = match materialised { Ok((result, builds)) if result.success => (result, builds), - // The copy was intact, and only the list said to vendor it - // again: it stays in force, whatever went wrong. - failed if moved => { - let failed = failed.map(|(result, _)| result); - return list_not_followed(failed, project_root, record, &prelude).await; - } - Ok((result, _)) => return done(result, None, warnings), - Err(outcome) => { - return wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await + failed => { + let failure = match failed { + Ok((result, _)) => done(result, None, warnings), + Err(outcome) => *outcome, + }; + return wired_copy_failed( + failure, + moved.is_some(), + project_root, + record, + &prelude, + dry_run, + ) + .await; } }; - warnings.push(match moved { + warnings.push(match moved.is_some() { true => VendorWarning::new( GEM_LIST_FOLLOWED, format!( @@ -1453,20 +1445,24 @@ pub async fn vendor_gem_previewing<'a>( [] => super::service_fetch::preview_service(service, record, extract_gem_data) .await .map(|()| Vec::new()), + _ if lock_wired => preview_platform_builds(service, record, name, &wired).await, _ => preview_platform_builds(service, record, name, &locked(standing)).await, }; match checked { Ok(builds) => *previewed = builds, - // As the wet run settles it: an intact copy stays in force. - Err(outcome) if moved => { - return list_not_followed(Err(outcome), project_root, record, &prelude).await - } - Err(outcome) => { - return match lock_wired { - true => wired_copy_not_rebuilt(*outcome, project_root, record, &prelude).await, - false => *outcome, - }; + // As the wet run settles it. + Err(outcome) if lock_wired => { + return wired_copy_failed( + *outcome, + moved.is_some(), + project_root, + record, + &prelude, + dry_run, + ) + .await } + Err(outcome) => return *outcome, } return done( super::common::preview_result(purl, copy_dir, &record.files), @@ -1702,93 +1698,117 @@ pub const GEM_LIST_FOLLOWED: &str = "vendor_gem_list_followed"; /// force as it is, and the run ends as it does for a copy in step. pub const GEM_LIST_NOT_FOLLOWED: &str = "vendor_gem_list_not_followed"; -/// The outcome of an INTACT copy the lock is wired to that this run tried -/// to vendor again, because the list of the gem's fix names another build -/// for a locked platform, and could not (`failed`: the refusal, or the -/// result that did not succeed). The copy is never made worse and the run -/// never fails over it: nothing of the copy was touched (the new one is -/// staged beside it), so it stays in force and the run reports it as it -/// reports a copy in step, with one line that says why it was not brought -/// in step ([`GEM_LIST_NOT_FOLLOWED`]). A build the list names that is not -/// served yet keeps the skip of [`wired_copy_not_rebuilt`]. -async fn list_not_followed( - failed: Result>, +/// Whether the copy the ledger records for `record` stands, with the git +/// metadata of its uuid dir in place: the one answer behind every "the +/// vendored copy stays in force". `verified`: this run's prelude found +/// the copy intact and nothing has written to it since, so its trees are +/// not read again; otherwise every tree the entry names is checked +/// ([`recorded_copy_stands`]), as after an attempt to vendor the copy +/// again, which can fail once the copy was already changed. The uuid +/// dir's `.gitignore` and `.gitattributes` are not part of the copy: one +/// that was deleted (or never written) is put back (never by a dry run), +/// or a project `*.so` rule drops the binaries from the next commit. +/// `None` when the copy does not stand; else what there is to say of the +/// metadata. +async fn copy_in_force( project_root: &Path, record: &PatchRecord, prelude: &GemPrelude, -) -> VendorOutcome { - let why = match failed { - Err(outcome) => match *outcome { - VendorOutcome::Refused { code, detail } - if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => - { - let pending = refused(code, detail); - return wired_copy_not_rebuilt(pending, project_root, record, prelude).await; - } - VendorOutcome::Refused { detail, .. } => detail, - VendorOutcome::Done { result, .. } => result.error.unwrap_or_default(), - }, - Ok(result) => result.error.unwrap_or_default(), - }; - let why = match why.trim().trim_end_matches('.') { - "" => String::new(), - why => format!(" ({why})"), - }; - let purl = build_gem_purl(&prelude.name, &prelude.version); - done( - already_patched_result(&purl, &prelude.copy_dir, &record.files), - None, - vec![VendorWarning::new( - GEM_LIST_NOT_FOLLOWED, - format!( - "{}@{} could not be brought in step with the builds the patch registry lists{why}; \ - its vendored copy stays in force as it is.", - prelude.name, prelude.version - ), - )], - ) + verified: bool, + dry_run: bool, +) -> Option> { + let (copy_rel, copy_dir) = (prelude.copy_rel.as_str(), prelude.copy_dir.as_path()); + let stands = verified + || recorded_copy_stands(project_root, record, copy_rel, copy_dir, &prelude.name).await; + if !stands { + return None; + } + let mut warnings: Vec = Vec::new(); + if !prelude.platforms.is_empty() && !dry_run { + if let Err(e) = restore_uuid_metadata(&prelude.uuid_dir).await { + warnings.push(VendorWarning::new( + super::npm_dir::GITIGNORE_UNCHECKED, + super::npm_dir::gitignore_unchecked_detail( + copy_rel, + &format!("cannot write the vendored dir's git metadata: {e}"), + ), + )); + } + } + Some(warnings) } /// The outcome of a copy the lock is ALREADY wired to that this run could -/// not rebuild because a locked platform has no patched build -/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]). While the copy the -/// ledger records is intact (the lock gained a platform since) it stays -/// in force as it is, and the outcome stays that skip. Otherwise the lock -/// names a tree that is missing or damaged and no older patch stands in -/// for it: the plain miss, a failure. -async fn wired_copy_not_rebuilt( - outcome: VendorOutcome, +/// not vendor again (`failure`: the refusal, or the result that did not +/// succeed). What is said depends on whether the copy the ledger records +/// still stands ([`copy_in_force`]), which is asked here and never +/// assumed: an attempt can fail after the copy was changed (the new trees +/// are in place and the uuid dir's metadata cannot be written, or the +/// swap of the stage fails and cannot be undone). +/// +/// * A locked platform has no patched build to vendor +/// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): while the copy stands +/// it stays in force as it is, and the outcome stays that skip. +/// * `moved`: the copy was intact and only the list of its fix, which +/// names another build for a locked platform, said to vendor it again. +/// While it still stands, an intact copy is never made worse and the +/// run never fails over it: it stays in force, the run reports it as it +/// reports a copy in step, and one line says why it was not brought in +/// step ([`GEM_LIST_NOT_FOLLOWED`]). +/// * Otherwise the lock names a copy that is missing or damaged: the +/// failure, as for any damaged copy. +async fn wired_copy_failed( + failure: VendorOutcome, + moved: bool, project_root: &Path, record: &PatchRecord, prelude: &GemPrelude, + dry_run: bool, ) -> VendorOutcome { - match outcome { - VendorOutcome::Refused { code, detail } - if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => - { - let stands = recorded_copy_stands( - project_root, - record, - &prelude.copy_rel, - &prelude.copy_dir, - &prelude.name, - ) - .await; - match stands { - true => refused( - code, - format!("{detail}; its vendored copy stays in force as it is."), - ), - false => refused( - super::VENDOR_PREBUILT_REQUIRED, - format!( - "{detail}; its vendored copy is missing or damaged and cannot be \ - rebuilt until then." - ), + let pending = matches!(&failure, VendorOutcome::Refused { code, .. } + if *code == super::VENDOR_PREBUILT_PLATFORM_PENDING); + if !pending && !moved { + return failure; + } + let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; + match (failure, in_force) { + (VendorOutcome::Refused { code, detail }, Some(_)) if pending => refused( + code, + format!("{detail}; its vendored copy stays in force as it is."), + ), + (VendorOutcome::Refused { detail, .. }, None) if pending => refused( + super::VENDOR_PREBUILT_REQUIRED, + format!( + "{detail}; its vendored copy is missing or damaged and cannot be rebuilt until \ + then." + ), + ), + (failure, Some(mut warnings)) => { + let why = match &failure { + VendorOutcome::Refused { detail, .. } => detail.clone(), + VendorOutcome::Done { result, .. } => result.error.clone().unwrap_or_default(), + }; + let why = match why.trim().trim_end_matches('.') { + "" => String::new(), + why => format!(" ({why})"), + }; + warnings.push(VendorWarning::new( + GEM_LIST_NOT_FOLLOWED, + format!( + "{}@{} could not be brought in step with the builds the patch registry \ + lists{why}; its vendored copy stays in force as it is.", + prelude.name, prelude.version ), - } + )); + let purl = build_gem_purl(&prelude.name, &prelude.version); + done( + already_patched_result(&purl, &prelude.copy_dir, &record.files), + None, + warnings, + ) } - other => other, + // The copy the lock names no longer stands. + (failure, None) => failure, } } @@ -2002,6 +2022,10 @@ pub(super) enum BuildsFrom<'a> { /// The trees a ledger entry records, each from its recorded patch: a /// restore of that copy. Recorded(&'a [GemBuildEntry]), + /// [`Self::Locked`] where the list was already read: the gem it names + /// for each locked platform ([`moved_sources`]), so the fix's + /// reference is asked for once. + Listed(&'a [BuildSource]), } /// What a gem has in place of the patch being vendored, should a locked @@ -2036,7 +2060,8 @@ pub(super) struct PlatformTrees<'a> { /// downloads must match beyond the digests that patch's own reference /// states for them. Or, for a platform the fix's list names no patched /// build for, upstream's own gem as the patch registry serves it. -struct BuildSource { +#[derive(Clone)] +pub(super) struct BuildSource { platform: String, /// The patch of the platform's patched build; empty for upstream's gem. uuid: String, @@ -2046,7 +2071,8 @@ struct BuildSource { pinned: BuildPin, } -enum BuildPin { +#[derive(Clone)] +pub(super) enum BuildPin { /// sha256 (hex) of the `.gem` the gem patch's registry lists for the /// platform (`gemBuilds[].gemChecksumSha256`). Registry(String), @@ -2105,7 +2131,7 @@ impl NoPatchedBuild<'_> { /// it, as `vex` does of such a build. For a lock already wired to this /// patch's copy /// ([`Standing::Wired`]) the caller ends the line with what became of -/// that copy ([`wired_copy_not_rebuilt`]); otherwise it is the whole +/// that copy ([`wired_copy_failed`]); otherwise it is the whole /// line. fn no_patched_build_detail( gem: &str, @@ -2388,13 +2414,42 @@ fn upstream_gem_artifact( }) } +/// Whether a restore of the trees `builds` of the copy of the fix `fix` +/// (the gem `name`@`version`) would be refused because the list of the +/// fix names another build for one of them +/// ([`VENDOR_PREBUILT_REPLACED`]): what a dry run asks in place of the +/// restore. ONE request, nothing downloaded. +pub(super) async fn recorded_list_moved( + cfg: &VendorServiceConfig, + fix: &str, + name: &str, + version: &str, + builds: &[GemBuildEntry], +) -> bool { + let gem = format!("{name}@{version}"); + let trees = PlatformTrees { + gem: &gem, + from: BuildsFrom::Recorded(builds), + standing: Standing::Wired, + held: Vec::new(), + }; + let sources = recorded_build_sources(cfg, fix, name, &trees, builds).await; + sources.is_err_and(|outcome| is_list_moved(&outcome)) +} + +/// Whether `outcome` is a restore's refusal of a copy whose list moved +/// ([`VENDOR_PREBUILT_REPLACED`]). +pub(super) fn is_list_moved(outcome: &VendorOutcome) -> bool { + matches!(outcome, VendorOutcome::Refused { code, .. } if *code == VENDOR_PREBUILT_REPLACED) +} + /// A restore found that the build a ledger entry records for a platform is /// no longer the one the list of the gem's fix names for it: it was rebuilt /// under another patch or with other bytes, or withdrawn. A fix that /// carries no list says neither ([`no_builds_listed`]). /// Nothing is unpacked. Not an integrity failure: the same state follows /// an edited ledger, and neither is told from the other here. -pub const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; +pub(crate) const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; /// The sources of the trees a ledger entry records, for a restore. /// @@ -2462,14 +2517,7 @@ async fn recorded_build_sources( // registry lists for the platform today, which must be the one the // entry pins. if built.is_upstream() { - let upstream = now.filter(|gem| gem.patch_uuid.is_none()).and_then(|gem| { - let index = served.gem_index_url.as_deref(); - Some(( - gem, - upstream_gem_artifact(index, trees.gem, &built.platform, gem)?, - )) - }); - let Some((gem, artifact)) = upstream else { + let Some(gem) = now.filter(|gem| gem.patch_uuid.is_none()) else { return Err(policy.hard( VENDOR_PREBUILT_REPLACED, format!( @@ -2484,6 +2532,17 @@ async fn recorded_build_sources( ), )); }; + // The list still names upstream's gem for the platform: a + // reference that does not say where it is, or pins no sha256 + // that is one, is a miss and not a list that moved. + let index = served.gem_index_url.as_deref(); + let Some(artifact) = upstream_gem_artifact(index, trees.gem, &built.platform, gem) + else { + return Err(policy.miss(format!( + "the patch service names no registry or no sha256 for upstream's gem of \ + {subject}" + ))); + }; if built.gem_integrity.is_empty() { return Err(policy.hard( "vendor_prebuilt_integrity_mismatch", @@ -2626,7 +2685,8 @@ async fn served_builds<'a>( source.platform ))); }; - if let (BuildsFrom::Locked(_), Some(unserved)) = (&trees.from, unserved) { + let from_list = !matches!(trees.from, BuildsFrom::Recorded(_)); + if let (true, Some(unserved)) = (from_list, unserved) { match unserved { Unserved::Building => missing.yet.push(&source.platform), Unserved::NotGranted => missing.unavailable.push(&source.platform), @@ -2724,6 +2784,7 @@ async fn stage_platform_builds( let platforms: Vec<&str> = match &trees.from { BuildsFrom::Locked(platforms) => platforms.iter().map(String::as_str).collect(), BuildsFrom::Recorded(builds) => builds.iter().map(|b| b.platform.as_str()).collect(), + BuildsFrom::Listed(sources) => sources.iter().map(|s| s.platform.as_str()).collect(), }; // SECURITY: a platform names a directory under the stage, and the // ledger a restore reads them from is committed, tamper-able data. @@ -2740,6 +2801,7 @@ async fn stage_platform_builds( BuildsFrom::Recorded(builds) => { recorded_build_sources(cfg, &record.uuid, name, trees, builds).await? } + BuildsFrom::Listed(sources) => sources.to_vec(), }; let builds = served_builds(cfg, name, trees, &sources).await?; @@ -3138,6 +3200,7 @@ const UUID_GITIGNORE: &str = "!*\n"; /// is part of the copy, so writing them is no rebuild. `true` when either /// was rewritten. pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result { + crate::utils::failpoint::hit_or_error("vendor_gem_uuid_metadata")?; super::npm_dir::write_uuid_metadata(uuid_dir, UUID_GITIGNORE).await } @@ -3243,7 +3306,7 @@ pub enum LockedBuildsPreview { /// tree the ledger records (a patched build published since, upstream's /// gem where the patched build was withdrawn), and serves each patched /// build it names, the wet run vendors the copy again with those -/// ([`listing_moved`]). +/// ([`moved_sources`]). /// /// `None` for a gem this does not judge, so the caller's own verdict /// stands: one the lock does not name as platform gems, one whose lock is @@ -14145,9 +14208,19 @@ mod tests { "arm64-darwin", ), ]; + // The git metadata of the uuid dir is no part of the copy: a + // run that leaves the copy in force puts back one that is gone, + // as a run that finds the copy in step does (a dry run writes + // nothing). + let metadata = format!(".socket/vendor/gem/{UUID}/.gitattributes"); for (list, why) in failing { let (_server, cfg) = service(UUID, &list).await; for dry_run in [true, false] { + tokio::fs::remove_file(root.join(&metadata)).await.unwrap(); + let mut before = before.clone(); + if dry_run { + before.remove(&metadata).expect("the metadata file"); + } let (result, rerun_entry, warnings) = unwrap_done( vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await, ); @@ -14169,6 +14242,10 @@ mod tests { said.detail ); assert_eq!(ts::tree_snapshot(&root), before, "{why}: byte for byte"); + let gitattributes = crate::vendor::npm_dir::UUID_GITATTRIBUTES; + tokio::fs::write(root.join(&metadata), gitattributes) + .await + .unwrap(); } } @@ -14213,58 +14290,78 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), ledgered); } - /// The lists of the gems a run finds already vendored are asked - /// for in one request, ahead of the gems - /// ([`VendorServiceConfig::remember_references`]). A copy in step - /// then asks nothing more, a copy whose list moved reads the fix's - /// reference from that answer (it is asked for once in all), and a - /// service that does not answer is asked once: the copy stands. + /// The lists of the gems a run finds already vendored are one + /// request: each such gem is a position of the run's download plan + /// whose reference alone is read + /// ([`crate::api::client::PlannedDownload::reference`]), and the + /// first of them asks for all. A copy in step then asks nothing + /// more. A copy whose list moved vendors from the list that was + /// read to find that out: the fix's reference is asked for once in + /// all, with a plan or without one. With no answer the copy stands. #[tokio::test] - async fn the_lists_asked_for_at_once_serve_the_gems_that_follow_them() { + async fn the_lists_of_the_gems_that_follow_one_are_one_request() { + use crate::api::client::PlannedDownload; let (_tmp, root, record) = project(&lock(None)).await; let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; vendor_and_persist(&root, &record, &cfg).await; - let fixes = [UUID.to_string()]; + // Two gems of the run follow a list: this one and another. + let planned = || { + vec![ + PlannedDownload::reference(UUID.to_string()), + PlannedDownload::reference(UUID_B.to_string()), + ] + }; let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; - cfg.remember_references(&fixes).await; - assert_eq!(ts::request_count(&server).await, 1); + let plan = cfg.prefetch_archives(planned()); + assert!(plan.is_some(), "the plan is attached"); let (again, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); - assert_eq!(ts::request_count(&server).await, 1, "read from the answer"); + assert_eq!( + reference_requests(&server).await, + [vec![UUID.to_string(), UUID_B.to_string()]], + "one request names both fixes, and nothing is downloaded" + ); + assert_eq!(ts::request_count(&server).await, 1); + drop(plan); - // No answer: one request (this client retries nothing), and the - // copy stands with nothing said. + // No answer: the copy stands with nothing said. let down = wiremock::MockServer::start().await; let cfg = ts::service_cfg(&down.uri(), crate::vendor::VendorSource::Service, false); + let plan = cfg.prefetch_archives(planned()); let before = ts::tree_snapshot(&root); - cfg.remember_references(&fixes).await; let (again, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); assert_eq!(ts::request_count(&down).await, 1); assert_eq!(ts::tree_snapshot(&root), before); - - let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; - cfg.remember_references(&fixes).await; - let (result, entry, _) = - unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert!(result.success, "{:?}", result.error); - assert_eq!( - entry.expect("the copy's new entry").gem_builds, - [built(UUID, DARWIN), built(UUID, LINUX)] - ); - assert_eq!( - reference_requests(&server).await, - [ - vec![UUID.to_string()], - vec![build_uuid(UUID, DARWIN), build_uuid(UUID, LINUX)] - ], - "the fix's reference once, then the builds' in one request" - ); + drop(plan); + + // The list moved: the rebuild takes the gems the list was read + // to name, so the fix's reference is one request, planned or + // not. + for planned_run in [true, false] { + let (first, second) = match planned_run { + true => (served(LINUX), upstream(LINUX)), + false => (upstream(LINUX), served(LINUX)), + }; + let _ = second; + let (server, cfg) = service(UUID, &[served(DARWIN), first]).await; + let plan = planned_run.then(|| cfg.prefetch_archives(planned())); + let (result, entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + ts::persist(&root, NOKO, entry.expect("the copy's new entry")).await; + let asked = reference_requests(&server).await; + let fixes = asked + .iter() + .filter(|uuids| uuids.contains(&UUID.to_string())); + assert_eq!(fixes.count(), 1, "planned {planned_run}: {asked:?}"); + drop(plan); + } } /// A gem that is left as it is whatever its gems are is never @@ -14493,7 +14590,30 @@ mod tests { assert!(refused.contains(says), "{refused}"); assert!(refused.contains("nokogiri (x86_64-linux-gnu)"), "{refused}"); assert_eq!(ts::tree_snapshot(&root), before, "{says}"); + // Only the list that names another build is a list that + // moved, which a dry run is told without a download. + let moved = code == VENDOR_PREBUILT_REPLACED; + assert_eq!(refused.list_moved, moved, "{refused}"); + let asked = crate::vendor::redownload::restore_follows_list(&entry, &record, &cfg); + assert_eq!(asked.await, moved, "{says}"); } + // A list that still names upstream's gem and does not pin it + // is a miss, not a list that moved. + let unpinned = Served { + listed_sha256: Some("not a sha256".to_string()), + ..upstream(LINUX) + }; + let (_server, loose) = service(UUID, &[served(DARWIN), unpinned]).await; + let refused = crate::vendor::redownload::restore(&root, &entry, &record, &loose) + .await + .expect_err("an upstream gem the list does not pin"); + assert!( + refused.contains("no sha256 for upstream's gem of nokogiri (x86_64-linux-gnu)") + && !refused.contains(VENDOR_PREBUILT_REPLACED), + "{refused}" + ); + assert!(!refused.list_moved, "{refused}"); + assert_eq!(ts::tree_snapshot(&root), before); // The restore: the fix's list, the patched build's reference, // and both gems again. @@ -14988,7 +15108,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that lists no builds restores nothing"); - assert_eq!(failed, RESTORE); + assert_eq!(failed.detail, RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); // The same from a fix that is not ready, in the same words. @@ -15003,7 +15123,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that is not ready restores nothing"); - assert_eq!(failed, RESTORE); + assert_eq!(failed.detail, RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); let pass_through = Served { @@ -15367,7 +15487,7 @@ mod tests { {NEEDS}; its vendored copy of an earlier patch stays in force as it is." ) ); - // Left open for `wired_copy_not_rebuilt`, which knows whether + // Left open for `wired_copy_failed`, which knows whether // this patch's copy still stands. assert_eq!( line(Standing::Wired, &[LINUX]), diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index df8c9d7aec..da4019e888 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -390,26 +390,6 @@ impl VendorServiceConfig { && crate::utils::concurrent::api_concurrency(self.use_public_proxy) > 1 } - /// Ask the service, in ONE request, for the package references of - /// `uuids` and keep the answers for this run's later reads of them - /// (see - /// [`crate::api::client::ApiClient::remember_vendor_references`]). - /// Nothing is asked offline or with no client. - pub async fn remember_references(&self, uuids: &[String]) { - if uuids.is_empty() || !self.service_enabled() { - return; - } - if let Some(client) = self.client.as_ref() { - client - .remember_vendor_references( - uuids, - self.use_public_proxy, - self.vendor_url.as_deref(), - ) - .await; - } - } - /// Attach a download plan to this config's client: `downloads` are the /// records the vendor loop is expected to download from the service, /// in loop order, each with the secondary artifact its backend fetches @@ -417,6 +397,9 @@ impl VendorServiceConfig { /// [`crate::api::client::ApiClient::prefetch_vendor_downloads`]). As /// many downloads run at once as the API's in-flight cap allows, and at /// most [`ARCHIVE_PREFETCH_BYTES`] of fetched archives wait for the loop. + /// A position whose reference alone the loop reads + /// ([`crate::api::client::PlannedDownload::reference`]) shares the + /// plan's one reference request and downloads nothing. /// `None` — nothing attached — when [`Self::wants_prefetch`] is false, /// or when fewer than two downloads are planned (nothing to overlap). pub fn prefetch_archives( diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 7ea9e8e259..4872efada4 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -70,12 +70,74 @@ pub(super) fn ledger_blocks_restore(entry: &VendorEntry) -> Option { None } +/// Why [`restore`] did not restore an entry's artifact. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RestoreError { + /// What to say: `: ` where the backend names a code. + pub detail: String, + /// gem: the copy cannot be restored AS IT WAS VENDORED because the + /// list of the gem's fix names another build for a platform than the + /// entry records (`vendor_prebuilt_replaced`). Nothing is wrong with + /// the service or the download: a run that vendors takes the copy + /// from the list as it is now. + pub list_moved: bool, +} + +impl std::fmt::Display for RestoreError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.detail) + } +} + +impl std::ops::Deref for RestoreError { + type Target = str; + fn deref(&self) -> &str { + &self.detail + } +} + /// Restore only the recorded artifact. Project wiring and ledger are never written. pub async fn restore( root: &Path, entry: &VendorEntry, record: &PatchRecord, service: &VendorServiceConfig, +) -> Result, RestoreError> { + let mut list_moved = false; + restore_artifact(root, entry, record, service, &mut list_moved) + .await + .map_err(|detail| RestoreError { detail, list_moved }) +} + +/// Whether [`restore`] of `entry` would be refused because the list of +/// its gem's fix moved ([`RestoreError::list_moved`]): what a dry run asks +/// in place of the restore. ONE request, nothing downloaded or written. +/// `false` for every entry that is not a gem vendored as platform gems, +/// and offline. +pub async fn restore_follows_list( + entry: &VendorEntry, + record: &PatchRecord, + service: &VendorServiceConfig, +) -> bool { + if !super::gem::follows_list(entry, &record.uuid) + || super::common::service_offline_conflict(Some(service)).is_some() + { + return false; + } + let Some((name, version)) = parse_gem_purl(&entry.base_purl) else { + return false; + }; + super::gem::recorded_list_moved(service, &record.uuid, &name, &version, &entry.gem_builds).await +} + +/// [`restore`], with its answer in words; `list_moved` is set where that +/// is the reason ([`RestoreError::list_moved`]). +async fn restore_artifact( + root: &Path, + entry: &VendorEntry, + record: &PatchRecord, + service: &VendorServiceConfig, + list_moved: &mut bool, ) -> Result, String> { let ecosystem = super::ecosystem_dir_for_purl(&entry.base_purl); if ecosystem != Some(layout::ledger_ecosystem(&entry.ecosystem)) { @@ -290,7 +352,10 @@ pub async fn restore( .map(|_| ()) } }; - copied.map_err(|outcome| detail(*outcome))?; + copied.map_err(|outcome| { + *list_moved = super::gem::is_list_moved(&outcome); + detail(*outcome) + })?; } "npm" => { let (name, version) = super::npm_common::parse_npm_purl(&entry.base_purl) From 85edd982eacbfd8afb57a1f04600dbf3f9be7e0a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 12:36:38 -0500 Subject: [PATCH 13/28] Plan the lists of vendored gems with the download plan, and settle a restore by its reason Review findings on the CLI side of a gem vendored as platform gems. - The collect, sort, dedup and remember block is gone from the vendor loop and from the dry-run preview of a scan. One helper, `list_follower`, says which packages follow the list of their fix; the vendor loop plans each as a position whose reference alone is read (a dry run plans nothing else), and the preview attaches the same plan for the rows in step. The plan's one reference request serves them, under its own guard. - The fall-through after a refused restore is decided by the restore's structured reason (`list_moved`), not by the prefix of a formatted error, so a reference that does not pin upstream's gem is the failure it is. - The dry run of a damaged copy whose list moved no longer reports `wouldRedownload` and stops: it asks whether the restore would be refused for a moved list and, as the wet run does, goes on to preview the copy vendored from the list. - `vex`: every tree of a vendored copy whose purl the view already attests is left to that record, as the hosted loop does, the patched ones included. Tests: each of the two failures that change the copy (the uuid dir's metadata after the trees are in place; a stage swap that cannot be undone) forced with a failure point, with what is printed and the exit code; the dry run of a damaged copy; the metadata put back by a run that leaves the copy in force; the vex view for a patched tree. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/vendor_flow.rs | 18 +- .../socket-patch-cli/src/commands/vendor.rs | 135 ++++++++------ .../src/commands/vendored_backend/repair.rs | 2 +- .../src/commands/vex_sources.rs | 24 ++- .../vendor/vendor_gem_platform_builds_e2e.rs | 166 +++++++++++++++++- 5 files changed, 280 insertions(+), 65 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index e628b3208d..0c2662c027 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -302,17 +302,19 @@ impl VendorPreview { // Offline, the backend refuses before it would ask. let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); let state = load_state(&common.cwd).await.unwrap_or_default(); - // The lists of the gems already vendored, in one request, as the - // wet run's vendor step asks for them. - let mut fixes: Vec = self + // The lists of the gems already vendored are one request, through + // the download plan the wet run's vendor step attaches for them: + // each such gem is a position whose reference alone is read. + let followers: Vec<_> = self .rows .iter() - .filter(|row| in_sync(row) && platform_gems.contains(&row.purl)) - .map(|row| row.uuid.clone()) + .filter(|row| in_sync(row)) + .filter_map(|row| { + let (purl, uuid) = (row.purl.as_str(), row.uuid.as_str()); + crate::commands::vendor::list_follower(&state, &platform_gems, purl, uuid) + }) .collect(); - fixes.sort(); - fixes.dedup(); - service.remember_references(&fixes).await; + let _plan = service.prefetch_archives(followers); for row in &mut self.rows { let vendored = in_sync(row); if !(would_vendor(row) || vendored) || !platform_gems.contains(&row.purl) { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index ddd5991037..e94b56804d 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -3669,12 +3669,49 @@ impl<'a> CandidateGates<'a> { } } +/// The plan position of a gem the run finds already vendored as platform +/// gems for the patch `uuid`: its backend reads the list of the gem's fix +/// on every run, to follow a build that was published or withdrawn, and +/// downloads nothing while the list names what the copy holds. So its +/// package reference shares the plan's one reference request and nothing +/// of it is fetched ahead. `None` for every other package. The one rule +/// for which packages these are, for the vendor loop (a wet and a dry run) +/// and for the dry-run preview of a scan. +pub(crate) fn list_follower( + ledger: &VendorState, + platform_gems: &HashSet, + purl: &str, + uuid: &str, +) -> Option { + let entry = lookup_entry(&ledger.entries, purl)?; + (platform_gems.contains(purl) && vendor::gem::follows_list(entry, uuid)) + .then(|| socket_patch_core::api::client::PlannedDownload::reference(uuid.to_string())) +} + /// The service downloads the vendor loop will ask for, in loop order: each /// candidate [`CandidateGates::judge`] sends to its backend, less the ones /// the loop answers without the service (a hosted takeover, an npm /// artifact the ledger anchors, an in-sync re-run) and the ones the -/// backend's own preflight refuses. +/// backend's own preflight refuses. An in-sync gem that follows the list +/// of its fix is a position of its own, whose reference alone is read +/// ([`list_follower`]). async fn plan_service_downloads( + gates: &CandidateGates<'_>, + ledger: &VendorState, + all_packages: &[(String, StagedSource)], + variant_groups: &HashMap>, + caches: ( + &tokio::sync::OnceCell>, + &vendor::pypi::InstalledSiteListings, + ), +) -> Vec { + plan_run_downloads(gates, ledger, all_packages, variant_groups, caches, false).await +} + +/// [`plan_service_downloads`], or with `followers_only` (a dry run, which +/// downloads nothing ahead) only its positions whose reference alone is +/// read: no backend's preflight is run for anything else. +async fn plan_run_downloads( gates: &CandidateGates<'_>, ledger: &VendorState, all_packages: &[(String, StagedSource)], @@ -3683,11 +3720,14 @@ async fn plan_service_downloads( &tokio::sync::OnceCell>, &vendor::pypi::InstalledSiteListings, ), + followers_only: bool, ) -> Vec { + use socket_patch_core::api::client::PlannedDownload; let cwd = gates.cwd; let uninstalled = cwd.join(UNINSTALLED_REL); - // Each loop candidate that reaches its backend, in loop order. - let mut reaching: Vec<(&str, &PatchRecord, &Path)> = Vec::new(); + // Each loop candidate that reaches its backend, in loop order: one to + // preflight, or a position that is already known. + let mut reaching: Vec<(&str, &PatchRecord, &Path, Option)> = Vec::new(); for group in candidate_groups(all_packages, variant_groups) { for candidate in &group.candidates { let CandidateVerdict::Vendor { @@ -3722,16 +3762,22 @@ async fn plan_service_downloads( // out of the plan: should the artifact need rebuilding after all, // the loop fetches it live. if lookup_entry(&ledger.entries, candidate).is_some_and(|e| e.uuid == record.uuid) { + let follower = list_follower(ledger, gates.platform_gems, candidate, &record.uuid); + if follower.is_some() { + reaching.push((candidate, record, source_path, follower)); + } continue; } - reaching.push((candidate, record, source_path)); + if !followers_only { + reaching.push((candidate, record, source_path, None)); + } } } let npm: Vec<(&str, &PatchRecord)> = reaching .iter() - .filter(|(purl, _, _)| purl.starts_with("pkg:npm/")) - .map(|(purl, record, _)| (*purl, *record)) + .filter(|(purl, ..)| purl.starts_with("pkg:npm/")) + .map(|(purl, record, ..)| (*purl, *record)) .collect(); let mut npm_verdicts = if npm.is_empty() { Vec::new() @@ -3743,14 +3789,14 @@ async fn plan_service_downloads( // of the project's lockfiles (a cargo gate clones the whole Cargo.lock // document), which a monorepo pays for in peak memory. let mut planned = Vec::new(); - for (purl, record, source_path) in &reaching { - let download = if purl.starts_with("pkg:npm/") { + for (purl, record, source_path, known) in &reaching { + let download = if known.is_some() { + known.clone() + } else if purl.starts_with("pkg:npm/") { npm_verdicts .next() .filter(|verdict| verdict.is_ok()) - .map(|_| { - socket_patch_core::api::client::PlannedDownload::archive(record.uuid.clone()) - }) + .map(|_| PlannedDownload::archive(record.uuid.clone())) } else { vendor::service_preflight( purl, @@ -4105,27 +4151,6 @@ pub(crate) async fn vendor_records_reusing( .await .into_iter() .collect(); - // A gem already vendored as platform gems follows the list of its - // fix. The lists of all of them are asked for in ONE request, here, - // and each gem's backend reads its own from the answer: a service - // that cannot be reached is asked once, and every copy then stands - // as it is. - if let Some(cfg) = service { - let mut fixes: Vec = platform_gems - .iter() - .filter_map(|purl| { - let record = records.get(purl)?; - let entry = lookup_entry(&state.entries, purl)?; - let vendored = entry.ecosystem == "gem" - && entry.uuid == record.uuid - && !entry.gem_builds.is_empty(); - vendored.then(|| record.uuid.clone()) - }) - .collect(); - fixes.sort(); - fixes.dedup(); - cfg.remember_references(&fixes).await; - } let gates = CandidateGates { cwd: &common.cwd, force, @@ -4146,14 +4171,18 @@ pub(crate) async fn vendor_records_reusing( // build and counts against quota, so a package the loop refuses is // never granted on its behalf. The plan stays advisory — every outcome // is still decided at the loop's own call (see `VendorPrefetch`). - let service_prefetch = match service.filter(|cfg| !common.dry_run && cfg.wants_prefetch()) { + // A dry run downloads nothing ahead; its plan holds only the gems + // whose backend reads the list of their fix on every run + // ([`list_follower`]), so that those lists are one request for it too. + let service_prefetch = match service.filter(|cfg| cfg.wants_prefetch()) { Some(cfg) => { - let planned = plan_service_downloads( + let planned = plan_run_downloads( &gates, &state, &all_packages, &variant_groups, (&pipenv_version, &installed_sites), + common.dry_run, ) .await; cfg.prefetch_archives(planned) @@ -4541,19 +4570,35 @@ pub(crate) async fn vendor_records_reusing( } _ => true, }; - if redownload { - if common.dry_run { + // A copy vendored as platform gems that cannot be restored + // as it was only because the list of the gem's fix names + // other builds now is not restored: the backend below + // vendors it again from that list, as it does for an intact + // copy. A dry run asks the same question, so that it says + // what the wet run does. + if redownload && common.dry_run { + let follows = match service { + Some(service) => { + vendor::redownload::restore_follows_list(entry, record, service).await + } + None => false, + }; + if !follows { env.record(PatchEvent::new(PatchAction::Verified, candidate.clone()).with_details(serde_json::json!({"wouldRedownload": true, "path": entry.artifact.path}))); continue; } + } else if redownload { let restored = match service { Some(service) => { - vendor::redownload::restore(&common.cwd, entry, record, service).await + vendor::redownload::restore(&common.cwd, entry, record, service) + .await + .map_err(|reason| (reason.list_moved, reason.detail)) } - None => Err( + None => Err(( + false, "vendoring requires a prebuilt artifact from the patch service" .to_string(), - ), + )), }; match restored { Ok(warnings) => { @@ -4562,16 +4607,8 @@ pub(crate) async fn vendor_records_reusing( } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); } - // A copy vendored as platform gems that cannot be - // restored as it was only because the list of the - // gem's fix names other builds now: the backend - // below vendors it again from that list, as it - // does for an intact copy. - Err(detail) - if entry.ecosystem == "gem" - && !entry.gem_builds.is_empty() - && detail.starts_with(vendor::gem::VENDOR_PREBUILT_REPLACED) => {} - Err(detail) => { + Err((true, _)) => {} + Err((false, detail)) => { has_errors = true; env.record( PatchEvent::new(PatchAction::Failed, candidate.clone()) diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 5f19fb83fa..42f2e9c72c 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -916,7 +916,7 @@ impl VendoredBackend<'_> { common.json, &candidate.purl, "vendor_artifact_redownload_failed", - error, + error.detail, ), } } diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index aee50eb596..89308fcd7f 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -642,12 +642,11 @@ impl GemBuildView { let purl = built.purl(&entry.base_purl); let upstream = built.is_upstream(); // A purl the view already attests keeps its own record, - // and the outcome of its own check: a tree of upstream's - // gem says nothing of it, as for a hosted build. - if upstream && view.patches.contains_key(&purl) { + // and the outcome of its own check: no tree of this copy + // says anything of it, as for a hosted build. + if view.patches.contains_key(&purl) { continue; } - // A purl the view already attests keeps its own record. view.patches .entry(purl.clone()) .or_insert_with(|| match upstream { @@ -2585,6 +2584,23 @@ mod tests { builds.not_patched() ); assert!(!builds.builds().contains_key(linux)); + + // The same for a patched tree: the purl is not attributed to this + // gem's fix as well, nor attested as one of its builds. + let darwin = "pkg:gem/nokogiri@1.18.10?platform=arm64-darwin"; + let mut plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", U2), + ]; + }); + plan.view.patches.insert(darwin.to_string(), record(U2)); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + assert_eq!(builds.view().patches[darwin], record(U2), "its own record"); + assert!(!builds.builds().contains_key(darwin)); + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert_eq!(vendored, [linux], "only the tree the view did not attest"); } /// The gem itself stays the attested package where the ledger does not diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 09af25151e..4a24c52e93 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -463,10 +463,35 @@ fn run(root: &Path, args: &[&str], api: &str) -> (i32, String, String) { ) } +/// [`run`] with the failure points `failing` (`SOCKET_PATCH_FAILPOINT`): +/// each named step fails once, as a real fault there would. +fn run_failing(root: &Path, args: &[&str], api: &str, failing: &str) -> (i32, String, String) { + run_with( + root, + args, + api, + &["--api-token", "fake-token", "--org", ORG], + Some(failing), + ) +} + /// [`run`] with the `credentials` flags in place of a token and its /// organisation. fn run_as(root: &Path, args: &[&str], api: &str, credentials: &[&str]) -> (i32, String, String) { + run_with(root, args, api, credentials, None) +} + +fn run_with( + root: &Path, + args: &[&str], + api: &str, + credentials: &[&str], + failing: Option<&str>, +) -> (i32, String, String) { let mut cmd = hermetic::command(&binary()); + if let Some(failing) = failing { + cmd.env("SOCKET_PATCH_FAILPOINT", failing); + } hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Bundle]); cmd.env_remove("GEM_HOME").env_remove("GEM_PATH"); crate::common::jvm_env::isolate_cli(&mut cmd); @@ -740,9 +765,9 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // 5. A damaged tree: the check fails per platform gem, and the next // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then - // those patches are asked for in one request. The run asks for the - // gem patch's reference once, ahead of its gems, and reads it there - // both for the restore and to find the rebuilt copy in step. + // those patches are asked for in one request. The run then finds + // the restored copy in step with the gem patch's list, which it + // reads again. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -758,6 +783,7 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { [ vec![UUID.to_string()], vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + vec![UUID.to_string()], ] ); assert_eq!( @@ -1235,6 +1261,32 @@ async fn a_damaged_copy_is_vendored_from_the_list_once_the_list_moved() { let (code, env, stderr) = run_json(root, &check, &server.uri()); assert_eq!(code, 1, "{damaged}: {env:#}\n{stderr}"); + // A dry run says what the wet run does: it would vendor the copy + // from the list, not download it again as it was. + let before = snapshot(root); + let dry = with(VENDOR, &["--dry-run"]); + let (code, env, stderr) = run_json(root, &dry, &server.uri()); + assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_per_platform_gem(&env, "verified", ""); + assert_eq!(env["summary"]["verified"], 2, "{damaged}: {env:#}"); + assert!( + !env.to_string().contains("wouldRedownload"), + "{damaged}: {env:#}" + ); + let newly: Vec<&str> = env["events"] + .as_array() + .unwrap() + .iter() + .filter(|event| event["details"]["newlyPatched"] == true) + .filter_map(|event| event["details"]["platform"].as_str()) + .collect(); + assert_eq!(newly, [DARWIN], "{damaged}: {env:#}"); + assert_eq!( + snapshot(root), + before, + "{damaged}: a dry run writes nothing" + ); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); assert_eq!(env["status"], "success", "{damaged}: {env:#}"); @@ -1296,7 +1348,20 @@ async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { let note = format!( "{NAME}@{VERSION} could not be brought in step with the builds the patch registry lists (" ); + // The git metadata of the uuid dir is not part of the copy: the wet + // run puts back a file of it that is gone, the dry run writes nothing. + let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); for flags in [&["--dry-run"][..], &[]] { + let dry_run = !flags.is_empty(); + // (Gone since the dry run, which wrote nothing, for the wet one.) + let _ = std::fs::remove_file(&gitattributes); + let mut before = before.clone(); + if dry_run { + let rel = gitattributes.strip_prefix(root).unwrap(); + before + .remove(&rel.to_string_lossy().into_owned()) + .expect("the file"); + } let args = with(VENDOR, flags); let (code, env, stderr) = run_json(root, &args, &server.uri()); assert_eq!(code, 0, "{args:?}\n{env:#}\n{stderr}"); @@ -1334,6 +1399,7 @@ async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { before, "{args:?}: every file, byte for byte" ); + assert_eq!(gitattributes.exists(), !dry_run, "{args:?}"); } // For a person: the copy is already vendored, the line of the gem as @@ -1366,6 +1432,100 @@ async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { assert_eq!(code, 0, "{env:#}\n{stderr}"); } +/// A run that could not vendor an intact copy again says that the copy +/// stays in force only when it still stands. Two failures happen after +/// the copy was changed, and each is a failure the user sees (exit 1, the +/// error, no word of a copy in force): +/// +/// * the new trees are in place and the git metadata of the uuid dir +/// cannot be written: the disk holds the new builds, the ledger the old; +/// * the stage cannot be moved into place and the copy that was moved +/// aside cannot be moved back: the lock names a path that holds nothing +/// (the old copy is kept beside it). +/// +/// The next run vendors the copy again from the list, as for any damaged +/// copy. +#[tokio::test] +async fn a_copy_changed_by_a_failed_rebuild_is_not_said_to_stay_in_force() { + let copy = format!(".socket/vendor/gem/{UUID}/{NAME}-{VERSION}"); + let cases = [ + ( + "vendor_gem_uuid_metadata~fail", + "cannot write the git metadata", + ), + ( + "vendor_swap_stage~fail,vendor_swap_restore~fail", + "failpoint `vendor_swap_stage` injected an error", + ), + ]; + for (failing, says) in cases { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let ledger = std::fs::read(root.join(".socket/vendor/state.json")).unwrap(); + + // The darwin build is published: the list moved. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run_failing(root, VENDOR_IT, &server.uri(), failing); + assert_eq!(code, 1, "{failing}:\n{stdout}\n{stderr}"); + assert!( + stderr.contains("Error:") && stderr.contains(says), + "{failing}:\n{stderr}" + ); + let said = format!("{stdout}\n{stderr}"); + assert!( + !said.contains("stays in force") && !said.contains("already vendored"), + "{failing}: the copy is not in force as it was:\n{said}" + ); + assert!(stdout.contains("1 failed"), "{failing}:\n{stdout}"); + assert_eq!( + std::fs::read(root.join(".socket/vendor/state.json")).unwrap(), + ledger, + "{failing}: the ledger is as it was" + ); + match failing.starts_with("vendor_swap") { + // The path the lock names holds nothing; the old copy is beside it. + true => { + assert!(!root.join(©).exists(), "{failing}"); + assert!( + root.join(format!("{copy}.socket-old")).exists(), + "{failing}" + ); + } + // The new trees are in place. + false => assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + stamped(DARWIN_UUID), + "{failing}" + ), + } + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{failing}: {env:#}\n{stderr}"); + + // The next run: vendored again from the list. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{failing}: {env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{failing}: {env:#}"); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{failing}: {platform}" + ); + } + assert!( + !root.join(format!("{copy}.socket-old")).exists(), + "{failing}" + ); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{failing}: {env:#}\n{stderr}"); + } +} + /// No locked platform has a patched build: the gem is not vendored, the /// run exits 0 with nothing written and nothing downloaded, and says so in /// one plain line (a counted benign skip in `--json`). From b7c53236ced740f62036a992a23b3cc65d9e661c Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 12:37:42 -0500 Subject: [PATCH 14/28] Document the plan's shared request, the in-force check and the dry run of a damaged copy `CLI_CONTRACT.md`: the references of the gems vendored as platform gems are positions of the run's download plan and share its one request; what an unreachable service costs; a run says a copy stays in force only after checking that it stands, with its git metadata put back; a rebuild that fails after it changed the copy is a failure; the fall-through after a refused restore is for a moved list alone, and its dry run previews the copy vendored from the list. `docs/ecosystems.md`: the same, briefly. The planner shim the tests call is compiled for tests only. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 ++-- crates/socket-patch-cli/src/commands/vendor.rs | 9 ++++++--- docs/ecosystems.md | 2 +- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 2264fcad83..fe9c781618 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: a run asks for the references of all the gems it finds vendored this way in ONE request, ahead of its packages (so a run over a copy that is in sync makes that one request for it, and a patch service that does not answer is asked once, not once per gem), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; with one such gem and nothing else to download, or with the API concurrency limited to one, there is no plan and each gem asks for its own), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer costs at most the two failed requests that open the client's breaker, not one per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new trees are in place and the uuid directory's git metadata cannot be written, or the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2523,7 +2523,7 @@ command's integration tests check its output. | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | | `vendor_prebuilt_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | -| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, or an upstream gem did not unpack. Nothing of the copy was touched and it stays in force; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | +| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, or an upstream gem did not unpack. Nothing of the copy was touched and it stays in force, which the run checks before it says so; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | | `vendor_gem_list_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): the run vendored an intact copy again because its fix lists another build for a locked platform. JSON only: the gem's line says which platforms changed (`now also patched for …`, `upstream gem back for …`), and the builds' events carry `details.newlyPatched` / `details.withdrawn`. | | `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index e94b56804d..75c42dc93f 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -3695,6 +3695,8 @@ pub(crate) fn list_follower( /// backend's own preflight refuses. An in-sync gem that follows the list /// of its fix is a position of its own, whose reference alone is read /// ([`list_follower`]). +// The tests name the plan of a wet run through this shim. +#[cfg(test)] async fn plan_service_downloads( gates: &CandidateGates<'_>, ledger: &VendorState, @@ -3708,9 +3710,10 @@ async fn plan_service_downloads( plan_run_downloads(gates, ledger, all_packages, variant_groups, caches, false).await } -/// [`plan_service_downloads`], or with `followers_only` (a dry run, which -/// downloads nothing ahead) only its positions whose reference alone is -/// read: no backend's preflight is run for anything else. +/// The plan of a run: [`plan_service_downloads`]'s, or with +/// `followers_only` (a dry run, which downloads nothing ahead) only its +/// positions whose reference alone is read. No backend's preflight is run +/// for anything else then. async fn plan_run_downloads( gates: &CandidateGates<'_>, ledger: &VendorState, diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 9f0ae3bab5..3d6b3cdf24 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (one request for all the gems vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (the gems vendored this way share one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From c34eb695e8da2db0229f0be8e6ac26ba40d1a854 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 13:13:24 -0500 Subject: [PATCH 15/28] Answer the plan's reference-only positions from its batch, and write a wired gem's metadata before the swap Third review round, the core side. - The download plan: a position whose reference alone is read keeps the batch's answer, so a restore and the rebuild after it read the same list with one request; a batch request that failed is the answer of every such position it named, so a batch the service refuses is not asked again once per position; and a package fetch never waits on such a position, of which nothing is fetched. `ApiError` is `Clone`. - A gem the lock names as platform gems is planned by its own backend as a reference-only position, and `in_step_reference` says which in-step packages still read one. Those positions no longer depend on what gates the downloads: where nothing is fetched ahead the plan holds them alone, and its task never runs. - The uuid dir's git metadata of a wired copy is written before the new trees are moved in, so a write that fails leaves the copy as it was and the copy stays in force. The failure point for the state this removes is gone; the ones for the swap and its undo stay. - The skip of a build that is not served yet says what there is to say of the metadata at the end of its line. - `RestoreError` is an enum (`ListMoved` or `Failed`, each with its detail) with no `Deref` and no out-parameter. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-core/src/api/client.rs | 2 +- .../src/api/vendor_prefetch.rs | 149 +++++++++++- .../src/vendor/composer_lock.rs | 2 +- crates/socket-patch-core/src/vendor/gem.rs | 226 ++++++++++++++---- crates/socket-patch-core/src/vendor/mod.rs | 31 ++- .../src/vendor/redownload.rs | 102 ++++---- 6 files changed, 400 insertions(+), 112 deletions(-) diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index c357a10b8b..ef9b5e0b77 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -3564,7 +3564,7 @@ fn assemble_batch_from_individual( // ── Error type ──────────────────────────────────────────────────────── /// Errors returned by [`ApiClient`] methods. -#[derive(Debug, thiserror::Error)] +#[derive(Debug, Clone, thiserror::Error)] pub enum ApiError { #[error("{0}")] Network(String), diff --git a/crates/socket-patch-core/src/api/vendor_prefetch.rs b/crates/socket-patch-core/src/api/vendor_prefetch.rs index 81fa693c66..96f025ef3c 100644 --- a/crates/socket-patch-core/src/api/vendor_prefetch.rs +++ b/crates/socket-patch-core/src/api/vendor_prefetch.rs @@ -170,7 +170,17 @@ pub(crate) struct VendorPrefetch { state: tokio::sync::Mutex, /// The plan's package references, resolved in one batch by the first /// planned call (see [`Self::reference`]) and taken uuid by uuid. - references: tokio::sync::OnceCell>>, + references: tokio::sync::OnceCell>, +} + +/// What the plan's one reference batch brought ([`VendorPrefetch::reference`]). +#[derive(Debug, Default)] +struct ReferenceBatch { + /// The answers, by uuid, less the patches still building. + answers: HashMap, + /// The request that failed, if one did, with the uuids it named: the + /// answer to every reference-only position among them. + failed: Option<(Vec, ApiError)>, } /// The window of plan positions the task may request: `[at, at + reach)`, @@ -397,6 +407,14 @@ impl VendorPrefetch { /// live request. A package still building (`pending_build`) is asked /// again at its own turn, as the serial loop did, since it may be /// ready by then; every other answer is final and is reused. + /// + /// A position whose reference alone is read + /// ([`PlannedDownload::reference_only`]) differs in two ways, because + /// nothing else of it is fetched and its backend may read the + /// reference more than once (a restore, then the rebuild): its answer + /// is kept, so every read of it sees the same one, and a request of + /// the batch that failed is its answer too, so a batch the service + /// refuses is not asked again once per such position. pub(crate) async fn reference( &self, client: &ApiClient, @@ -408,6 +426,7 @@ impl VendorPrefetch { return None; } let at = self.planned.iter().position(|planned| planned == uuid)?; + let kept_for_all = self.riders[at].reference_only; let mut own = None; let cache = self .references @@ -420,7 +439,7 @@ impl VendorPrefetch { order.push(planned.clone()); } } - let mut kept = HashMap::new(); + let mut batch = ReferenceBatch::default(); for (i, chunk) in order.chunks(MAX_REFERENCE_BATCH).enumerate() { match client .request_vendor_references(chunk, free_only, vendor_url) @@ -428,7 +447,11 @@ impl VendorPrefetch { { Ok(mut results) => { if i == 0 { - own = Some(results.remove(uuid).ok_or_else(|| { + let answer = match kept_for_all { + true => results.get(uuid).cloned(), + false => results.remove(uuid), + }; + own = Some(answer.ok_or_else(|| { ( ApiError::Other(format!( "package response missing a result for {uuid}" @@ -437,27 +460,44 @@ impl VendorPrefetch { ) })); } - kept.extend( + batch.answers.extend( results .into_iter() .filter(|(_, r)| r.status != "pending_build"), ); } - Err(e) if i == 0 => { - own = Some(Err(e)); + // The chunk's uuids make their live requests, but + // for the positions whose reference alone is read. + Err((e, retryable)) => { + batch.failed = Some((chunk.to_vec(), e.clone())); + if i == 0 { + own = Some(Err((e, retryable))); + } break; } - // The chunk's uuids make their live requests. - Err(_) => break, } } - std::sync::Mutex::new(kept) + std::sync::Mutex::new(batch) }) .await; if own.is_some() { return own; } - cache.lock().ok()?.remove(uuid).map(Ok) + let mut batch = cache.lock().ok()?; + if !kept_for_all { + return batch.answers.remove(uuid).map(Ok); + } + if let Some(answer) = batch.answers.get(uuid) { + return Some(Ok(answer.clone())); + } + // The request that named this position failed: that is its answer. + // It was one request, counted once, so it is no further + // availability failure. + let (asked, failure) = batch.failed.as_ref()?; + asked + .iter() + .any(|asked| asked == uuid) + .then(|| Err((failure.clone(), false))) } /// The prefetched outcome of the loop's call for `uuid`, or `None` to @@ -479,10 +519,13 @@ impl VendorPrefetch { } let mut state = self.state.lock().await; let from = state.next; + // A position whose reference alone is read is never fetched, so + // there is no outcome of it to take. let position = from + self.planned[from..] .iter() - .position(|planned| planned == uuid)?; + .zip(&self.riders[from..]) + .position(|(planned, riders)| planned == uuid && !riders.reference_only)?; // Pass over every position before this one: the task must not // request them, anything they already answered is dropped // (unreleased, with its debug lines), and the loop's arrival here @@ -805,6 +848,90 @@ mod tests { ); } + /// A position whose reference alone is read keeps the batch's answer: + /// every read of it is that answer, with no further request. When the + /// batch failed, that failure is the answer of every such position it + /// named, so a batch the service refuses is not asked again once per + /// position. And no package fetch waits on such a position, of which + /// nothing is ever fetched: it makes its own requests. + #[tokio::test] + async fn a_reference_only_answer_is_kept_and_a_failed_batch_is_its_answer() { + let (first, second) = (uuid(1), uuid(2)); + let plan = |client: &ApiClient| { + client.prefetch_vendor_downloads( + vec![ + PlannedDownload::reference(first.clone()), + PlannedDownload::reference(second.clone()), + ], + false, + None, + None, + 4, + usize::MAX, + ) + }; + let posts = |requests: &[wiremock::Request]| { + let posted = requests.iter().filter(|r| r.method.as_str() == "POST"); + posted.count() + }; + + let server = MockServer::start().await; + let url = format!("{}/serve/a.gem", server.uri()); + let granted = serde_json::json!({ "status": "granted", "url": url, "artifacts": [ + { "kind": "tarball", "url": url, "integrity": { "sha512": "sha512-GEM==" } } + ] }); + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "results": { first.clone(): granted.clone(), second.clone(): granted } + }))) + .mount(&server) + .await; + let client = client(&server.uri()); + let guard = plan(&client); + for uuid in [&first, &first, &second, &second, &first] { + let read = client.fetch_vendor_reference(uuid, false, None, None).await; + assert!(matches!(read, VendorServiceOutcome::Ready(_)), "{uuid}"); + } + let requests = server.received_requests().await.unwrap_or_default(); + assert_eq!(posts(&requests), 1, "every read is the batch's answer"); + // A package fetch of such a position does not wait for the plan. + let fetched = tokio::time::timeout( + Duration::from_secs(20), + client.fetch_vendor_package(&first, false, None, None), + ) + .await + .expect("the fetch makes its own requests"); + assert!( + !matches!(fetched, VendorServiceOutcome::Pending), + "{fetched:?}" + ); + drop(guard); + + // The service refuses the batch (not an availability failure). + let refusing = MockServer::start().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(403).set_body_string("forbidden")) + .mount(&refusing) + .await; + let client = super::tests::client(&refusing.uri()); + let _guard = plan(&client); + for uuid in [&first, &second, &second] { + let read = client.fetch_vendor_reference(uuid, false, None, None).await; + assert!( + matches!(read, VendorServiceOutcome::Failed(_)), + "{uuid}: {read:?}" + ); + } + let requests = refusing.received_requests().await.unwrap_or_default(); + assert_eq!( + posts(&requests), + 1, + "the refusal is every position's answer" + ); + } + fn uuid(i: usize) -> String { format!("{i:08x}-0000-4000-8000-{i:012x}") } diff --git a/crates/socket-patch-core/src/vendor/composer_lock.rs b/crates/socket-patch-core/src/vendor/composer_lock.rs index 46b33ee717..ac4dc25f26 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -4252,7 +4252,7 @@ mod tests { let err = super::super::redownload::restore(root, &entry, &record, &cfg) .await .unwrap_err(); - assert!(err.contains("no complete file inventory"), "{err}"); + assert!(err.detail().contains("no complete file inventory"), "{err}"); } #[tokio::test] diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index bce4855535..5165ec698e 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -1169,10 +1169,12 @@ fn gem_edits( /// enabled — makes for `record`: past every refusal it raises first /// ([`gem_prelude`], [`gem_edits`]) and not answered by the in-sync hot /// path. The vendor loop's download plan consults this; the `.gem`'s -/// `gem-stub-gemspec` secondary rides the same planned download. `None` -/// for a gem the lock pins as platform gems: it is vendored from the -/// patches the service's package reference names for its platforms -/// ([`stage_platform_builds`]), and the ruby gem is never downloaded. +/// `gem-stub-gemspec` secondary rides the same planned download. A gem +/// the lock pins as platform gems is a position whose reference alone is +/// read: it is vendored from the patches the service's package reference +/// names for its platforms ([`stage_platform_builds`]), and the ruby gem +/// is never downloaded. (A copy of such a gem that is in step reads that +/// reference too, to follow its list: [`follows_list`].) pub(crate) async fn service_preflight( purl: &str, installed_path: &Path, @@ -1189,7 +1191,12 @@ pub(crate) async fn service_preflight( true => !prelude.copy_ok, false => gem_edits(purl, &prelude).is_ok(), }; - (asks && prelude.platforms.is_empty()).then(|| { + if asks && !prelude.platforms.is_empty() { + return Some(crate::api::client::PlannedDownload::reference( + record.uuid.clone(), + )); + } + asks.then(|| { // `gem_service_copy` fetches the stub gemspec right after the `.gem`, // and extracts the `.gem`'s data.tar.gz into the copy dir's stage. crate::api::client::PlannedDownload { @@ -1742,9 +1749,8 @@ async fn copy_in_force( /// not vendor again (`failure`: the refusal, or the result that did not /// succeed). What is said depends on whether the copy the ledger records /// still stands ([`copy_in_force`]), which is asked here and never -/// assumed: an attempt can fail after the copy was changed (the new trees -/// are in place and the uuid dir's metadata cannot be written, or the -/// swap of the stage fails and cannot be undone). +/// assumed: an attempt can fail after the copy was changed (the swap of +/// the stage fails and cannot be undone). /// /// * A locked platform has no patched build to vendor /// ([`super::VENDOR_PREBUILT_PLATFORM_PENDING`]): while the copy stands @@ -1772,10 +1778,18 @@ async fn wired_copy_failed( } let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; match (failure, in_force) { - (VendorOutcome::Refused { code, detail }, Some(_)) if pending => refused( - code, - format!("{detail}; its vendored copy stays in force as it is."), - ), + // A refusal carries no advisory of its own: what there is to say + // of the metadata ends its line. + (VendorOutcome::Refused { code, detail }, Some(warnings)) if pending => { + let also: String = warnings + .iter() + .map(|warning| format!(" Also: {}.", warning.detail.trim_end_matches('.'))) + .collect(); + refused( + code, + format!("{detail}; its vendored copy stays in force as it is.{also}"), + ) + } (VendorOutcome::Refused { detail, .. }, None) if pending => refused( super::VENDOR_PREBUILT_REQUIRED, format!( @@ -3200,7 +3214,6 @@ const UUID_GITIGNORE: &str = "!*\n"; /// is part of the copy, so writing them is no rebuild. `true` when either /// was rewritten. pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result { - crate::utils::failpoint::hit_or_error("vendor_gem_uuid_metadata")?; super::npm_dir::write_uuid_metadata(uuid_dir, UUID_GITIGNORE).await } @@ -3429,6 +3442,26 @@ async fn materialise_patched_copy( .await? } _ => { + let metadata_failed = |e: std::io::Error| { + ServicePolicy::Refused.hard( + "vendor_prebuilt_write_failed", + format!( + "cannot write the git metadata of {}: {e}", + uuid_dir.display() + ), + ) + }; + // The metadata is not part of the copy and writing it changes + // nothing that is in place. For a copy the lock is wired to it + // is written BEFORE the new trees are moved in, so a failure + // leaves that copy as it was. + if !unwind_uuid_dir { + let written = match tokio::fs::create_dir_all(uuid_dir).await { + Ok(()) => restore_uuid_metadata(uuid_dir).await.map(|_| ()), + Err(e) => Err(e), + }; + written.map_err(metadata_failed)?; + } builds = gem_platform_service_copy( service, record, @@ -3440,18 +3473,13 @@ async fn materialise_patched_copy( warnings, ) .await?; - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - if unwind_uuid_dir { + // A first vendor has no uuid dir before its trees are in place. + if unwind_uuid_dir { + if let Err(e) = restore_uuid_metadata(uuid_dir).await { let _ = remove_tree(uuid_dir).await; prune_empty_vendor_levels(uuid_dir).await; + return Err(metadata_failed(e)); } - return Err(ServicePolicy::Refused.hard( - "vendor_prebuilt_write_failed", - format!( - "cannot write the git metadata of {}: {e}", - uuid_dir.display() - ), - )); } } } @@ -14290,6 +14318,87 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), ledgered); } + /// The git metadata of the uuid dir is written before the new + /// trees are moved in, so a write that fails leaves the copy the + /// lock is wired to as it was: it stays in force, with what there + /// is to say of the metadata. The skip of a build that is not + /// served yet says the same at the end of its line, a refusal + /// having no advisory of its own. + #[tokio::test] + async fn metadata_that_cannot_be_written_leaves_the_copy_in_force() { + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // A directory where the file belongs: the write fails. + let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); + tokio::fs::remove_file(&gitattributes).await.unwrap(); + tokio::fs::create_dir(&gitattributes).await.unwrap(); + tokio::fs::write(gitattributes.join("in the way"), b"") + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + let unchecked = "could not check whether git would commit the vendored artifact"; + + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!(entry.is_none(), "the ledger entry stands"); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!( + codes, + [ + crate::vendor::npm_dir::GITIGNORE_UNCHECKED, + GEM_LIST_NOT_FOLLOWED + ], + "{warnings:?}" + ); + assert!(warnings[0].detail.starts_with(unchecked), "{warnings:?}"); + assert!( + warnings[1] + .detail + .contains("cannot write the git metadata of"), + "{warnings:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "nothing was moved in"); + + // The skip of a build that is not served yet: what it says of + // the copy and, at the end of its line, of the metadata. + let prelude = gem_prelude(NOKO, ¬_installed(&root), &root, &record) + .await + .unwrap_or_else(|_| panic!("the prelude of a wired gem")); + let pending = refused( + crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java" + .to_string(), + ); + let settled = wired_copy_failed(pending, false, &root, &record, &prelude, false).await; + let (code, detail) = unwrap_refused(settled); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!( + detail.starts_with(&format!( + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java; \ + its vendored copy stays in force as it is. Also: {unchecked}" + )), + "{detail}" + ); + assert_eq!(ts::tree_snapshot(&root), before); + } + + /// A gem the lock names as platform gems is a position of the + /// download plan whose reference alone is read: its trees come + /// from other patches, and nothing of the gem's own patch is + /// downloaded. + #[tokio::test] + async fn a_platform_locked_gem_is_planned_as_a_reference() { + let (_tmp, root, record) = project(&lock(None)).await; + let planned = service_preflight(NOKO, ¬_installed(&root), &root, &record) + .await + .expect("the gem asks the service"); + assert_eq!(planned.uuid, UUID); + assert!(planned.reference_only && planned.secondary.is_none()); + } + /// The lists of the gems a run finds already vendored are one /// request: each such gem is a position of the run's download plan /// whose reference alone is read @@ -14304,9 +14413,12 @@ mod tests { let (_tmp, root, record) = project(&lock(None)).await; let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; vendor_and_persist(&root, &record, &cfg).await; - // Two gems of the run follow a list: this one and another. + // Two gems of the run follow a list: this one and another. One + // archive beside them is nothing to fetch ahead, so the plan + // holds the two references alone. let planned = || { vec![ + PlannedDownload::archive("c0c0c0c0-0000-4000-8000-000000000003".to_string()), PlannedDownload::reference(UUID.to_string()), PlannedDownload::reference(UUID_B.to_string()), ] @@ -14344,12 +14456,11 @@ mod tests { // to name, so the fix's reference is one request, planned or // not. for planned_run in [true, false] { - let (first, second) = match planned_run { - true => (served(LINUX), upstream(LINUX)), - false => (upstream(LINUX), served(LINUX)), + let linux = match planned_run { + true => served(LINUX), + false => upstream(LINUX), }; - let _ = second; - let (server, cfg) = service(UUID, &[served(DARWIN), first]).await; + let (server, cfg) = service(UUID, &[served(DARWIN), linux]).await; let plan = planned_run.then(|| cfg.prefetch_archives(planned())); let (result, entry, _) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); @@ -14562,7 +14673,7 @@ mod tests { let refused = crate::vendor::redownload::restore(&root, &no_pin, &record, &cfg) .await .expect_err("an entry with no digest for the tree"); - assert!(refused.contains("pins no digest"), "{refused}"); + assert!(refused.detail().contains("pins no digest"), "{refused}"); let another_gem = Served { gem: Some(make_gem_with_metadata( upstream_gemspec_yaml(LINUX).as_bytes(), @@ -14586,14 +14697,21 @@ mod tests { let refused = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a list that moved"); - assert!(refused.starts_with(code), "{refused}"); - assert!(refused.contains(says), "{refused}"); - assert!(refused.contains("nokogiri (x86_64-linux-gnu)"), "{refused}"); + assert!(refused.detail().starts_with(code), "{refused}"); + assert!(refused.detail().contains(says), "{refused}"); + assert!( + refused.detail().contains("nokogiri (x86_64-linux-gnu)"), + "{refused}" + ); assert_eq!(ts::tree_snapshot(&root), before, "{says}"); // Only the list that names another build is a list that // moved, which a dry run is told without a download. let moved = code == VENDOR_PREBUILT_REPLACED; - assert_eq!(refused.list_moved, moved, "{refused}"); + let list_moved = matches!( + refused, + crate::vendor::redownload::RestoreError::ListMoved(_) + ); + assert_eq!(list_moved, moved, "{refused}"); let asked = crate::vendor::redownload::restore_follows_list(&entry, &record, &cfg); assert_eq!(asked.await, moved, "{says}"); } @@ -14608,11 +14726,16 @@ mod tests { .await .expect_err("an upstream gem the list does not pin"); assert!( - refused.contains("no sha256 for upstream's gem of nokogiri (x86_64-linux-gnu)") - && !refused.contains(VENDOR_PREBUILT_REPLACED), + refused + .detail() + .contains("no sha256 for upstream's gem of nokogiri (x86_64-linux-gnu)") + && !refused.detail().contains(VENDOR_PREBUILT_REPLACED), + "{refused}" + ); + assert!( + matches!(refused, crate::vendor::redownload::RestoreError::Failed(_)), "{refused}" ); - assert!(!refused.list_moved, "{refused}"); assert_eq!(ts::tree_snapshot(&root), before); // The restore: the fix's list, the patched build's reference, @@ -15062,8 +15185,11 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a recorded tree whose patch is not served cannot be restored"); - assert!(failed.starts_with("vendor_prebuilt_required: "), "{failed}"); - assert!(failed.contains(restore_says), "{failed}"); + assert!( + failed.detail().starts_with("vendor_prebuilt_required: "), + "{failed}" + ); + assert!(failed.detail().contains(restore_says), "{failed}"); assert_eq!(ts::tree_snapshot(&root), before, "restore"); } } @@ -15108,7 +15234,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that lists no builds restores nothing"); - assert_eq!(failed.detail, RESTORE); + assert_eq!(failed.detail(), RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); // The same from a fix that is not ready, in the same words. @@ -15123,7 +15249,7 @@ mod tests { let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await .expect_err("a fix that is not ready restores nothing"); - assert_eq!(failed.detail, RESTORE); + assert_eq!(failed.detail(), RESTORE); assert_eq!(ts::tree_snapshot(&root), before, "restore"); let pass_through = Served { @@ -15135,8 +15261,8 @@ mod tests { .await .expect_err("a list with no patched build for the platform restores nothing"); assert!( - failed.starts_with("vendor_prebuilt_replaced: ") - && failed.contains("(it was withdrawn)"), + failed.detail().starts_with("vendor_prebuilt_replaced: ") + && failed.detail().contains("(it was withdrawn)"), "{failed}" ); assert_eq!(ts::tree_snapshot(&root), before, "restore"); @@ -15809,9 +15935,13 @@ mod tests { tokio::fs::write(installed.join(RB), RB_PRISTINE) .await .unwrap(); + // The plan reads the reference of the gem's patch and downloads + // nothing of it. assert_eq!( service_preflight(NOKO, &installed, &root, &record).await, - None + Some(crate::api::client::PlannedDownload::reference( + UUID.to_string() + )) ); let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; let (result, entry, _) = @@ -16435,11 +16565,15 @@ mod tests { .await .expect_err("a download that is not the recorded one"); assert!( - err.starts_with("vendor_prebuilt_integrity_mismatch"), + err.detail() + .starts_with("vendor_prebuilt_integrity_mismatch"), + "{err}" + ); + assert!(err.detail().contains(says), "{err}"); + assert!( + err.detail().contains("nokogiri (x86_64-linux-gnu)"), "{err}" ); - assert!(err.contains(says), "{err}"); - assert!(err.contains("nokogiri (x86_64-linux-gnu)"), "{err}"); assert_eq!(ts::tree_snapshot(&root), before); } } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index da4019e888..3d0a7d2239 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -400,13 +400,22 @@ impl VendorServiceConfig { /// A position whose reference alone the loop reads /// ([`crate::api::client::PlannedDownload::reference`]) shares the /// plan's one reference request and downloads nothing. - /// `None` — nothing attached — when [`Self::wants_prefetch`] is false, - /// or when fewer than two downloads are planned (nothing to overlap). + /// Those positions do not depend on what gates the downloads: where + /// nothing is fetched ahead ([`Self::wants_prefetch`] is false, or + /// fewer than two downloads are planned, with nothing to overlap) the + /// plan holds them alone, and its task, which only a download starts, + /// never runs. `None` — nothing attached — when the service is not + /// enabled or the plan would hold fewer than two positions (one has + /// nothing to share a request with). pub fn prefetch_archives( &self, - downloads: Vec, + mut downloads: Vec, ) -> Option { - if !self.wants_prefetch() || downloads.len() < 2 { + let archives = downloads.iter().filter(|d| !d.reference_only).count(); + if !self.wants_prefetch() || archives < 2 { + downloads.retain(|d| d.reference_only); + } + if !self.service_enabled() || downloads.len() < 2 { return None; } let client = self.client.as_ref()?; @@ -993,6 +1002,20 @@ pub async fn service_preflight( } } +/// The plan position of a package the ledger already records at the uuid +/// of the patch being vendored: a re-run, which every backend answers +/// without downloading. `None` where it asks the service nothing either. +/// A gem copy vendored as platform gems reads the list of its fix on +/// every run, to follow a build that was published or withdrawn +/// ([`gem::follows_list`]): a position whose reference alone is read. +pub fn in_step_reference( + entry: &VendorEntry, + uuid: &str, +) -> Option { + gem::follows_list(entry, uuid) + .then(|| crate::api::client::PlannedDownload::reference(uuid.to_string())) +} + /// The lock-text refusals among `candidates` (purls with the uuid of the /// patch to vendor): each purl its backend refuses on the project's lock /// and manifest text alone, with the backend's `(code, detail)` — the npm diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 4872efada4..0c1677c741 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -70,47 +70,49 @@ pub(super) fn ledger_blocks_restore(entry: &VendorEntry) -> Option { None } -/// Why [`restore`] did not restore an entry's artifact. +/// Why [`restore`] did not restore an entry's artifact, each with what to +/// say of it (`: ` where the backend names a code). #[derive(Debug, Clone, PartialEq, Eq)] -pub struct RestoreError { - /// What to say: `: ` where the backend names a code. - pub detail: String, +pub enum RestoreError { /// gem: the copy cannot be restored AS IT WAS VENDORED because the /// list of the gem's fix names another build for a platform than the /// entry records (`vendor_prebuilt_replaced`). Nothing is wrong with /// the service or the download: a run that vendors takes the copy /// from the list as it is now. - pub list_moved: bool, + ListMoved(String), + /// Every other reason. + Failed(String), +} + +impl RestoreError { + /// What to say of it. + pub fn detail(&self) -> &str { + match self { + RestoreError::ListMoved(detail) | RestoreError::Failed(detail) => detail, + } + } } impl std::fmt::Display for RestoreError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.detail) + f.write_str(self.detail()) } } -impl std::ops::Deref for RestoreError { - type Target = str; - fn deref(&self) -> &str { - &self.detail +impl From for RestoreError { + fn from(detail: String) -> Self { + RestoreError::Failed(detail) } } -/// Restore only the recorded artifact. Project wiring and ledger are never written. -pub async fn restore( - root: &Path, - entry: &VendorEntry, - record: &PatchRecord, - service: &VendorServiceConfig, -) -> Result, RestoreError> { - let mut list_moved = false; - restore_artifact(root, entry, record, service, &mut list_moved) - .await - .map_err(|detail| RestoreError { detail, list_moved }) +impl From<&str> for RestoreError { + fn from(detail: &str) -> Self { + RestoreError::Failed(detail.to_string()) + } } /// Whether [`restore`] of `entry` would be refused because the list of -/// its gem's fix moved ([`RestoreError::list_moved`]): what a dry run asks +/// its gem's fix moved ([`RestoreError::ListMoved`]): what a dry run asks /// in place of the restore. ONE request, nothing downloaded or written. /// `false` for every entry that is not a gem vendored as platform gems, /// and offline. @@ -130,15 +132,13 @@ pub async fn restore_follows_list( super::gem::recorded_list_moved(service, &record.uuid, &name, &version, &entry.gem_builds).await } -/// [`restore`], with its answer in words; `list_moved` is set where that -/// is the reason ([`RestoreError::list_moved`]). -async fn restore_artifact( +/// Restore only the recorded artifact. Project wiring and ledger are never written. +pub async fn restore( root: &Path, entry: &VendorEntry, record: &PatchRecord, service: &VendorServiceConfig, - list_moved: &mut bool, -) -> Result, String> { +) -> Result, RestoreError> { let ecosystem = super::ecosystem_dir_for_purl(&entry.base_purl); if ecosystem != Some(layout::ledger_ecosystem(&entry.ecosystem)) { return Err("ledger package identity does not match its artifact ecosystem".into()); @@ -149,16 +149,17 @@ async fn restore_artifact( return Err(format!( "vendor_dir_symlink_unsupported: {}", super::path::vendor_dir_symlink_detail(&link) - )); + ) + .into()); } if let Some(outcome) = super::common::service_offline_conflict(Some(service)) { - return Err(detail(outcome)); + return Err(detail(outcome).into()); } // A JVM tree belongs to its build root: repairing from a subproject // would restore it where the real build never looks (#428). if entry.ecosystem == layout::LEDGER_ECOSYSTEM { if let Some(detail) = super::maven_repo::not_build_root(root) { - return Err(format!("vendor_jvm_shape_unsupported: {detail}")); + return Err(format!("vendor_jvm_shape_unsupported: {detail}").into()); } } let artifact = match super::verify::checked_artifact_path(root, entry, record) { @@ -176,13 +177,13 @@ async fn restore_artifact( &record.uuid, )?) } - Err(reason) => return Err(reason), + Err(reason) => return Err(reason.into()), }; if crate::utils::containment::linked_level(root, &root.join(&entry.artifact.path)).is_some() { return Err("vendor_path_unsafe: artifact path contains a symlink".into()); } if let Some(detail) = ledger_blocks_restore(entry) { - return Err(detail); + return Err(detail.into()); } let file_shaped = !super::verify::is_vlt_dir_entry(entry) && super::verify::artifact_is_file_shaped(&entry.artifact.path); @@ -352,9 +353,9 @@ async fn restore_artifact( .map(|_| ()) } }; - copied.map_err(|outcome| { - *list_moved = super::gem::is_list_moved(&outcome); - detail(*outcome) + copied.map_err(|outcome| match super::gem::is_list_moved(&outcome) { + true => RestoreError::ListMoved(detail(*outcome)), + false => RestoreError::Failed(detail(*outcome)), })?; } "npm" => { @@ -404,12 +405,7 @@ async fn restore_artifact( return Err("server module does not carry the patched files".into()); } } - _ => { - return Err(format!( - "unsupported artifact ecosystem {}", - entry.ecosystem - )) - } + _ => return Err(format!("unsupported artifact ecosystem {}", entry.ecosystem).into()), } { let inventory = entry @@ -479,7 +475,7 @@ async fn restore_artifact( let _ = super::vlt_lock::keep_vlt_links(entry, &temporary.path().join(rel), root).await; } - return Err(error.to_string()); + return Err(error.to_string().into()); } } restore_npm_uuid_metadata(entry, root) @@ -1123,7 +1119,7 @@ mod tests { .await .unwrap_err(); assert!( - error.starts_with("vendor_dir_symlink_unsupported"), + error.detail().starts_with("vendor_dir_symlink_unsupported"), "{error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1148,9 +1144,11 @@ mod tests { let error = restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err(); - assert!(error.contains("no archive SHA-256"), "{error}"); + assert!(error.detail().contains("no archive SHA-256"), "{error}"); assert!( - error.contains(super::super::common::REVERT_ALL_AND_REVENDOR), + error + .detail() + .contains(super::super::common::REVERT_ALL_AND_REVENDOR), "the refusal names the remedy that records a new fingerprint: {error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1182,6 +1180,7 @@ mod tests { assert!(restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err() + .detail() .contains("recorded SHA-256")); assert_eq!(tree_snapshot(root.path()), before); server.reset().await; @@ -1215,6 +1214,7 @@ mod tests { ) .await .unwrap_err() + .detail() .contains("hash_mismatch")); assert!(!root.path().join(&entry.artifact.path).exists()); } @@ -1280,13 +1280,16 @@ mod tests { ) .await .unwrap_err(); - assert!(error.contains("no complete file inventory"), "{error}"); assert!( - error.contains("re-run the vendoring command"), + error.detail().contains("no complete file inventory"), + "{error}" + ); + assert!( + error.detail().contains("re-run the vendoring command"), "the refusal names the remedy that rebuilds the copy: {error}" ); assert!( - !error.contains("--revert"), + !error.detail().contains("--revert"), "no revert is needed for a dir copy: {error}" ); assert!(server.received_requests().await.unwrap().is_empty()); @@ -1300,6 +1303,7 @@ mod tests { ) .await .unwrap_err() + .detail() .contains("identity")); assert_eq!(tree_snapshot(root.path()), before); } @@ -1367,7 +1371,7 @@ mod tests { let error = restore(root.path(), &entry, &record(), &cfg) .await .unwrap_err(); - assert!(error.contains(expected), "{status}: {error}"); + assert!(error.detail().contains(expected), "{status}: {error}"); assert_eq!(tree_snapshot(root.path()), before, "{status}"); } } From d108bc2350f1e096fd9028707d4768506ee60334 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 13:15:33 -0500 Subject: [PATCH 16/28] Plan reference positions by the backend's rule, and tally a replaced build as not in step Third review round, the CLI side and the contract. - `vex`: a tree of a vendored copy is left to an existing record only when that record is of another patch. A record of the tree's own patch is of the same build, which the committed tree attests. (End to end, the manifest record of a platform gem's own patch is set aside for the wired patch before this is reached, `vex_record_superseded`; the test of that scenario passed before the change and stays as a regression test.) - The planner asks the backend which in-step packages still read a reference (`vendor::in_step_reference`); the CLI's own helper is gone. A run that fetches nothing ahead (a dry run, or an API in-flight cap of one) judges only the candidates whose ledger entry is such a package, and none when the ledger has no such entry. - A dry run counts a copy as in step only when its trees are the builds the ledger records: a build replaced under another patch is one the wet run vendors again. - `RestoreError` is matched as the enum it is, in the vendor loop and in `repair`. - `CLI_CONTRACT.md`: the shared request no longer depends on the archive gates; a failed request is the answer for every gem it named; the metadata is written before the trees are moved in. Tests: the dry-run tally of a damaged copy with a replaced build; the planner with nothing to plan; a copy whose metadata cannot be written stays in force (exit 0, nothing moved in); the swap that cannot be undone, kept; the vex view for a record of the tree's own patch. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../src/commands/scan/vendor_flow.rs | 6 +- .../socket-patch-cli/src/commands/vendor.rs | 120 +++++++----- .../src/commands/vendored_backend/repair.rs | 5 +- .../src/commands/vex_sources.rs | 35 +++- .../vendor/vendor_gem_platform_builds_e2e.rs | 185 ++++++++++-------- 6 files changed, 213 insertions(+), 140 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index fe9c781618..726fdb9b3e 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; with one such gem and nothing else to download, or with the API concurrency limited to one, there is no plan and each gem asks for its own), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer costs at most the two failed requests that open the client's breaker, not one per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new trees are in place and the uuid directory's git metadata cannot be written, or the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem has nothing to share a request with and asks for its own), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 0c2662c027..fcb86e8656 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -308,10 +308,10 @@ impl VendorPreview { let followers: Vec<_> = self .rows .iter() - .filter(|row| in_sync(row)) + .filter(|row| in_sync(row) && platform_gems.contains(&row.purl)) .filter_map(|row| { - let (purl, uuid) = (row.purl.as_str(), row.uuid.as_str()); - crate::commands::vendor::list_follower(&state, &platform_gems, purl, uuid) + let entry = lookup_entry(&state.entries, &row.purl)?; + socket_patch_core::vendor::in_step_reference(entry, &row.uuid) }) .collect(); let _plan = service.prefetch_archives(followers); diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 75c42dc93f..d72cf1d913 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -3669,32 +3669,14 @@ impl<'a> CandidateGates<'a> { } } -/// The plan position of a gem the run finds already vendored as platform -/// gems for the patch `uuid`: its backend reads the list of the gem's fix -/// on every run, to follow a build that was published or withdrawn, and -/// downloads nothing while the list names what the copy holds. So its -/// package reference shares the plan's one reference request and nothing -/// of it is fetched ahead. `None` for every other package. The one rule -/// for which packages these are, for the vendor loop (a wet and a dry run) -/// and for the dry-run preview of a scan. -pub(crate) fn list_follower( - ledger: &VendorState, - platform_gems: &HashSet, - purl: &str, - uuid: &str, -) -> Option { - let entry = lookup_entry(&ledger.entries, purl)?; - (platform_gems.contains(purl) && vendor::gem::follows_list(entry, uuid)) - .then(|| socket_patch_core::api::client::PlannedDownload::reference(uuid.to_string())) -} - /// The service downloads the vendor loop will ask for, in loop order: each /// candidate [`CandidateGates::judge`] sends to its backend, less the ones /// the loop answers without the service (a hosted takeover, an npm /// artifact the ledger anchors, an in-sync re-run) and the ones the -/// backend's own preflight refuses. An in-sync gem that follows the list -/// of its fix is a position of its own, whose reference alone is read -/// ([`list_follower`]). +/// backend's own preflight refuses. An in-sync package whose backend still +/// reads its package reference (a gem that follows the list of its fix) is +/// a position of its own, whose reference alone is read +/// ([`vendor::in_step_reference`]). // The tests name the plan of a wet run through this shim. #[cfg(test)] async fn plan_service_downloads( @@ -3711,9 +3693,11 @@ async fn plan_service_downloads( } /// The plan of a run: [`plan_service_downloads`]'s, or with -/// `followers_only` (a dry run, which downloads nothing ahead) only its -/// positions whose reference alone is read. No backend's preflight is run -/// for anything else then. +/// `references_only` (a run that fetches nothing ahead: a dry run, or one +/// whose API in-flight cap is one) only the in-step positions whose +/// reference alone is read. Then no candidate is judged and no backend's +/// preflight is run for anything else, and a ledger with no such entry +/// costs nothing. async fn plan_run_downloads( gates: &CandidateGates<'_>, ledger: &VendorState, @@ -3723,16 +3707,28 @@ async fn plan_run_downloads( &tokio::sync::OnceCell>, &vendor::pypi::InstalledSiteListings, ), - followers_only: bool, + references_only: bool, ) -> Vec { use socket_patch_core::api::client::PlannedDownload; let cwd = gates.cwd; let uninstalled = cwd.join(UNINSTALLED_REL); + // Whether the ledger's entry for `purl` is one whose backend still + // reads a reference for the patch it records. + let reads_reference = |purl: &str| { + lookup_entry(&ledger.entries, purl) + .is_some_and(|entry| vendor::in_step_reference(entry, &entry.uuid).is_some()) + }; + if references_only && !ledger.entries.keys().any(|purl| reads_reference(purl)) { + return Vec::new(); + } // Each loop candidate that reaches its backend, in loop order: one to // preflight, or a position that is already known. let mut reaching: Vec<(&str, &PatchRecord, &Path, Option)> = Vec::new(); for group in candidate_groups(all_packages, variant_groups) { for candidate in &group.candidates { + if references_only && !reads_reference(candidate) { + continue; + } let CandidateVerdict::Vendor { purl: candidate, record, @@ -3764,14 +3760,16 @@ async fn plan_run_downloads( // committed artifact, which the loop's own call repeats. Left // out of the plan: should the artifact need rebuilding after all, // the loop fetches it live. - if lookup_entry(&ledger.entries, candidate).is_some_and(|e| e.uuid == record.uuid) { - let follower = list_follower(ledger, gates.platform_gems, candidate, &record.uuid); - if follower.is_some() { - reaching.push((candidate, record, source_path, follower)); + let in_step = + lookup_entry(&ledger.entries, candidate).filter(|e| e.uuid == record.uuid); + if let Some(entry) = in_step { + let reference = vendor::in_step_reference(entry, &record.uuid); + if reference.is_some() { + reaching.push((candidate, record, source_path, reference)); } continue; } - if !followers_only { + if !references_only { reaching.push((candidate, record, source_path, None)); } } @@ -4174,18 +4172,20 @@ pub(crate) async fn vendor_records_reusing( // build and counts against quota, so a package the loop refuses is // never granted on its behalf. The plan stays advisory — every outcome // is still decided at the loop's own call (see `VendorPrefetch`). - // A dry run downloads nothing ahead; its plan holds only the gems - // whose backend reads the list of their fix on every run - // ([`list_follower`]), so that those lists are one request for it too. - let service_prefetch = match service.filter(|cfg| cfg.wants_prefetch()) { + // A dry run fetches nothing ahead, nor does a run whose API in-flight + // cap is one. Its plan still holds the in-step packages whose backend + // reads a reference on every run, so that those are one request for it + // too: that does not depend on what gates the downloads. + let service_prefetch = match service.filter(|cfg| cfg.service_enabled()) { Some(cfg) => { + let references_only = common.dry_run || !cfg.wants_prefetch(); let planned = plan_run_downloads( &gates, &state, &all_packages, &variant_groups, (&pipenv_version, &installed_sites), - common.dry_run, + references_only, ) .await; cfg.prefetch_archives(planned) @@ -4591,14 +4591,12 @@ pub(crate) async fn vendor_records_reusing( continue; } } else if redownload { + use vendor::redownload::RestoreError; let restored = match service { Some(service) => { - vendor::redownload::restore(&common.cwd, entry, record, service) - .await - .map_err(|reason| (reason.list_moved, reason.detail)) + vendor::redownload::restore(&common.cwd, entry, record, service).await } - None => Err(( - false, + None => Err(RestoreError::Failed( "vendoring requires a prebuilt artifact from the patch service" .to_string(), )), @@ -4610,8 +4608,8 @@ pub(crate) async fn vendor_records_reusing( } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); } - Err((true, _)) => {} - Err((false, detail)) => { + Err(RestoreError::ListMoved(_)) => {} + Err(RestoreError::Failed(detail)) => { has_errors = true; env.record( PatchEvent::new(PatchAction::Failed, candidate.clone()) @@ -4702,12 +4700,20 @@ pub(crate) async fn vendor_records_reusing( ); // The run puts other trees in place than the ledger records: // the list of the gem's fix names another build for a locked - // platform (a patched build published since, or upstream's - // gem where the patched build was withdrawn). - let gem_moved = gem_reports - .iter() - .any(|report| report.newly_patched || report.withdrawn) - && gem_recorded.is_some(); + // platform (a patched build published since, upstream's gem + // where the patched build was withdrawn, or the build of + // another patch). + let gem_moved = gem_wrote + && gem_recorded.as_deref().is_some_and(|recorded| { + let held = |built: &vendor::GemBuildEntry| { + let same = |was: &&vendor::GemBuildEntry| { + was.platform == built.platform + && was.uuid.eq_ignore_ascii_case(&built.uuid) + }; + recorded.iter().any(|was| same(&was)) + }; + gem_builds.len() != recorded.len() || !gem_builds.iter().all(held) + }); match outcome { None => { env.record( @@ -6548,6 +6554,22 @@ mod plan_gate_tests { ), ) .await; + // A run that fetches nothing ahead plans only the in-step packages + // whose backend still reads a reference: with none in the ledger, + // nothing is planned (and no candidate is judged for it). + let references = plan_run_downloads( + &gates(root, &records, &HashSet::new()), + &VendorState::default(), + &all_packages, + &HashMap::new(), + ( + &tokio::sync::OnceCell::new(), + &vendor::pypi::InstalledSiteListings::default(), + ), + true, + ) + .await; + assert!(references.is_empty(), "{references:?}"); let uuids: Vec<&str> = planned.iter().map(|d| d.uuid.as_str()).collect(); assert_eq!( uuids, diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 42f2e9c72c..3ac6ba949f 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -916,7 +916,10 @@ impl VendoredBackend<'_> { common.json, &candidate.purl, "vendor_artifact_redownload_failed", - error.detail, + match error { + vendor::redownload::RestoreError::ListMoved(detail) + | vendor::redownload::RestoreError::Failed(detail) => detail, + }, ), } } diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 89308fcd7f..6065f9daf7 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -641,10 +641,13 @@ impl GemBuildView { for built in &entry.gem_builds { let purl = built.purl(&entry.base_purl); let upstream = built.is_upstream(); - // A purl the view already attests keeps its own record, - // and the outcome of its own check: no tree of this copy - // says anything of it, as for a hosted build. - if view.patches.contains_key(&purl) { + // A purl the view already attests under another patch + // keeps its own record and the outcome of its own check: + // no tree of this copy says anything of it, as for a + // hosted build. A record of the tree's own patch is of + // the same build, which the committed tree attests. + let own = |held: &PatchRecord| !upstream && held.uuid == built.uuid; + if view.patches.get(&purl).is_some_and(|held| !own(held)) { continue; } view.patches @@ -2601,6 +2604,30 @@ mod tests { let mut vendored = vec![key.to_string()]; builds.expand(&mut vendored); assert_eq!(vendored, [linux], "only the tree the view did not attest"); + + // A record of the tree's OWN patch is of the same build: the + // committed tree attests it, and the record stays the view's. + let mut plan = vendored_gem_plan(key, |entry| { + entry.gem_builds = vec![ + gem_build("arm64-darwin", DARWIN), + gem_build("x86_64-linux-gnu", U2), + ]; + }); + let same = PatchRecord { + description: "the build's own record".to_string(), + ..record(DARWIN) + }; + plan.view.patches.insert(darwin.to_string(), same.clone()); + let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); + assert_eq!(builds.view().patches[darwin], same, "kept as it is"); + assert_eq!(builds.builds()[darwin].gem_fix, U1); + let mut vendored = vec![key.to_string()]; + builds.expand(&mut vendored); + assert_eq!( + vendored, + [darwin, linux], + "both trees are the copy's to attest" + ); } /// The gem itself stays the attested package where the ledger does not diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 4a24c52e93..730e1b4181 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -803,6 +803,16 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { let honest = std::fs::read_to_string(&state_path).unwrap(); std::fs::write(&state_path, honest.replace(LINUX_UUID, DARWIN_UUID)).unwrap(); std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); + // A dry run says what the wet run does. Both trees are patched in + // the ledger and in the list, under another patch for one of them: the + // copy is not in step, it would be vendored again. + let dry = with(VENDOR_IT, &["--dry-run"]); + let (code, stdout, stderr) = run(root, &dry, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("Would vendor 1 package.") && !stdout.contains("already vendored"), + "{stdout}\n{stderr}" + ); let fetched = downloads(&server).await.len(); let repair = ["repair", "--download-only", "--json"]; let (code, env, stderr) = run_json(root, &repair, &server.uri()); @@ -1433,97 +1443,108 @@ async fn an_intact_copy_stays_in_force_when_its_list_cannot_be_followed() { } /// A run that could not vendor an intact copy again says that the copy -/// stays in force only when it still stands. Two failures happen after -/// the copy was changed, and each is a failure the user sees (exit 1, the -/// error, no word of a copy in force): -/// -/// * the new trees are in place and the git metadata of the uuid dir -/// cannot be written: the disk holds the new builds, the ledger the old; -/// * the stage cannot be moved into place and the copy that was moved -/// aside cannot be moved back: the lock names a path that holds nothing -/// (the old copy is kept beside it). -/// +/// stays in force only when it still stands. One failure happens after +/// the copy was changed, and is a failure the user sees (exit 1, the +/// error, no word of a copy in force): the stage cannot be moved into +/// place and the copy that was moved aside cannot be moved back, so the +/// lock names a path that holds nothing (the old copy is kept beside it). /// The next run vendors the copy again from the list, as for any damaged /// copy. #[tokio::test] async fn a_copy_changed_by_a_failed_rebuild_is_not_said_to_stay_in_force() { let copy = format!(".socket/vendor/gem/{UUID}/{NAME}-{VERSION}"); - let cases = [ - ( - "vendor_gem_uuid_metadata~fail", - "cannot write the git metadata", - ), - ( - "vendor_swap_stage~fail,vendor_swap_restore~fail", - "failpoint `vendor_swap_stage` injected an error", - ), - ]; - for (failing, says) in cases { - let tmp = tempfile::tempdir().unwrap(); - let root = tmp.path(); - write_project(root); - let first = service(&[LINUX], &[DARWIN]).await; - let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); - assert_eq!(code, 0, "{env:#}\n{stderr}"); - let ledger = std::fs::read(root.join(".socket/vendor/state.json")).unwrap(); + let failing = "vendor_swap_stage~fail,vendor_swap_restore~fail"; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let ledger = std::fs::read(root.join(".socket/vendor/state.json")).unwrap(); - // The darwin build is published: the list moved. - let server = service(&[DARWIN, LINUX], &[]).await; - let (code, stdout, stderr) = run_failing(root, VENDOR_IT, &server.uri(), failing); - assert_eq!(code, 1, "{failing}:\n{stdout}\n{stderr}"); - assert!( - stderr.contains("Error:") && stderr.contains(says), - "{failing}:\n{stderr}" - ); - let said = format!("{stdout}\n{stderr}"); - assert!( - !said.contains("stays in force") && !said.contains("already vendored"), - "{failing}: the copy is not in force as it was:\n{said}" - ); - assert!(stdout.contains("1 failed"), "{failing}:\n{stdout}"); - assert_eq!( - std::fs::read(root.join(".socket/vendor/state.json")).unwrap(), - ledger, - "{failing}: the ledger is as it was" - ); - match failing.starts_with("vendor_swap") { - // The path the lock names holds nothing; the old copy is beside it. - true => { - assert!(!root.join(©).exists(), "{failing}"); - assert!( - root.join(format!("{copy}.socket-old")).exists(), - "{failing}" - ); - } - // The new trees are in place. - false => assert_eq!( - std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), - stamped(DARWIN_UUID), - "{failing}" - ), - } - let check = ["vendor", "--check", "--json"]; - let (code, env, stderr) = run_json(root, &check, &server.uri()); - assert_eq!(code, 1, "{failing}: {env:#}\n{stderr}"); + // The darwin build is published: the list moved. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run_failing(root, VENDOR_IT, &server.uri(), failing); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stderr.contains("Error:") + && stderr.contains("failpoint `vendor_swap_stage` injected an error"), + "{stderr}" + ); + let said = format!("{stdout}\n{stderr}"); + assert!( + !said.contains("stays in force") && !said.contains("already vendored"), + "the copy is not in force as it was:\n{said}" + ); + assert!(stdout.contains("1 failed"), "{stdout}"); + assert_eq!( + std::fs::read(root.join(".socket/vendor/state.json")).unwrap(), + ledger, + "the ledger is as it was" + ); + // The path the lock names holds nothing; the old copy is beside it. + assert!(!root.join(©).exists()); + assert!(root.join(format!("{copy}.socket-old")).exists()); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); - // The next run: vendored again from the list. - let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); - assert_eq!(code, 0, "{failing}: {env:#}\n{stderr}"); - assert_eq!(env["summary"]["failed"], 0, "{failing}: {env:#}"); - for platform in [DARWIN, LINUX] { - assert_eq!( - std::fs::read(tree(root, platform).join(LIB)).unwrap(), - stamped(build_uuid(platform)), - "{failing}: {platform}" - ); - } - assert!( - !root.join(format!("{copy}.socket-old")).exists(), - "{failing}" + // The next run: vendored again from the list. + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{platform}" ); - let (code, env, stderr) = run_json(root, &check, &server.uri()); - assert_eq!(code, 0, "{failing}: {env:#}\n{stderr}"); } + assert!(!root.join(format!("{copy}.socket-old")).exists()); + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// The git metadata of the uuid directory is written before the new trees +/// are moved in. When it cannot be written (a directory stands where the +/// file belongs), the copy the lock is wired to is as it was: it stays in +/// force, the run exits 0 and says why it was not brought in step. +#[tokio::test] +async fn metadata_that_cannot_be_written_leaves_the_copy_in_force() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); + std::fs::remove_file(&gitattributes).unwrap(); + std::fs::create_dir(&gitattributes).unwrap(); + std::fs::write(gitattributes.join("in the way"), b"").unwrap(); + let before = snapshot(root); + + // The darwin build is published: the list moved. + let server = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!( + stderr.contains(&format!( + "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ + registry lists (" + )) && stderr.contains("cannot write the git metadata of") + && stderr.contains("its vendored copy stays in force as it is."), + "{stderr}" + ); + assert!(!stderr.contains("Error:"), "{stderr}"); + assert_eq!(snapshot(root), before, "nothing was moved in"); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + PRISTINE + ); } /// No locked platform has a patched build: the gem is not vendored, the From 6910805e244cb82ccb83beb15036f2d9251d3d53 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 13:23:23 -0500 Subject: [PATCH 17/28] Plan a single reference-only position too A gem that follows the list of its fix may read that reference more than once in a run: the restore of a damaged copy, then the rebuild or the in-step check. With one such gem and nothing else planned there was no plan, so the two reads were two requests that could see two lists. The plan is now attached for one reference-only position as well; its task, which only a download starts, never runs. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/vendor/vendor_gem_platform_builds_e2e.rs | 5 ++--- crates/socket-patch-core/src/vendor/gem.rs | 6 ++++++ crates/socket-patch-core/src/vendor/mod.rs | 10 ++++++---- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 726fdb9b3e..3b54d35f2c 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem has nothing to share a request with and asks for its own), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem is planned too, so that a run which reads its reference more than once, a restore and then the rebuild, reads one answer), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 730e1b4181..d710a91bc3 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -766,8 +766,8 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then // those patches are asked for in one request. The run then finds - // the restored copy in step with the gem patch's list, which it - // reads again. + // the restored copy in step with the gem patch's list: the same + // answer, read once. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -783,7 +783,6 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { [ vec![UUID.to_string()], vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], - vec![UUID.to_string()], ] ); assert_eq!( diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 5165ec698e..0513e31bdb 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -14427,6 +14427,12 @@ mod tests { let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; let plan = cfg.prefetch_archives(planned()); assert!(plan.is_some(), "the plan is attached"); + // A single such gem is worth a plan too: its reads share one + // answer. + let alone = vec![PlannedDownload::reference(UUID_B.to_string())]; + assert!(cfg.prefetch_archives(alone).is_some()); + drop(plan); + let plan = cfg.prefetch_archives(planned()); let (again, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 3d0a7d2239..83627b24da 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -404,9 +404,11 @@ impl VendorServiceConfig { /// nothing is fetched ahead ([`Self::wants_prefetch`] is false, or /// fewer than two downloads are planned, with nothing to overlap) the /// plan holds them alone, and its task, which only a download starts, - /// never runs. `None` — nothing attached — when the service is not - /// enabled or the plan would hold fewer than two positions (one has - /// nothing to share a request with). + /// never runs. One such position is worth a plan by itself: its + /// backend may read the reference more than once (a restore, then the + /// rebuild), and the plan answers every read with the one answer. + /// `None` — nothing attached — when the service is not enabled or the + /// plan would hold nothing. pub fn prefetch_archives( &self, mut downloads: Vec, @@ -415,7 +417,7 @@ impl VendorServiceConfig { if !self.wants_prefetch() || archives < 2 { downloads.retain(|d| d.reference_only); } - if !self.service_enabled() || downloads.len() < 2 { + if !self.service_enabled() || downloads.is_empty() { return None; } let client = self.client.as_ref()?; From 5412a448964f46f6a16fd2117f7ab75a76ed6e5a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 13:55:53 -0500 Subject: [PATCH 18/28] Name what works in three texts of a platform-locked vendored gem The `vendor_prebuilt_replaced` error and its contract row told the user to roll the gem back and then run a vendored scan. A vendored scan alone vendors the copy again from the list, so the message and the row name that one command, once. The skip of a build that is listed but not served yet, and the skip of a platform the registry does not list, still said "Vendored mode needs every locked platform". They say what is needed now: a gem, patched or upstream's own, for every locked platform. The contract and the guide state which releases read a copy with a tree of upstream's gem: one with this support and the platform-gem vendoring it builds on. 5.1.0 and earlier do not know such a tree and can attest the gem as patched for every platform. Tests pin the remedy sentence and that it names one command in the core restore tests and the CLI repair test, the two skip lines at 80 columns, and the contract row and the guide sentence. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 6 +- .../socket-patch-cli/src/commands/vendor.rs | 17 +-- crates/socket-patch-cli/src/ui/text.rs | 26 ++++- .../tests/e2e_redirect_gem_stale_install.rs | 3 +- .../tests/e2e_vendor_gem_build.rs | 6 +- .../vendor/vendor_gem_platform_builds_e2e.rs | 75 +++++++++++-- crates/socket-patch-core/src/vendor/gem.rs | 105 +++++++++++++----- docs/ecosystems.md | 2 +- 8 files changed, 186 insertions(+), 54 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 3b54d35f2c..11768fa1ac 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem is planned too, so that a run which reads its reference more than once, a restore and then the rebuild, reads one answer), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch rollback ` and then `socket-patch scan --mode vendored`. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem is planned too, so that a run which reads its reference more than once, a restore and then the rebuild, reads one answer), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2522,10 +2522,10 @@ command's integration tests check its output. | `vendor_maven_selection_undetermined` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven): what the build selects for the artifact cannot be read (the reason says why: typically a pom the local repository does not hold, because the project was never resolved) and no declaration names the patch's base version, so nothing is pinned on a guess and no file is written. The reason carries the remedy that fits its cause (resolve the project once and re-run when a pom is missing from the local repository; otherwise declare the artifact at the base version). The vendored twin of `redirect_maven_selection_undetermined`. | | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | -| `vendor_prebuilt_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy: `socket-patch rollback `, then `socket-patch scan --mode vendored`. | +| `vendor_prebuilt_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy, the one command that works: run `socket-patch scan --mode vendored`, which vendors what the patch service serves now. | | `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, or an upstream gem did not unpack. Nothing of the copy was touched and it stays in force, which the run checks before it says so; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | | `vendor_gem_list_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): the run vendored an intact copy again because its fix lists another build for a locked platform. JSON only: the gem's line says which platforms changed (`now also patched for …`, `upstream gem back for …`), and the builds' events carry `details.newlyPatched` / `details.withdrawn`. | -| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | +| `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs a gem, patched or upstream's own, for every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | | `revert_failed` | `failed` | vendor --revert: a recorded entry could not be reverted. | | `vendor_ledger_missing` | `failed` (artifact-level: `uuid` + `details.{ecosystem,path}`, no purl) | repair (v5.0) and `vendor --check`: a lockfile references `.socket/vendor///` but the vendor ledger has no entry for it; repair no longer rebuilds ledger entries from lockfiles. Recovery: restore `.socket/vendor/state.json` from version control and re-run `repair`, or `git checkout -- ` and re-vendor. | diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index d72cf1d913..bf22bed640 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -9476,16 +9476,19 @@ mod ui_format_tests { let purl = "pkg:gem/nokogiri@1.19.3?platform=ruby"; for line in [ "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ - (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every \ - locked platform; `scan --mode hosted` can patch the others now.", + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched \ + or upstream's own, for every locked platform; `scan --mode hosted` can patch the \ + others now.", "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ - (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every \ - locked platform; the gem stays hosted.", + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched \ + or upstream's own, for every locked platform; the gem stays hosted.", "nokogiri@1.19.3 was not brought up to date: no patched build yet for java. \ - Vendored mode needs every locked platform; its vendored copy stays in force as \ + Vendored mode needs a gem, patched or upstream's own, for every locked platform; its \ + vendored copy stays in force as \ it is.", - "nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored \ - mode needs every locked platform, and a re-run does not change what the registry \ + "nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode \ + needs a gem, patched or upstream's own, for every locked platform, and a re-run does \ + not change what the registry \ lists: this is settled once the lockfile no longer names java (`bundle lock \ --remove-platform java`), or the registry lists a gem for every locked platform.", "nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right \ diff --git a/crates/socket-patch-cli/src/ui/text.rs b/crates/socket-patch-cli/src/ui/text.rs index 96be986c97..5f6f60f162 100644 --- a/crates/socket-patch-cli/src/ui/text.rs +++ b/crates/socket-patch-cli/src/ui/text.rs @@ -482,16 +482,32 @@ mod tests { x86_64-linux-gnu; left on its upstream registry" ); let vendored = "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin \ - (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs \ - every locked platform; `scan --mode hosted` can patch the others now."; + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a \ + gem, patched or upstream's own, for every locked platform; `scan --mode \ + hosted` can patch the others now."; assert_eq!( wrap_line(vendored, Some(80)), "nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin\n \ - (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs every\n \ - locked platform; `scan --mode hosted` can patch the others now." + (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem,\n \ + patched or upstream's own, for every locked platform;\n \ + `scan --mode hosted` can patch the others now." + ); + let unlisted = "nokogiri@1.19.3 is not vendored: the patch registry does not list java. \ + Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform, and a re-run does not change what the registry lists: this is \ + settled once the lockfile no longer names java (`bundle lock \ + --remove-platform java`), or the registry lists a gem for every locked \ + platform."; + assert_eq!( + wrap_line(unlisted, Some(80)), + "nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored\n \ + mode needs a gem, patched or upstream's own, for every locked platform, and a\n \ + re-run does not change what the registry lists: this is settled once the\n \ + lockfile no longer names java (`bundle lock --remove-platform java`), or the\n \ + registry lists a gem for every locked platform." ); for width in [80, 100, 120] { - for line in [kept, waiting, vendored] { + for line in [kept, waiting, vendored, unlisted] { let wrapped = wrap_line(line, Some(width)); assert!( wrapped.lines().all(|row| row.chars().count() <= width), diff --git a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs index 5e28de5d68..d9d39decc8 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_gem_stale_install.rs @@ -4364,7 +4364,8 @@ async fn refused_platform_gem_is_counted_as_left_to_patch() { _ => ( format!( "{DEP}@{DEP_VERSION} is not vendored: the patch registry does not list \ - {OTHER_PLATFORM}. Vendored mode needs every locked platform, and a re-run \ + {OTHER_PLATFORM}. Vendored mode needs a gem, patched or upstream's own, for \ + every locked platform, and a re-run \ does not change what the registry lists: this is settled once the \ lockfile no longer names {OTHER_PLATFORM} (`bundle lock --remove-platform \ {OTHER_PLATFORM}`), or the registry lists a gem for every locked platform." diff --git a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs index 92151786e1..cd9b1adfa2 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -3371,13 +3371,15 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) have.sort(); let not_vendored = format!( "{PLAT}@{PLAT_VERSION} is not vendored: no patched build yet for {} ({} and {} have \ - one). Vendored mode needs every locked platform; `scan --mode hosted` can patch the \ + one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; \ + `scan --mode hosted` can patch the \ others now.", without_build[0], have[0], have[1] ); let not_listed = format!( "{PLAT}@{PLAT_VERSION} is not vendored: the patch registry does not list {0}. Vendored \ - mode needs every locked platform, and a re-run does not change what the registry \ + mode needs a gem, patched or upstream's own, for every locked platform, and a re-run does \ + not change what the registry \ lists: this is settled once the lockfile no longer names {0} (`bundle lock \ --remove-platform {0}`), or the registry lists a gem for every locked platform.", without_build[0] diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index d710a91bc3..08df4511d7 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -824,7 +824,12 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { said.contains("vendor_prebuilt_replaced") && said.contains("cannot be restored as it was vendored") && said.contains("the gem's fix now names patch") - && said.contains("socket-patch scan --mode vendored"), + && said.contains( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which vendors \ + what the patch service serves now" + ) + && said.matches("`socket-patch ").count() == 1 + && !said.contains("rollback"), "{env:#}" ); assert!( @@ -1730,7 +1735,8 @@ async fn an_eject_of_a_gem_with_a_build_still_being_built_is_refused_whole() { failed["error"], format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ - one). Vendored mode needs every locked platform; the gem stays hosted." + one). Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform; the gem stays hosted." ) .as_str(), "{failed:#}" @@ -2019,7 +2025,8 @@ async fn a_vendored_scan_leaves_a_hosted_gem_with_a_build_still_being_built_host skipped["reason"], format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has \ - one). Vendored mode needs every locked platform; the gem stays hosted." + one). Vendored mode needs a gem, patched or upstream's own, for every locked \ + platform; the gem stays hosted." ) .as_str(), "{skipped:#}" @@ -2528,7 +2535,8 @@ async fn a_platform_patch_that_is_not_served_is_the_same_skip_in_every_dry_and_w ] { let line = format!( "{NAME}@{VERSION} is not vendored: {none} {DARWIN} ({LINUX} has one). Vendored mode \ - needs every locked platform; `scan --mode hosted` can patch the others now." + needs a gem, patched or upstream's own, for every locked platform; `scan --mode \ + hosted` can patch the others now." ); for command in [VENDOR_IT, SCAN_IT, GET_IT] { let server = service_of(UUID, &[(DARWIN, Some(status)), (LINUX, None)], &[]).await; @@ -2562,7 +2570,8 @@ async fn an_unserved_platform_patch_keeps_the_vendored_copy_of_an_earlier_patch( let newer = service_of(UUID_B, &[(DARWIN, Some(status)), (LINUX, None)], &[]).await; let line = format!( "{NAME}@{VERSION} was not brought up to date: {none} {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; its vendored copy of an earlier patch \ + Vendored mode needs a gem, patched or upstream's own, for every locked platform; its \ + vendored copy of an earlier patch \ stays in force as it is." ); for flags in [&["--dry-run"][..], &[]] { @@ -2637,7 +2646,8 @@ async fn an_unserved_platform_patch_still_fails_a_damaged_wired_copy_and_an_ejec failed["error"], format!( "{NAME}@{VERSION} is not vendored: {none} {DARWIN} ({LINUX} has one). Vendored \ - mode needs every locked platform; the gem stays hosted." + mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ) .as_str(), "{failed:#}" @@ -2663,7 +2673,8 @@ async fn an_unserved_platform_patch_still_fails_a_damaged_wired_copy_and_an_ejec async fn a_takeover_of_a_hosted_gem_with_a_build_still_being_built_stays_hosted_dry_or_wet() { let line = format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; the gem stays hosted." + Vendored mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ); for server in [service_still_building_darwin().await] { mount_search(&server).await; @@ -2706,7 +2717,8 @@ async fn a_takeover_of_a_hosted_gem_with_a_build_still_being_built_stays_hosted_ async fn no_run_tells_a_gem_that_stays_hosted_to_run_hosted_mode() { let stays = format!( "{NAME}@{VERSION} is not vendored: no patched build yet for {DARWIN} ({LINUX} has one). \ - Vendored mode needs every locked platform; the gem stays hosted." + Vendored mode needs a gem, patched or upstream's own, for every locked platform; the gem \ + stays hosted." ); for command in [SCAN_IT, GET_IT, VENDOR_IT] { let server = service_still_building_darwin().await; @@ -2795,3 +2807,50 @@ async fn an_offline_dry_run_asks_nothing_and_promises_nothing() { "offline" ); } + +/// The contract and the guide say what the CLI says. The remedy of a build +/// that was replaced is the vendored scan alone, in the row of its code as +/// in the message. What vendored mode needs of a gem locked as platform +/// gems is a gem for every locked platform, patched or upstream's. And both +/// say which releases read a copy with a tree of upstream's gem. +#[test] +fn the_contract_and_the_guide_say_what_the_cli_says() { + let cli = Path::new(env!("CARGO_MANIFEST_DIR")); + let read = |path: std::path::PathBuf| { + std::fs::read_to_string(&path) + .unwrap_or_else(|e| panic!("{}: {e}", path.display())) + .replace("\r\n", "\n") + }; + let contract = read(cli.join("CLI_CONTRACT.md")); + let guide = read(cli.join("../../docs/ecosystems.md")); + + let row = contract + .lines() + .find(|line| line.starts_with("| `vendor_prebuilt_replaced` |")) + .expect("the row of vendor_prebuilt_replaced"); + assert!( + row.ends_with( + "the one command that works: run `socket-patch scan --mode vendored`, which vendors \ + what the patch service serves now. |" + ), + "{row}" + ); + assert!(!row.contains("socket-patch rollback"), "{row}"); + + assert!( + contract.contains( + "Vendored mode needs a gem, patched or upstream's own, for every locked platform" + ), + "the contract quotes the line" + ); + for (name, text) in [("contract", &contract), ("guide", &guide)] { + assert!(!text.contains("needs every locked platform"), "{name}"); + assert!( + text.contains( + "5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as \ + patched for every platform" + ), + "{name}" + ); + } +} diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0513e31bdb..6f3b2f1272 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -2135,6 +2135,18 @@ impl NoPatchedBuild<'_> { } } +/// What vendored mode needs of the patch registry for a gem locked as +/// platform gems, in the lines of a gem it leaves as it is: a tree for +/// each locked platform, of the patched build or of upstream's own gem. +const NEEDS_A_GEM: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; + +/// The remedy of a copy that cannot be restored as it was vendored because +/// the list of its fix moved ([`VENDOR_PREBUILT_REPLACED`]): the run that +/// vendors the copy again from that list. +const VENDOR_FROM_THE_LIST: &str = + "Run `socket-patch scan --mode vendored`, which vendors what the patch service serves now"; + /// The one line for a gem left as it is because the locked platforms of /// `missing` have no patched build, while `patched` (the other locked /// platforms) have one. Its last clause says what the gem's `standing` @@ -2182,11 +2194,10 @@ fn no_patched_build_detail( Standing::Hosted => "; the gem stays hosted.", }; return format!( - "{gem} {lead}: the patch registry does not list {names}{also}. Vendored mode needs \ - every locked platform, and a re-run does not change what the registry lists: this \ - is settled once the lockfile no longer names {names} (`bundle lock \ - --remove-platform {args}`), or the registry lists a gem for every locked \ - platform{tail}", + "{gem} {lead}: the patch registry does not list {names}{also}. {NEEDS_A_GEM}, and a \ + re-run does not change what the registry lists: this is settled once the \ + lockfile no longer names {names} (`bundle lock --remove-platform {args}`), or the \ + registry lists a gem for every locked platform{tail}", names = listed(unlisted), args = unlisted.join(" "), ); @@ -2205,7 +2216,7 @@ fn no_patched_build_detail( (Standing::NotVendored, false) => "; `scan --mode hosted` can patch the others now.", (Standing::Hosted, false) => "; the gem stays hosted.", }; - format!("{gem} {lead}: {none}{have}. Vendored mode needs every locked platform{tail}") + format!("{gem} {lead}: {none}{have}. {NEEDS_A_GEM}{tail}") } /// The skip of a gem none of whose locked platforms (`upstream`) has a @@ -2519,10 +2530,8 @@ async fn recorded_build_sources( format!( "the copy of the platform gem for {subject} cannot be restored as it was \ vendored: the vendor ledger records patch {} for it, and the gem's fix \ - {now}. Nothing was restored. To vendor what the patch service serves \ - now, run `socket-patch rollback pkg:gem/{}` and then \ - `socket-patch scan --mode vendored`", - built.uuid, trees.gem + {now}. Nothing was restored. {VENDOR_FROM_THE_LIST}", + built.uuid ), ) }; @@ -2537,8 +2546,7 @@ async fn recorded_build_sources( format!( "the copy of upstream's gem for {subject} cannot be restored as it \ was vendored: the gem's fix {} for that platform now. Nothing was \ - restored. Run `socket-patch scan --mode vendored`, which vendors \ - what the patch service serves now", + restored. {VENDOR_FROM_THE_LIST}", match now.and_then(|gem| gem.patch_uuid.as_deref()) { Some(uuid) => format!("names the patched build of patch {uuid}"), None => "lists no gem".to_string(), @@ -14718,6 +14726,21 @@ mod tests { crate::vendor::redownload::RestoreError::ListMoved(_) ); assert_eq!(list_moved, moved, "{refused}"); + // A list that moved names the one command that works, once: + // the scan that vendors the copy again from that list. + assert_eq!( + refused.detail().ends_with( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which \ + vendors what the patch service serves now" + ), + moved, + "{refused}" + ); + assert_eq!( + refused.detail().matches("`socket-patch ").count(), + usize::from(moved), + "{refused}" + ); let asked = crate::vendor::redownload::restore_follows_list(&entry, &record, &cfg); assert_eq!(asked.await, moved, "{says}"); } @@ -14795,7 +14818,8 @@ mod tests { vec![listed(DARWIN, Listed::Unlisted), served(LINUX)], true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin. Vendored mode needs every locked platform, and a re-run does \ + arm64-darwin. Vendored mode needs a gem, patched or upstream's own, for every \ + locked platform, and a re-run does \ not change what the registry lists: this is settled once the lockfile no \ longer names arm64-darwin (`bundle lock --remove-platform arm64-darwin`), \ or the registry lists a gem for every locked platform.", @@ -14807,7 +14831,8 @@ mod tests { ], true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin. Vendored mode needs every locked platform, and a re-run does \ + arm64-darwin. Vendored mode needs a gem, patched or upstream's own, for every \ + locked platform, and a re-run does \ not change what the registry lists: this is settled once the lockfile no \ longer names arm64-darwin (`bundle lock --remove-platform arm64-darwin`), \ or the registry lists a gem for every locked platform.", @@ -14825,8 +14850,9 @@ mod tests { Vec::new(), true, "nokogiri@1.18.10 is not vendored: the patch registry does not list \ - arm64-darwin and x86_64-linux-gnu. Vendored mode needs every locked \ - platform, and a re-run does not change what the registry lists: this is \ + arm64-darwin and x86_64-linux-gnu. Vendored mode needs a gem, patched or \ + upstream's own, for every locked platform, and a re-run does not change what \ + the registry lists: this is \ settled once the lockfile no longer names arm64-darwin and \ x86_64-linux-gnu (`bundle lock --remove-platform arm64-darwin \ x86_64-linux-gnu`), or the registry lists a gem for every locked platform.", @@ -14949,8 +14975,9 @@ mod tests { assert_eq!( detail, "nokogiri@1.18.10 was not brought up to date: no patched build yet for java \ - (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs every \ - locked platform; its vendored copy stays in force as it is." + (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs a gem, \ + patched or upstream's own, for every locked platform; its vendored copy stays \ + in force as it is." ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); } @@ -14982,7 +15009,8 @@ mod tests { assert_eq!( detail, "nokogiri@1.18.10 was not brought up to date: the patch registry does not \ - list x86_64-linux-gnu. Vendored mode needs every locked platform, and a \ + list x86_64-linux-gnu. Vendored mode needs a gem, patched or upstream's own, \ + for every locked platform, and a \ re-run does not change what the registry lists: this is settled once the \ lockfile no longer names x86_64-linux-gnu (`bundle lock --remove-platform \ x86_64-linux-gnu`), or the registry lists a gem for every locked platform; \ @@ -15021,7 +15049,8 @@ mod tests { /// download and nothing written. #[tokio::test] async fn a_platform_patch_that_is_not_served_is_a_skip_that_downloads_nothing() { - const NEEDS: &str = "Vendored mode needs every locked platform"; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; const HOSTED: &str = "`scan --mode hosted` can patch the others now."; let mut cases: Vec<(Vec, String)> = vec![ ( @@ -15113,8 +15142,9 @@ mod tests { detail, format!( "nokogiri@1.18.10 was not brought up to date: {none} \ - x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs every \ - locked platform; its vendored copy of an earlier patch stays in \ + x86_64-linux-gnu (arm64-darwin has one). Vendored mode needs a gem, \ + patched or upstream's own, for every locked platform; its vendored \ + copy of an earlier patch stays in \ force as it is." ) ); @@ -15141,8 +15171,9 @@ mod tests { detail, format!( "nokogiri@1.18.10 was not brought up to date: {none} java \ - (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs \ - every locked platform; its vendored copy stays in force as it is." + (arm64-darwin and x86_64-linux-gnu have one). Vendored mode needs a \ + gem, patched or upstream's own, for every locked platform; its \ + vendored copy stays in force as it is." ) ); assert_eq!(ts::tree_snapshot(&root), before, "dry_run={dry_run}"); @@ -15182,7 +15213,8 @@ mod tests { format!( "nokogiri@1.18.10 was not brought up to date: no patched build \ {none} for x86_64-linux-gnu (arm64-darwin has one). Vendored mode \ - needs every locked platform; its vendored copy is missing or \ + needs a gem, patched or upstream's own, for every locked platform; \ + its vendored copy is missing or \ damaged and cannot be rebuilt until then." ) ); @@ -15590,7 +15622,8 @@ mod tests { fn the_line_of_an_unpatched_platform_ends_with_what_the_gem_is_left_with() { const GEM: &str = "nokogiri@1.18.10"; const NONE_YET: &str = "no patched build yet for arm64-darwin"; - const NEEDS: &str = "Vendored mode needs every locked platform"; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; let yet = NoPatchedBuild { yet: vec![DARWIN], ..NoPatchedBuild::default() @@ -15743,7 +15776,8 @@ mod tests { .await; unwrap_refused(outcome) } - const NEEDS: &str = "Vendored mode needs every locked platform"; + const NEEDS: &str = + "Vendored mode needs a gem, patched or upstream's own, for every locked platform"; let cases: [(Vec, String); 3] = [ ( vec![served(DARWIN), unserved(LINUX, "pending_build")], @@ -16486,6 +16520,23 @@ mod tests { .await .expect_err("an edited ledger entry is refused"); assert!(format!("{refused:?}").contains(why), "{refused:?}"); + // Only the list that names another patch has a remedy, the + // scan that vendors the copy again from it, named once and + // with no rollback before it. + let replaced = why.starts_with("the gem's fix"); + assert_eq!( + refused.detail().ends_with( + "Nothing was restored. Run `socket-patch scan --mode vendored`, which \ + vendors what the patch service serves now" + ), + replaced, + "{refused}" + ); + assert_eq!( + refused.detail().matches("`socket-patch ").count(), + usize::from(replaced), + "{refused}" + ); assert!(!tree.exists(), "nothing is unpacked: {why}"); assert_eq!(downloads(&server).await.len(), fetched, "{why}"); } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 3d6b3cdf24..961952ce37 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. A later scan asks the patch registry which builds it lists (the gems vendored this way share one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy: 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (the gems vendored this way share one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 31594cbc5bf780a39b19f583fc0213838cd8d8cd Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 14:34:33 -0500 Subject: [PATCH 19/28] Leave a vendored tree whose purl the view attests to that record The vendored loop of the vex view made an exception for a record of the tree's own patch. By the account of the commit that added it, no run reaches it: a manifest record of a platform gem's own patch is set aside for the wired patch before the loop runs. The loop follows the hosted loop's rule again, a purl the view already attests keeps its record, and compares no uuid. What is left is always an insert, so it is one. `repair` reads the detail of a refused restore through the one accessor. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/vendored_backend/repair.rs | 5 +-- .../src/commands/vex_sources.rs | 44 ++++--------------- 2 files changed, 10 insertions(+), 39 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs index 3ac6ba949f..7b3b3ccf1e 100644 --- a/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs +++ b/crates/socket-patch-cli/src/commands/vendored_backend/repair.rs @@ -916,10 +916,7 @@ impl VendoredBackend<'_> { common.json, &candidate.purl, "vendor_artifact_redownload_failed", - match error { - vendor::redownload::RestoreError::ListMoved(detail) - | vendor::redownload::RestoreError::Failed(detail) => detail, - }, + error.detail().to_string(), ), } } diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 6065f9daf7..0cecff706e 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -641,18 +641,15 @@ impl GemBuildView { for built in &entry.gem_builds { let purl = built.purl(&entry.base_purl); let upstream = built.is_upstream(); - // A purl the view already attests under another patch - // keeps its own record and the outcome of its own check: - // no tree of this copy says anything of it, as for a - // hosted build. A record of the tree's own patch is of - // the same build, which the committed tree attests. - let own = |held: &PatchRecord| !upstream && held.uuid == built.uuid; - if view.patches.get(&purl).is_some_and(|held| !own(held)) { + // A purl the view already attests keeps its own record, + // and the outcome of its own check: no tree of this copy + // says anything of it, as for a hosted build. + if view.patches.contains_key(&purl) { continue; } - view.patches - .entry(purl.clone()) - .or_insert_with(|| match upstream { + view.patches.insert( + purl.clone(), + match upstream { // A tree of upstream's own gem, named for the // document alone: what it is affected by, as the // record of the gem's patch states it. No copy is @@ -663,7 +660,8 @@ impl GemBuildView { files: entry.gem_tree_files(&built.platform, &record.files), ..record.clone() }, - }); + }, + ); builds.insert( purl.clone(), GemBuildInfo { @@ -2604,30 +2602,6 @@ mod tests { let mut vendored = vec![key.to_string()]; builds.expand(&mut vendored); assert_eq!(vendored, [linux], "only the tree the view did not attest"); - - // A record of the tree's OWN patch is of the same build: the - // committed tree attests it, and the record stays the view's. - let mut plan = vendored_gem_plan(key, |entry| { - entry.gem_builds = vec![ - gem_build("arm64-darwin", DARWIN), - gem_build("x86_64-linux-gnu", U2), - ]; - }); - let same = PatchRecord { - description: "the build's own record".to_string(), - ..record(DARWIN) - }; - plan.view.patches.insert(darwin.to_string(), same.clone()); - let builds = GemBuildView::of(&plan).expect("a gem vendored as platform gems"); - assert_eq!(builds.view().patches[darwin], same, "kept as it is"); - assert_eq!(builds.builds()[darwin].gem_fix, U1); - let mut vendored = vec![key.to_string()]; - builds.expand(&mut vendored); - assert_eq!( - vendored, - [darwin, linux], - "both trees are the copy's to attest" - ); } /// The gem itself stays the attested package where the ledger does not From 76bb806b5ea7bf1a861951ca1f91fbfddc32449a Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 14:34:49 -0500 Subject: [PATCH 20/28] Ask for each vendored gem's list by its own request, and write the metadata after the swap The fourth review's findings came from two things that are now gone. The lists of the gems a run finds vendored as platform gems no longer ride the download plan. `reference_only`, the single-position plan, the kept answers, the replayed failure and the planner's reference pass are removed, and the prefetch plan is what it is on the base branch. Each such gem asks for the reference of its own fix, live, where it needs it: one small request per vendored platform gem per run. A service that does not answer is bounded by the client's circuit breaker, and a gem whose reference cannot be read keeps its copy and says nothing. A restore and the rebuild that follows it are decided by one answer without a cache: the restore reads the fix's list once (`FixList`), and a refusal over it (`RestoreError::ListMoved`) carries it to the backend, which vendors the copy again from it. The dry run's question hands the same list. `BuildsFrom::Listed` holds the list where it was already read, and the request is made in one function. The uuid directory's git metadata is written after the new trees are in place again. It is not part of the copy, so a write that fails is the warning every backend gives for ignore rules it could not vouch for, and never a failure: the trees are in place, and the entry handed back records them. A failed rebuild no longer leaves a uuid directory holding the metadata alone, and unwritable metadata no longer stops a rebuild. The "Also:" suffix of the pending skip, which nothing could produce, is removed. Tests: the request of a copy in step names its own fix alone; a refused restore hands its list on and the fix's reference is asked for once, wet and dry, at the core and CLI levels; unwritable metadata is a warning with the new trees in place and recorded; a failed rebuild leaves no uuid directory where there was none. Co-Authored-By: Claude Fable 5.2 --- .../src/commands/scan/vendor_flow.rs | 13 - .../socket-patch-cli/src/commands/vendor.rs | 122 +--- .../vendor/vendor_gem_platform_builds_e2e.rs | 79 ++- crates/socket-patch-core/src/api/client.rs | 18 +- .../src/api/vendor_prefetch.rs | 229 +------ crates/socket-patch-core/src/vendor/gem.rs | 595 ++++++++++-------- crates/socket-patch-core/src/vendor/mod.rs | 36 +- .../src/vendor/redownload.rs | 82 +-- 8 files changed, 498 insertions(+), 676 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index fcb86e8656..9fc7c34ede 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -302,19 +302,6 @@ impl VendorPreview { // Offline, the backend refuses before it would ask. let service = common.vendor_service_config(Some(client.clone()), use_public_proxy); let state = load_state(&common.cwd).await.unwrap_or_default(); - // The lists of the gems already vendored are one request, through - // the download plan the wet run's vendor step attaches for them: - // each such gem is a position whose reference alone is read. - let followers: Vec<_> = self - .rows - .iter() - .filter(|row| in_sync(row) && platform_gems.contains(&row.purl)) - .filter_map(|row| { - let entry = lookup_entry(&state.entries, &row.purl)?; - socket_patch_core::vendor::in_step_reference(entry, &row.uuid) - }) - .collect(); - let _plan = service.prefetch_archives(followers); for row in &mut self.rows { let vendored = in_sync(row); if !(would_vendor(row) || vendored) || !platform_gems.contains(&row.purl) { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index bf22bed640..52af75008b 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -318,6 +318,7 @@ async fn takeover_dry_refusal( // The pin this previews the takeover of stays when the backend // refuses. true, + None, &mut Vec::new(), )) .await; @@ -357,11 +358,13 @@ fn restored_text_previewable( /// Dispatch one purl to its ecosystem backend. `pkg_path` is the crawler's /// installed location (site-packages root for pypi, the package dir /// otherwise), when available. Returns `None` for purls with no vendor -/// backend in this build. Two arguments are the gem backend's alone (see +/// backend in this build. Three arguments are the gem backend's alone (see /// [`vendor::gem::vendor_gem_previewing`]): `hosted` says the lockfile /// pins the package hosted and the caller keeps that pin when the backend /// does not vendor it (a takeover or an eject), so the backend words its -/// refusal for a gem that stays hosted; `gem_preview` receives the +/// refusal for a gem that stays hosted; `gem_list` is the list of the +/// gem's fix that an exact restore of its copy was refused over, from +/// which the backend vendors the copy again; `gem_preview` receives the /// platform gems a dry run found the wet run would vendor for a gem /// locked as platform gems. #[allow(clippy::too_many_arguments)] @@ -378,6 +381,7 @@ pub(crate) async fn dispatch_vendor_one( pipenv_version: &tokio::sync::OnceCell>, installed_sites: &vendor::pypi::InstalledSiteListings, hosted: bool, + gem_list: Option<&vendor::gem::FixList>, gem_preview: &mut Vec, ) -> Option { let eco = ecosystem_dir_for_purl(purl)?; @@ -454,6 +458,7 @@ pub(crate) async fn dispatch_vendor_one( force, service, hosted, + gem_list, gem_preview, ) .await @@ -3673,32 +3678,8 @@ impl<'a> CandidateGates<'a> { /// candidate [`CandidateGates::judge`] sends to its backend, less the ones /// the loop answers without the service (a hosted takeover, an npm /// artifact the ledger anchors, an in-sync re-run) and the ones the -/// backend's own preflight refuses. An in-sync package whose backend still -/// reads its package reference (a gem that follows the list of its fix) is -/// a position of its own, whose reference alone is read -/// ([`vendor::in_step_reference`]). -// The tests name the plan of a wet run through this shim. -#[cfg(test)] +/// backend's own preflight refuses. async fn plan_service_downloads( - gates: &CandidateGates<'_>, - ledger: &VendorState, - all_packages: &[(String, StagedSource)], - variant_groups: &HashMap>, - caches: ( - &tokio::sync::OnceCell>, - &vendor::pypi::InstalledSiteListings, - ), -) -> Vec { - plan_run_downloads(gates, ledger, all_packages, variant_groups, caches, false).await -} - -/// The plan of a run: [`plan_service_downloads`]'s, or with -/// `references_only` (a run that fetches nothing ahead: a dry run, or one -/// whose API in-flight cap is one) only the in-step positions whose -/// reference alone is read. Then no candidate is judged and no backend's -/// preflight is run for anything else, and a ledger with no such entry -/// costs nothing. -async fn plan_run_downloads( gates: &CandidateGates<'_>, ledger: &VendorState, all_packages: &[(String, StagedSource)], @@ -3707,28 +3688,13 @@ async fn plan_run_downloads( &tokio::sync::OnceCell>, &vendor::pypi::InstalledSiteListings, ), - references_only: bool, ) -> Vec { - use socket_patch_core::api::client::PlannedDownload; let cwd = gates.cwd; let uninstalled = cwd.join(UNINSTALLED_REL); - // Whether the ledger's entry for `purl` is one whose backend still - // reads a reference for the patch it records. - let reads_reference = |purl: &str| { - lookup_entry(&ledger.entries, purl) - .is_some_and(|entry| vendor::in_step_reference(entry, &entry.uuid).is_some()) - }; - if references_only && !ledger.entries.keys().any(|purl| reads_reference(purl)) { - return Vec::new(); - } - // Each loop candidate that reaches its backend, in loop order: one to - // preflight, or a position that is already known. - let mut reaching: Vec<(&str, &PatchRecord, &Path, Option)> = Vec::new(); + // Each loop candidate that reaches its backend, in loop order. + let mut reaching: Vec<(&str, &PatchRecord, &Path)> = Vec::new(); for group in candidate_groups(all_packages, variant_groups) { for candidate in &group.candidates { - if references_only && !reads_reference(candidate) { - continue; - } let CandidateVerdict::Vendor { purl: candidate, record, @@ -3760,25 +3726,17 @@ async fn plan_run_downloads( // committed artifact, which the loop's own call repeats. Left // out of the plan: should the artifact need rebuilding after all, // the loop fetches it live. - let in_step = - lookup_entry(&ledger.entries, candidate).filter(|e| e.uuid == record.uuid); - if let Some(entry) = in_step { - let reference = vendor::in_step_reference(entry, &record.uuid); - if reference.is_some() { - reaching.push((candidate, record, source_path, reference)); - } + if lookup_entry(&ledger.entries, candidate).is_some_and(|e| e.uuid == record.uuid) { continue; } - if !references_only { - reaching.push((candidate, record, source_path, None)); - } + reaching.push((candidate, record, source_path)); } } let npm: Vec<(&str, &PatchRecord)> = reaching .iter() - .filter(|(purl, ..)| purl.starts_with("pkg:npm/")) - .map(|(purl, record, ..)| (*purl, *record)) + .filter(|(purl, _, _)| purl.starts_with("pkg:npm/")) + .map(|(purl, record, _)| (*purl, *record)) .collect(); let mut npm_verdicts = if npm.is_empty() { Vec::new() @@ -3790,14 +3748,14 @@ async fn plan_run_downloads( // of the project's lockfiles (a cargo gate clones the whole Cargo.lock // document), which a monorepo pays for in peak memory. let mut planned = Vec::new(); - for (purl, record, source_path, known) in &reaching { - let download = if known.is_some() { - known.clone() - } else if purl.starts_with("pkg:npm/") { + for (purl, record, source_path) in &reaching { + let download = if purl.starts_with("pkg:npm/") { npm_verdicts .next() .filter(|verdict| verdict.is_ok()) - .map(|_| PlannedDownload::archive(record.uuid.clone())) + .map(|_| { + socket_patch_core::api::client::PlannedDownload::archive(record.uuid.clone()) + }) } else { vendor::service_preflight( purl, @@ -4172,20 +4130,14 @@ pub(crate) async fn vendor_records_reusing( // build and counts against quota, so a package the loop refuses is // never granted on its behalf. The plan stays advisory — every outcome // is still decided at the loop's own call (see `VendorPrefetch`). - // A dry run fetches nothing ahead, nor does a run whose API in-flight - // cap is one. Its plan still holds the in-step packages whose backend - // reads a reference on every run, so that those are one request for it - // too: that does not depend on what gates the downloads. - let service_prefetch = match service.filter(|cfg| cfg.service_enabled()) { + let service_prefetch = match service.filter(|cfg| !common.dry_run && cfg.wants_prefetch()) { Some(cfg) => { - let references_only = common.dry_run || !cfg.wants_prefetch(); - let planned = plan_run_downloads( + let planned = plan_service_downloads( &gates, &state, &all_packages, &variant_groups, (&pipenv_version, &installed_sites), - references_only, ) .await; cfg.prefetch_archives(planned) @@ -4546,6 +4498,10 @@ pub(crate) async fn vendor_records_reusing( } } + // The list of a gem's fix that the exact restore below was + // refused over: handed to the backend, which vendors the copy + // again from it, so the two read one answer. + let mut gem_list: Option = None; // A dir-shaped entry with no file inventory (vendored before // inventories were recorded, or past the inventory cap) gives an // exact restore nothing to check a download against: the backend @@ -4580,13 +4536,13 @@ pub(crate) async fn vendor_records_reusing( // copy. A dry run asks the same question, so that it says // what the wet run does. if redownload && common.dry_run { - let follows = match service { + gem_list = match service { Some(service) => { - vendor::redownload::restore_follows_list(entry, record, service).await + vendor::redownload::restore_refused_over(entry, record, service).await } - None => false, + None => None, }; - if !follows { + if gem_list.is_none() { env.record(PatchEvent::new(PatchAction::Verified, candidate.clone()).with_details(serde_json::json!({"wouldRedownload": true, "path": entry.artifact.path}))); continue; } @@ -4608,7 +4564,7 @@ pub(crate) async fn vendor_records_reusing( } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); } - Err(RestoreError::ListMoved(_)) => {} + Err(RestoreError::ListMoved(_, list)) => gem_list = Some(list), Err(RestoreError::Failed(detail)) => { has_errors = true; env.record( @@ -4647,6 +4603,7 @@ pub(crate) async fn vendor_records_reusing( // A takeover the backend does not carry through keeps its // hosted pin (below). hosted_pin_of(candidate).is_some(), + gem_list.as_ref(), &mut gem_preview, ) .await; @@ -6284,6 +6241,7 @@ mod dispatch_tests { &tokio::sync::OnceCell::new(), &Default::default(), false, + None, &mut Vec::new(), ) .await; @@ -6554,22 +6512,6 @@ mod plan_gate_tests { ), ) .await; - // A run that fetches nothing ahead plans only the in-step packages - // whose backend still reads a reference: with none in the ledger, - // nothing is planned (and no candidate is judged for it). - let references = plan_run_downloads( - &gates(root, &records, &HashSet::new()), - &VendorState::default(), - &all_packages, - &HashMap::new(), - ( - &tokio::sync::OnceCell::new(), - &vendor::pypi::InstalledSiteListings::default(), - ), - true, - ) - .await; - assert!(references.is_empty(), "{references:?}"); let uuids: Vec<&str> = planned.iter().map(|d| d.uuid.as_str()).collect(); assert_eq!( uuids, diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index 08df4511d7..df761ab2e3 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -766,8 +766,8 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then // those patches are asked for in one request. The run then finds - // the restored copy in step with the gem patch's list: the same - // answer, read once. + // the restored copy in step with the gem patch's list, which it + // asks for where it needs it: once more. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -783,6 +783,7 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { [ vec![UUID.to_string()], vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + vec![UUID.to_string()], ] ); assert_eq!( @@ -1276,11 +1277,23 @@ async fn a_damaged_copy_is_vendored_from_the_list_once_the_list_moved() { assert_eq!(code, 1, "{damaged}: {env:#}\n{stderr}"); // A dry run says what the wet run does: it would vendor the copy - // from the list, not download it again as it was. + // from the list, not download it again as it was. The refused + // restore hands the list it read to the backend, so either run + // asks for the fix's list once, and then for the patches it names. + let one_list = [ + vec![UUID.to_string()], + vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], + ]; let before = snapshot(root); + let asked = reference_requests(&server).await.len(); let dry = with(VENDOR, &["--dry-run"]); let (code, env, stderr) = run_json(root, &dry, &server.uri()); assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_eq!( + reference_requests(&server).await[asked..], + one_list, + "{damaged}: the dry run" + ); assert_per_platform_gem(&env, "verified", ""); assert_eq!(env["summary"]["verified"], 2, "{damaged}: {env:#}"); assert!( @@ -1301,8 +1314,14 @@ async fn a_damaged_copy_is_vendored_from_the_list_once_the_list_moved() { "{damaged}: a dry run writes nothing" ); + let asked = reference_requests(&server).await.len(); let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); assert_eq!(code, 0, "{damaged}: {env:#}\n{stderr}"); + assert_eq!( + reference_requests(&server).await[asked..], + one_list, + "{damaged}: the wet run" + ); assert_eq!(env["status"], "success", "{damaged}: {env:#}"); assert_eq!(env["summary"]["failed"], 0, "{damaged}: {env:#}"); assert_eq!(env["summary"]["applied"], 2, "{damaged}: {env:#}"); @@ -1509,12 +1528,15 @@ async fn a_copy_changed_by_a_failed_rebuild_is_not_said_to_stay_in_force() { assert_eq!(code, 0, "{env:#}\n{stderr}"); } -/// The git metadata of the uuid directory is written before the new trees -/// are moved in. When it cannot be written (a directory stands where the -/// file belongs), the copy the lock is wired to is as it was: it stays in -/// force, the run exits 0 and says why it was not brought in step. +/// The git metadata of the uuid directory is not part of the copy: it is +/// written once the new trees are in place, and a write that fails (a +/// directory stands where the file belongs) is a warning, never a +/// failure. The run exits 0 with the trees the list names in place and +/// the ledger recording them, says the warning every backend gives for +/// ignore rules it could not vouch for, and says nothing of a copy that +/// stays as it was. #[tokio::test] -async fn metadata_that_cannot_be_written_leaves_the_copy_in_force() { +async fn metadata_that_cannot_be_written_is_a_warning_and_the_copy_is_vendored() { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path(); write_project(root); @@ -1525,30 +1547,47 @@ async fn metadata_that_cannot_be_written_leaves_the_copy_in_force() { std::fs::remove_file(&gitattributes).unwrap(); std::fs::create_dir(&gitattributes).unwrap(); std::fs::write(gitattributes.join("in the way"), b"").unwrap(); - let before = snapshot(root); // The darwin build is published: the list moved. let server = service(&[DARWIN, LINUX], &[]).await; let (code, stdout, stderr) = run(root, VENDOR_IT, &server.uri()); assert_eq!(code, 0, "{stdout}\n{stderr}"); assert!( - stdout.contains("1 package is already vendored; nothing to do."), + stdout.contains("Vendored 1 package.") + && stdout.contains(&format!( + "{NAME} {VERSION}: now also patched for {DARWIN}; already patched for {LINUX}" + )), "{stdout}" ); assert!( - stderr.contains(&format!( - "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ - registry lists (" - )) && stderr.contains("cannot write the git metadata of") - && stderr.contains("its vendored copy stays in force as it is."), + stderr + .contains("Warning: could not check whether git would commit the vendored artifact at") + && stderr.contains("cannot write the vendored dir's git metadata"), "{stderr}" ); - assert!(!stderr.contains("Error:"), "{stderr}"); - assert_eq!(snapshot(root), before, "nothing was moved in"); - assert_eq!( - std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), - PRISTINE + let said = format!("{stdout}\n{stderr}"); + assert!( + !said.contains("Error:") && !said.contains("stays in force") && !said.contains("failed"), + "{said}" ); + for platform in [DARWIN, LINUX] { + assert_eq!( + std::fs::read(tree(root, platform).join(LIB)).unwrap(), + stamped(build_uuid(platform)), + "{platform}" + ); + } + let recorded = &ledger(root)["entries"][PURL]["gemBuilds"]; + let patches: Vec<&str> = recorded + .as_array() + .into_iter() + .flatten() + .filter_map(|built| built["uuid"].as_str()) + .collect(); + assert_eq!(patches, [DARWIN_UUID, LINUX_UUID], "{recorded:#}"); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); } /// No locked platform has a patched build: the gem is not vendored, the diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index ef9b5e0b77..e2c881590a 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -2622,12 +2622,6 @@ pub struct PlannedDownload { /// backend's stage, or run its afterHash check (see /// [`crate::vendor::prestage`]). Built by the backends' plan gates. pub stage: Option, - /// The loop reads this patch's package reference and downloads nothing - /// of it (a gem vendored as platform gems, whose backend reads the - /// list of its fix and takes its gems from other patches). The - /// position takes part in the plan's one reference request and is - /// never fetched ahead. - pub reference_only: bool, } impl PlannedDownload { @@ -2637,16 +2631,6 @@ impl PlannedDownload { uuid, secondary: None, stage: None, - reference_only: false, - } - } - - /// A patch whose package reference alone the loop reads - /// ([`Self::reference_only`]). - pub fn reference(uuid: String) -> Self { - Self { - reference_only: true, - ..Self::archive(uuid) } } } @@ -3564,7 +3548,7 @@ fn assemble_batch_from_individual( // ── Error type ──────────────────────────────────────────────────────── /// Errors returned by [`ApiClient`] methods. -#[derive(Debug, Clone, thiserror::Error)] +#[derive(Debug, thiserror::Error)] pub enum ApiError { #[error("{0}")] Network(String), diff --git a/crates/socket-patch-core/src/api/vendor_prefetch.rs b/crates/socket-patch-core/src/api/vendor_prefetch.rs index 96f025ef3c..259669d942 100644 --- a/crates/socket-patch-core/src/api/vendor_prefetch.rs +++ b/crates/socket-patch-core/src/api/vendor_prefetch.rs @@ -170,17 +170,7 @@ pub(crate) struct VendorPrefetch { state: tokio::sync::Mutex, /// The plan's package references, resolved in one batch by the first /// planned call (see [`Self::reference`]) and taken uuid by uuid. - references: tokio::sync::OnceCell>, -} - -/// What the plan's one reference batch brought ([`VendorPrefetch::reference`]). -#[derive(Debug, Default)] -struct ReferenceBatch { - /// The answers, by uuid, less the patches still building. - answers: HashMap, - /// The request that failed, if one did, with the uuids it named: the - /// answer to every reference-only position among them. - failed: Option<(Vec, ApiError)>, + references: tokio::sync::OnceCell>>, } /// The window of plan positions the task may request: `[at, at + reach)`, @@ -376,7 +366,6 @@ impl VendorPrefetch { Riders { secondary: d.secondary, stage: d.stage, - reference_only: d.reference_only, }, ) }) @@ -407,14 +396,6 @@ impl VendorPrefetch { /// live request. A package still building (`pending_build`) is asked /// again at its own turn, as the serial loop did, since it may be /// ready by then; every other answer is final and is reused. - /// - /// A position whose reference alone is read - /// ([`PlannedDownload::reference_only`]) differs in two ways, because - /// nothing else of it is fetched and its backend may read the - /// reference more than once (a restore, then the rebuild): its answer - /// is kept, so every read of it sees the same one, and a request of - /// the batch that failed is its answer too, so a batch the service - /// refuses is not asked again once per such position. pub(crate) async fn reference( &self, client: &ApiClient, @@ -426,7 +407,6 @@ impl VendorPrefetch { return None; } let at = self.planned.iter().position(|planned| planned == uuid)?; - let kept_for_all = self.riders[at].reference_only; let mut own = None; let cache = self .references @@ -439,7 +419,7 @@ impl VendorPrefetch { order.push(planned.clone()); } } - let mut batch = ReferenceBatch::default(); + let mut kept = HashMap::new(); for (i, chunk) in order.chunks(MAX_REFERENCE_BATCH).enumerate() { match client .request_vendor_references(chunk, free_only, vendor_url) @@ -447,11 +427,7 @@ impl VendorPrefetch { { Ok(mut results) => { if i == 0 { - let answer = match kept_for_all { - true => results.get(uuid).cloned(), - false => results.remove(uuid), - }; - own = Some(answer.ok_or_else(|| { + own = Some(results.remove(uuid).ok_or_else(|| { ( ApiError::Other(format!( "package response missing a result for {uuid}" @@ -460,44 +436,27 @@ impl VendorPrefetch { ) })); } - batch.answers.extend( + kept.extend( results .into_iter() .filter(|(_, r)| r.status != "pending_build"), ); } - // The chunk's uuids make their live requests, but - // for the positions whose reference alone is read. - Err((e, retryable)) => { - batch.failed = Some((chunk.to_vec(), e.clone())); - if i == 0 { - own = Some(Err((e, retryable))); - } + Err(e) if i == 0 => { + own = Some(Err(e)); break; } + // The chunk's uuids make their live requests. + Err(_) => break, } } - std::sync::Mutex::new(batch) + std::sync::Mutex::new(kept) }) .await; if own.is_some() { return own; } - let mut batch = cache.lock().ok()?; - if !kept_for_all { - return batch.answers.remove(uuid).map(Ok); - } - if let Some(answer) = batch.answers.get(uuid) { - return Some(Ok(answer.clone())); - } - // The request that named this position failed: that is its answer. - // It was one request, counted once, so it is no further - // availability failure. - let (asked, failure) = batch.failed.as_ref()?; - asked - .iter() - .any(|asked| asked == uuid) - .then(|| Err((failure.clone(), false))) + cache.lock().ok()?.remove(uuid).map(Ok) } /// The prefetched outcome of the loop's call for `uuid`, or `None` to @@ -519,13 +478,10 @@ impl VendorPrefetch { } let mut state = self.state.lock().await; let from = state.next; - // A position whose reference alone is read is never fetched, so - // there is no outcome of it to take. let position = from + self.planned[from..] .iter() - .zip(&self.riders[from..]) - .position(|(planned, riders)| planned == uuid && !riders.reference_only)?; + .position(|planned| planned == uuid)?; // Pass over every position before this one: the task must not // request them, anything they already answered is dropped // (unreleased, with its debug lines), and the loop's arrival here @@ -603,9 +559,7 @@ impl VendorPrefetch { .map( move |(offset, (uuid, riders)): (usize, (String, Riders))| async move { let index = from + offset; - // Its reference is the plan's batch's to - // answer; nothing of it is downloaded. - if riders.reference_only || !look.admits(index).await { + if !look.admits(index).await { return None; } let mut held = hold_back_debug(client.fetch_vendor_package_once( @@ -675,10 +629,6 @@ fn archive_bytes(fetched: &Fetched) -> usize { struct Riders { secondary: Option, stage: Option, - /// The loop reads this position's reference and never its archive - /// ([`PlannedDownload::reference_only`]): the task fetches nothing - /// for it. - reference_only: bool, } /// Do what rides a planned download — exactly when the loop's backend @@ -692,9 +642,7 @@ struct Riders { /// * The stage recipe runs on the bytes (see [`crate::vendor::prestage`]); /// what it produced rides the archive to the backend. async fn ride_along(client: &ApiClient, held: &mut Fetched, riders: Riders) { - let Riders { - secondary, stage, .. - } = riders; + let Riders { secondary, stage } = riders; if secondary.is_none() && stage.is_none() { return; } @@ -781,157 +729,6 @@ mod tests { NotFound, } - /// A position whose reference alone is read shares the plan's one - /// reference request and is never fetched ahead: once the loop takes - /// the archive before it and the task runs, nothing of that position - /// is downloaded, and its reference is answered from the batch. - #[tokio::test] - async fn a_reference_only_position_is_batched_and_never_downloaded() { - let server = MockServer::start().await; - let (archive, listed) = (uuid(1), uuid(2)); - let sri = |bytes: &[u8]| { - let digest = base64::engine::general_purpose::STANDARD.encode(Sha512::digest(bytes)); - format!("sha512-{digest}") - }; - let url = |u: &str| format!("{}/serve/{u}.gem", server.uri()); - let granted = |u: &str| { - serde_json::json!({ "status": "granted", "url": url(u), "artifacts": [ - { "kind": "tarball", "url": url(u), "integrity": { "sha512": sri(b"bytes") } } - ] }) - }; - Mock::given(method("POST")) - .and(path(POST_PATH)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { archive.clone(): granted(&archive), listed.clone(): granted(&listed) } - }))) - .mount(&server) - .await; - Mock::given(method("GET")) - .respond_with(ResponseTemplate::new(200).set_body_bytes(b"bytes".to_vec())) - .mount(&server) - .await; - let client = client(&server.uri()); - let _guard = client.prefetch_vendor_downloads( - vec![ - PlannedDownload::archive(archive.clone()), - PlannedDownload::reference(listed.clone()), - ], - false, - None, - None, - 4, - usize::MAX, - ); - let fetched = client - .fetch_vendor_package(&archive, false, None, None) - .await; - assert!( - matches!(fetched, VendorServiceOutcome::Ready(_)), - "{fetched:?}" - ); - // The task has had every chance to run ahead of the loop. - tokio::time::sleep(Duration::from_millis(100)).await; - let read = client - .fetch_vendor_reference(&listed, false, None, None) - .await; - assert!(matches!(read, VendorServiceOutcome::Ready(_))); - let requests = server.received_requests().await.unwrap_or_default(); - let asked = |verb: &str| -> Vec { - let of_verb = requests.iter().filter(|r| r.method.as_str() == verb); - of_verb.map(|r| r.url.path().to_string()).collect() - }; - assert_eq!(asked("POST"), [POST_PATH], "one reference request for both"); - assert_eq!( - asked("GET"), - [format!("/serve/{archive}.gem")], - "one download" - ); - } - - /// A position whose reference alone is read keeps the batch's answer: - /// every read of it is that answer, with no further request. When the - /// batch failed, that failure is the answer of every such position it - /// named, so a batch the service refuses is not asked again once per - /// position. And no package fetch waits on such a position, of which - /// nothing is ever fetched: it makes its own requests. - #[tokio::test] - async fn a_reference_only_answer_is_kept_and_a_failed_batch_is_its_answer() { - let (first, second) = (uuid(1), uuid(2)); - let plan = |client: &ApiClient| { - client.prefetch_vendor_downloads( - vec![ - PlannedDownload::reference(first.clone()), - PlannedDownload::reference(second.clone()), - ], - false, - None, - None, - 4, - usize::MAX, - ) - }; - let posts = |requests: &[wiremock::Request]| { - let posted = requests.iter().filter(|r| r.method.as_str() == "POST"); - posted.count() - }; - - let server = MockServer::start().await; - let url = format!("{}/serve/a.gem", server.uri()); - let granted = serde_json::json!({ "status": "granted", "url": url, "artifacts": [ - { "kind": "tarball", "url": url, "integrity": { "sha512": "sha512-GEM==" } } - ] }); - Mock::given(method("POST")) - .and(path(POST_PATH)) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "results": { first.clone(): granted.clone(), second.clone(): granted } - }))) - .mount(&server) - .await; - let client = client(&server.uri()); - let guard = plan(&client); - for uuid in [&first, &first, &second, &second, &first] { - let read = client.fetch_vendor_reference(uuid, false, None, None).await; - assert!(matches!(read, VendorServiceOutcome::Ready(_)), "{uuid}"); - } - let requests = server.received_requests().await.unwrap_or_default(); - assert_eq!(posts(&requests), 1, "every read is the batch's answer"); - // A package fetch of such a position does not wait for the plan. - let fetched = tokio::time::timeout( - Duration::from_secs(20), - client.fetch_vendor_package(&first, false, None, None), - ) - .await - .expect("the fetch makes its own requests"); - assert!( - !matches!(fetched, VendorServiceOutcome::Pending), - "{fetched:?}" - ); - drop(guard); - - // The service refuses the batch (not an availability failure). - let refusing = MockServer::start().await; - Mock::given(method("POST")) - .and(path(POST_PATH)) - .respond_with(ResponseTemplate::new(403).set_body_string("forbidden")) - .mount(&refusing) - .await; - let client = super::tests::client(&refusing.uri()); - let _guard = plan(&client); - for uuid in [&first, &second, &second] { - let read = client.fetch_vendor_reference(uuid, false, None, None).await; - assert!( - matches!(read, VendorServiceOutcome::Failed(_)), - "{uuid}: {read:?}" - ); - } - let requests = refusing.received_requests().await.unwrap_or_default(); - assert_eq!( - posts(&requests), - 1, - "the refusal is every position's answer" - ); - } - fn uuid(i: usize) -> String { format!("{i:08x}-0000-4000-8000-{i:012x}") } diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 6f3b2f1272..c2615f484d 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -107,7 +107,7 @@ //! Ruby gemspec). Hosted mode installs the same gem for such a platform. //! A later run follows the list: the tree becomes the patched build's //! once one is published, and a tree whose patched build was withdrawn -//! goes back to upstream's gem ([`moved_sources`]). While no locked +//! goes back to upstream's gem ([`moved_list`]). While no locked //! platform has a patched build, the registry does not list one of them //! or lists no platform gem at all, or the patch it names for one is not //! served (it is still being built, or the service does not grant it), @@ -933,8 +933,8 @@ pub fn follows_list(entry: &VendorEntry, uuid: &str) -> bool { entry.ecosystem == "gem" && entry.uuid == uuid && !entry.gem_builds.is_empty() } -/// What the list of the gem's fix `uuid` names for each locked platform -/// now, where that is not what the ledger records for the copy: a patched +/// The list of the gem's fix `uuid` where it names, for a locked +/// platform, another gem than the ledger records for the copy: a patched /// build where the copy holds upstream's gem (the build was published /// since), upstream's gem where it holds a patched one (the build was /// withdrawn), or the build of another patch. `None` while the list names @@ -942,16 +942,16 @@ pub fn follows_list(entry: &VendorEntry, uuid: &str) -> bool { /// platform says that it moved: with no list (the service has not read /// the version's gems, or is building one again), a platform the list /// leaves out, a request that fails or no service to ask, the copy stands -/// as it is and nothing is said. ONE request, the fix's reference (the -/// one request of a run's download plan, where the copy is planned). -async fn moved_sources( +/// as it is and nothing is said. ONE request, the fix's reference, asked +/// for this gem alone: a run makes one per gem it finds vendored this way. +async fn moved_list( project_root: &Path, service: Option<&VendorServiceConfig>, uuid: &str, name: &str, copy_rel: &str, trees: &PlatformTrees<'_>, -) -> Option> { +) -> Option { let cfg = service.filter(|cfg| cfg.service_enabled())?; if service_offline_conflict(service).is_some() { return None; @@ -963,9 +963,8 @@ async fn moved_sources( if !follows_list(&entry, uuid) { return None; } - let sources = locked_build_sources(cfg, uuid, name, trees, platforms) - .await - .ok()?; + let list = read_fix_list(cfg, uuid, name).await.ok()??; + let sources = listed_sources(&list, name, trees, platforms).ok()?; let moved = sources.iter().any(|source| { let recorded = entry .gem_builds @@ -973,7 +972,7 @@ async fn moved_sources( .find(|b| b.platform == source.platform); !recorded.is_some_and(|built| built.uuid.eq_ignore_ascii_case(&source.uuid)) }); - moved.then_some(sources) + moved.then_some(list) } /// The platforms whose patched build the vendored copy of ANOTHER patch @@ -1169,12 +1168,10 @@ fn gem_edits( /// enabled — makes for `record`: past every refusal it raises first /// ([`gem_prelude`], [`gem_edits`]) and not answered by the in-sync hot /// path. The vendor loop's download plan consults this; the `.gem`'s -/// `gem-stub-gemspec` secondary rides the same planned download. A gem -/// the lock pins as platform gems is a position whose reference alone is -/// read: it is vendored from the patches the service's package reference -/// names for its platforms ([`stage_platform_builds`]), and the ruby gem -/// is never downloaded. (A copy of such a gem that is in step reads that -/// reference too, to follow its list: [`follows_list`].) +/// `gem-stub-gemspec` secondary rides the same planned download. `None` +/// for a gem the lock pins as platform gems: it is vendored from the +/// patches the service's package reference names for its platforms +/// ([`stage_platform_builds`]), and the ruby gem is never downloaded. pub(crate) async fn service_preflight( purl: &str, installed_path: &Path, @@ -1191,12 +1188,7 @@ pub(crate) async fn service_preflight( true => !prelude.copy_ok, false => gem_edits(purl, &prelude).is_ok(), }; - if asks && !prelude.platforms.is_empty() { - return Some(crate::api::client::PlannedDownload::reference( - record.uuid.clone(), - )); - } - asks.then(|| { + (asks && prelude.platforms.is_empty()).then(|| { // `gem_service_copy` fetches the stub gemspec right after the `.gem`, // and extracts the `.gem`'s data.tar.gz into the copy dir's stage. crate::api::client::PlannedDownload { @@ -1234,6 +1226,7 @@ pub async fn vendor_gem<'a>( force, service, false, + None, &mut Vec::new(), ) .await @@ -1251,6 +1244,12 @@ pub async fn vendor_gem<'a>( /// which restores the gem's upstream entry before it calls and puts the /// pin back after a refusal). The skip of a gem with a locked platform /// that has no patched build then says that the gem stays hosted. +/// +/// `list`: the list of the gem's fix that an exact restore of the copy +/// was just refused over +/// ([`RestoreError::ListMoved`](super::redownload::RestoreError::ListMoved)). +/// The damaged copy is vendored again from it, so the restore and this +/// call read one answer: the fix's reference is not asked for again. #[allow(clippy::too_many_arguments)] pub async fn vendor_gem_previewing<'a>( purl: &str, @@ -1263,6 +1262,7 @@ pub async fn vendor_gem_previewing<'a>( _force: bool, service: Option<&VendorServiceConfig>, hosted: bool, + list: Option<&FixList>, previewed: &mut Vec, ) -> VendorOutcome { let installed_dir = installed_dir.into(); @@ -1330,16 +1330,20 @@ pub async fn vendor_gem_previewing<'a>( let moved = match lock_wired && copy_ok && !platforms.is_empty() { true => { let wired = locked(Standing::Wired); - moved_sources(project_root, service, &record.uuid, name, copy_rel, &wired).await + moved_list(project_root, service, &record.uuid, name, copy_rel, &wired).await } false => None, }; - // The trees of the wired copy: the ones the list was just read to - // name, where it moved (it is not read again), else the locked ones. - let wired = match &moved { - Some(sources) => PlatformTrees { + // The list of the fix where it was already read, which is then not + // read again: by the check above, or by the exact restore of a damaged + // copy that was refused because the list names other builds. + let read = moved + .as_ref() + .or(list.filter(|_| lock_wired && !copy_ok && !platforms.is_empty())); + let wired = match read { + Some(list) => PlatformTrees { gem: &label, - from: BuildsFrom::Listed(sources), + from: BuildsFrom::Listed(platforms, list), standing: Standing::Wired, held: Vec::new(), }, @@ -1373,6 +1377,7 @@ pub async fn vendor_gem_previewing<'a>( let materialised = materialise_patched_copy( purl, copy_dir, + copy_rel, uuid_dir, name, &wired, @@ -1495,6 +1500,7 @@ pub async fn vendor_gem_previewing<'a>( let (mut result, builds) = match materialise_patched_copy( purl, copy_dir, + copy_rel, uuid_dir, name, &locked(plan.standing(hosted)), @@ -1732,19 +1738,31 @@ async fn copy_in_force( } let mut warnings: Vec = Vec::new(); if !prelude.platforms.is_empty() && !dry_run { - if let Err(e) = restore_uuid_metadata(&prelude.uuid_dir).await { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail( - copy_rel, - &format!("cannot write the vendored dir's git metadata: {e}"), - ), - )); - } + write_uuid_metadata_or_warn(&prelude.uuid_dir, copy_rel, &mut warnings).await; } Some(warnings) } +/// Write the git metadata of the uuid dir of a copy vendored as platform +/// gems ([`restore_uuid_metadata`]). It is not part of the copy: a write +/// that fails is a warning, the one every backend gives for ignore rules +/// it could not vouch for, and never a failure. +async fn write_uuid_metadata_or_warn( + uuid_dir: &Path, + copy_rel: &str, + warnings: &mut Vec, +) { + if let Err(e) = restore_uuid_metadata(uuid_dir).await { + warnings.push(VendorWarning::new( + super::npm_dir::GITIGNORE_UNCHECKED, + super::npm_dir::gitignore_unchecked_detail( + copy_rel, + &format!("cannot write the vendored dir's git metadata: {e}"), + ), + )); + } +} + /// The outcome of a copy the lock is ALREADY wired to that this run could /// not vendor again (`failure`: the refusal, or the result that did not /// succeed). What is said depends on whether the copy the ledger records @@ -1778,18 +1796,10 @@ async fn wired_copy_failed( } let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; match (failure, in_force) { - // A refusal carries no advisory of its own: what there is to say - // of the metadata ends its line. - (VendorOutcome::Refused { code, detail }, Some(warnings)) if pending => { - let also: String = warnings - .iter() - .map(|warning| format!(" Also: {}.", warning.detail.trim_end_matches('.'))) - .collect(); - refused( - code, - format!("{detail}; its vendored copy stays in force as it is.{also}"), - ) - } + (VendorOutcome::Refused { code, detail }, Some(_)) if pending => refused( + code, + format!("{detail}; its vendored copy stays in force as it is."), + ), (VendorOutcome::Refused { detail, .. }, None) if pending => refused( super::VENDOR_PREBUILT_REQUIRED, format!( @@ -2034,12 +2044,46 @@ pub(super) enum BuildsFrom<'a> { /// (`gemBuilds[].patchUuid`). Locked(&'a [String]), /// The trees a ledger entry records, each from its recorded patch: a - /// restore of that copy. - Recorded(&'a [GemBuildEntry]), - /// [`Self::Locked`] where the list was already read: the gem it names - /// for each locked platform ([`moved_sources`]), so the fix's - /// reference is asked for once. - Listed(&'a [BuildSource]), + /// restore of that copy, held to the list of the fix as it was read + /// for it ([`restore_list`]). + Recorded(&'a [GemBuildEntry], &'a FixList), + /// [`Self::Locked`] where the list was already read ([`moved_list`], + /// or a restore that was refused over it), so the fix's reference is + /// asked for once. + Listed(&'a [String], &'a FixList), +} + +/// The list of a gem's fix as ONE request read it: the gem its registry +/// lists for each platform (a patched build with its patch, or upstream's +/// own), and where that registry serves the gem files. What reads it +/// hands it on, so a copy is judged and vendored by one answer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FixList { + builds: Vec, + index_url: Option, +} + +/// The list of the gem's fix `uuid`: ONE request, the fix's package +/// reference, and nothing downloaded. `None` when the reference carries +/// no list right now (the service has not read the version's gems, or is +/// building one again). +async fn read_fix_list( + cfg: &VendorServiceConfig, + uuid: &str, + name: &str, +) -> Result, Box> { + let served = match fetch_served_reference(cfg, uuid).await { + ServiceArtifact::Pending => return Ok(None), + reference => ServicePolicy::Refused.settle( + reference, + "platform gem", + &format!("platform gems for {name}"), + )?, + }; + let index_url = served.gem_index_url; + Ok(served + .gem_builds + .map(|builds| FixList { builds, index_url })) } /// What a gem has in place of the patch being vendored, should a locked @@ -2334,19 +2378,22 @@ async fn locked_build_sources( name: &str, trees: &PlatformTrees<'_>, platforms: &[String], +) -> Result, Box> { + match read_fix_list(cfg, uuid, name).await? { + Some(list) => listed_sources(&list, name, trees, platforms), + None => Err(no_builds_listed_skip(trees)), + } +} + +/// [`locked_build_sources`] of a list that was already read: no request. +fn listed_sources( + list: &FixList, + name: &str, + trees: &PlatformTrees<'_>, + platforms: &[String], ) -> Result, Box> { let policy = ServicePolicy::Refused; - let served = match fetch_served_reference(cfg, uuid).await { - ServiceArtifact::Pending => return Err(no_builds_listed_skip(trees)), - reference => policy.settle( - reference, - "platform gem", - &format!("platform gems for {name}"), - )?, - }; - let Some(builds) = served.gem_builds.as_deref() else { - return Err(no_builds_listed_skip(trees)); - }; + let builds = list.builds.as_slice(); let mut listed = Vec::with_capacity(platforms.len()); let mut missing = NoPatchedBuild::default(); for platform in platforms { @@ -2390,7 +2437,7 @@ async fn locked_build_sources( Some(_) => None, // Upstream's own gem, from the registry that lists it. None => { - let index = served.gem_index_url.as_deref(); + let index = list.index_url.as_deref(); let gem = upstream_gem_artifact(index, trees.gem, platform, build); Some(gem.ok_or_else(|| { policy.miss(format!( @@ -2439,27 +2486,48 @@ fn upstream_gem_artifact( }) } -/// Whether a restore of the trees `builds` of the copy of the fix `fix` -/// (the gem `name`@`version`) would be refused because the list of the -/// fix names another build for one of them -/// ([`VENDOR_PREBUILT_REPLACED`]): what a dry run asks in place of the -/// restore. ONE request, nothing downloaded. +/// The list a restore of a copy of the fix `fix` (the gem `gem`, +/// `@`) is held to: ONE request. A restore has no copy to +/// leave in force: with no list it fails, and says when to run it again. +pub(super) async fn restore_list( + service: Option<&VendorServiceConfig>, + fix: &str, + gem: &str, +) -> Result> { + let cfg = service + .filter(|cfg| cfg.service_enabled()) + .ok_or_else(|| Box::new(super::service_fetch::required()))?; + let name = gem.rsplit_once('@').map_or(gem, |(name, _)| name); + read_fix_list(cfg, fix, name).await?.ok_or_else(|| { + ServicePolicy::Refused.unserved( + super::VENDOR_PREBUILT_PENDING, + format!("{}; run this again later", no_builds_listed(gem)), + ) + }) +} + +/// The list of the fix `fix` (the gem `name`@`version`) where a restore +/// of the trees `builds` would be refused because it names another build +/// for one of them ([`VENDOR_PREBUILT_REPLACED`]): what a dry run asks in +/// place of the restore. ONE request, nothing downloaded. pub(super) async fn recorded_list_moved( cfg: &VendorServiceConfig, fix: &str, name: &str, version: &str, builds: &[GemBuildEntry], -) -> bool { +) -> Option { let gem = format!("{name}@{version}"); + let list = restore_list(Some(cfg), fix, &gem).await.ok()?; let trees = PlatformTrees { gem: &gem, - from: BuildsFrom::Recorded(builds), + from: BuildsFrom::Recorded(builds, &list), standing: Standing::Wired, held: Vec::new(), }; - let sources = recorded_build_sources(cfg, fix, name, &trees, builds).await; - sources.is_err_and(|outcome| is_list_moved(&outcome)) + let moved = recorded_build_sources(name, &trees, builds, &list) + .is_err_and(|outcome| is_list_moved(&outcome)); + moved.then_some(list) } /// Whether `outcome` is a restore's refusal of a copy whose list moved @@ -2493,34 +2561,15 @@ pub(crate) const VENDOR_PREBUILT_REPLACED: &str = "vendor_prebuilt_replaced"; /// or none, is not worded as tampering nor as a first vendoring: the copy /// cannot be restored as it was ([`VENDOR_PREBUILT_REPLACED`]), and the /// message names the commands that vendor the current build. -async fn recorded_build_sources( - cfg: &VendorServiceConfig, - fix: &str, +fn recorded_build_sources( name: &str, trees: &PlatformTrees<'_>, builds: &[GemBuildEntry], + list: &FixList, ) -> Result, Box> { let policy = ServicePolicy::Refused; - // A restore has no copy to leave in force: it fails, and says when to - // run it again. - let not_listed = || { - policy.unserved( - super::VENDOR_PREBUILT_PENDING, - format!("{}; run this again later", no_builds_listed(trees.gem)), - ) - }; - let served = match fetch_served_reference(cfg, fix).await { - ServiceArtifact::Pending => return Err(not_listed()), - reference => policy.settle( - reference, - "platform gem", - &format!("platform gems for {name}"), - )?, - }; // Only a list says a build was replaced or withdrawn. - let Some(listed) = served.gem_builds.as_deref() else { - return Err(not_listed()); - }; + let listed = list.builds.as_slice(); let mut sources = Vec::with_capacity(builds.len()); for built in builds { let subject = format!("{name} ({})", built.platform); @@ -2557,7 +2606,7 @@ async fn recorded_build_sources( // The list still names upstream's gem for the platform: a // reference that does not say where it is, or pins no sha256 // that is one, is a miss and not a list that moved. - let index = served.gem_index_url.as_deref(); + let index = list.index_url.as_deref(); let Some(artifact) = upstream_gem_artifact(index, trees.gem, &built.platform, gem) else { return Err(policy.miss(format!( @@ -2707,7 +2756,7 @@ async fn served_builds<'a>( source.platform ))); }; - let from_list = !matches!(trees.from, BuildsFrom::Recorded(_)); + let from_list = !matches!(trees.from, BuildsFrom::Recorded(..)); if let (true, Some(unserved)) = (from_list, unserved) { match unserved { Unserved::Building => missing.yet.push(&source.platform), @@ -2804,9 +2853,10 @@ async fn stage_platform_builds( use futures_util::StreamExt as _; let policy = ServicePolicy::Refused; let platforms: Vec<&str> = match &trees.from { - BuildsFrom::Locked(platforms) => platforms.iter().map(String::as_str).collect(), - BuildsFrom::Recorded(builds) => builds.iter().map(|b| b.platform.as_str()).collect(), - BuildsFrom::Listed(sources) => sources.iter().map(|s| s.platform.as_str()).collect(), + BuildsFrom::Locked(platforms) | BuildsFrom::Listed(platforms, _) => { + platforms.iter().map(String::as_str).collect() + } + BuildsFrom::Recorded(builds, _) => builds.iter().map(|b| b.platform.as_str()).collect(), }; // SECURITY: a platform names a directory under the stage, and the // ledger a restore reads them from is committed, tamper-able data. @@ -2820,10 +2870,8 @@ async fn stage_platform_builds( BuildsFrom::Locked(platforms) => { locked_build_sources(cfg, &record.uuid, name, trees, platforms).await? } - BuildsFrom::Recorded(builds) => { - recorded_build_sources(cfg, &record.uuid, name, trees, builds).await? - } - BuildsFrom::Listed(sources) => sources.to_vec(), + BuildsFrom::Recorded(builds, list) => recorded_build_sources(name, trees, builds, list)?, + BuildsFrom::Listed(platforms, list) => listed_sources(list, name, trees, platforms)?, }; let builds = served_builds(cfg, name, trees, &sources).await?; @@ -2865,7 +2913,7 @@ async fn stage_platform_builds( if stub.is_some() { let stub_text = String::from_utf8_lossy(&stub_bytes); refuse_unusable_stub(policy, name, subject, &stub_text)?; - if matches!(trees.from, BuildsFrom::Recorded(_)) { + if matches!(trees.from, BuildsFrom::Recorded(..)) { refuse_foreign_stub(policy, trees.gem, platform, subject, &stub_text)?; } } @@ -3327,7 +3375,7 @@ pub enum LockedBuildsPreview { /// tree the ledger records (a patched build published since, upstream's /// gem where the patched build was withdrawn), and serves each patched /// build it names, the wet run vendors the copy again with those -/// ([`moved_sources`]). +/// ([`moved_list`]). /// /// `None` for a gem this does not judge, so the caller's own verdict /// stands: one the lock does not name as platform gems, one whose lock is @@ -3375,7 +3423,8 @@ pub async fn preview_locked_builds( held: Vec::new(), }; let (name, copy_rel) = (prelude.name.as_str(), prelude.copy_rel.as_str()); - let sources = moved_sources(project_root, service, uuid, name, copy_rel, &trees).await?; + let list = moved_list(project_root, service, uuid, name, copy_rel, &trees).await?; + let sources = listed_sources(&list, name, &trees, &prelude.platforms).ok()?; let cfg = service.filter(|cfg| cfg.service_enabled())?; let served = served_builds(cfg, name, &trees, &sources).await; return served.is_ok().then(|| builds_of(sources)); @@ -3420,13 +3469,17 @@ pub async fn preview_locked_builds( /// Acquire a verified service copy without replacing the prior copy on /// failure: the gem's own tree, or one patched platform gem's tree per -/// platform of `trees` when the lock pins the gem as platform gems (with -/// the uuid dir's git metadata, see [`restore_uuid_metadata`]). Returns -/// what the ledger records of each such tree, with the result. +/// platform of `trees` when the lock pins the gem as platform gems. +/// Those trees get the uuid dir's git metadata once they are in place +/// ([`write_uuid_metadata_or_warn`]; `copy_rel` names the copy in its +/// warning): it is not part of the copy, so the trees are in place and +/// correct whether or not it can be written. Returns what the ledger +/// records of each such tree, with the result. #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, copy_dir: &Path, + copy_rel: &str, uuid_dir: &Path, name: &str, trees: &PlatformTrees<'_>, @@ -3450,26 +3503,6 @@ async fn materialise_patched_copy( .await? } _ => { - let metadata_failed = |e: std::io::Error| { - ServicePolicy::Refused.hard( - "vendor_prebuilt_write_failed", - format!( - "cannot write the git metadata of {}: {e}", - uuid_dir.display() - ), - ) - }; - // The metadata is not part of the copy and writing it changes - // nothing that is in place. For a copy the lock is wired to it - // is written BEFORE the new trees are moved in, so a failure - // leaves that copy as it was. - if !unwind_uuid_dir { - let written = match tokio::fs::create_dir_all(uuid_dir).await { - Ok(()) => restore_uuid_metadata(uuid_dir).await.map(|_| ()), - Err(e) => Err(e), - }; - written.map_err(metadata_failed)?; - } builds = gem_platform_service_copy( service, record, @@ -3481,14 +3514,7 @@ async fn materialise_patched_copy( warnings, ) .await?; - // A first vendor has no uuid dir before its trees are in place. - if unwind_uuid_dir { - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - return Err(metadata_failed(e)); - } - } + write_uuid_metadata_or_warn(uuid_dir, copy_rel, warnings).await; } } Ok(( @@ -14114,6 +14140,7 @@ mod tests { false, Some(&cfg), false, + None, &mut previewed, ) .await; @@ -14326,14 +14353,14 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), ledgered); } - /// The git metadata of the uuid dir is written before the new - /// trees are moved in, so a write that fails leaves the copy the - /// lock is wired to as it was: it stays in force, with what there - /// is to say of the metadata. The skip of a build that is not - /// served yet says the same at the end of its line, a refusal - /// having no advisory of its own. + /// The git metadata of the uuid dir is not part of the copy. It is + /// written once the new trees are in place, and a write that fails + /// is a warning, never a failure: the trees are in place and + /// correct, the entry handed back records them, and nothing is + /// said of a copy left as it was. The same for a damaged copy, + /// which is rebuilt all the same. #[tokio::test] - async fn metadata_that_cannot_be_written_leaves_the_copy_in_force() { + async fn metadata_that_cannot_be_written_is_a_warning_and_the_trees_are_in_place() { let (_tmp, root, record) = project(&lock(None)).await; let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; vendor_and_persist(&root, &record, &cfg).await; @@ -14344,148 +14371,218 @@ mod tests { tokio::fs::write(gitattributes.join("in the way"), b"") .await .unwrap(); - let before = ts::tree_snapshot(&root); let unchecked = "could not check whether git would commit the vendored artifact"; + let linux = root.join(rel(UUID)).join(LINUX); + // The list moved: the copy takes the build that was published. let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; let (result, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); - assert!(entry.is_none(), "the ledger entry stands"); let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); assert_eq!( - codes, - [ - crate::vendor::npm_dir::GITIGNORE_UNCHECKED, - GEM_LIST_NOT_FOLLOWED - ], + codes + .iter() + .filter(|code| code.contains("gitignore")) + .count(), + 1, "{warnings:?}" ); - assert!(warnings[0].detail.starts_with(unchecked), "{warnings:?}"); assert!( - warnings[1] - .detail - .contains("cannot write the git metadata of"), + codes.contains(&crate::vendor::npm_dir::GITIGNORE_UNCHECKED) + && codes.contains(&GEM_LIST_FOLLOWED) + && !codes.contains(&GEM_LIST_NOT_FOLLOWED), "{warnings:?}" ); - assert_eq!(ts::tree_snapshot(&root), before, "nothing was moved in"); - - // The skip of a build that is not served yet: what it says of - // the copy and, at the end of its line, of the metadata. - let prelude = gem_prelude(NOKO, ¬_installed(&root), &root, &record) - .await - .unwrap_or_else(|_| panic!("the prelude of a wired gem")); - let pending = refused( - crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, - "nokogiri@1.18.10 was not brought up to date: no patched build yet for java" - .to_string(), + let said = warnings + .iter() + .find(|w| w.code == crate::vendor::npm_dir::GITIGNORE_UNCHECKED) + .expect("the warning"); + assert!( + said.detail.starts_with(unchecked) + && said + .detail + .contains("cannot write the vendored dir's git metadata"), + "{said:?}" ); - let settled = wired_copy_failed(pending, false, &root, &record, &prelude, false).await; - let (code, detail) = unwrap_refused(settled); - assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + let entry = entry.expect("the entry of the trees that are in place"); + assert_eq!( + entry.gem_builds, + [built(UUID, DARWIN), built(UUID, LINUX)], + "the ledger is handed what is on disk" + ); + let patched = tokio::fs::read(linux.join(RB)).await.unwrap(); + assert_eq!(patched, stamped(LINUX), "the patched build"); + ts::persist(&root, NOKO, entry).await; + + // A damaged copy is rebuilt while the metadata stays unwritable. + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); assert!( - detail.starts_with(&format!( - "nokogiri@1.18.10 was not brought up to date: no patched build yet for java; \ - its vendored copy stays in force as it is. Also: {unchecked}" - )), - "{detail}" + warnings + .iter() + .any(|w| w.code == crate::vendor::npm_dir::GITIGNORE_UNCHECKED) + && warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + "{warnings:?}" ); - assert_eq!(ts::tree_snapshot(&root), before); + assert!(entry.is_some(), "the rebuilt copy's entry"); + let rebuilt = tokio::fs::read(linux.join(RB)).await.unwrap(); + assert_eq!(rebuilt, stamped(LINUX), "rebuilt"); } - /// A gem the lock names as platform gems is a position of the - /// download plan whose reference alone is read: its trees come - /// from other patches, and nothing of the gem's own patch is - /// downloaded. + /// A rebuild that fails leaves no uuid dir behind where there was + /// none: the metadata is written after the trees are in place, + /// never before them. #[tokio::test] - async fn a_platform_locked_gem_is_planned_as_a_reference() { + async fn a_failed_rebuild_leaves_no_uuid_dir_of_metadata_alone() { let (_tmp, root, record) = project(&lock(None)).await; - let planned = service_preflight(NOKO, ¬_installed(&root), &root, &record) - .await - .expect("the gem asks the service"); - assert_eq!(planned.uuid, UUID); - assert!(planned.reference_only && planned.secondary.is_none()); + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + let uuid_dir = root.join(format!(".socket/vendor/gem/{UUID}")); + tokio::fs::remove_dir_all(&uuid_dir).await.unwrap(); + // Upstream's gem for linux does not unpack. + let broken = Served { + gem: Some(b"not a gem".to_vec()), + ..upstream(LINUX) + }; + let (_server, cfg) = service(UUID, &[served(DARWIN), broken]).await; + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, false).await; + assert!( + !matches!(&outcome, VendorOutcome::Done { result, .. } if result.success), + "the rebuild fails" + ); + assert!(!uuid_dir.exists(), "no directory of metadata alone"); } - /// The lists of the gems a run finds already vendored are one - /// request: each such gem is a position of the run's download plan - /// whose reference alone is read - /// ([`crate::api::client::PlannedDownload::reference`]), and the - /// first of them asks for all. A copy in step then asks nothing - /// more. A copy whose list moved vendors from the list that was - /// read to find that out: the fix's reference is asked for once in - /// all, with a plan or without one. With no answer the copy stands. + /// A gem the lock names as platform gems is no position of the + /// download plan, and each such gem a run finds vendored asks for + /// the list of its own fix, live: ONE request, which names that + /// fix alone, and nothing downloaded for a copy in step. With no + /// answer the copy stands and nothing is said. A copy whose list + /// moved is vendored from the list that was read to find that + /// out, so the fix's reference is asked for once. #[tokio::test] - async fn the_lists_of_the_gems_that_follow_one_are_one_request() { - use crate::api::client::PlannedDownload; + async fn each_vendored_gem_asks_for_the_list_of_its_own_fix() { let (_tmp, root, record) = project(&lock(None)).await; let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; vendor_and_persist(&root, &record, &cfg).await; - // Two gems of the run follow a list: this one and another. One - // archive beside them is nothing to fetch ahead, so the plan - // holds the two references alone. - let planned = || { - vec![ - PlannedDownload::archive("c0c0c0c0-0000-4000-8000-000000000003".to_string()), - PlannedDownload::reference(UUID.to_string()), - PlannedDownload::reference(UUID_B.to_string()), - ] - }; + assert_eq!( + service_preflight(NOKO, ¬_installed(&root), &root, &record).await, + None, + "nothing of the gem's own patch is downloaded, so nothing is planned" + ); let (server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; - let plan = cfg.prefetch_archives(planned()); - assert!(plan.is_some(), "the plan is attached"); - // A single such gem is worth a plan too: its reads share one - // answer. - let alone = vec![PlannedDownload::reference(UUID_B.to_string())]; - assert!(cfg.prefetch_archives(alone).is_some()); - drop(plan); - let plan = cfg.prefetch_archives(planned()); let (again, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); assert_eq!( reference_requests(&server).await, - [vec![UUID.to_string(), UUID_B.to_string()]], - "one request names both fixes, and nothing is downloaded" + [vec![UUID.to_string()]], + "one request, for this gem's fix alone" ); - assert_eq!(ts::request_count(&server).await, 1); - drop(plan); + assert_eq!(ts::request_count(&server).await, 1, "nothing is downloaded"); // No answer: the copy stands with nothing said. let down = wiremock::MockServer::start().await; let cfg = ts::service_cfg(&down.uri(), crate::vendor::VendorSource::Service, false); - let plan = cfg.prefetch_archives(planned()); let before = ts::tree_snapshot(&root); let (again, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(again.success, "{:?}", again.error); assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); - assert_eq!(ts::request_count(&down).await, 1); assert_eq!(ts::tree_snapshot(&root), before); - drop(plan); // The list moved: the rebuild takes the gems the list was read - // to name, so the fix's reference is one request, planned or - // not. - for planned_run in [true, false] { - let linux = match planned_run { - true => served(LINUX), - false => upstream(LINUX), - }; - let (server, cfg) = service(UUID, &[served(DARWIN), linux]).await; - let plan = planned_run.then(|| cfg.prefetch_archives(planned())); - let (result, entry, _) = - unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert!(result.success, "{:?}", result.error); - ts::persist(&root, NOKO, entry.expect("the copy's new entry")).await; - let asked = reference_requests(&server).await; - let fixes = asked + // to name. + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (result, entry, _) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + ts::persist(&root, NOKO, entry.expect("the copy's new entry")).await; + let asked = reference_requests(&server).await; + let fixes = asked + .iter() + .filter(|uuids| uuids.contains(&UUID.to_string())); + assert_eq!(fixes.count(), 1, "{asked:?}"); + } + + /// A damaged copy whose list moved: the exact restore is refused + /// over the list it read, and hands that list on. The backend + /// vendors the copy again from it and does not ask for the fix's + /// reference again, wet or dry, so the two read one answer. + #[tokio::test] + async fn a_refused_restore_hands_its_list_to_the_rebuild() { + use crate::vendor::redownload::{restore, restore_refused_over, RestoreError}; + let (_tmp, root, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let linux = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let blobs = root.join("no-blobs"); + let sources = PatchSources::blobs_only(&blobs); + let fix_requests = |asked: Vec>| { + let of_fix = asked .iter() .filter(|uuids| uuids.contains(&UUID.to_string())); - assert_eq!(fixes.count(), 1, "planned {planned_run}: {asked:?}"); - drop(plan); + of_fix.count() + }; + + for dry_run in [true, false] { + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let list = match dry_run { + true => restore_refused_over(&entry, &record, &cfg).await, + false => match restore(&root, &entry, &record, &cfg).await { + Err(RestoreError::ListMoved(_, list)) => Some(list), + other => panic!("the restore is refused over the list: {other:?}"), + }, + }; + let list = list.expect("the list that moved"); + assert_eq!(fix_requests(reference_requests(&server).await), 1); + assert!(!linux.exists(), "the restore unpacked nothing"); + let mut previewed = Vec::new(); + let outcome = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &sources, + "2026-06-09T00:00:00Z", + dry_run, + false, + Some(&cfg), + false, + Some(&list), + &mut previewed, + ) + .await; + let (result, rebuilt, _) = unwrap_done(outcome); + assert!(result.success, "dry run {dry_run}: {:?}", result.error); + assert_eq!( + fix_requests(reference_requests(&server).await), + 1, + "dry run {dry_run}: the backend does not ask for the fix's list again" + ); + let builds = match dry_run { + true => previewed, + false => rebuilt.expect("the rebuilt copy's entry").gem_builds, + }; + let named: Vec<(&str, &str)> = builds + .iter() + .map(|b| (b.platform.as_str(), b.uuid.as_str())) + .collect(); + assert_eq!( + named, + [ + (DARWIN, build_uuid(UUID, DARWIN).as_str()), + (LINUX, build_uuid(UUID, LINUX).as_str()) + ], + "dry run {dry_run}: vendored from the list that was handed over" + ); + assert_eq!(linux.exists(), !dry_run, "dry run {dry_run}"); } } @@ -14723,7 +14820,7 @@ mod tests { let moved = code == VENDOR_PREBUILT_REPLACED; let list_moved = matches!( refused, - crate::vendor::redownload::RestoreError::ListMoved(_) + crate::vendor::redownload::RestoreError::ListMoved(..) ); assert_eq!(list_moved, moved, "{refused}"); // A list that moved names the one command that works, once: @@ -14741,8 +14838,8 @@ mod tests { usize::from(moved), "{refused}" ); - let asked = crate::vendor::redownload::restore_follows_list(&entry, &record, &cfg); - assert_eq!(asked.await, moved, "{says}"); + let asked = crate::vendor::redownload::restore_refused_over(&entry, &record, &cfg); + assert_eq!(asked.await.is_some(), moved, "{says}"); } // A list that still names upstream's gem and does not pin it // is a miss, not a list that moved. @@ -15385,6 +15482,7 @@ mod tests { false, Some(cfg), false, + None, previewed, ) .await @@ -15771,6 +15869,7 @@ mod tests { false, Some(cfg), hosted, + None, &mut Vec::new(), ) .await; @@ -15975,13 +16074,9 @@ mod tests { tokio::fs::write(installed.join(RB), RB_PRISTINE) .await .unwrap(); - // The plan reads the reference of the gem's patch and downloads - // nothing of it. assert_eq!( service_preflight(NOKO, &installed, &root, &record).await, - Some(crate::api::client::PlannedDownload::reference( - UUID.to_string() - )) + None ); let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; let (result, entry, _) = diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 83627b24da..d3c3ec8f2b 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -397,27 +397,13 @@ impl VendorServiceConfig { /// [`crate::api::client::ApiClient::prefetch_vendor_downloads`]). As /// many downloads run at once as the API's in-flight cap allows, and at /// most [`ARCHIVE_PREFETCH_BYTES`] of fetched archives wait for the loop. - /// A position whose reference alone the loop reads - /// ([`crate::api::client::PlannedDownload::reference`]) shares the - /// plan's one reference request and downloads nothing. - /// Those positions do not depend on what gates the downloads: where - /// nothing is fetched ahead ([`Self::wants_prefetch`] is false, or - /// fewer than two downloads are planned, with nothing to overlap) the - /// plan holds them alone, and its task, which only a download starts, - /// never runs. One such position is worth a plan by itself: its - /// backend may read the reference more than once (a restore, then the - /// rebuild), and the plan answers every read with the one answer. - /// `None` — nothing attached — when the service is not enabled or the - /// plan would hold nothing. + /// `None` — nothing attached — when [`Self::wants_prefetch`] is false, + /// or when fewer than two downloads are planned (nothing to overlap). pub fn prefetch_archives( &self, - mut downloads: Vec, + downloads: Vec, ) -> Option { - let archives = downloads.iter().filter(|d| !d.reference_only).count(); - if !self.wants_prefetch() || archives < 2 { - downloads.retain(|d| d.reference_only); - } - if !self.service_enabled() || downloads.is_empty() { + if !self.wants_prefetch() || downloads.len() < 2 { return None; } let client = self.client.as_ref()?; @@ -1004,20 +990,6 @@ pub async fn service_preflight( } } -/// The plan position of a package the ledger already records at the uuid -/// of the patch being vendored: a re-run, which every backend answers -/// without downloading. `None` where it asks the service nothing either. -/// A gem copy vendored as platform gems reads the list of its fix on -/// every run, to follow a build that was published or withdrawn -/// ([`gem::follows_list`]): a position whose reference alone is read. -pub fn in_step_reference( - entry: &VendorEntry, - uuid: &str, -) -> Option { - gem::follows_list(entry, uuid) - .then(|| crate::api::client::PlannedDownload::reference(uuid.to_string())) -} - /// The lock-text refusals among `candidates` (purls with the uuid of the /// patch to vendor): each purl its backend refuses on the project's lock /// and manifest text alone, with the backend's `(code, detail)` — the npm diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 0c1677c741..061bafe63f 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -78,8 +78,9 @@ pub enum RestoreError { /// list of the gem's fix names another build for a platform than the /// entry records (`vendor_prebuilt_replaced`). Nothing is wrong with /// the service or the download: a run that vendors takes the copy - /// from the list as it is now. - ListMoved(String), + /// from the list as it is now, which comes with the refusal so that + /// the run does not ask for it again. + ListMoved(String, super::gem::FixList), /// Every other reason. Failed(String), } @@ -88,7 +89,7 @@ impl RestoreError { /// What to say of it. pub fn detail(&self) -> &str { match self { - RestoreError::ListMoved(detail) | RestoreError::Failed(detail) => detail, + RestoreError::ListMoved(detail, _) | RestoreError::Failed(detail) => detail, } } } @@ -111,24 +112,22 @@ impl From<&str> for RestoreError { } } -/// Whether [`restore`] of `entry` would be refused because the list of -/// its gem's fix moved ([`RestoreError::ListMoved`]): what a dry run asks -/// in place of the restore. ONE request, nothing downloaded or written. -/// `false` for every entry that is not a gem vendored as platform gems, -/// and offline. -pub async fn restore_follows_list( +/// The list of its gem's fix that [`restore`] of `entry` would be refused +/// over because it moved ([`RestoreError::ListMoved`]): what a dry run +/// asks in place of the restore. ONE request, nothing downloaded or +/// written. `None` when the restore would not be refused for that, for +/// every entry that is not a gem vendored as platform gems, and offline. +pub async fn restore_refused_over( entry: &VendorEntry, record: &PatchRecord, service: &VendorServiceConfig, -) -> bool { +) -> Option { if !super::gem::follows_list(entry, &record.uuid) || super::common::service_offline_conflict(Some(service)).is_some() { - return false; + return None; } - let Some((name, version)) = parse_gem_purl(&entry.base_purl) else { - return false; - }; + let (name, version) = parse_gem_purl(&entry.base_purl)?; super::gem::recorded_list_moved(service, &record.uuid, &name, &version, &entry.gem_builds).await } @@ -318,28 +317,32 @@ pub async fn restore( // A gem vendored as platform gems is restored tree by tree, // each from the patch the gem's fix names for its platform // today, which must be the one the ledger records, and - // against the digests recorded with it. - let copied = match entry.gem_builds.as_slice() { - [] => { - super::gem::gem_service_copy( - Some(service), - record, - &name, - &stage, - uuid_dir, - true, - &mut warnings, - ) - .await - } + // against the digests recorded with it. The fix's list is + // read once, here: a refusal over it hands it on. + match entry.gem_builds.as_slice() { + [] => super::gem::gem_service_copy( + Some(service), + record, + &name, + &stage, + uuid_dir, + true, + &mut warnings, + ) + .await + .map_err(|outcome| detail(*outcome))?, builds => { + let gem = format!("{name}@{version}"); + let list = super::gem::restore_list(Some(service), &record.uuid, &gem) + .await + .map_err(|outcome| detail(*outcome))?; let trees = super::gem::PlatformTrees { - gem: &format!("{name}@{version}"), - from: super::gem::BuildsFrom::Recorded(builds), + gem: &gem, + from: super::gem::BuildsFrom::Recorded(builds, &list), standing: super::gem::Standing::Wired, held: Vec::new(), }; - super::gem::gem_platform_service_copy( + let copied = super::gem::gem_platform_service_copy( Some(service), record, &name, @@ -349,14 +352,17 @@ pub async fn restore( true, &mut warnings, ) - .await - .map(|_| ()) + .await; + if let Err(outcome) = copied { + let moved = super::gem::is_list_moved(&outcome); + let detail = detail(*outcome); + return Err(match moved { + true => RestoreError::ListMoved(detail, list), + false => RestoreError::Failed(detail), + }); + } } - }; - copied.map_err(|outcome| match super::gem::is_list_moved(&outcome) { - true => RestoreError::ListMoved(detail(*outcome)), - false => RestoreError::Failed(detail(*outcome)), - })?; + } } "npm" => { let (name, version) = super::npm_common::parse_npm_purl(&entry.base_purl) From 6ab62226d6cd098f93089521371a31783aa947a5 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 14:34:50 -0500 Subject: [PATCH 21/28] Document the per-gem list request, the handed list and the metadata warning The contract and the guide state the cost of following a list plainly: one small request per vendored platform gem per run, not batched. A refused restore hands the list it read to the rebuild; a damaged copy whose list did not move is restored and then asked about once more. The uuid directory's git metadata is written after the trees are in place, and a failed write is `vendor_artifact_gitignore_unchecked`, whose row now names the gem. The "Also:" suffix is gone from the contract. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 4 ++-- docs/ecosystems.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 11768fa1ac..143e318c2a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way is a position of the run's download plan whose reference alone is read, so the references of all of them are ONE request, sent when the run reaches the first (a run over a copy that is in sync makes that one request for it and downloads nothing; this does not depend on whether the run fetches archives ahead, so it holds for a dry run and with the API concurrency limited to one; a single such gem is planned too, so that a run which reads its reference more than once, a restore and then the rebuild, reads one answer), and where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (the one request that failed is the answer for every gem it named, so a patch service that does not answer, or that refuses the request, is asked once and not once per gem), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is written before the new trees are moved in, so a write of it that fails changes nothing of the copy, which then stays in force like any copy that could not follow its list. A skip of a build that is not served yet ends its line with what there is to say of that metadata (`… stays in force as it is. Also: could not check whether git would commit …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). Its dry run asks the same question (one request, no download) and previews the copy vendored from the list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer stops being asked for the rest of the run once two requests in a row have failed, by the circuit breaker every vendor request shares), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is not part of the copy: it is written once the new trees are in place, and a write of it that fails is the warning `vendor_artifact_gitignore_unchecked`, never a failure (the trees are in place and correct, and the ledger records them). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). The refused restore hands the list it read to that rebuild, so the two are decided by one answer and the fix's reference is asked for once. Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. A damaged copy whose list did not move is restored as it was vendored, and the run then asks for the list once more, as it does for any copy it finds in step. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2615,7 +2615,7 @@ command's integration tests check its output. | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | | `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | -| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | +| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet, every PyPI flavor and a gem vendored as platform gems): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error), or the vendored directory's own `.gitignore` and `.gitattributes` could not be written (a PyPI wheel, a gem vendored as platform gems); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | | `vendor_variant_ambiguous` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): the package is not installed and the manifest holds several release variants of it (`?artifact_id=` / `?platform=`), none of which the vendor ledger records, so nothing says which distribution to vendor; install the package or keep one release variant. A variant the ledger records (at any patch uuid) is taken as the wired one and its siblings are left out without an event. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 961952ce37..dec9256022 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy: 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (the gems vendored this way share one request) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy: 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 70cc021460f5b4f65b5cb89185dce2a9d4cc6fb8 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 14:58:43 -0500 Subject: [PATCH 22/28] Say what released 5.1.0 does on a copy vendored as platform gems The contract and the guide said that 5.1.0 and earlier could attest the gem as patched for every platform. Run against a project vendored with one patched platform and one platform on upstream's gem, 5.1.0 does neither: it has no platform-gem vendoring, so `vendor --check` fails (`vendor_check_failed`, a patched file is missing) and `vex` leaves the gem out (`vendor_unwired`) and attests nothing for it. Both texts say that, and the test that pins them follows. The metadata test gains the first vendor: a uuid directory whose git metadata cannot be written is vendored, wired and recorded all the same, with the warning. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../vendor/vendor_gem_platform_builds_e2e.rs | 7 ++--- crates/socket-patch-core/src/vendor/gem.rs | 27 +++++++++++++------ docs/ecosystems.md | 2 +- 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 143e318c2a..b55efc111d 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer stops being asked for the rest of the run once two requests in a row have failed, by the circuit breaker every vendor request shares), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is not part of the copy: it is written once the new trees are in place, and a write of it that fails is the warning `vendor_artifact_gitignore_unchecked`, never a failure (the trees are in place and correct, and the ledger records them). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). The refused restore hands the list it read to that rebuild, so the two are decided by one answer and the fix's reference is asked for once. Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. A damaged copy whose list did not move is restored as it was vendored, and the run then asks for the list once more, as it does for any copy it finds in step. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer stops being asked for the rest of the run once two requests in a row have failed, by the circuit breaker every vendor request shares), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is not part of the copy: it is written once the new trees are in place, and a write of it that fails is the warning `vendor_artifact_gitignore_unchecked`, never a failure (the trees are in place and correct, and the ledger records them). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). The refused restore hands the list it read to that rebuild, so the two are decided by one answer and the fix's reference is asked for once. Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. A damaged copy whose list did not move is restored as it was vendored, and the run then asks for the list once more, as it does for any copy it finds in step. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index df761ab2e3..b2c515fbcc 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -2884,11 +2884,12 @@ fn the_contract_and_the_guide_say_what_the_cli_says() { ); for (name, text) in [("contract", &contract), ("guide", &guide)] { assert!(!text.contains("needs every locked platform"), "{name}"); + // What released 5.1.0 does on such a copy was run, not assumed: + // it fails the check and attests nothing for the gem. assert!( text.contains( - "5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as \ - patched for every platform" - ), + "5.1.0 and earlier have no platform-gem vendoring and do not read such a copy" + ) && !text.contains("can attest the gem as patched for every platform"), "{name}" ); } diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index c2615f484d..d6b04216c2 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -14357,22 +14357,33 @@ mod tests { /// written once the new trees are in place, and a write that fails /// is a warning, never a failure: the trees are in place and /// correct, the entry handed back records them, and nothing is - /// said of a copy left as it was. The same for a damaged copy, - /// which is rebuilt all the same. + /// said of a copy left as it was. The same for a first vendor and + /// for a damaged copy, which is rebuilt all the same. #[tokio::test] async fn metadata_that_cannot_be_written_is_a_warning_and_the_trees_are_in_place() { let (_tmp, root, record) = project(&lock(None)).await; - let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; - vendor_and_persist(&root, &record, &cfg).await; - // A directory where the file belongs: the write fails. + // A directory where the file belongs: every write of it fails. let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); - tokio::fs::remove_file(&gitattributes).await.unwrap(); - tokio::fs::create_dir(&gitattributes).await.unwrap(); - tokio::fs::write(gitattributes.join("in the way"), b"") + tokio::fs::create_dir_all(gitattributes.join("in the way")) .await .unwrap(); let unchecked = "could not check whether git would commit the vendored artifact"; let linux = root.join(rel(UUID)).join(LINUX); + let warned = |warnings: &[VendorWarning]| { + let unchecked = crate::vendor::npm_dir::GITIGNORE_UNCHECKED; + warnings.iter().any(|w| w.code == unchecked) + }; + + // A first vendor: vendored, wired and recorded, with the warning. + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + assert!(warned(&warnings), "{warnings:?}"); + let entry = entry.expect("the first vendor's entry"); + assert_eq!(entry.gem_builds, [built(UUID, DARWIN), kept(LINUX)]); + assert!(text(root.join(GEMFILE_LOCK)).await.contains("PATH\n")); + ts::persist(&root, NOKO, entry).await; // The list moved: the copy takes the build that was published. let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index dec9256022..a28f3537b9 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy: 5.1.0 and earlier do not know a tree of upstream's gem and can attest the gem as patched for every platform, so attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 001e279553df89454b9350a9ef87006535efc059 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 15:40:38 -0500 Subject: [PATCH 23/28] Finish every copy of a platform-locked gem with one function, and ask about its list once, briefly The fifth review found the uuid directory's git metadata handled five ways. One function, `finish_platform_copy`, now ends every path that puts the trees of a gem vendored as platform gems in place or says they stay in force: a first vendor, a rebuild of a wired copy, a restore, a copy found in step and one that stays in force. - It writes the uuid directory's `.gitignore` and `.gitattributes`. A write that fails is the warning `vendor_gem_git_metadata_unwritten`, which names the two files and says to make them writable. No path treats it as an error any more (`restore` did), and none drops it: a skip that leaves the copy in force ends its line with it. - Then it asks git whether it would commit the copy. Only a first vendor did; a rebuild of a wired copy with a project `*.so` rule and an unwritable `.gitignore` left the binaries out of the commit with a generic warning. The refusal names the unwritten files as its cause when that is why, with that remedy. A first vendor removes the copy it made; a copy the lock already names stays where it is, and git is asked with its index, since it keeps committing a file it tracks. The question a copy in step asks of its fix's list is advisory: one attempt of at most five seconds, never retried and outside the circuit breaker (`fetch_vendor_reference_once`, on the client's existing single POST). Two such reads that failed used to open the breaker and fail the run's real vendoring unasked, after two retry ladders. `restore_with_list` hands back the list a restore read when it restores the copy too, and the backend judges the copy by it, so the two no longer ask twice. `FixList` carries its fix's uuid, and a list of another fix is ignored. `restore_list` takes the service and the name and version it is given; the gems a list names are resolved once and handed on as such. The vendored `vex` loop is unchanged: a new end-to-end test with a manifest record of a build's own patch beside the vendored entry shows the build attested from the committed tree. Tests: unwritable metadata on every path, at the core and CLI levels, with and without a project rule that ignores the binaries, tracked and not; the advisory read at the client (one request whatever the policy, the breaker untouched, its own bound when nothing answers) and in the backend; the list handed on by a restore that succeeds, and a list of another fix. Co-Authored-By: Claude Fable 5.2 --- .../socket-patch-cli/src/commands/vendor.rs | 23 +- .../vendor/vendor_gem_platform_builds_e2e.rs | 314 +++++++- crates/socket-patch-core/src/api/client.rs | 121 +++ crates/socket-patch-core/src/vendor/gem.rs | 716 +++++++++++++----- .../src/vendor/redownload.rs | 41 +- .../src/vendor/service_fetch.rs | 22 + 6 files changed, 1007 insertions(+), 230 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 52af75008b..ea4b33a5aa 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -4498,10 +4498,14 @@ pub(crate) async fn vendor_records_reusing( } } - // The list of a gem's fix that the exact restore below was - // refused over: handed to the backend, which vendors the copy - // again from it, so the two read one answer. + // The list of a gem's fix that the exact restore below read, + // whether it restored the copy or was refused over that list: + // handed to the backend, which judges the copy by it and + // vendors it again from it, so the two are decided by one + // answer. And what the restore said of the copy, which the + // backend, finishing the same copy, need not say again. let mut gem_list: Option = None; + let mut restore_said: Vec = Vec::new(); // A dir-shaped entry with no file inventory (vendored before // inventories were recorded, or past the inventory cap) gives an // exact restore nothing to check a download against: the backend @@ -4550,7 +4554,8 @@ pub(crate) async fn vendor_records_reusing( use vendor::redownload::RestoreError; let restored = match service { Some(service) => { - vendor::redownload::restore(&common.cwd, entry, record, service).await + let cwd = &common.cwd; + vendor::redownload::restore_with_list(cwd, entry, record, service).await } None => Err(RestoreError::Failed( "vendoring requires a prebuilt artifact from the patch service" @@ -4558,11 +4563,12 @@ pub(crate) async fn vendor_records_reusing( )), }; match restored { - Ok(warnings) => { + Ok((warnings, list)) => { for warning in &warnings { record_warning(env, candidate, warning, common); } env.record(PatchEvent::new(PatchAction::Rebuilt, candidate.clone()).with_details(serde_json::json!({"redownloaded": true, "path": entry.artifact.path}))); + (gem_list, restore_said) = (list, warnings); } Err(RestoreError::ListMoved(_, list)) => gem_list = Some(list), Err(RestoreError::Failed(detail)) => { @@ -4790,7 +4796,12 @@ pub(crate) async fn vendor_records_reusing( for w in &symlinked { record_warning(env, candidate, w, common); } - for w in &warnings { + let said_before = |w: &VendorWarning| { + let same = + |said: &VendorWarning| said.code == w.code && said.detail == w.detail; + restore_said.iter().any(same) + }; + for w in warnings.iter().filter(|w| !said_before(w)) { // "vendored X from the patch service" on a package // this run left untouched would contradict the // "already vendored" count: JSON only. diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index b2c515fbcc..ce092211c7 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -766,8 +766,8 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { // run rebuilds the copy. The gem patch's reference says which patch // each platform's gem is (the ledger must name the same ones), then // those patches are asked for in one request. The run then finds - // the restored copy in step with the gem patch's list, which it - // asks for where it needs it: once more. + // the restored copy in step by the list the restore read, which + // hands it on: the gem patch's reference is asked for once. std::fs::write(tree(root, LINUX).join(SO), b"another binary").unwrap(); let (code, env, stderr) = run_json(root, &["vendor", "--check", "--json"], &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); @@ -783,7 +783,6 @@ async fn a_platform_locked_gem_vendors_and_reports_per_platform_gem() { [ vec![UUID.to_string()], vec![DARWIN_UUID.to_string(), LINUX_UUID.to_string()], - vec![UUID.to_string()], ] ); assert_eq!( @@ -1560,9 +1559,10 @@ async fn metadata_that_cannot_be_written_is_a_warning_and_the_copy_is_vendored() "{stdout}" ); assert!( - stderr - .contains("Warning: could not check whether git would commit the vendored artifact at") - && stderr.contains("cannot write the vendored dir's git metadata"), + stderr.contains(&format!( + "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and \ + `.socket/vendor/gem/{UUID}/.gitattributes` (" + )) && stderr.contains("make those two files writable and run this again"), "{stderr}" ); let said = format!("{stdout}\n{stderr}"); @@ -1590,6 +1590,308 @@ async fn metadata_that_cannot_be_written_is_a_warning_and_the_copy_is_vendored() assert_eq!(code, 0, "{env:#}\n{stderr}"); } +/// `git ` in `root`, which must succeed. +fn git(root: &Path, args: &[&str]) { + let status = std::process::Command::new("git") + .arg("-C") + .arg(root) + .args(args) + .status() + .expect("run git"); + assert!(status.success(), "git {args:?}"); +} + +/// A project that is a git work tree whose own rules ignore compiled +/// binaries (`*.so`), as stock templates do. `None` without git. +fn git_project_ignoring_binaries() -> Option { + let tmp = tempfile::tempdir().unwrap(); + let init = std::process::Command::new("git") + .arg("-C") + .arg(tmp.path()) + .args(["init", "-q"]) + .status(); + if !init.is_ok_and(|status| status.success()) { + return None; + } + write_project(tmp.path()); + std::fs::write(tmp.path().join(".gitignore"), "*.so\n").unwrap(); + Some(tmp) +} + +/// Put a directory where the uuid directory's `.gitignore` belongs, so +/// that no run can write that file. +fn obstruct_gitignore(root: &Path) { + let gitignore = root.join(format!(".socket/vendor/gem/{UUID}/.gitignore")); + let _ = std::fs::remove_file(&gitignore); + std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); +} + +/// What a run says of a copy git would not commit because the uuid +/// directory's own ignore rules could not be written. +fn assert_refused_for_unwritten_metadata(said: &str) { + let cause = format!( + "`.socket/vendor/gem/{UUID}/.gitignore` and `.socket/vendor/gem/{UUID}/.gitattributes`, \ + which keep such a rule off it, could not be written (" + ); + assert!( + said.contains("git would not commit the vendored artifact at") + && said.contains(&cause) + && said.contains("make those two files writable and vendor again"), + "{said}" + ); +} + +/// Every path that puts the trees of a platform-locked gem in place, or +/// says they stay in force, finishes the copy the same way, so a copy git +/// would not commit is refused on each of them and the refusal names its +/// cause. Here a project rule ignores the binaries (`*.so`) and the uuid +/// directory's `.gitignore`, which keeps such a rule off them, cannot be +/// written. A first vendor removes what it made; a copy the lock already +/// names stays where it is. +#[tokio::test] +async fn a_copy_git_would_not_commit_is_refused_on_every_path() { + let check = ["vendor", "--check", "--json"]; + let failed_with = |env: &serde_json::Value, code: &str| -> String { + let failed = env["events"] + .as_array() + .into_iter() + .flatten() + .find(|event| event["action"] == "failed" && event["errorCode"] == code); + let failed = failed.unwrap_or_else(|| panic!("a failed `{code}` event: {env:#}")); + failed["error"].as_str().unwrap_or_default().to_string() + }; + + // 1. A first vendor: refused, and nothing of it is left. + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to commit + }; + let root = project.path(); + let lock_before = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); + let first = service(&[LINUX], &[DARWIN]).await; + obstruct_gitignore(root); + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + assert_eq!( + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(), + lock_before + ); + // (The refused copy was removed whole, with what stood in its way.) + obstruct_gitignore(root); + let (code, _stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 1, "{stderr}"); + assert!(stderr.contains("Error:"), "{stderr}"); + assert_refused_for_unwritten_metadata(&stderr); + + // The copy vendored, then its `.gitignore` made unwritable. + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + obstruct_gitignore(root); + let vendored = snapshot(root); + + // 2. In step: refused, nothing touched. + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!(snapshot(root), vendored, "in step"); + + // 3. A build the list names is not served yet: the copy stays in + // force, and is refused all the same. + let building = service_still_building_darwin().await; + let (code, env, stderr) = run_json(root, VENDOR, &building.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!(snapshot(root), vendored, "a pending build"); + + // 4. A damaged tree: `repair` restores it and refuses the copy, and + // so does the restore of a vendor run. + for restore in [&["repair", "--download-only", "--json"][..], VENDOR] { + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let (code, env, stderr) = run_json(root, restore, &first.uri()); + assert_ne!(code, 0, "{restore:?}: {env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&env.to_string()); + assert!( + env.to_string().contains("vendor_artifact_gitignored"), + "{restore:?}: {env:#}" + ); + assert_eq!(snapshot(root), vendored, "{restore:?}: the tree is back"); + let (code, env, stderr) = run_json(root, &check, &first.uri()); + assert_eq!(code, 0, "{restore:?}: {env:#}\n{stderr}"); + } + + // 5. The list moved: the copy is vendored again, and refused where it + // stands, with the trees the list names in place. + let moved = service(&[DARWIN, LINUX], &[]).await; + let (code, env, stderr) = run_json(root, VENDOR, &moved.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!( + std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), + stamped(DARWIN_UUID), + "the build the list names" + ); + + // Tracked, git keeps committing the copy whatever the rules say: the + // run succeeds, and says what could not be written. + git(root, &["add", "-f", ".socket"]); + let (code, stdout, stderr) = run(root, VENDOR_IT, &moved.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains(&format!( + "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and" + )) && stderr.contains("make those two files writable and run this again"), + "{stderr}" + ); + assert!(!stderr.contains("Error:"), "{stderr}"); +} + +/// The same paths with no rule that ignores the copy: the files that +/// could not be written are a warning, never a failure, on each of them, +/// said once per run. A skip, which carries no warning, ends its line +/// with it. +#[tokio::test] +async fn unwritable_metadata_is_a_warning_on_every_path() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let warning = format!( + "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and \ + `.socket/vendor/gem/{UUID}/.gitattributes` (" + ); + let warned_once = |stderr: &str| stderr.matches(warning.as_str()).count() == 1; + let first = service(&[LINUX], &[DARWIN]).await; + + // A first vendor. + obstruct_gitignore(root); + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + assert!( + warned_once(&stderr) && !stderr.contains("Error:"), + "{stderr}" + ); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // In step. + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!(warned_once(&stderr), "{stderr}"); + + // A build the list names is not served yet: the skip's line ends + // with it. + let building = service_still_building_darwin().await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &building.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("its vendored copy stays in force as it is. Also: could not write `") + && stderr.contains("make those two files writable and run this again."), + "{stderr}" + ); + + // A damaged tree, restored by a vendor run and by `repair`: the + // warning is said once, though the run finishes the copy twice. + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(warned_once(&stderr), "{stderr}"); + assert_eq!( + std::fs::read(tree(root, LINUX).join(SO)).unwrap(), + LINUX.as_bytes() + ); + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let (code, stdout, stderr) = run(root, &["repair", "--download-only"], &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(warned_once(&stderr), "{stdout}\n{stderr}"); + + // The list moved. + let moved = service(&[DARWIN, LINUX], &[]).await; + let (code, stdout, stderr) = run(root, VENDOR_IT, &moved.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!(stdout.contains("Vendored 1 package."), "{stdout}"); + assert!(warned_once(&stderr), "{stderr}"); +} + +/// A manifest record for the purl of a platform gem at that build's own +/// patch, beside the vendored entry (what a record of the build fetched +/// by its uuid leaves): `vex` attests that build from the committed tree +/// all the same, online and offline, and names the vendored copy as what +/// patches it. +#[tokio::test] +async fn a_manifest_record_of_a_builds_own_patch_leaves_the_build_attested_from_the_tree() { + let server = service(&[DARWIN, LINUX], &[]).await; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + write_project(root); + let (code, env, stderr) = run_json(root, VENDOR, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + let manifest_path = root.join(".socket/manifest.json"); + let mut manifest: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap(); + let view = build_view(LINUX); + manifest["patches"][format!("{PURL}?platform={LINUX}")] = serde_json::json!({ + "uuid": LINUX_UUID, + "exportedAt": "2026-01-01T00:00:00Z", + "files": build_files(LINUX), + "vulnerabilities": view["vulnerabilities"], + "description": view["description"], + "license": "MIT", + "tier": "free" + }); + std::fs::write( + &manifest_path, + serde_json::to_vec_pretty(&manifest).unwrap(), + ) + .unwrap(); + + let out = root.join("vex.json"); + for offline in [true, false] { + let _ = std::fs::remove_file(&out); + let mut args = vec!["vex", "--product", "pkg:gem/app@1.0.0", "--output"]; + args.push(out.to_str().unwrap()); + if offline { + args.push("--offline"); + } + let (code, stdout, stderr) = run(root, &args, &server.uri()); + assert_eq!(code, 0, "offline {offline}: {stdout}\n{stderr}"); + let doc: serde_json::Value = + serde_json::from_str(&std::fs::read_to_string(&out).unwrap()).unwrap(); + let statements = doc["statements"].as_array().expect("statements"); + assert_eq!(statements.len(), 1, "offline {offline}: {doc:#}"); + let statement = &statements[0]; + assert_eq!(statement["status"], "not_affected", "{doc:#}"); + let attested: Vec<&str> = statement["products"] + .as_array() + .into_iter() + .flatten() + .flat_map(|product| product["subcomponents"].as_array().into_iter().flatten()) + .filter_map(|component| component["@id"].as_str()) + .collect(); + for platform in [DARWIN, LINUX] { + let purl = format!("{PURL}?platform={platform}"); + assert!( + attested.contains(&purl.as_str()), + "offline {offline}: {platform}: {attested:?}" + ); + } + let impact = statement["impact_statement"].as_str().unwrap_or_default(); + for own in [DARWIN_UUID, LINUX_UUID] { + let part = format!("Patched via Socket patch {own} (vendored)"); + assert!( + impact.split("; ").any(|p| p == part), + "offline {offline}: {impact}" + ); + } + } +} + /// No locked platform has a patched build: the gem is not vendored, the /// run exits 0 with nothing written and nothing downloaded, and says so in /// one plain line (a counted benign skip in `--json`). diff --git a/crates/socket-patch-core/src/api/client.rs b/crates/socket-patch-core/src/api/client.rs index e2c881590a..3e966d2405 100644 --- a/crates/socket-patch-core/src/api/client.rs +++ b/crates/socket-patch-core/src/api/client.rs @@ -558,6 +558,12 @@ impl VendorRetryPolicy { /// `service` fails closed — the existing miss policy). pub(crate) const VENDOR_BREAKER_THRESHOLD: u32 = 2; +/// Bound on an advisory reference read +/// ([`ApiClient::fetch_vendor_reference_once`]): a service that answers +/// does so well inside it, and one that does not costs the run this much +/// and no retry. +pub(crate) const ADVISORY_REFERENCE_TIMEOUT: Duration = Duration::from_secs(5); + /// The jitter key of the package-reference POST's retries (archive and /// artifact downloads are keyed by their URL). const VENDOR_REFERENCES_KEY: &str = "POST vendor package references"; @@ -1826,6 +1832,45 @@ impl ApiClient { outcome } + /// [`Self::fetch_vendor_reference`] as an advisory question, one whose + /// caller goes on as it was when it gets no answer: ONE attempt, bounded + /// by [`ADVISORY_REFERENCE_TIMEOUT`], never retried, and outside the + /// circuit breaker, which neither counts its failure nor is reset by + /// its answer. So a service that is down costs such a caller one short + /// attempt, and cannot make the run's real requests fail unasked. While + /// the breaker is open the service is down for this run and nothing is + /// asked. Always a request of its own: no plan answers it. + pub(crate) async fn fetch_vendor_reference_once( + &self, + uuid: &str, + free_only: bool, + vendor_url: Option<&str>, + patch_server_url: Option<&str>, + ) -> VendorServiceOutcome { + if let Some(refused) = self.vendor_request_refused(uuid) { + return VendorServiceOutcome::Failed(refused); + } + let uuids = [uuid.to_string()]; + let asked = tokio::time::timeout( + ADVISORY_REFERENCE_TIMEOUT, + self.request_vendor_references_once(&uuids, free_only, vendor_url), + ) + .await; + match asked { + Ok(Ok(results)) => match results.get(uuid) { + Some(result) => vendor_reference(result, patch_server_url), + None => VendorServiceOutcome::Failed(ApiError::Other(format!( + "package response missing a result for {uuid}" + ))), + }, + Ok(Err((e, _))) => VendorServiceOutcome::Failed(e), + Err(_) => VendorServiceOutcome::Failed(ApiError::Network(format!( + "no answer within {}s", + ADVISORY_REFERENCE_TIMEOUT.as_secs() + ))), + } + } + /// [`Self::fetch_vendor_reference`] for several patches in ONE request /// (per [`MAX_REFERENCE_BATCH`] uuids): the outcome of each of `uuids`, /// in their order. `Err` when no answer was had at all (a refused or @@ -7148,6 +7193,82 @@ mod vendor_retry_tests { assert_eq!(c.vendor_outage.load(Ordering::Relaxed), 0); } + /// An advisory reference read is ONE request, whatever the retry + /// policy, and stands outside the breaker: its failures are not + /// counted and cannot open it, so the run's real requests are still + /// made after any number of them, and its answer resets nothing. With + /// the breaker already open it asks nothing. A service that accepts + /// the request and never answers costs the bound of the read, not the + /// ladder's attempts. + #[tokio::test] + async fn an_advisory_reference_read_is_one_attempt_outside_the_breaker() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(503)) + .mount(&server) + .await; + let c = client(&server.uri(), fast()); + for uuid in [UUID_A, UUID_B, UUID_C] { + let o = c.fetch_vendor_reference_once(uuid, false, None, None).await; + assert!(matches!(o, VendorServiceOutcome::Failed(_)), "{o:?}"); + } + assert_eq!(posts(&server).await, 3, "one request each, never retried"); + assert_eq!(c.vendor_outage_count(), 0, "not counted"); + // The run's real request is made, with its ladder, and counted. + let o = c.fetch_vendor_reference(UUID_A, false, None, None).await; + assert!( + matches!(&o, VendorServiceOutcome::Failed(e) if !e.to_string().contains("not attempted")), + "{o:?}" + ); + assert_eq!(posts(&server).await, 6); + assert_eq!(c.vendor_outage_count(), 1); + // An open breaker: the service is down for this run. + c.vendor_outage + .store(VENDOR_BREAKER_THRESHOLD, Ordering::Relaxed); + let o = c + .fetch_vendor_reference_once(UUID_B, false, None, None) + .await; + assert!(matches!(o, VendorServiceOutcome::Failed(_)), "{o:?}"); + assert_eq!(posts(&server).await, 6, "nothing is asked"); + + // An answer changes the count no more than a failure does. + c.vendor_outage.store(1, Ordering::Relaxed); + server.reset().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(granted(&server, UUID_A)) + .mount(&server) + .await; + let o = c + .fetch_vendor_reference_once(UUID_A, false, None, None) + .await; + assert!(matches!(o, VendorServiceOutcome::Ready(_)), "{o:?}"); + assert_eq!(c.vendor_outage_count(), 1); + + // No answer at all: the read gives up at its own bound. + server.reset().await; + Mock::given(method("POST")) + .and(path(POST_PATH)) + .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(120))) + .mount(&server) + .await; + let started = std::time::Instant::now(); + let o = c + .fetch_vendor_reference_once(UUID_A, false, None, None) + .await; + let took = started.elapsed(); + assert!( + matches!(&o, VendorServiceOutcome::Failed(e) if e.to_string().contains("no answer within")), + "{o:?}" + ); + assert!( + took >= ADVISORY_REFERENCE_TIMEOUT && took < ADVISORY_REFERENCE_TIMEOUT * 3, + "{took:?}" + ); + assert_eq!(c.vendor_outage_count(), 1); + } + /// Pending / Unavailable answers prove the service is up: they reset /// the count, so an isolated failure never opens the breaker. #[tokio::test] diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index d6b04216c2..ed96b134b3 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -107,7 +107,7 @@ //! Ruby gemspec). Hosted mode installs the same gem for such a platform. //! A later run follows the list: the tree becomes the patched build's //! once one is published, and a tree whose patched build was withdrawn -//! goes back to upstream's gem ([`moved_list`]). While no locked +//! goes back to upstream's gem ([`moved_sources`]). While no locked //! platform has a patched build, the registry does not list one of them //! or lists no platform gem at all, or the patch it names for one is not //! served (it is still being built, or the service does not grant it), @@ -153,9 +153,9 @@ use super::path::{parse_vendor_path, vendor_uuid_dir_rel}; use super::registry_fetch::{extract_gem_data, extract_on_blocking_pool}; use super::revert::{self, KeepPolicy}; use super::service_fetch::{ - claim_prestaged, downloaded_warning, fetch_served_reference, fetch_served_references, - fetch_verified_archive, fetch_verified_artifact, fetch_verified_secondary, - SecondaryArtifactResult, ServiceArtifact, ServicePolicy, Unserved, + ask_served_reference, claim_prestaged, downloaded_warning, fetch_served_reference, + fetch_served_references, fetch_verified_archive, fetch_verified_artifact, + fetch_verified_secondary, SecondaryArtifactResult, ServiceArtifact, ServicePolicy, Unserved, }; use super::source::PackageSource; use super::state::{ @@ -795,8 +795,8 @@ async fn gem_prelude_of( // ignores the dir itself (`.socket/`) cannot be overridden from inside // it, so the commit would drop the trees the lock names: refused here, // dry run or not, before anything is downloaded. Rules that ignore - // single files are for [`keep_platform_trees_committable`], once the - // trees are known. + // single files are for [`finish_platform_copy`], once the trees are + // known. let in_sync = lock_wired && copy_ok; if !locked.platforms.is_empty() && !in_sync { if let Some((code, detail)) = @@ -933,29 +933,32 @@ pub fn follows_list(entry: &VendorEntry, uuid: &str) -> bool { entry.ecosystem == "gem" && entry.uuid == uuid && !entry.gem_builds.is_empty() } -/// The list of the gem's fix `uuid` where it names, for a locked -/// platform, another gem than the ledger records for the copy: a patched +/// What the list of the gem's fix `uuid` names for each locked platform +/// now, where that is not what the ledger records for the copy: a patched /// build where the copy holds upstream's gem (the build was published /// since), upstream's gem where it holds a patched one (the build was /// withdrawn), or the build of another patch. `None` while the list names /// what the copy holds. Only a list that names a gem for every locked /// platform says that it moved: with no list (the service has not read /// the version's gems, or is building one again), a platform the list -/// leaves out, a request that fails or no service to ask, the copy stands -/// as it is and nothing is said. ONE request, the fix's reference, asked -/// for this gem alone: a run makes one per gem it finds vendored this way. -async fn moved_list( +/// leaves out, no answer or no service to ask, the copy stands as it is +/// and nothing is said. +/// +/// The list is `handed`, where a restore of the copy has just read it, +/// and else asked for: ONE request for this gem alone, and an advisory +/// one ([`ask_served_reference`]: a single short attempt, outside the +/// retry ladder and the circuit breaker), since the copy stands either +/// way. A service that is down costs a run that attempt per such gem, +/// and cannot fail what the run really has to vendor. +async fn moved_sources( project_root: &Path, service: Option<&VendorServiceConfig>, uuid: &str, name: &str, copy_rel: &str, trees: &PlatformTrees<'_>, -) -> Option { - let cfg = service.filter(|cfg| cfg.service_enabled())?; - if service_offline_conflict(service).is_some() { - return None; - } + handed: Option<&FixList>, +) -> Option> { let BuildsFrom::Locked(platforms) = &trees.from else { return None; }; @@ -963,8 +966,19 @@ async fn moved_list( if !follows_list(&entry, uuid) { return None; } - let list = read_fix_list(cfg, uuid, name).await.ok()??; - let sources = listed_sources(&list, name, trees, platforms).ok()?; + let asked; + let list = match handed { + Some(list) => list, + None => { + let cfg = service.filter(|cfg| cfg.service_enabled())?; + if service_offline_conflict(service).is_some() { + return None; + } + asked = fix_list_of(uuid, name, ask_served_reference(cfg, uuid).await).ok()??; + &asked + } + }; + let sources = listed_sources(list, name, trees, platforms).ok()?; let moved = sources.iter().any(|source| { let recorded = entry .gem_builds @@ -972,7 +986,7 @@ async fn moved_list( .find(|b| b.platform == source.platform); !recorded.is_some_and(|built| built.uuid.eq_ignore_ascii_case(&source.uuid)) }); - moved.then_some(list) + moved.then_some(sources) } /// The platforms whose patched build the vendored copy of ANOTHER patch @@ -1245,11 +1259,12 @@ pub async fn vendor_gem<'a>( /// pin back after a refusal). The skip of a gem with a locked platform /// that has no patched build then says that the gem stays hosted. /// -/// `list`: the list of the gem's fix that an exact restore of the copy -/// was just refused over -/// ([`RestoreError::ListMoved`](super::redownload::RestoreError::ListMoved)). -/// The damaged copy is vendored again from it, so the restore and this -/// call read one answer: the fix's reference is not asked for again. +/// `list`: the list of the gem's fix that a restore of the copy has just +/// read ([`restore_with_list`](super::redownload::restore_with_list)), +/// whether it restored the copy or was refused over that list. This call +/// judges the copy by it, and vendors a damaged copy again from it, so +/// the two are decided by one answer and the fix's reference is not asked +/// for again. A list of another fix than `record`'s is ignored. #[allow(clippy::too_many_arguments)] pub async fn vendor_gem_previewing<'a>( purl: &str, @@ -1327,23 +1342,36 @@ pub async fn vendor_gem_previewing<'a>( // An intact copy vendored as platform gems still follows the fix's // list: a locked platform that gained a patched build, or lost one to // a withdrawal, is vendored again as the list has it now. + let list = list.filter(|list| list.is_of(&record.uuid) && lock_wired && !platforms.is_empty()); let moved = match lock_wired && copy_ok && !platforms.is_empty() { true => { let wired = locked(Standing::Wired); - moved_list(project_root, service, &record.uuid, name, copy_rel, &wired).await + let (uuid, root) = (record.uuid.as_str(), project_root); + moved_sources(root, service, uuid, name, copy_rel, &wired, list).await } false => None, }; - // The list of the fix where it was already read, which is then not - // read again: by the check above, or by the exact restore of a damaged - // copy that was refused because the list names other builds. - let read = moved - .as_ref() - .or(list.filter(|_| lock_wired && !copy_ok && !platforms.is_empty())); - let wired = match read { - Some(list) => PlatformTrees { + // A damaged copy whose exact restore was refused because the list + // names other builds is vendored again from the list that restore + // read: the gems it names, which settle the copy as the rebuild's own + // read of them would. + let handed = match list.filter(|_| !copy_ok) { + Some(list) => match listed_sources(list, name, &locked(Standing::Wired), platforms) { + Ok(sources) => Some(sources), + Err(unlisted) => { + let prelude = &prelude; + return wired_copy_failed(*unlisted, false, project_root, record, prelude, dry_run) + .await; + } + }, + None => None, + }; + // The trees of the wired copy: the ones the list was already read to + // name (it is not read again), else the locked ones. + let wired = match moved.as_ref().or(handed.as_ref()) { + Some(sources) => PlatformTrees { gem: &label, - from: BuildsFrom::Listed(platforms, list), + from: BuildsFrom::Listed(sources), standing: Standing::Wired, held: Vec::new(), }, @@ -1351,14 +1379,14 @@ pub async fn vendor_gem_previewing<'a>( }; if lock_wired { if copy_ok && moved.is_none() { - let warnings = copy_in_force(project_root, record, &prelude, true, dry_run) - .await - .unwrap_or_default(); - return done( - already_patched_result(purl, copy_dir, &record.files), - None, - warnings, - ); + return match copy_in_force(project_root, record, &prelude, true, dry_run).await { + Some(Err(refusal)) => refusal, + finished => done( + already_patched_result(purl, copy_dir, &record.files), + None, + finished.and_then(Result::ok).unwrap_or_default(), + ), + }; } // Wired (Gemfile + lock + CHECKSUMS) but the committed copy is // missing/stale: rebuild the ARTIFACT only — the pair edit is @@ -1377,7 +1405,6 @@ pub async fn vendor_gem_previewing<'a>( let materialised = materialise_patched_copy( purl, copy_dir, - copy_rel, uuid_dir, name, &wired, @@ -1429,6 +1456,16 @@ pub async fn vendor_gem_previewing<'a>( // first run's records, the only copy of the pre-vendor originals. let file_inventory = inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; + // The new trees are in place, and the lock names them: one git + // would not commit is refused where it stands. + if !platforms.is_empty() { + let inventory = file_inventory.as_ref(); + let finished = + finish_platform_copy(project_root, copy_rel, inventory, false, &mut warnings); + if let Err(refusal) = finished.await { + return refusal; + } + } let entry = gem_entry( build_gem_purl(name, version), record, @@ -1500,7 +1537,6 @@ pub async fn vendor_gem_previewing<'a>( let (mut result, builds) = match materialise_patched_copy( purl, copy_dir, - copy_rel, uuid_dir, name, &locked(plan.standing(hosted)), @@ -1523,20 +1559,20 @@ pub async fn vendor_gem_previewing<'a>( // ── prebuilt trees git would not commit ────────────────────────────── // Asked before either project file is written (see - // `keep_platform_trees_committable`). The inventory taken for it is - // the entry's, below. + // `finish_platform_copy`). The inventory taken for it is the entry's, + // below. let mut platform_inventory = None; if !platforms.is_empty() { let inventory = inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; - if let Err(refusal) = keep_platform_trees_committable( + let finished = finish_platform_copy( project_root, copy_rel, inventory.as_ref(), + true, &mut warnings, - ) - .await - { + ); + if let Err(refusal) = finished.await { let _ = remove_tree(uuid_dir).await; prune_empty_vendor_levels(uuid_dir).await; return refusal; @@ -1717,19 +1753,20 @@ pub const GEM_LIST_NOT_FOLLOWED: &str = "vendor_gem_list_not_followed"; /// the copy intact and nothing has written to it since, so its trees are /// not read again; otherwise every tree the entry names is checked /// ([`recorded_copy_stands`]), as after an attempt to vendor the copy -/// again, which can fail once the copy was already changed. The uuid -/// dir's `.gitignore` and `.gitattributes` are not part of the copy: one -/// that was deleted (or never written) is put back (never by a dry run), -/// or a project `*.so` rule drops the binaries from the next commit. -/// `None` when the copy does not stand; else what there is to say of the -/// metadata. +/// again, which can fail once the copy was already changed. A copy +/// vendored as platform gems that stands is then finished as every such +/// copy is ([`finish_platform_copy`], never by a dry run): the uuid dir's +/// `.gitignore` and `.gitattributes` are put back where one is missing, +/// and git is asked whether it would commit the copy. `None` when the +/// copy does not stand; else what there is to say of it, or the refusal +/// of a copy git would not commit. async fn copy_in_force( project_root: &Path, record: &PatchRecord, prelude: &GemPrelude, verified: bool, dry_run: bool, -) -> Option> { +) -> Option, VendorOutcome>> { let (copy_rel, copy_dir) = (prelude.copy_rel.as_str(), prelude.copy_dir.as_path()); let stands = verified || recorded_copy_stands(project_root, record, copy_rel, copy_dir, &prelude.name).await; @@ -1737,29 +1774,106 @@ async fn copy_in_force( return None; } let mut warnings: Vec = Vec::new(); - if !prelude.platforms.is_empty() && !dry_run { - write_uuid_metadata_or_warn(&prelude.uuid_dir, copy_rel, &mut warnings).await; + if prelude.platforms.is_empty() || dry_run { + return Some(Ok(warnings)); } - Some(warnings) + let entry = recorded_copy(project_root, &record.uuid, copy_rel).await; + let inventory = entry + .as_ref() + .and_then(|entry| entry.artifact.file_inventory.as_ref()); + let finished = finish_platform_copy(project_root, copy_rel, inventory, false, &mut warnings); + Some(finished.await.map(|()| warnings)) } -/// Write the git metadata of the uuid dir of a copy vendored as platform -/// gems ([`restore_uuid_metadata`]). It is not part of the copy: a write -/// that fails is a warning, the one every backend gives for ignore rules -/// it could not vouch for, and never a failure. -async fn write_uuid_metadata_or_warn( - uuid_dir: &Path, +/// Advisory of a copy vendored as platform gems whose uuid dir's +/// `.gitignore` and `.gitattributes` could not be written. The trees are +/// in place and correct, but those two files are what keeps a project +/// ignore rule or filter (such as `*.so`) off them: the detail names the +/// files and says to make them writable. +pub const GEM_GIT_METADATA_UNWRITTEN: &str = "vendor_gem_git_metadata_unwritten"; + +/// Finish a copy vendored as platform gems whose trees are in place. Every +/// path that puts such trees in place, or says that they stay in force, +/// ends here: a first vendor, a rebuild of a copy the lock is wired to, a +/// restore, a copy found in step and one that stays in force. +/// +/// 1. The uuid dir's `.gitignore` and `.gitattributes` are written where +/// absent or different ([`restore_uuid_metadata`]). They are not part +/// of the copy, so a write that fails is never a failure: it is the +/// warning [`GEM_GIT_METADATA_UNWRITTEN`]. +/// 2. Git is asked whether it would commit every file of the trees +/// (`inventory`: the copy's files) and those two files. A rule that +/// keeps one of them out is the refusal `vendor_artifact_gitignored`, +/// which gives the files that could not be written as its cause, and +/// what to do about them, when that is why. Git failing to answer is +/// only a warning, and nothing is asked without an inventory, whose +/// absence is already reported. `fresh`: nothing of the copy was there +/// before this run (a first vendor), so git is asked as if none of it +/// were tracked. Otherwise the index counts: git keeps committing a +/// file it tracks whatever the ignore rules say. +/// +/// What a path does about the refusal is its own: a first vendor removes +/// the copy it just made; every other one has a copy the lock already +/// names, which stays where it is. +pub(super) async fn finish_platform_copy( + project_root: &Path, copy_rel: &str, + inventory: Option<&BTreeMap>, + fresh: bool, warnings: &mut Vec, -) { - if let Err(e) = restore_uuid_metadata(uuid_dir).await { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail( - copy_rel, - &format!("cannot write the vendored dir's git metadata: {e}"), +) -> Result<(), VendorOutcome> { + let Some((uuid_dir_rel, _)) = copy_rel.rsplit_once('/') else { + return Ok(()); + }; + let metadata = format!("`{uuid_dir_rel}/.gitignore` and `{uuid_dir_rel}/.gitattributes`"); + let unwritten = restore_uuid_metadata(&project_root.join(uuid_dir_rel)) + .await + .err(); + let ignoring = match inventory { + Some(inventory) => { + let mut paths: Vec = inventory + .keys() + .map(|file| format!("{copy_rel}/{file}")) + .collect(); + paths.push(format!("{uuid_dir_rel}/.gitignore")); + paths.push(format!("{uuid_dir_rel}/.gitattributes")); + super::npm_dir::ignoring_rule_lines(project_root, &paths, fresh).await + } + None => Ok(None), + }; + let ignoring = ignoring.map(|lines| lines.map(|lines| super::npm_dir::summarize_rules(&lines))); + match (ignoring, unwritten) { + (Ok(Some(rules)), None) => Err(refused( + super::npm_dir::GITIGNORED, + super::npm_dir::gitignored_detail(copy_rel, &rules), + )), + (Ok(Some(rules)), Some(e)) => Err(refused( + super::npm_dir::GITIGNORED, + format!( + "git would not commit the vendored artifact at {copy_rel} ({rules}): {metadata}, \ + which keep such a rule off it, could not be written ({e}); make those two files \ + writable and vendor again" ), - )); + )), + (unanswered, unwritten) => { + if let Some(e) = unwritten { + warnings.push(VendorWarning::new( + GEM_GIT_METADATA_UNWRITTEN, + format!( + "could not write {metadata} ({e}): they keep a project ignore rule or \ + filter (such as `*.so`) off the vendored copy at {copy_rel}; make those \ + two files writable and run this again" + ), + )); + } + if let Err(why) = unanswered { + warnings.push(VendorWarning::new( + super::npm_dir::GITIGNORE_UNCHECKED, + super::npm_dir::gitignore_unchecked_detail(copy_rel, &why), + )); + } + Ok(()) + } } } @@ -1796,10 +1910,21 @@ async fn wired_copy_failed( } let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; match (failure, in_force) { - (VendorOutcome::Refused { code, detail }, Some(_)) if pending => refused( - code, - format!("{detail}; its vendored copy stays in force as it is."), - ), + // The copy that stays in force is one git would not commit: that + // is what the run has to say of it. + (_, Some(Err(refusal))) => refusal, + // A skip carries no advisory of its own: what there is to say of + // the copy ends its line. + (VendorOutcome::Refused { code, detail }, Some(Ok(warnings))) if pending => { + let also: String = warnings + .iter() + .map(|warning| format!(" Also: {}.", warning.detail.trim_end_matches('.'))) + .collect(); + refused( + code, + format!("{detail}; its vendored copy stays in force as it is.{also}"), + ) + } (VendorOutcome::Refused { detail, .. }, None) if pending => refused( super::VENDOR_PREBUILT_REQUIRED, format!( @@ -1807,7 +1932,7 @@ async fn wired_copy_failed( then." ), ), - (failure, Some(mut warnings)) => { + (failure, Some(Ok(mut warnings))) => { let why = match &failure { VendorOutcome::Refused { detail, .. } => detail.clone(), VendorOutcome::Done { result, .. } => result.error.clone().unwrap_or_default(), @@ -2047,10 +2172,10 @@ pub(super) enum BuildsFrom<'a> { /// restore of that copy, held to the list of the fix as it was read /// for it ([`restore_list`]). Recorded(&'a [GemBuildEntry], &'a FixList), - /// [`Self::Locked`] where the list was already read ([`moved_list`], - /// or a restore that was refused over it), so the fix's reference is - /// asked for once. - Listed(&'a [String], &'a FixList), + /// [`Self::Locked`] where the list was already read: the gem it names + /// for each locked platform ([`moved_sources`], or a restore that was + /// refused over it), so the fix's reference is asked for once. + Listed(&'a [BuildSource]), } /// The list of a gem's fix as ONE request read it: the gem its registry @@ -2059,10 +2184,19 @@ pub(super) enum BuildsFrom<'a> { /// hands it on, so a copy is judged and vendored by one answer. #[derive(Debug, Clone, PartialEq, Eq)] pub struct FixList { + /// The fix whose list this is. A list is only ever used for that fix. + fix: String, builds: Vec, index_url: Option, } +impl FixList { + /// Whether this is the list of the fix `uuid`. + fn is_of(&self, uuid: &str) -> bool { + self.fix.eq_ignore_ascii_case(uuid) + } +} + /// The list of the gem's fix `uuid`: ONE request, the fix's package /// reference, and nothing downloaded. `None` when the reference carries /// no list right now (the service has not read the version's gems, or is @@ -2072,7 +2206,16 @@ async fn read_fix_list( uuid: &str, name: &str, ) -> Result, Box> { - let served = match fetch_served_reference(cfg, uuid).await { + fix_list_of(uuid, name, fetch_served_reference(cfg, uuid).await) +} + +/// The list in the `reference` the service answered for the fix `uuid`. +fn fix_list_of( + uuid: &str, + name: &str, + reference: ServiceArtifact, +) -> Result, Box> { + let served = match reference { ServiceArtifact::Pending => return Ok(None), reference => ServicePolicy::Refused.settle( reference, @@ -2080,10 +2223,12 @@ async fn read_fix_list( &format!("platform gems for {name}"), )?, }; - let index_url = served.gem_index_url; - Ok(served - .gem_builds - .map(|builds| FixList { builds, index_url })) + let (fix, index_url) = (uuid.to_string(), served.gem_index_url); + Ok(served.gem_builds.map(|builds| FixList { + fix, + builds, + index_url, + })) } /// What a gem has in place of the patch being vendored, should a locked @@ -2486,22 +2631,23 @@ fn upstream_gem_artifact( }) } -/// The list a restore of a copy of the fix `fix` (the gem `gem`, -/// `@`) is held to: ONE request. A restore has no copy to +/// The list a restore of a copy of the fix `fix` (the gem +/// `name`@`version`) is held to: ONE request. A restore has no copy to /// leave in force: with no list it fails, and says when to run it again. pub(super) async fn restore_list( - service: Option<&VendorServiceConfig>, + cfg: &VendorServiceConfig, fix: &str, - gem: &str, + name: &str, + version: &str, ) -> Result> { - let cfg = service - .filter(|cfg| cfg.service_enabled()) - .ok_or_else(|| Box::new(super::service_fetch::required()))?; - let name = gem.rsplit_once('@').map_or(gem, |(name, _)| name); + if !cfg.service_enabled() { + return Err(Box::new(super::service_fetch::required())); + } read_fix_list(cfg, fix, name).await?.ok_or_else(|| { + let gem = format!("{name}@{version}"); ServicePolicy::Refused.unserved( super::VENDOR_PREBUILT_PENDING, - format!("{}; run this again later", no_builds_listed(gem)), + format!("{}; run this again later", no_builds_listed(&gem)), ) }) } @@ -2518,7 +2664,7 @@ pub(super) async fn recorded_list_moved( builds: &[GemBuildEntry], ) -> Option { let gem = format!("{name}@{version}"); - let list = restore_list(Some(cfg), fix, &gem).await.ok()?; + let list = restore_list(cfg, fix, name, version).await.ok()?; let trees = PlatformTrees { gem: &gem, from: BuildsFrom::Recorded(builds, &list), @@ -2853,10 +2999,9 @@ async fn stage_platform_builds( use futures_util::StreamExt as _; let policy = ServicePolicy::Refused; let platforms: Vec<&str> = match &trees.from { - BuildsFrom::Locked(platforms) | BuildsFrom::Listed(platforms, _) => { - platforms.iter().map(String::as_str).collect() - } + BuildsFrom::Locked(platforms) => platforms.iter().map(String::as_str).collect(), BuildsFrom::Recorded(builds, _) => builds.iter().map(|b| b.platform.as_str()).collect(), + BuildsFrom::Listed(sources) => sources.iter().map(|s| s.platform.as_str()).collect(), }; // SECURITY: a platform names a directory under the stage, and the // ledger a restore reads them from is committed, tamper-able data. @@ -2871,7 +3016,7 @@ async fn stage_platform_builds( locked_build_sources(cfg, &record.uuid, name, trees, platforms).await? } BuildsFrom::Recorded(builds, list) => recorded_build_sources(name, trees, builds, list)?, - BuildsFrom::Listed(platforms, list) => listed_sources(list, name, trees, platforms)?, + BuildsFrom::Listed(sources) => sources.to_vec(), }; let builds = served_builds(cfg, name, trees, &sources).await?; @@ -3136,7 +3281,7 @@ const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; /// /// A `.gitignore` the patch itself rewrites is left as the patch has it /// (its hash is the record's); what it ignores is then for -/// [`keep_platform_trees_committable`] to refuse. Returns the paths +/// [`finish_platform_copy`] to refuse. Returns the paths /// emptied, relative to `tree`. async fn empty_shipped_gitignores( tree: &Path, @@ -3218,8 +3363,8 @@ async fn build_artifact( /// is the verified patched gem of each platform of `trees`, each from its /// own patch, staged in full and then swapped into place, so a failure /// leaves any pre-existing (possibly live-wired) copy untouched and no -/// husk behind. The uuid dir's git metadata is the caller's to write -/// ([`restore_uuid_metadata`]): `copy_dir` may itself sit in a stage +/// husk behind. The copy is the caller's to finish, with the uuid dir's +/// git metadata ([`finish_platform_copy`]): `copy_dir` may itself sit in a stage /// (`repair`'s restore). Returns what the ledger records of each tree. #[allow(clippy::too_many_arguments)] pub(super) async fn gem_platform_service_copy( @@ -3273,45 +3418,6 @@ pub(crate) async fn restore_uuid_metadata(uuid_dir: &Path) -> std::io::Result>, - warnings: &mut Vec, -) -> Result<(), VendorOutcome> { - let Some(inventory) = inventory else { - return Ok(()); - }; - let mut paths: Vec = inventory - .keys() - .map(|file| format!("{copy_rel}/{file}")) - .collect(); - if let Some((uuid_dir_rel, _)) = copy_rel.rsplit_once('/') { - paths.push(format!("{uuid_dir_rel}/.gitignore")); - paths.push(format!("{uuid_dir_rel}/.gitattributes")); - } - match super::npm_dir::gitignore_probe(project_root, &paths).await { - Ok(Some(rules)) => Err(refused( - super::npm_dir::GITIGNORED, - super::npm_dir::gitignored_detail(copy_rel, &rules), - )), - Ok(None) => Ok(()), - Err(why) => { - warnings.push(VendorWarning::new( - super::npm_dir::GITIGNORE_UNCHECKED, - super::npm_dir::gitignore_unchecked_detail(copy_rel, &why), - )); - Ok(()) - } - } -} - /// A dry run's check of a gem the lock pins as platform gems: the whole /// download, verification and unpacking of [`gem_platform_service_copy`], /// into a scratch directory. Returns what the wet run's ledger entry @@ -3375,7 +3481,7 @@ pub enum LockedBuildsPreview { /// tree the ledger records (a patched build published since, upstream's /// gem where the patched build was withdrawn), and serves each patched /// build it names, the wet run vendors the copy again with those -/// ([`moved_list`]). +/// ([`moved_sources`]). /// /// `None` for a gem this does not judge, so the caller's own verdict /// stands: one the lock does not name as platform gems, one whose lock is @@ -3423,8 +3529,8 @@ pub async fn preview_locked_builds( held: Vec::new(), }; let (name, copy_rel) = (prelude.name.as_str(), prelude.copy_rel.as_str()); - let list = moved_list(project_root, service, uuid, name, copy_rel, &trees).await?; - let sources = listed_sources(&list, name, &trees, &prelude.platforms).ok()?; + let moved = moved_sources(project_root, service, uuid, name, copy_rel, &trees, None); + let sources = moved.await?; let cfg = service.filter(|cfg| cfg.service_enabled())?; let served = served_builds(cfg, name, &trees, &sources).await; return served.is_ok().then(|| builds_of(sources)); @@ -3470,16 +3576,12 @@ pub async fn preview_locked_builds( /// Acquire a verified service copy without replacing the prior copy on /// failure: the gem's own tree, or one patched platform gem's tree per /// platform of `trees` when the lock pins the gem as platform gems. -/// Those trees get the uuid dir's git metadata once they are in place -/// ([`write_uuid_metadata_or_warn`]; `copy_rel` names the copy in its -/// warning): it is not part of the copy, so the trees are in place and -/// correct whether or not it can be written. Returns what the ledger -/// records of each such tree, with the result. +/// Those trees are then the caller's to finish ([`finish_platform_copy`]). +/// Returns what the ledger records of each such tree, with the result. #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, copy_dir: &Path, - copy_rel: &str, uuid_dir: &Path, name: &str, trees: &PlatformTrees<'_>, @@ -3514,7 +3616,6 @@ async fn materialise_patched_copy( warnings, ) .await?; - write_uuid_metadata_or_warn(uuid_dir, copy_rel, warnings).await; } } Ok(( @@ -14353,25 +14454,36 @@ mod tests { assert_eq!(ts::tree_snapshot(&root), ledgered); } - /// The git metadata of the uuid dir is not part of the copy. It is - /// written once the new trees are in place, and a write that fails - /// is a warning, never a failure: the trees are in place and - /// correct, the entry handed back records them, and nothing is - /// said of a copy left as it was. The same for a first vendor and - /// for a damaged copy, which is rebuilt all the same. + /// The git metadata of the uuid dir is not part of the copy. Every + /// path that puts the trees in place, or says they stay in force, + /// finishes the copy the same way: a write of it that fails is a + /// warning, never a failure, that names the two files and says to + /// make them writable. The trees are in place and correct, and the + /// entry handed back records them. A skip, which carries no + /// advisory, ends its line with it. #[tokio::test] - async fn metadata_that_cannot_be_written_is_a_warning_and_the_trees_are_in_place() { + async fn metadata_that_cannot_be_written_is_a_warning_on_every_path() { let (_tmp, root, record) = project(&lock(None)).await; // A directory where the file belongs: every write of it fails. - let gitattributes = root.join(format!(".socket/vendor/gem/{UUID}/.gitattributes")); + let uuid_rel = format!(".socket/vendor/gem/{UUID}"); + let gitattributes = root.join(&uuid_rel).join(".gitattributes"); tokio::fs::create_dir_all(gitattributes.join("in the way")) .await .unwrap(); - let unchecked = "could not check whether git would commit the vendored artifact"; let linux = root.join(rel(UUID)).join(LINUX); - let warned = |warnings: &[VendorWarning]| { - let unchecked = crate::vendor::npm_dir::GITIGNORE_UNCHECKED; - warnings.iter().any(|w| w.code == unchecked) + let said = format!( + "could not write `{uuid_rel}/.gitignore` and `{uuid_rel}/.gitattributes` (" + ); + let remedy = "make those two files writable and run this again"; + let warned = |warnings: &[VendorWarning]| -> bool { + let of_it: Vec<&VendorWarning> = warnings + .iter() + .filter(|w| w.code == GEM_GIT_METADATA_UNWRITTEN) + .collect(); + let gitignore = warnings.iter().filter(|w| w.code.contains("gitignore")); + matches!(of_it.as_slice(), [w] if w.detail.starts_with(&said) + && w.detail.ends_with(remedy)) + && gitignore.count() == 0 }; // A first vendor: vendored, wired and recorded, with the warning. @@ -14385,37 +14497,44 @@ mod tests { assert!(text(root.join(GEMFILE_LOCK)).await.contains("PATH\n")); ts::persist(&root, NOKO, entry).await; + // The copy in step: left as it is, with the warning alone. + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + assert!(warned(&warnings) && warnings.len() == 1, "{warnings:?}"); + + // A skip while the copy stays in force ends its line with it. + let prelude = gem_prelude(NOKO, ¬_installed(&root), &root, &record) + .await + .unwrap_or_else(|_| panic!("the prelude of a wired gem")); + let pending = refused( + crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING, + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java" + .to_string(), + ); + let settled = wired_copy_failed(pending, false, &root, &record, &prelude, false).await; + let (code, detail) = unwrap_refused(settled); + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!( + detail.starts_with(&format!( + "nokogiri@1.18.10 was not brought up to date: no patched build yet for java; \ + its vendored copy stays in force as it is. Also: {said}" + )) && detail.ends_with(&format!("{remedy}.")), + "{detail}" + ); + // The list moved: the copy takes the build that was published. let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; let (result, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); - assert_eq!( - codes - .iter() - .filter(|code| code.contains("gitignore")) - .count(), - 1, - "{warnings:?}" - ); assert!( - codes.contains(&crate::vendor::npm_dir::GITIGNORE_UNCHECKED) + warned(&warnings) && codes.contains(&GEM_LIST_FOLLOWED) && !codes.contains(&GEM_LIST_NOT_FOLLOWED), "{warnings:?}" ); - let said = warnings - .iter() - .find(|w| w.code == crate::vendor::npm_dir::GITIGNORE_UNCHECKED) - .expect("the warning"); - assert!( - said.detail.starts_with(unchecked) - && said - .detail - .contains("cannot write the vendored dir's git metadata"), - "{said:?}" - ); let entry = entry.expect("the entry of the trees that are in place"); assert_eq!( entry.gem_builds, @@ -14425,17 +14544,24 @@ mod tests { let patched = tokio::fs::read(linux.join(RB)).await.unwrap(); assert_eq!(patched, stamped(LINUX), "the patched build"); ts::persist(&root, NOKO, entry).await; + let entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); - // A damaged copy is rebuilt while the metadata stays unwritable. + // A damaged copy is restored, and rebuilt, while the metadata + // stays unwritable. + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let restored = crate::vendor::redownload::restore(&root, &entry, &record, &cfg).await; + let warnings = restored.expect("a restore never fails over the metadata"); + assert!(warned(&warnings), "{warnings:?}"); + assert_eq!( + tokio::fs::read(linux.join(RB)).await.unwrap(), + stamped(LINUX) + ); tokio::fs::remove_dir_all(&linux).await.unwrap(); let (result, entry, warnings) = unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); assert!(result.success, "{:?}", result.error); assert!( - warnings - .iter() - .any(|w| w.code == crate::vendor::npm_dir::GITIGNORE_UNCHECKED) - && warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), + warned(&warnings) && warnings.iter().any(|w| w.code == "vendor_artifact_rebuilt"), "{warnings:?}" ); assert!(entry.is_some(), "the rebuilt copy's entry"); @@ -14443,6 +14569,98 @@ mod tests { assert_eq!(rebuilt, stamped(LINUX), "rebuilt"); } + /// A copy git would not commit is refused wherever it is finished, + /// and the refusal names its cause: a project rule ignores the + /// binaries (`*.so`), and the uuid dir's own `.gitignore`, which + /// keeps such a rule off them, could not be written. A first + /// vendor removes what it made; a copy the lock already names + /// stays where it is. Once git tracks the copy it keeps committing + /// it whatever the rules say, and what is left is the warning. + #[tokio::test] + async fn a_copy_git_would_not_commit_is_refused_wherever_it_is_finished() { + let uuid_rel = format!(".socket/vendor/gem/{UUID}"); + let cause = format!( + "`{uuid_rel}/.gitignore` and `{uuid_rel}/.gitattributes`, which keep such a rule \ + off it, could not be written (" + ); + let refused_for_it = |outcome: VendorOutcome| { + let (code, detail) = unwrap_refused(outcome); + assert_eq!(code, "vendor_artifact_gitignored", "{detail}"); + assert!( + detail.starts_with("git would not commit the vendored artifact at") + && detail.contains(&cause) + && detail.ends_with("make those two files writable and vendor again"), + "{detail}" + ); + }; + let obstruct = |root: &Path| { + let gitignore = root.join(&uuid_rel).join(".gitignore"); + let _ = std::fs::remove_file(&gitignore); + std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); + }; + + // A first vendor: refused, and nothing of it is left. + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, "*.so\n").is_none() { + return; // no git, nothing to commit + } + obstruct(&root); + let wired_before = text(root.join(GEMFILE_LOCK)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(!root.join(&uuid_rel).exists(), "the copy is removed"); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, wired_before); + + // A copy the lock names: in step, restored and rebuilt. + let entry = vendor_and_persist(&root, &record, &cfg).await; + obstruct(&root); + let before = ts::tree_snapshot(&root); + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert_eq!( + ts::tree_snapshot(&root), + before, + "in step: nothing is touched" + ); + let linux = root.join(rel(UUID)).join(LINUX); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) + .await + .expect_err("a restored copy git would not commit"); + assert!( + failed.detail().starts_with("vendor_artifact_gitignored: ") + && failed.detail().contains(&cause), + "{failed}" + ); + assert_eq!( + ts::tree_snapshot(&root), + before, + "the trees are back in place" + ); + let (_server, moved) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + refused_for_it(vendor(&root, ¬_installed(&root), &record, &moved, false).await); + let patched = tokio::fs::read(linux.join(RB)).await.unwrap(); + assert_eq!(patched, stamped(LINUX), "the new trees stay in place"); + + // Tracked, git keeps committing the copy: the warning is left. + let git = crate::utils::process::resolve_tool("git").expect("git"); + let added = std::process::Command::new(git) + .arg("-C") + .arg(&root) + .args(["add", "-f", ".socket"]) + .status() + .expect("git add"); + assert!(added.success(), "git add"); + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &moved, false).await); + assert!(result.success, "{:?}", result.error); + assert!( + warnings + .iter() + .any(|w| w.code == GEM_GIT_METADATA_UNWRITTEN), + "{warnings:?}" + ); + } + /// A rebuild that fails leaves no uuid dir behind where there was /// none: the metadata is written after the trees are in place, /// never before them. @@ -14470,10 +14688,13 @@ mod tests { /// A gem the lock names as platform gems is no position of the /// download plan, and each such gem a run finds vendored asks for /// the list of its own fix, live: ONE request, which names that - /// fix alone, and nothing downloaded for a copy in step. With no - /// answer the copy stands and nothing is said. A copy whose list - /// moved is vendored from the list that was read to find that - /// out, so the fix's reference is asked for once. + /// fix alone, and nothing downloaded for a copy in step. The + /// question is advisory: with no answer the copy stands, nothing + /// is said, and the circuit breaker is not touched, so a service + /// that is down for these reads cannot fail what the run really + /// has to vendor. A copy whose list moved is vendored from the + /// list that was read to find that out, so the fix's reference is + /// asked for once. #[tokio::test] async fn each_vendored_gem_asks_for_the_list_of_its_own_fix() { let (_tmp, root, record) = project(&lock(None)).await; @@ -14497,14 +14718,29 @@ mod tests { ); assert_eq!(ts::request_count(&server).await, 1, "nothing is downloaded"); - // No answer: the copy stands with nothing said. + // No answer (the service is unavailable): the copy stands with + // nothing said, each read is one request, and after any number + // of them the breaker is closed. let down = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::method("POST")) + .respond_with(wiremock::ResponseTemplate::new(503)) + .mount(&down) + .await; let cfg = ts::service_cfg(&down.uri(), crate::vendor::VendorSource::Service, false); let before = ts::tree_snapshot(&root); - let (again, entry, warnings) = - unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert!(again.success, "{:?}", again.error); - assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + for asked in 1..=3 { + let (again, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(again.success, "{:?}", again.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + assert_eq!(ts::request_count(&down).await, asked); + } + let client = cfg.client.as_ref().expect("the service's client"); + assert_eq!( + client.vendor_outage_count(), + 0, + "the breaker is not touched" + ); assert_eq!(ts::tree_snapshot(&root), before); // The list moved: the rebuild takes the gems the list was read @@ -14521,13 +14757,17 @@ mod tests { assert_eq!(fixes.count(), 1, "{asked:?}"); } - /// A damaged copy whose list moved: the exact restore is refused - /// over the list it read, and hands that list on. The backend - /// vendors the copy again from it and does not ask for the fix's - /// reference again, wet or dry, so the two read one answer. + /// A restore reads the list of the gem's fix once and hands it on, + /// whether it is refused over that list or restores the copy, and + /// the backend does not ask for the fix's reference again, wet or + /// dry: a damaged copy whose list moved is vendored again from the + /// list the restore read, and a restored copy is judged in step by + /// it. A list of another fix is not used: the backend asks. #[tokio::test] - async fn a_refused_restore_hands_its_list_to_the_rebuild() { - use crate::vendor::redownload::{restore, restore_refused_over, RestoreError}; + async fn a_restore_hands_the_list_it_read_to_the_backend() { + use crate::vendor::redownload::{ + restore_refused_over, restore_with_list, RestoreError, + }; let (_tmp, root, record) = project(&lock(None)).await; let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; let entry = vendor_and_persist(&root, &record, &cfg).await; @@ -14546,7 +14786,7 @@ mod tests { let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; let list = match dry_run { true => restore_refused_over(&entry, &record, &cfg).await, - false => match restore(&root, &entry, &record, &cfg).await { + false => match restore_with_list(&root, &entry, &record, &cfg).await { Err(RestoreError::ListMoved(_, list)) => Some(list), other => panic!("the restore is refused over the list: {other:?}"), }, @@ -14570,7 +14810,8 @@ mod tests { &mut previewed, ) .await; - let (result, rebuilt, _) = unwrap_done(outcome); + let (result, rebuilt_entry, _) = unwrap_done(outcome); + let rebuilt = rebuilt_entry.clone(); assert!(result.success, "dry run {dry_run}: {:?}", result.error); assert_eq!( fix_requests(reference_requests(&server).await), @@ -14594,7 +14835,64 @@ mod tests { "dry run {dry_run}: vendored from the list that was handed over" ); assert_eq!(linux.exists(), !dry_run, "dry run {dry_run}"); + if !dry_run { + ts::persist(&root, NOKO, rebuilt_entry.expect("the wet run's entry")).await; + } } + + // A restore that succeeds hands its list on too: the copy it + // put back is found in step by that list, with no request. + let entry = crate::vendor::load_state(&root).await.unwrap().entries[NOKO].clone(); + tokio::fs::remove_dir_all(&linux).await.unwrap(); + let (server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let (_, list) = restore_with_list(&root, &entry, &record, &cfg) + .await + .expect("the list did not move: the copy is restored"); + let list = list.expect("the list the restore read"); + assert!(linux.exists(), "restored"); + let asked = ts::request_count(&server).await; + let in_step = |list: Option| { + let (root, record, cfg) = (root.clone(), record.clone(), cfg.clone()); + async move { + let blobs = root.join("no-blobs"); + let outcome = vendor_gem_previewing( + NOKO, + not_installed(&root).as_path(), + &root, + &record, + &PatchSources::blobs_only(&blobs), + "2026-06-09T00:00:00Z", + false, + false, + Some(&cfg), + false, + list.as_ref(), + &mut Vec::new(), + ) + .await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "{:?}", result.error); + assert!(entry.is_none() && warnings.is_empty(), "{warnings:?}"); + } + }; + in_step(Some(list.clone())).await; + assert_eq!( + ts::request_count(&server).await, + asked, + "judged by the list the restore read" + ); + // The list of another fix says nothing of this gem. + let foreign = FixList { + fix: UUID_B.to_string(), + ..list + }; + in_step(Some(foreign)).await; + assert_eq!( + reference_requests(&server).await.last(), + Some(&vec![UUID.to_string()]), + "the backend asks for its own fix's list" + ); + assert_eq!(ts::request_count(&server).await, asked + 1); } /// A gem that is left as it is whatever its gems are is never diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 061bafe63f..10fbfa08d6 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -138,6 +138,21 @@ pub async fn restore( record: &PatchRecord, service: &VendorServiceConfig, ) -> Result, RestoreError> { + let restored = restore_with_list(root, entry, record, service).await; + restored.map(|(warnings, _)| warnings) +} + +/// [`restore`], which also hands back the list of the gem's fix it read +/// for a gem vendored as platform gems (`None` for every other entry). A +/// run that goes on to the gem's backend hands it that list, so the copy +/// is restored and then judged by one answer. +pub async fn restore_with_list( + root: &Path, + entry: &VendorEntry, + record: &PatchRecord, + service: &VendorServiceConfig, +) -> Result<(Vec, Option), RestoreError> { + let mut gem_list = None; let ecosystem = super::ecosystem_dir_for_purl(&entry.base_purl); if ecosystem != Some(layout::ledger_ecosystem(&entry.ecosystem)) { return Err("ledger package identity does not match its artifact ecosystem".into()); @@ -332,12 +347,12 @@ pub async fn restore( .await .map_err(|outcome| detail(*outcome))?, builds => { - let gem = format!("{name}@{version}"); - let list = super::gem::restore_list(Some(service), &record.uuid, &gem) + let fix = record.uuid.as_str(); + let list = super::gem::restore_list(service, fix, &name, &version) .await .map_err(|outcome| detail(*outcome))?; let trees = super::gem::PlatformTrees { - gem: &gem, + gem: &format!("{name}@{version}"), from: super::gem::BuildsFrom::Recorded(builds, &list), standing: super::gem::Standing::Wired, held: Vec::new(), @@ -361,6 +376,7 @@ pub async fn restore( false => RestoreError::Failed(detail), }); } + gem_list = Some(list); } } } @@ -496,16 +512,23 @@ pub async fn restore( .map_err(|e| e.to_string())?; } } - // Likewise a gem vendored as platform gems: only the artifact dir was - // swapped in from the stage, and without the uuid dir's own metadata a - // `*.so` / `*.bundle` rule drops the compiled binaries from the commit. - let archive = super::gem::bazel::is_archive(entry); - if entry.ecosystem == "gem" && (archive || !entry.gem_tree_platforms().is_empty()) { + // Likewise a gem committed as its archive: only the artifact was + // swapped in from the stage. + if entry.ecosystem == "gem" && super::gem::bazel::is_archive(entry) { if let Some(rel) = super::path::vendor_uuid_dir_rel("gem", &entry.uuid) { super::gem::restore_uuid_metadata(&root.join(rel)) .await .map_err(|e| format!("cannot restore the vendored dir's git metadata: {e}"))?; } + } else if entry.ecosystem == "gem" && !entry.gem_tree_platforms().is_empty() { + // A gem vendored as platform gems is finished as on every other + // path that puts its trees in place: the uuid dir's metadata (a + // write that fails is a warning), then git's word on the commit. + let copy_rel = entry.artifact.path.replace('\\', "/"); + let inventory = entry.artifact.file_inventory.as_ref(); + super::gem::finish_platform_copy(root, ©_rel, inventory, false, &mut warnings) + .await + .map_err(detail)?; } // The jar that vendored mode keeps for the hub of a Bazel workspace // alone is one file of a directory that is a repository: the stage held @@ -513,7 +536,7 @@ pub async fn restore( if entry.flavor.as_deref() == Some(super::maven_repo::HUB_FLAVOR) { super::maven_repo::restore_hub_files(root, entry).await?; } - Ok(warnings) + Ok((warnings, gem_list)) } /// Rewrite an npm-family entry's `/.gitignore` and diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index 608f13ad48..033f3270ef 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -247,6 +247,28 @@ pub(crate) async fn fetch_served_reference( served_reference(outcome) } +/// [`fetch_served_reference`] as an advisory question, for a caller that +/// leaves things as they are when it gets no answer: one short attempt, +/// outside the retry ladder and the circuit breaker +/// ([`crate::api::client::ApiClient::fetch_vendor_reference_once`]). +pub(crate) async fn ask_served_reference( + cfg: &VendorServiceConfig, + uuid: &str, +) -> ServiceArtifact { + let Some(client) = cfg.client.as_ref() else { + return ServiceArtifact::Unavailable("vendor service not configured".to_string()); + }; + let outcome = client + .fetch_vendor_reference_once( + uuid, + cfg.use_public_proxy, + cfg.vendor_url.as_deref(), + cfg.patch_server_url.as_deref(), + ) + .await; + served_reference(outcome) +} + /// Why the service does not serve one patch of a /// [`fetch_served_references`] batch, when it answered for that patch: the /// status of the patch's own reference, which says nothing of the request. From a8b26e55423e7e8223f7fcb163f0e261439bd766 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 15:40:38 -0500 Subject: [PATCH 24/28] Document how a platform-locked copy is finished and that its list check is advisory The contract describes the one step every path ends a copy with, the new warning `vendor_gem_git_metadata_unwritten` in a row of its own, and the refusal that names it as the cause. The row of `vendor_artifact_gitignore_unchecked` is what it was: it never covered a write failure. The list request of a copy in step is described as what it is, one short attempt outside the circuit breaker, and a restore as handing its list on whether it restores the copy or is refused. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 7 ++++--- docs/ecosystems.md | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index b55efc111d..0ef5cc6ae8 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said (a patch service that does not answer stops being asked for the rest of the run once two requests in a row have failed, by the circuit breaker every vendor request shares), a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. The uuid directory's git metadata is not part of the copy: it is written once the new trees are in place, and a write of it that fails is the warning `vendor_artifact_gitignore_unchecked`, never a failure (the trees are in place and correct, and the ledger records them). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). The refused restore hands the list it read to that rebuild, so the two are decided by one answer and the fix's reference is asked for once. Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. A damaged copy whose list did not move is restored as it was vendored, and the run then asks for the list once more, as it does for any copy it finds in step. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. The question is advisory, since the copy stands whatever the answer: it is one attempt of at most five seconds, never retried, and outside the circuit breaker the run's other requests share, so a patch service that is down costs such a run one short attempt per vendored platform gem and cannot fail what the run has to vendor. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. Every path that puts the trees in place, or says that they stay in force, finishes the copy the same way (a first vendor, a rebuild of a copy the lock is wired to, a restore, a copy found in step, a copy that stays in force). First it writes the uuid directory's `.gitignore` and `.gitattributes` where one is missing or changed. They are not part of the copy, so a write that fails is the warning `vendor_gem_git_metadata_unwritten`, which names the two files and says to make them writable, and never a failure: the trees are in place and correct, and the ledger records them. Then it asks git whether it would commit every file of the copy, and a rule that keeps one out is the failure `vendor_artifact_gitignored`, which names the files that could not be written as its cause, and that remedy, when that is why. A first vendor removes the copy it made; a copy the lock already names stays where it is (after a rebuild the trees the list names are in place and the ledger still records the earlier ones, until a run vendors the copy again). For a copy that was already there git is asked with its index, since it keeps committing a file it tracks whatever the ignore rules say. A skip that leaves the copy in force carries no warning of its own and ends its line with it (`… stays in force as it is. Also: could not write …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). A restore hands the list it read to the gem's backend, whether it was refused over that list or restored the copy, so the copy is vendored again, or found in step, by the one answer the restore read, and the fix's reference is asked for once (a list of another fix is never used). Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2614,8 +2614,9 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. | -| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet, every PyPI flavor and a gem vendored as platform gems): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error), or the vendored directory's own `.gitignore` and `.gitattributes` could not be written (a PyPI wheel, a gem vendored as platform gems); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | +| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. A gem vendored as platform gems is asked about on every path that finishes its copy, not only when it is first vendored: a copy the lock already names is refused where it stands (it is not removed), git is then asked with its index, and a refusal that comes from the uuid directory's own `.gitignore` and `.gitattributes` not being writable names them and that remedy (see `vendor_gem_git_metadata_unwritten`). | +| `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | +| `vendor_gem_git_metadata_unwritten` | warning | vendor / scan / get `--mode vendored` and `repair` (a gem vendored as platform gems): the `.gitignore` and `.gitattributes` of the copy's uuid directory could not be written. Those two files keep a project ignore rule or filter (such as `*.so`, or a Git LFS rule) off the vendored binaries; they are not part of the copy, so the trees are in place and correct and the run does not fail. The detail names the two files and the error. Remedy: make them writable and run again. Said by every path that puts the trees in place or leaves them in force, once per run (a skip that leaves the copy in force ends its line with it). Where git would then not commit a file of the copy, the run fails instead with `vendor_artifact_gitignored`, which names these files as the cause. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | | `vendor_variant_ambiguous` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): the package is not installed and the manifest holds several release variants of it (`?artifact_id=` / `?platform=`), none of which the vendor ledger records, so nothing says which distribution to vendor; install the package or keep one release variant. A variant the ledger records (at any patch uuid) is taken as the wired one and its siblings are left out without an event. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index a28f3537b9..6cd3779fbb 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way: a single short attempt, which a patch service that is down cannot turn into a failure) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. A run that cannot write those two files says so and goes on (`vendor_gem_git_metadata_unwritten`: make them writable and run again); where git would then leave a binary out of the commit, the run fails and names them. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 0be8bc98dbf1c70814fb8d276faed7d2a2793f93 Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 16:42:14 -0500 Subject: [PATCH 25/28] Ask git about a platform-locked copy only where trees are about to be placed, before the swap The sixth review's findings came from asking git on every path that finishes a copy. That was wrong for a copy that is already committed. `finish_platform_copy` keeps its one write of the uuid directory's `.gitignore` and `.gitattributes` (a failure is the warning, never an error) and takes a mode in place of a flag: - `CopyStep::Placing`: a first vendor, a rebuild of a wired copy, a restore, and a dry run's preview of one. Git is asked BEFORE the staged trees are moved in, as if nothing were tracked, which does not read the index. With the uuid directory's own rules in place no rule above them reaches a file of the copy, so the question is whether a rule excludes the directory; where they could not be written it is asked of every staged file, and the refusal names that as its cause. A refusal leaves what is on disk as it was: a first vendor writes nothing, an intact copy whose list moved stays in force through the note that already says so, with the refusal as the reason, and a restore reports its failure with the copy as it was. A dry run asks the same question and writes nothing. - `CopyStep::Confirming`: a copy found in step or left in force. Git is asked nothing, as on the base branch. Before, a rebuild was refused only after the new trees were swapped in, which left an intact copy with trees the ledger did not record and exit 1, and made every later scan download the gems again. An in-step scan ran `git check-ignore` against the index for every file of the copy on every run, and could fail a copy in a project without a `.git` of its own. A run that did not place its trees leaves no uuid directory holding the metadata alone. Tests, at the core and CLI levels: a refusal on each path with the copy compared before and after, dry and wet alike; a committed copy whose list moves under a rule that excludes its directory stays byte for byte with one note that names the rule; a copy in step starts git for the run's own ledger check and nothing else, and a rebuild asks one question without the index, the same in a dry run (counted with a logging `git` on PATH); a copy in step in an ignored directory of an outer repository stands. Co-Authored-By: Claude Fable 5.2 --- .../vendor/vendor_gem_platform_builds_e2e.rs | 337 ++++++++++-- crates/socket-patch-core/src/vendor/gem.rs | 495 ++++++++++++------ .../src/vendor/redownload.rs | 26 +- 3 files changed, 653 insertions(+), 205 deletions(-) diff --git a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs index da88e62aa8..e70cd45a43 100644 --- a/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs +++ b/crates/socket-patch-cli/tests/vendor/vendor_gem_platform_builds_e2e.rs @@ -466,19 +466,24 @@ fn run(root: &Path, args: &[&str], api: &str) -> (i32, String, String) { /// [`run`] with the failure points `failing` (`SOCKET_PATCH_FAILPOINT`): /// each named step fails once, as a real fault there would. fn run_failing(root: &Path, args: &[&str], api: &str, failing: &str) -> (i32, String, String) { + run_in(root, args, api, &[("SOCKET_PATCH_FAILPOINT", failing)]) +} + +/// [`run`] with `env` set for the process. +fn run_in(root: &Path, args: &[&str], api: &str, env: &[(&str, &str)]) -> (i32, String, String) { run_with( root, args, api, &["--api-token", "fake-token", "--org", ORG], - Some(failing), + env, ) } /// [`run`] with the `credentials` flags in place of a token and its /// organisation. fn run_as(root: &Path, args: &[&str], api: &str, credentials: &[&str]) -> (i32, String, String) { - run_with(root, args, api, credentials, None) + run_with(root, args, api, credentials, &[]) } fn run_with( @@ -486,12 +491,10 @@ fn run_with( args: &[&str], api: &str, credentials: &[&str], - failing: Option<&str>, + env: &[(&str, &str)], ) -> (i32, String, String) { let mut cmd = hermetic::command(&binary()); - if let Some(failing) = failing { - cmd.env("SOCKET_PATCH_FAILPOINT", failing); - } + cmd.envs(env.iter().copied()); hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Bundle]); cmd.env_remove("GEM_HOME").env_remove("GEM_PATH"); crate::common::jvm_env::isolate_cli(&mut cmd); @@ -1626,6 +1629,11 @@ fn obstruct_gitignore(root: &Path) { std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); } +/// Whether a run's summary says it vendored the gem, or would. +fn says_it_vendors(stdout: &str) -> bool { + stdout.contains("Vendored 1 package.") || stdout.contains("Would vendor 1 package.") +} + /// What a run says of a copy git would not commit because the uuid /// directory's own ignore rules could not be written. fn assert_refused_for_unwritten_metadata(said: &str) { @@ -1641,15 +1649,16 @@ fn assert_refused_for_unwritten_metadata(said: &str) { ); } -/// Every path that puts the trees of a platform-locked gem in place, or -/// says they stay in force, finishes the copy the same way, so a copy git -/// would not commit is refused on each of them and the refusal names its -/// cause. Here a project rule ignores the binaries (`*.so`) and the uuid -/// directory's `.gitignore`, which keeps such a rule off them, cannot be -/// written. A first vendor removes what it made; a copy the lock already -/// names stays where it is. +/// Git is asked whether it would commit a copy only where trees are about +/// to be placed, before they are moved in, and a dry run asks the same. A +/// refusal leaves what is on disk as it was: a first vendor writes +/// nothing, an intact copy whose list moved stays in force with the +/// refusal as the reason, and a damaged copy is not restored. A copy that +/// is already there asks git nothing. Here a project rule ignores the +/// binaries (`*.so`) and the uuid directory's `.gitignore`, which keeps +/// such a rule off them, cannot be written. #[tokio::test] -async fn a_copy_git_would_not_commit_is_refused_on_every_path() { +async fn a_copy_git_would_not_commit_is_refused_before_its_trees_are_placed() { let check = ["vendor", "--check", "--json"]; let failed_with = |env: &serde_json::Value, code: &str| -> String { let failed = env["events"] @@ -1660,8 +1669,9 @@ async fn a_copy_git_would_not_commit_is_refused_on_every_path() { let failed = failed.unwrap_or_else(|| panic!("a failed `{code}` event: {env:#}")); failed["error"].as_str().unwrap_or_default().to_string() }; + let dry = with(VENDOR, &["--dry-run"]); - // 1. A first vendor: refused, and nothing of it is left. + // 1. A first vendor, dry and wet: refused, and nothing is written. let Some(project) = git_project_ignoring_binaries() else { return; // no git, nothing to commit }; @@ -1669,6 +1679,11 @@ async fn a_copy_git_would_not_commit_is_refused_on_every_path() { let lock_before = std::fs::read_to_string(root.join("Gemfile.lock")).unwrap(); let first = service(&[LINUX], &[DARWIN]).await; obstruct_gitignore(root); + let before = snapshot(root); + let (code, env, stderr) = run_json(root, &dry, &first.uri()); + assert_eq!(code, 1, "{env:#}\n{stderr}"); + assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!(snapshot(root), before, "a dry run writes nothing"); let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); @@ -1689,25 +1704,63 @@ async fn a_copy_git_would_not_commit_is_refused_on_every_path() { assert_eq!(code, 0, "{env:#}\n{stderr}"); obstruct_gitignore(root); let vendored = snapshot(root); + let warning = format!("Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and"); - // 2. In step: refused, nothing touched. - let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); - assert_eq!(code, 1, "{env:#}\n{stderr}"); - assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + // 2. In step: git is asked nothing. The copy stands, and the run says + // what it could not write. + let (code, stdout, stderr) = run(root, VENDOR_IT, &first.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stdout.contains("1 package is already vendored; nothing to do."), + "{stdout}" + ); + assert!( + stderr.contains(&warning) && !stderr.contains("Error:"), + "{stderr}" + ); assert_eq!(snapshot(root), vendored, "in step"); // 3. A build the list names is not served yet: the copy stays in - // force, and is refused all the same. + // force, and the skip's line ends with the same. let building = service_still_building_darwin().await; - let (code, env, stderr) = run_json(root, VENDOR, &building.uri()); - assert_eq!(code, 1, "{env:#}\n{stderr}"); - assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + let (code, stdout, stderr) = run(root, VENDOR_IT, &building.uri()); + assert_eq!(code, 0, "{stdout}\n{stderr}"); + assert!( + stderr.contains("its vendored copy stays in force as it is. Also: could not write `"), + "{stderr}" + ); assert_eq!(snapshot(root), vendored, "a pending build"); - // 4. A damaged tree: `repair` restores it and refuses the copy, and - // so does the restore of a vendor run. + // 4. The list moved: the intact copy stays in force, byte for byte, + // dry and wet, and the note names the rule and the cause. + let moved = service(&[DARWIN, LINUX], &[]).await; + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let (code, stdout, stderr) = run(root, &args, &moved.uri()); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + let notes: Vec<&str> = stderr.lines().filter(|l| l.starts_with("Note:")).collect(); + assert!( + matches!(notes.as_slice(), [note] if note.starts_with(&format!( + "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ + registry lists (git would not commit the vendored artifact at" + )) && note.contains(".gitignore:1:*.so") + && note.ends_with("its vendored copy stays in force as it is.")), + "{args:?}: {stderr}" + ); + assert_refused_for_unwritten_metadata(&stderr); + assert!( + !stderr.contains("Error:") && !says_it_vendors(&stdout), + "{args:?}: {stdout}\n{stderr}" + ); + assert_eq!(snapshot(root), vendored, "{args:?}"); + } + let (code, env, stderr) = run_json(root, &check, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + // 5. A damaged tree: neither `repair` nor a vendor run moves in trees + // git would not commit, and the copy is as it was. + std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); + let damaged = snapshot(root); for restore in [&["repair", "--download-only", "--json"][..], VENDOR] { - std::fs::write(tree(root, LINUX).join(SO), b"damaged").unwrap(); let (code, env, stderr) = run_json(root, restore, &first.uri()); assert_ne!(code, 0, "{restore:?}: {env:#}\n{stderr}"); assert_refused_for_unwritten_metadata(&env.to_string()); @@ -1715,35 +1768,227 @@ async fn a_copy_git_would_not_commit_is_refused_on_every_path() { env.to_string().contains("vendor_artifact_gitignored"), "{restore:?}: {env:#}" ); - assert_eq!(snapshot(root), vendored, "{restore:?}: the tree is back"); - let (code, env, stderr) = run_json(root, &check, &first.uri()); - assert_eq!(code, 0, "{restore:?}: {env:#}\n{stderr}"); + assert_eq!( + snapshot(root), + damaged, + "{restore:?}: the copy is as it was" + ); } +} + +/// An intact copy that is committed, whose list moves while a project +/// rule would keep a new file out of the commit (one that excludes the +/// vendored directory, added since): the copy is byte for byte what it +/// was, the run ends as it does for an intact copy, and one note names +/// the rule. A dry run says the same. +#[tokio::test] +async fn a_committed_copy_stays_as_it_is_when_a_rule_would_ignore_what_its_list_names() { + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to commit + }; + let root = project.path(); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + git(root, &["add", "-f", "."]); + git( + root, + &[ + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "-q", + "-m", + "vendor", + ], + ); + std::fs::write(root.join(".gitignore"), "*.so\n/.socket/vendor/gem/\n").unwrap(); + let committed = snapshot(root); - // 5. The list moved: the copy is vendored again, and refused where it - // stands, with the trees the list names in place. let moved = service(&[DARWIN, LINUX], &[]).await; + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let (code, stdout, stderr) = run(root, &args, &moved.uri()); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + let notes: Vec<&str> = stderr.lines().filter(|l| l.starts_with("Note:")).collect(); + assert!( + matches!(notes.as_slice(), [note] if note.starts_with(&format!( + "Note: {NAME}@{VERSION} could not be brought in step with the builds the patch \ + registry lists (git would not commit the vendored artifact at" + )) && note.contains(".gitignore:2:/.socket/vendor/gem/") + && note.ends_with("its vendored copy stays in force as it is.")), + "{args:?}: {stderr}" + ); + let warned = stderr + .lines() + .any(|l| l.starts_with("Warning:") && !l.contains("--api-token")); + assert!( + !stderr.contains("Error:") && !warned && !says_it_vendors(&stdout), + "{args:?}: {stdout}\n{stderr}" + ); + assert_eq!(snapshot(root), committed, "{args:?}: byte for byte"); + } let (code, env, stderr) = run_json(root, VENDOR, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_eq!(env["summary"]["failed"], 0, "{env:#}"); + assert_eq!(env["summary"]["applied"], 0, "{env:#}"); + let check = ["vendor", "--check", "--json"]; + let (code, env, stderr) = run_json(root, &check, &moved.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); +} + +/// A project that was exported without its `.git` into a directory an +/// outer repository ignores (an artifact in `build/` of a CI workspace). +/// The gem's backend asks git nothing about a copy in step, so it adds +/// no refusal there: a scan's dry run finds the copy `already_vendored` +/// and exits 0. A wet scan still refuses such a project before it looks +/// at any package, as it does on the base branch and in 5.1.0, by the +/// run's own ledger check (`vendor_artifact_gitignored` for +/// `.socket/vendor`, by the outer rule): git would commit neither the +/// ledger nor the copy from there. What is pinned here is that the +/// refusal is that one, and not one of the gem's. +#[tokio::test] +async fn a_project_in_an_ignored_directory_of_an_outer_repository_is_refused_by_the_run_alone() { + 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.path().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } + } + let scan = with(SCAN_IT, &["--json"]); + let server = service(&[DARWIN, LINUX], &[]).await; + mount_search(&server).await; + let made = fresh_project(SCAN_IT); + let (code, env, stderr) = run_json(made.path(), &scan, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "applied", ""); + + let outer = tempfile::tempdir().unwrap(); + let init = std::process::Command::new("git") + .arg("-C") + .arg(outer.path()) + .args(["init", "-q"]) + .status(); + if !init.is_ok_and(|status| status.success()) { + return; // no git, nothing to ask + } + std::fs::write(outer.path().join(".gitignore"), "build/\n").unwrap(); + let root = outer.path().join("build/app"); + copy_tree(made.path(), &root); + let exported = snapshot(&root); + + let dry = with(SCAN_IT, &["--json", "--dry-run"]); + let (code, env, stderr) = run_json(&root, &dry, &server.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + assert_per_platform_gem(&env, "skipped", "already_vendored"); + assert!( + !env.to_string().contains("vendor_artifact_gitignored"), + "{env:#}" + ); + assert_eq!(snapshot(&root), exported, "the dry run"); + + let (code, env, stderr) = run_json(&root, &scan, &server.uri()); assert_eq!(code, 1, "{env:#}\n{stderr}"); - assert_refused_for_unwritten_metadata(&failed_with(&env, "vendor_artifact_gitignored")); + assert_eq!(env["status"], "error", "{env:#}"); assert_eq!( - std::fs::read(tree(root, DARWIN).join(LIB)).unwrap(), - stamped(DARWIN_UUID), - "the build the list names" + env["error"]["code"], "vendor_artifact_gitignored", + "{env:#}" ); - - // Tracked, git keeps committing the copy whatever the rules say: the - // run succeeds, and says what could not be written. - git(root, &["add", "-f", ".socket"]); - let (code, stdout, stderr) = run(root, VENDOR_IT, &moved.uri()); - assert_eq!(code, 0, "{stdout}\n{stderr}"); + let message = env["error"]["message"].as_str().unwrap_or_default(); assert!( - stderr.contains(&format!( - "Warning: could not write `.socket/vendor/gem/{UUID}/.gitignore` and" - )) && stderr.contains("make those two files writable and run this again"), - "{stderr}" + message.starts_with( + "git would not commit the vendored artifact at .socket/vendor (.gitignore:1:build/" + ), + "the run's own check, of the vendor directory: {message}" + ); + assert!( + env["events"].as_array().is_some_and(Vec::is_empty), + "no package was looked at: {env:#}" + ); + assert_eq!(snapshot(&root), exported); +} + +/// A run that finds a copy in step starts git for its own ledger check +/// and for nothing else: the copy asks git nothing. A run that is about +/// to place trees asks, and never with the index. Counted with a `git` +/// first on `PATH` that logs each call and hands it on. +#[cfg(unix)] +#[tokio::test] +async fn a_copy_in_step_asks_git_nothing() { + use std::os::unix::fs::PermissionsExt as _; + let Some(project) = git_project_ignoring_binaries() else { + return; // no git, nothing to count + }; + let root = project.path(); + let first = service(&[LINUX], &[DARWIN]).await; + let (code, env, stderr) = run_json(root, VENDOR, &first.uri()); + assert_eq!(code, 0, "{env:#}\n{stderr}"); + + let path = std::env::var("PATH").unwrap_or_default(); + let real = std::env::split_paths(&path) + .map(|dir| dir.join("git")) + .find(|git| git.is_file()) + .expect("git on PATH"); + let shim = tempfile::tempdir().unwrap(); + let log = shim.path().join("calls.log"); + let script = format!( + "#!/bin/sh\necho \"$@\" >> '{}'\nexec '{}' \"$@\"\n", + log.display(), + real.display() + ); + let git_shim = shim.path().join("git"); + std::fs::write(&git_shim, script).unwrap(); + std::fs::set_permissions(&git_shim, std::fs::Permissions::from_mode(0o755)).unwrap(); + let shimmed = format!("{}:{path}", shim.path().display()); + let calls = || std::fs::read_to_string(&log).unwrap_or_default(); + // What every vendored run asks of git, whatever it finds: whether the + // vendor directory and its ledger would be committed. + let ledger_check = "-C . rev-parse --is-inside-work-tree\n-C . check-ignore -v -z --stdin\n"; + + // In step, wet and dry. + for args in [VENDOR_IT.to_vec(), with(VENDOR_IT, &["--dry-run"])] { + let _ = std::fs::remove_file(&log); + let (code, stdout, stderr) = run_in(root, &args, &first.uri(), &[("PATH", &shimmed)]); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + assert!(stdout.contains("already vendored"), "{args:?}: {stdout}"); + assert_eq!( + calls(), + ledger_check, + "{args:?}: the run's ledger check, and nothing for the copy" + ); + } + + // The list moved: trees are about to be placed, so git is asked about + // them, dry and wet alike and never with its index. + let moved = service(&[DARWIN, LINUX], &[]).await; + let mut asked_each = Vec::new(); + for args in [with(VENDOR_IT, &["--dry-run"]), VENDOR_IT.to_vec()] { + let _ = std::fs::remove_file(&log); + let (code, stdout, stderr) = run_in(root, &args, &moved.uri(), &[("PATH", &shimmed)]); + assert_eq!(code, 0, "{args:?}: {stdout}\n{stderr}"); + assert!(says_it_vendors(&stdout), "{args:?}: {stdout}"); + let asked = calls(); + let about_the_copy = asked.strip_prefix(ledger_check).unwrap_or_default(); + assert_eq!( + about_the_copy, + "-C . rev-parse --is-inside-work-tree\n-C . check-ignore -v -z --stdin --no-index\n", + "{args:?}: one question about the trees, without the index: {asked}" + ); + asked_each.push(asked); + } + assert_eq!( + asked_each[0], asked_each[1], + "a dry run asks what the wet run asks" ); - assert!(!stderr.contains("Error:"), "{stderr}"); } /// The same paths with no rule that ignores the copy: the files that diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index ed96b134b3..3b3319aad0 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -796,7 +796,7 @@ async fn gem_prelude_of( // it, so the commit would drop the trees the lock names: refused here, // dry run or not, before anything is downloaded. Rules that ignore // single files are for [`finish_platform_copy`], once the trees are - // known. + // staged. let in_sync = lock_wired && copy_ok; if !locked.platforms.is_empty() && !in_sync { if let Some((code, detail)) = @@ -1379,14 +1379,14 @@ pub async fn vendor_gem_previewing<'a>( }; if lock_wired { if copy_ok && moved.is_none() { - return match copy_in_force(project_root, record, &prelude, true, dry_run).await { - Some(Err(refusal)) => refusal, - finished => done( - already_patched_result(purl, copy_dir, &record.files), - None, - finished.and_then(Result::ok).unwrap_or_default(), - ), - }; + let warnings = copy_in_force(project_root, record, &prelude, true, dry_run) + .await + .unwrap_or_default(); + return done( + already_patched_result(purl, copy_dir, &record.files), + None, + warnings, + ); } // Wired (Gemfile + lock + CHECKSUMS) but the committed copy is // missing/stale: rebuild the ARTIFACT only — the pair edit is @@ -1404,6 +1404,7 @@ pub async fn vendor_gem_previewing<'a>( let mut warnings: Vec = Vec::new(); let materialised = materialise_patched_copy( purl, + (project_root, copy_rel), copy_dir, uuid_dir, name, @@ -1456,16 +1457,6 @@ pub async fn vendor_gem_previewing<'a>( // first run's records, the only copy of the pre-vendor originals. let file_inventory = inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; - // The new trees are in place, and the lock names them: one git - // would not commit is refused where it stands. - if !platforms.is_empty() { - let inventory = file_inventory.as_ref(); - let finished = - finish_platform_copy(project_root, copy_rel, inventory, false, &mut warnings); - if let Err(refusal) = finished.await { - return refusal; - } - } let entry = gem_entry( build_gem_purl(name, version), record, @@ -1494,8 +1485,14 @@ pub async fn vendor_gem_previewing<'a>( [] => super::service_fetch::preview_service(service, record, extract_gem_data) .await .map(|()| Vec::new()), - _ if lock_wired => preview_platform_builds(service, record, name, &wired).await, - _ => preview_platform_builds(service, record, name, &locked(standing)).await, + _ => { + let trees = match lock_wired { + true => wired, + false => locked(standing), + }; + let place = (project_root, copy_rel); + preview_platform_builds(service, record, name, &trees, place).await + } }; match checked { Ok(builds) => *previewed = builds, @@ -1536,6 +1533,7 @@ pub async fn vendor_gem_previewing<'a>( } let (mut result, builds) = match materialise_patched_copy( purl, + (project_root, copy_rel), copy_dir, uuid_dir, name, @@ -1557,26 +1555,13 @@ pub async fn vendor_gem_previewing<'a>( } result.package_path = copy_dir.display().to_string(); - // ── prebuilt trees git would not commit ────────────────────────────── - // Asked before either project file is written (see - // `finish_platform_copy`). The inventory taken for it is the entry's, - // below. + // The inventory of the platform trees, which the entry records below. + // (Whether git would commit them was asked before they were moved into + // place: `finish_platform_copy`.) let mut platform_inventory = None; if !platforms.is_empty() { let inventory = inventory_or_warn(copy_dir, &format!("{name}@{version}"), &mut warnings).await; - let finished = finish_platform_copy( - project_root, - copy_rel, - inventory.as_ref(), - true, - &mut warnings, - ); - if let Err(refusal) = finished.await { - let _ = remove_tree(uuid_dir).await; - prune_empty_vendor_levels(uuid_dir).await; - return refusal; - } platform_inventory = Some(inventory); } @@ -1754,19 +1739,19 @@ pub const GEM_LIST_NOT_FOLLOWED: &str = "vendor_gem_list_not_followed"; /// not read again; otherwise every tree the entry names is checked /// ([`recorded_copy_stands`]), as after an attempt to vendor the copy /// again, which can fail once the copy was already changed. A copy -/// vendored as platform gems that stands is then finished as every such -/// copy is ([`finish_platform_copy`], never by a dry run): the uuid dir's +/// vendored as platform gems that stands is then confirmed +/// ([`CopyStep::Confirming`], never by a dry run): the uuid dir's /// `.gitignore` and `.gitattributes` are put back where one is missing, -/// and git is asked whether it would commit the copy. `None` when the -/// copy does not stand; else what there is to say of it, or the refusal -/// of a copy git would not commit. +/// and git is asked nothing, since the copy is already what the project +/// commits. `None` when the copy does not stand; else what there is to +/// say of it. async fn copy_in_force( project_root: &Path, record: &PatchRecord, prelude: &GemPrelude, verified: bool, dry_run: bool, -) -> Option, VendorOutcome>> { +) -> Option> { let (copy_rel, copy_dir) = (prelude.copy_rel.as_str(), prelude.copy_dir.as_path()); let stands = verified || recorded_copy_stands(project_root, record, copy_rel, copy_dir, &prelude.name).await; @@ -1774,15 +1759,18 @@ async fn copy_in_force( return None; } let mut warnings: Vec = Vec::new(); - if prelude.platforms.is_empty() || dry_run { - return Some(Ok(warnings)); - } - let entry = recorded_copy(project_root, &record.uuid, copy_rel).await; - let inventory = entry - .as_ref() - .and_then(|entry| entry.artifact.file_inventory.as_ref()); - let finished = finish_platform_copy(project_root, copy_rel, inventory, false, &mut warnings); - Some(finished.await.map(|()| warnings)) + if !prelude.platforms.is_empty() && !dry_run { + // Confirming a copy refuses nothing. + let _ = finish_platform_copy( + project_root, + copy_rel, + CopyStep::Confirming, + false, + &mut warnings, + ) + .await; + } + Some(warnings) } /// Advisory of a copy vendored as platform gems whose uuid dir's @@ -1792,56 +1780,78 @@ async fn copy_in_force( /// files and says to make them writable. pub const GEM_GIT_METADATA_UNWRITTEN: &str = "vendor_gem_git_metadata_unwritten"; -/// Finish a copy vendored as platform gems whose trees are in place. Every -/// path that puts such trees in place, or says that they stay in force, -/// ends here: a first vendor, a rebuild of a copy the lock is wired to, a -/// restore, a copy found in step and one that stays in force. +/// What a run is doing with the copy it finishes ([`finish_platform_copy`]). +pub(super) enum CopyStep<'a> { + /// Trees are about to be moved into place: a first vendor, a rebuild of + /// a copy the lock is wired to, a restore, or a dry run's preview of + /// one. They are staged at this directory. + Placing(&'a Path), + /// The copy that is there stands: one found in step, or one left in + /// force. + Confirming, +} + +/// Finish a copy vendored as platform gems: the one step of every path +/// that is about to put such trees in place, or that says the ones that +/// are there stay. /// /// 1. The uuid dir's `.gitignore` and `.gitattributes` are written where /// absent or different ([`restore_uuid_metadata`]). They are not part /// of the copy, so a write that fails is never a failure: it is the -/// warning [`GEM_GIT_METADATA_UNWRITTEN`]. -/// 2. Git is asked whether it would commit every file of the trees -/// (`inventory`: the copy's files) and those two files. A rule that -/// keeps one of them out is the refusal `vendor_artifact_gitignored`, -/// which gives the files that could not be written as its cause, and -/// what to do about them, when that is why. Git failing to answer is -/// only a warning, and nothing is asked without an inventory, whose -/// absence is already reported. `fresh`: nothing of the copy was there -/// before this run (a first vendor), so git is asked as if none of it -/// were tracked. Otherwise the index counts: git keeps committing a -/// file it tracks whatever the ignore rules say. +/// warning [`GEM_GIT_METADATA_UNWRITTEN`]. A dry run writes nothing, +/// and says what it can tell of that write. +/// 2. Where trees are about to be placed ([`CopyStep::Placing`]), git is +/// asked whether it would commit them, BEFORE they are moved in, so a +/// refusal leaves what is on disk as it was. The question needs only +/// path names, and is asked as if nothing were tracked, which does not +/// read the index. With the uuid dir's own rules in place no rule +/// above them reaches a file of the copy, so what can keep the copy out +/// of a commit is a rule that excludes the directory itself. Without +/// them every rule of the project applies to every staged file, and +/// the refusal (`vendor_artifact_gitignored`) gives the files that +/// could not be written as its cause, with what to do about them. Git +/// failing to answer is only a warning. A dry run asks the same. /// -/// What a path does about the refusal is its own: a first vendor removes -/// the copy it just made; every other one has a copy the lock already -/// names, which stays where it is. +/// A copy that is already there ([`CopyStep::Confirming`]) is what the +/// project commits, and git is asked nothing about it. pub(super) async fn finish_platform_copy( project_root: &Path, copy_rel: &str, - inventory: Option<&BTreeMap>, - fresh: bool, + step: CopyStep<'_>, + dry_run: bool, warnings: &mut Vec, ) -> Result<(), VendorOutcome> { let Some((uuid_dir_rel, _)) = copy_rel.rsplit_once('/') else { return Ok(()); }; + let uuid_dir = project_root.join(uuid_dir_rel); let metadata = format!("`{uuid_dir_rel}/.gitignore` and `{uuid_dir_rel}/.gitattributes`"); - let unwritten = restore_uuid_metadata(&project_root.join(uuid_dir_rel)) - .await - .err(); - let ignoring = match inventory { - Some(inventory) => { - let mut paths: Vec = inventory - .keys() - .map(|file| format!("{copy_rel}/{file}")) - .collect(); - paths.push(format!("{uuid_dir_rel}/.gitignore")); - paths.push(format!("{uuid_dir_rel}/.gitattributes")); - super::npm_dir::ignoring_rule_lines(project_root, &paths, fresh).await + let unwritten: Option = match dry_run { + true => metadata_write_would_fail(&uuid_dir).await, + false => match restore_uuid_metadata(&uuid_dir).await { + Ok(_) => None, + Err(e) => Some(e.to_string()), + }, + }; + let ignoring = match (&step, &unwritten) { + (CopyStep::Confirming, _) => Ok(None), + (CopyStep::Placing(_), None) => { + super::npm_dir::gitignore_probe(project_root, &[format!("{uuid_dir_rel}/")]).await + } + (CopyStep::Placing(staged), Some(_)) => { + match super::verify::compute_dir_inventory(staged).await { + Ok(inventory) => { + let paths: Vec = inventory + .keys() + .map(|file| format!("{copy_rel}/{file}")) + .collect(); + super::npm_dir::gitignore_probe(project_root, &paths).await + } + // What could not be listed is already said of the copy. + Err(_) => Ok(None), + } } - None => Ok(None), }; - let ignoring = ignoring.map(|lines| lines.map(|lines| super::npm_dir::summarize_rules(&lines))); match (ignoring, unwritten) { (Ok(Some(rules)), None) => Err(refused( super::npm_dir::GITIGNORED, @@ -1877,6 +1887,42 @@ pub(super) async fn finish_platform_copy( } } +/// What a wet run's write of the uuid dir's `.gitignore` and +/// `.gitattributes` would fail on, as far as a dry run can tell without +/// writing: something that is not a regular file stands where one of them +/// belongs. +async fn metadata_write_would_fail(uuid_dir: &Path) -> Option { + for name in [".gitignore", ".gitattributes"] { + let there = tokio::fs::symlink_metadata(uuid_dir.join(name)).await; + if there.is_ok_and(|file| !file.is_file()) { + return Some(format!("{name} is not a regular file")); + } + } + None +} + +/// Remove a uuid dir that holds nothing but its git metadata, and the +/// vendor levels that leaves empty: a run that did not put its trees in +/// place leaves no such directory behind. +pub(super) async fn remove_metadata_alone(uuid_dir: &Path) { + let Ok(mut entries) = tokio::fs::read_dir(uuid_dir).await else { + return; + }; + let mut names = Vec::new(); + while let Ok(Some(entry)) = entries.next_entry().await { + names.push(entry.file_name()); + } + if names + .iter() + .all(|name| name == ".gitignore" || name == ".gitattributes") + { + for name in &names { + let _ = tokio::fs::remove_file(uuid_dir.join(name)).await; + } + prune_empty_vendor_levels(uuid_dir).await; + } +} + /// The outcome of a copy the lock is ALREADY wired to that this run could /// not vendor again (`failure`: the refusal, or the result that did not /// succeed). What is said depends on whether the copy the ledger records @@ -1910,12 +1956,9 @@ async fn wired_copy_failed( } let in_force = copy_in_force(project_root, record, prelude, false, dry_run).await; match (failure, in_force) { - // The copy that stays in force is one git would not commit: that - // is what the run has to say of it. - (_, Some(Err(refusal))) => refusal, // A skip carries no advisory of its own: what there is to say of // the copy ends its line. - (VendorOutcome::Refused { code, detail }, Some(Ok(warnings))) if pending => { + (VendorOutcome::Refused { code, detail }, Some(warnings)) if pending => { let also: String = warnings .iter() .map(|warning| format!(" Also: {}.", warning.detail.trim_end_matches('.'))) @@ -1932,7 +1975,7 @@ async fn wired_copy_failed( then." ), ), - (failure, Some(Ok(mut warnings))) => { + (failure, Some(mut warnings)) => { let why = match &failure { VendorOutcome::Refused { detail, .. } => detail.clone(), VendorOutcome::Done { result, .. } => result.error.clone().unwrap_or_default(), @@ -3280,8 +3323,9 @@ const GITIGNORE_NEUTRALIZED: &str = "vendor_gem_gitignore_neutralized"; /// see the same bytes. /// /// A `.gitignore` the patch itself rewrites is left as the patch has it -/// (its hash is the record's); what it ignores is then for -/// [`finish_platform_copy`] to refuse. Returns the paths +/// (its hash is the record's), with what it ignores: git is asked about +/// the copy before its trees are in place, where it reads no such file. +/// Returns the paths /// emptied, relative to `tree`. async fn empty_shipped_gitignores( tree: &Path, @@ -3363,15 +3407,19 @@ async fn build_artifact( /// is the verified patched gem of each platform of `trees`, each from its /// own patch, staged in full and then swapped into place, so a failure /// leaves any pre-existing (possibly live-wired) copy untouched and no -/// husk behind. The copy is the caller's to finish, with the uuid dir's -/// git metadata ([`finish_platform_copy`]): `copy_dir` may itself sit in a stage -/// (`repair`'s restore). Returns what the ledger records of each tree. +/// husk behind. `place` is the project and the copy's path in it, where +/// `copy_dir` is that place: the copy is then finished between the stage +/// and the swap ([`CopyStep::Placing`]), so one git would not commit is +/// refused with nothing moved. Without it `copy_dir` itself sits in a +/// stage (`repair`'s restore), and the copy is the caller's to finish +/// before it moves that in. Returns what the ledger records of each tree. #[allow(clippy::too_many_arguments)] pub(super) async fn gem_platform_service_copy( service: Option<&VendorServiceConfig>, record: &PatchRecord, name: &str, trees: &PlatformTrees<'_>, + place: Option<(&Path, &str)>, copy_dir: &Path, uuid_dir: &Path, unwind_uuid_dir: bool, @@ -3389,8 +3437,24 @@ pub(super) async fn gem_platform_service_copy( return Err(outcome); } }; - if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { + // Nothing was moved in: neither the stage nor a uuid dir that would + // hold its git metadata alone is left behind. + let abandon = || async { cleanup_failed_stage(&stage, uuid_dir, unwind_uuid_dir).await; + if place.is_some() && !unwind_uuid_dir { + remove_metadata_alone(uuid_dir).await; + } + }; + if let Some((project_root, copy_rel)) = place { + let placing = CopyStep::Placing(&stage); + let finished = finish_platform_copy(project_root, copy_rel, placing, false, warnings); + if let Err(refusal) = finished.await { + abandon().await; + return Err(Box::new(refusal)); + } + } + if let Err(e) = swap_stage_into_place(&stage, copy_dir).await { + abandon().await; return Err(ServicePolicy::Refused.hard( "vendor_prebuilt_write_failed", format!("cannot move the extracted platform gems into place: {e}"), @@ -3427,6 +3491,7 @@ async fn preview_platform_builds( record: &PatchRecord, name: &str, trees: &PlatformTrees<'_>, + (project_root, copy_rel): (&Path, &str), ) -> Result, Box> { if let Some(outcome) = service_offline_conflict(service) { return Err(Box::new(outcome)); @@ -3436,9 +3501,14 @@ async fn preview_platform_builds( .ok_or_else(|| Box::new(super::service_fetch::required()))?; let scratch = tempfile::tempdir() .map_err(|e| Box::new(refused("vendor_prebuilt_extract_failed", e.to_string())))?; - stage_platform_builds(cfg, record, name, trees, scratch.path()) + let (_, built) = stage_platform_builds(cfg, record, name, trees, scratch.path()).await?; + // What the wet run asks before it moves the trees in, with nothing + // written: the dry run says what that run does. + let placing = CopyStep::Placing(scratch.path()); + finish_platform_copy(project_root, copy_rel, placing, true, &mut Vec::new()) .await - .map(|(_, built)| built) + .map_err(Box::new)?; + Ok(built) } /// What a run would do with a gem `Gemfile.lock` names as precompiled @@ -3576,11 +3646,13 @@ pub async fn preview_locked_builds( /// Acquire a verified service copy without replacing the prior copy on /// failure: the gem's own tree, or one patched platform gem's tree per /// platform of `trees` when the lock pins the gem as platform gems. -/// Those trees are then the caller's to finish ([`finish_platform_copy`]). +/// Those trees are finished before they are moved into `place`, the +/// project and the copy's path in it ([`gem_platform_service_copy`]). /// Returns what the ledger records of each such tree, with the result. #[allow(clippy::too_many_arguments)] async fn materialise_patched_copy( purl: &str, + place: (&Path, &str), copy_dir: &Path, uuid_dir: &Path, name: &str, @@ -3610,6 +3682,7 @@ async fn materialise_patched_copy( record, name, trees, + Some(place), copy_dir, uuid_dir, unwind_uuid_dir, @@ -14569,29 +14642,33 @@ mod tests { assert_eq!(rebuilt, stamped(LINUX), "rebuilt"); } - /// A copy git would not commit is refused wherever it is finished, - /// and the refusal names its cause: a project rule ignores the - /// binaries (`*.so`), and the uuid dir's own `.gitignore`, which - /// keeps such a rule off them, could not be written. A first - /// vendor removes what it made; a copy the lock already names - /// stays where it is. Once git tracks the copy it keeps committing - /// it whatever the rules say, and what is left is the warning. + /// Git is asked whether it would commit a copy only where trees are + /// about to be placed, before they are moved in and as if nothing + /// were tracked, and a dry run asks the same. So a refusal leaves + /// what is on disk as it was: a first vendor writes nothing, an + /// intact copy whose list moved stays in force with the refusal as + /// the reason, and a damaged copy is neither restored nor rebuilt. + /// A copy that is already there asks git nothing. Here a project + /// rule ignores the binaries (`*.so`) and the uuid dir's own + /// `.gitignore`, which keeps such a rule off them, cannot be + /// written: the refusal names that as its cause. #[tokio::test] - async fn a_copy_git_would_not_commit_is_refused_wherever_it_is_finished() { + async fn a_copy_git_would_not_commit_is_refused_before_its_trees_are_placed() { let uuid_rel = format!(".socket/vendor/gem/{UUID}"); let cause = format!( "`{uuid_rel}/.gitignore` and `{uuid_rel}/.gitattributes`, which keep such a rule \ off it, could not be written (" ); + let names_the_cause = |detail: &str| { + detail.contains("git would not commit the vendored artifact at") + && detail.contains(".gitignore:1:*.so") + && detail.contains(&cause) + && detail.contains("make those two files writable and vendor again") + }; let refused_for_it = |outcome: VendorOutcome| { let (code, detail) = unwrap_refused(outcome); assert_eq!(code, "vendor_artifact_gitignored", "{detail}"); - assert!( - detail.starts_with("git would not commit the vendored artifact at") - && detail.contains(&cause) - && detail.ends_with("make those two files writable and vendor again"), - "{detail}" - ); + assert!(names_the_cause(&detail), "{detail}"); }; let obstruct = |root: &Path| { let gitignore = root.join(&uuid_rel).join(".gitignore"); @@ -14599,66 +14676,184 @@ mod tests { std::fs::create_dir_all(gitignore.join("in the way")).unwrap(); }; - // A first vendor: refused, and nothing of it is left. + // A first vendor, dry and wet: refused, and nothing is written. let (_tmp, root, record) = project(&lock(None)).await; if ts::git_project(&root, "*.so\n").is_none() { return; // no git, nothing to commit } obstruct(&root); - let wired_before = text(root.join(GEMFILE_LOCK)).await; + let before = ts::tree_snapshot(&root); let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, true).await); + assert_eq!(ts::tree_snapshot(&root), before, "a dry run"); refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert!(!root.join(&uuid_rel).exists(), "the copy is removed"); - assert_eq!(text(root.join(GEMFILE_LOCK)).await, wired_before); + assert!( + !root.join(&uuid_rel).exists(), + "nothing of the copy is left" + ); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock(None)); - // A copy the lock names: in step, restored and rebuilt. + // A copy the lock names, with its `.gitignore` unwritable. let entry = vendor_and_persist(&root, &record, &cfg).await; obstruct(&root); let before = ts::tree_snapshot(&root); - refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); - assert_eq!( - ts::tree_snapshot(&root), - before, - "in step: nothing is touched" - ); + + // In step: git is asked nothing. The copy stands, with the + // warning of the file that could not be written. + let (result, _, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success, "{:?}", result.error); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!(codes, [GEM_GIT_METADATA_UNWRITTEN], "{warnings:?}"); + + // The list moved: the intact copy stays in force, byte for + // byte, dry and wet, and the note names the rule and the cause. + let (_server, moved) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &moved, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success && entry.is_none(), "dry run {dry_run}"); + let note = warnings.iter().find(|w| w.code == GEM_LIST_NOT_FOLLOWED); + let note = note.unwrap_or_else(|| panic!("dry run {dry_run}: {warnings:?}")); + assert!( + names_the_cause(¬e.detail) + && note + .detail + .ends_with("its vendored copy stays in force as it is."), + "dry run {dry_run}: {note:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } + + // A damaged copy: neither a restore nor the rebuild moves trees + // git would not commit, and the copy is as it was. let linux = root.join(rel(UUID)).join(LINUX); tokio::fs::remove_dir_all(&linux).await.unwrap(); + let damaged = ts::tree_snapshot(&root); let failed = crate::vendor::redownload::restore(&root, &entry, &record, &cfg) .await - .expect_err("a restored copy git would not commit"); + .expect_err("a restore git would not commit"); assert!( failed.detail().starts_with("vendor_artifact_gitignored: ") - && failed.detail().contains(&cause), + && names_the_cause(failed.detail()), "{failed}" ); - assert_eq!( - ts::tree_snapshot(&root), - before, - "the trees are back in place" + assert_eq!(ts::tree_snapshot(&root), damaged, "the restore"); + for dry_run in [true, false] { + refused_for_it(vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await); + assert_eq!(ts::tree_snapshot(&root), damaged, "dry run {dry_run}"); + } + } + + /// With the uuid dir's own rules in place no rule above them + /// reaches a file of the copy, and what git can still refuse is a + /// rule that excludes the directory itself. Added after the copy + /// was vendored, such a rule keeps a moved list from being + /// followed: the copy stays in force, dry and wet, and the note + /// names the rule. In step, the same copy is asked about nothing. + #[tokio::test] + async fn a_rule_that_excludes_the_directory_keeps_a_wired_copy_as_it_is() { + let (_tmp, root, record) = project(&lock(None)).await; + if ts::git_project(&root, "*.so\n").is_none() { + return; // no git, nothing to commit + } + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&root, &record, &cfg).await; + // (Without the rule, a scan's preview says the wet run vendors.) + let (_server, published) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let previewed = preview_locked_builds(&root, NOKO, UUID, false, Some(&published)).await; + assert!( + matches!(previewed, Some(LockedBuildsPreview::Vendor(_))), + "{previewed:?}" ); + tokio::fs::write(root.join(".gitignore"), "*.so\n/.socket/vendor/gem/\n") + .await + .unwrap(); + let before = ts::tree_snapshot(&root); + + let (result, entry, warnings) = + unwrap_done(vendor(&root, ¬_installed(&root), &record, &cfg, false).await); + assert!(result.success && entry.is_none(), "{:?}", result.error); + assert!(warnings.is_empty(), "in step: {warnings:?}"); + let (_server, moved) = service(UUID, &[served(DARWIN), served(LINUX)]).await; - refused_for_it(vendor(&root, ¬_installed(&root), &record, &moved, false).await); - let patched = tokio::fs::read(linux.join(RB)).await.unwrap(); - assert_eq!(patched, stamped(LINUX), "the new trees stay in place"); + // The preview of a scan, which downloads nothing, does not say + // that the copy would be vendored either. + let previewed = preview_locked_builds(&root, NOKO, UUID, false, Some(&moved)).await; + assert!( + !matches!(previewed, Some(LockedBuildsPreview::Vendor(_))), + "{previewed:?}" + ); + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &moved, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success && entry.is_none(), "dry run {dry_run}"); + let codes: Vec<&str> = warnings.iter().map(|w| w.code).collect(); + assert_eq!( + codes, + [GEM_LIST_NOT_FOLLOWED], + "dry run {dry_run}: {warnings:?}" + ); + assert!( + warnings[0] + .detail + .contains(".gitignore:2:/.socket/vendor/gem/") + && warnings[0] + .detail + .ends_with("its vendored copy stays in force as it is."), + "dry run {dry_run}: {warnings:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } + } - // Tracked, git keeps committing the copy: the warning is left. - let git = crate::utils::process::resolve_tool("git").expect("git"); - let added = std::process::Command::new(git) - .arg("-C") - .arg(&root) - .args(["add", "-f", ".socket"]) - .status() - .expect("git add"); - assert!(added.success(), "git add"); - let (result, _, warnings) = - unwrap_done(vendor(&root, ¬_installed(&root), &record, &moved, false).await); - assert!(result.success, "{:?}", result.error); + /// A copy that is already there asks git nothing, wherever the + /// project sits: one exported without its `.git` into a directory + /// an outer repository ignores is found in step like any other, + /// with nothing said, though git would call every path of it + /// ignored. + #[tokio::test] + async fn a_copy_in_step_in_an_ignored_directory_of_an_outer_repository_stands() { + 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.path().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } + } + let (_tmp, made, record) = project(&lock(None)).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), upstream(LINUX)]).await; + vendor_and_persist(&made, &record, &cfg).await; + + let outer = tempfile::tempdir().unwrap(); + if ts::git_project(outer.path(), "build/\n").is_none() { + return; // no git, nothing to ask + } + let root = outer.path().join("build/app"); + copy_tree(&made, &root); + let binary = format!("build/app/{}/{DARWIN}/{SO}", rel(UUID)); assert!( - warnings - .iter() - .any(|w| w.code == GEM_GIT_METADATA_UNWRITTEN), - "{warnings:?}" + crate::vendor::npm_dir::gitignored(outer.path(), &[binary]) + .await + .is_some(), + "git calls the copy ignored there" ); + let before = ts::tree_snapshot(&root); + for dry_run in [true, false] { + let outcome = vendor(&root, ¬_installed(&root), &record, &cfg, dry_run).await; + let (result, entry, warnings) = unwrap_done(outcome); + assert!(result.success, "dry run {dry_run}: {:?}", result.error); + assert!( + entry.is_none() && warnings.is_empty(), + "dry run {dry_run}: {warnings:?}" + ); + assert_eq!(ts::tree_snapshot(&root), before, "dry run {dry_run}"); + } } /// A rebuild that fails leaves no uuid dir behind where there was diff --git a/crates/socket-patch-core/src/vendor/redownload.rs b/crates/socket-patch-core/src/vendor/redownload.rs index 10fbfa08d6..64ba1fce9c 100644 --- a/crates/socket-patch-core/src/vendor/redownload.rs +++ b/crates/socket-patch-core/src/vendor/redownload.rs @@ -362,6 +362,7 @@ pub async fn restore_with_list( record, &name, &trees, + None, &stage, uuid_dir, true, @@ -483,6 +484,22 @@ pub async fn restore_with_list( warnings.push(warning); } } + // A gem vendored as platform gems is finished as on every path + // that places its trees, before they are moved in: the uuid dir's + // metadata (a write that fails is a warning), then git's word on + // the commit. Refused, the copy is as it was. + if entry.ecosystem == "gem" && !file_shaped && !entry.gem_tree_platforms().is_empty() { + let copy_rel = entry.artifact.path.replace('\\', "/"); + let placing = super::gem::CopyStep::Placing(&stage); + let finished = + super::gem::finish_platform_copy(root, ©_rel, placing, false, &mut warnings); + if let Err(refusal) = finished.await { + if let Some(real_uuid_dir) = artifact.parent() { + super::gem::remove_metadata_alone(real_uuid_dir).await; + } + return Err(detail(refusal).into()); + } + } let swapped = if file_shaped { let result = tokio::fs::rename(&stage, &artifact).await; if result.is_ok() { @@ -520,15 +537,6 @@ pub async fn restore_with_list( .await .map_err(|e| format!("cannot restore the vendored dir's git metadata: {e}"))?; } - } else if entry.ecosystem == "gem" && !entry.gem_tree_platforms().is_empty() { - // A gem vendored as platform gems is finished as on every other - // path that puts its trees in place: the uuid dir's metadata (a - // write that fails is a warning), then git's word on the commit. - let copy_rel = entry.artifact.path.replace('\\', "/"); - let inventory = entry.artifact.file_inventory.as_ref(); - super::gem::finish_platform_copy(root, ©_rel, inventory, false, &mut warnings) - .await - .map_err(detail)?; } // The jar that vendored mode keeps for the hub of a Bazel workspace // alone is one file of a directory that is a repository: the stage held From 72463e60ee2c98b31beae967ab707f4d79a42b7d Mon Sep 17 00:00:00 2001 From: Mikola Lysenko Date: Sat, 28 Nov 2026 16:42:14 -0500 Subject: [PATCH 26/28] Document where git is asked about a platform-locked copy The contract and the guide say that git is asked only where trees are about to be placed, before they are moved in and without the index, in a dry run too; that a refusal leaves what is on disk as it was, on each path; and that a copy in step or left in force asks git nothing. Co-Authored-By: Claude Fable 5.2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 8 ++++---- docs/ecosystems.md | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 0ef5cc6ae8..7d1e5ef96a 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1743,7 +1743,7 @@ to **six flavors**. | cargo | crate dir `-/` (no `.cargo-checksum.json`) | (v5.0) `[patch.crates-io]` path entry in the **workspace-root `Cargo.toml`** (the manifest beside the `Cargo.lock` it detaches — never `.cargo/config*`) **+** Cargo.lock surgery (the `[[package]]` entry's `source`/`checksum` removed and its `version` set to the copy's TAGGED version `+socket.` — `+.socket.` when the version already has build metadata — with every lock reference that spells the old version rewritten, formats v1–v4; the copy's own `Cargo.toml` version carries the same tag, so the patched crate sees it in `CARGO_PKG_VERSION`; revert restores the lock byte for byte). Key: always the Socket-owned `-socket-` with `package = ""` (the full uuid hex when that key is taken), never the bare crate name — cargo lets a config-file `[patch]` item (project, ancestor directory or `$CARGO_HOME`) replace the manifest item with the same key whatever its version, so keys any of those configs use are avoided and a re-run moves an entry off a now-shadowed key; two versions of one crate are wired side by side. Pre-v5 wiring in `.cargo/config.toml` / `.cargo/config` is moved into `Cargo.toml` by a re-run (`vendor`, `scan`/`get --mode vendored`) or `repair` (`cargo_wiring_migrated` note; the ledger's `cargo_patch_entry` record then names `Cargo.toml`); a detached lock entry left unwired by the pre-v5 multi-version overwrite is re-wired the same way (`cargo_wiring_restored`); every revert removes both spellings | `cargo build --locked --offline` on a fresh checkout — single-version manifest `[patch]` also builds with no network on cargo older than 1.56 (the old config-file wiring's floor); two vendored versions of ONE crate need cargo 1.45 or newer (`--offline` from an empty CARGO_HOME is enough there); older cargo fails closed whatever the index state, and a project that does not pin cargo ≥ 1.45 (`rust-version`, a `rust-version.workspace = true` inheritor's `[workspace.package]` value, or toolchain file) gets the `cargo_multi_version_old_cargo` warning. Note: path deps build **without** `--cap-lints allow` | | golang | module dir `@/` | `go.mod` `replace => ./.socket/vendor/golang//@` | `go build` with `GOPROXY=off` + empty `GOMODCACHE` (directory replaces bypass go.sum entirely; survives `go mod tidy`) | | composer | package dir `/@/`; the copy's `.gitignore` / `.hgignore` are emptied and its `.gitattributes` `export-ignore` rules dropped, because Composer's path mirror skips the files they match (`vendor_composer_mirror_filters_neutralized`; a patch that rewrites one of them is refused `vendor_composer_mirror_filter_conflict`). Re-runs heal copies vendored before this | `composer.lock` only: entry's `dist` → `{type: "path", url, reference: ""}`, `source` removed, `transport-options: {symlink: false}` added. `content-hash` unaffected; `composer.json` untouched | `composer install` (from the lock alone, real copy not symlink, works under `--network none`). Composer 1 does not reinstall an already-installed package whose dist changed: remove `//` first (the hint names the project's resolved vendor dir: `COMPOSER_VENDOR_DIR`, else `config.vendor-dir`, else `vendor`). `composer update ` reverts it. See `docs/testing/composer-compatibility.md`. In a Bazel workspace the project is refused `vendor_composer_bazel_workspace` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` or the lock already names a vendored copy (see that code) | -| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. The question is advisory, since the copy stands whatever the answer: it is one attempt of at most five seconds, never retried, and outside the circuit breaker the run's other requests share, so a patch service that is down costs such a run one short attempt per vendored platform gem and cannot fail what the run has to vendor. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. Every path that puts the trees in place, or says that they stay in force, finishes the copy the same way (a first vendor, a rebuild of a copy the lock is wired to, a restore, a copy found in step, a copy that stays in force). First it writes the uuid directory's `.gitignore` and `.gitattributes` where one is missing or changed. They are not part of the copy, so a write that fails is the warning `vendor_gem_git_metadata_unwritten`, which names the two files and says to make them writable, and never a failure: the trees are in place and correct, and the ledger records them. Then it asks git whether it would commit every file of the copy, and a rule that keeps one out is the failure `vendor_artifact_gitignored`, which names the files that could not be written as its cause, and that remedy, when that is why. A first vendor removes the copy it made; a copy the lock already names stays where it is (after a rebuild the trees the list names are in place and the ledger still records the earlier ones, until a run vendors the copy again). For a copy that was already there git is asked with its index, since it keeps committing a file it tracks whatever the ignore rules say. A skip that leaves the copy in force carries no warning of its own and ends its line with it (`… stays in force as it is. Also: could not write …`). A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). A restore hands the list it read to the gem's backend, whether it was refused over that list or restored the copy, so the copy is vendored again, or found in step, by the one answer the restore read, and the fix's reference is asked for once (a list of another fix is never used). Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | +| gem | gem dir `-/` + gemspec materialized from `specifications/`; for a gem locked as platform gems, one unpacked platform gem per locked platform, `-//`: the patched one, from that platform's own patch (its `tarball` and `gem-stub-gemspec`; the gem patch's reference names the patch of each platform under `gemBuilds`, and the platform patches are asked for in one reference request) and with its gemspec, or, for a locked platform that has no patched build, upstream's own gem as the gem patch's registry serves it (`/gems/--.gem`, from the patch server, never from the upstream registry: the download follows no redirect, and one the registry answers is the gem not being served) with the gemspec that gem carries; all under the `` of the gem's patch, plus `/.gitignore` (`!*`: re-includes the binaries against the project's ignores, such as a `*.so` or `*.bundle` rule) and the same `/.gitattributes` the npm tarballs get (so a project filter such as a Git LFS `*.so` rule does not change the committed bytes); an in-sync re-run and `repair` put the pair back when it is missing. A `.gitignore` a patched platform gem ships inside its own tree would hide files below the uuid dir's `!*`, so each is emptied in the copy (`vendor_gem_gitignore_neutralized`; the ledger's inventory is of the copy as vendored; one the patch itself rewrites is kept). Refuses `vendor_artifact_gitignored` before any download, dry run included, when a rule ignores the uuid directory itself, and after the download when git would still drop a file | **Gemfile + Gemfile.lock pair**: the `gem` line gains `path:` (or a managed block for transitive deps, whose declaration is `require: false` so `Bundler.require` does not start loading the gem at boot; a block that 5.1 or earlier wrote without the option gains it when a patch update re-vendors the gem); the lock's spec block moves GEM→PATH and the DEPENDENCIES entry becomes ` (= )!`, in bundler's exact canonical form. A gem the lock pins as precompiled platform gems (one ` (-)` entry per platform and no plain ` ()`, as Bundler locks nokogiri) cannot be vendored as its own tree, because Bundler never builds a `path:` gem's extensions. It is vendored as the patched platform gems: the `path:` and the `PATH` `remote:` still name `-/`, which holds one unpacked tree per locked platform, each downloaded and checked against its own patch's digests and against the sha256 the gem patch lists for that platform, and its unpacked tree checked against the files of its own patch's record (`…/patches/view/`, one request per platform gem: a platform gem is a patch of its own, whose files carry that patch's header and, for a compiled build, its binaries, so they never match the hashes of the gem's patch); EVERY platform block of the gem moves into the one `PATH` section; and Bundler loads the tree of the platform it runs on, with no build. At least one locked platform needs a patched build, and the registry has to list a gem for every one of them. A locked platform with no patched build (`gemBuilds[].patchUuid` null) gets upstream's own gem, the one hosted mode installs for it: the `.gem` is downloaded from the gem patch's registry on the patch server, checked against the sha256 the list names, and unpacked as it is, with the gemspec it carries (its `metadata.gz`, YAML, which Bundler reads like a Ruby gemspec; one that names another gem, version or platform, or declares extensions to build, is refused and nothing is vendored). The run then prints hosted mode's line for the gem under its summary line, on stdout: `nokogiri 1.19.3: patched for arm64-darwin; upstream gem kept for x86_64-linux-gnu (no patched build yet)` (a dry run: `would be patched for …`); a gem whose every tree is a patched build prints no such line. While no locked platform has a patched build the gem is not vendored (`vendor_prebuilt_platform_pending`, no failure, one line) with nothing written. The copy follows the gem patch's list: each gem a run finds vendored this way asks the patch service for the reference of its own fix when the run reaches it. That costs ONE small request per vendored platform gem per run, wet or dry: the requests are not batched, and a run over a copy that is in sync makes that one request for it and downloads nothing. The question is advisory, since the copy stands whatever the answer: it is one attempt of at most five seconds, never retried, and outside the circuit breaker the run's other requests share, so a patch service that is down costs such a run one short attempt per vendored platform gem and cannot fail what the run has to vendor. Where its list names another build for a locked platform than the ledger records it vendors the copy again with the `Gemfile` and the lock untouched: a patched build published since takes the place of upstream's gem (`now also patched for x86_64-linux-gnu; already patched for arm64-darwin`, `details.newlyPatched: true` on that build's `applied` event), and upstream's gem takes the place of a patched build that was withdrawn (`upstream gem back for x86_64-linux-gnu (its patched build was withdrawn)`, `details.withdrawn: true`), the last one included. That re-vendoring is recorded as the uncounted advisory `vendor_gem_list_followed` in `--json` and prints no warning. An intact copy is never made worse, and a run never fails over it: a list that cannot be read (offline, a failed request, no list right now, a platform it leaves out) leaves the copy as it is with nothing said, a ledger entry that names no build of its trees is not asked about at all, and when the list does name another build but the copy cannot be vendored again from it (a download that fails, a build whose gem fails its digest or whose stub is not served, an upstream gem that does not unpack) nothing of the copy is touched, the run ends as it does for a copy in step (exit 0, the `already_vendored` events of its trees, the uuid directory's `.gitignore` and `.gitattributes` put back when one is missing) and ONE line says so, a note on stderr and the uncounted advisory `vendor_gem_list_not_followed`: `Note: nokogiri@1.19.3 could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` A build the list names that is not served yet keeps the skip `vendor_prebuilt_platform_pending` (`…; its vendored copy stays in force as it is.`). A run says that a copy stays in force only after checking that the copy the ledger records still stands: a rebuild that fails once the copy was changed (the new copy cannot be moved into place and the old one cannot be moved back, in which case it is kept beside the path as `-.socket-old`) is a failure (exit 1, `vendor_prebuilt_write_failed`), and the next run vendors the copy again from the list. Every path that is about to put the trees in place, or that says the ones that are there stay, finishes the copy with one step. It writes the uuid directory's `.gitignore` and `.gitattributes` where one is missing or changed. They are not part of the copy, so a write that fails is the warning `vendor_gem_git_metadata_unwritten`, which names the two files and says to make them writable, and never a failure (a skip that leaves the copy in force carries no warning of its own and ends its line with it: `… stays in force as it is. Also: could not write …`). Git is asked whether it would commit the copy only where trees are about to be placed (a first vendor, a rebuild of a copy the lock is wired to, a restore), before they are moved in and as if nothing were tracked, which does not read the index; a dry run asks the same question and writes nothing. With the uuid directory's own rules in place no rule above them reaches a file of the copy, so the question is whether a rule excludes the directory itself; where those rules could not be written it is asked of every staged file, and the refusal names the files that could not be written as its cause, with that remedy. A refusal (`vendor_artifact_gitignored`) leaves what is on disk as it was: a first vendor writes nothing, an intact copy whose list moved stays in force with the refusal as the reason (the note `vendor_gem_list_not_followed`, exit 0), and a damaged copy is neither restored nor rebuilt (the run fails, as for any copy it cannot put back). A copy that is in step, or that is left in force, asks git nothing: it is already what the project commits. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is not taken: the earlier copy stays in force (`vendor_prebuilt_platform_pending`: `nokogiri@1.19.3 was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.`). The ledger entry records which patch each tree came from (`gemBuilds`: `platform`, `uuid`, `gemIntegrity`, `gemspecIntegrity` and `files`, the file hashes of that patch's record, in lock order; a tree of upstream's gem has its `platform` and `gemIntegrity`, the `sha256-…` of the gem the list named, and no `uuid`, `gemspecIntegrity` or `files`: no patch stands behind it, and the entry's file inventory vouches for every file of it; only a release that contains this support and the platform-gem vendoring it builds on reads such an entry: socket-patch 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy, with or without a tree of upstream's gem (on 5.1.0 `vendor --check` fails, `vendor_check_failed`: a patched file is missing, and `vex` leaves the gem out, `vendor_unwired`, attesting nothing for it), so a project vendored this way is attested, by `vex` or `vendor --check`, with the release that vendored it or a later one), a restore fetches each tree by it, and `vendor --check` and `vex` check each tree against its own `files` with no request (an entry written before `files` was recorded is checked against the gem patch's files, as before). A restore (`repair`, or a run that finds a tree damaged) does not take the ledger's word for what to unpack: it asks the gem patch's reference which patch each platform's gem is, answers `vendor_prebuilt_replaced` when the fix names another patch for a platform than the entry records, or none (the build was rebuilt under another patch or withdrawn; an edited ledger looks the same), or names a patched build, or no gem, for a platform whose tree the entry records as upstream's gem: the copy cannot be restored as it was vendored, nothing is unpacked or downloaded, and the message names what works, `socket-patch scan --mode vendored`, which vendors the copy again from the list. That is `repair`'s answer. A vendor / scan / get `--mode vendored` run that finds a tree damaged and is refused the restore for this reason alone (the list names another build; a reference that does not pin upstream's gem is a failure as before) does not fail: it goes on to vendor the copy again from the list as it is now, as it does for an intact copy whose list moved (so the tree is the build the list names, and the ledger names its patch). A restore hands the list it read to the gem's backend, whether it was refused over that list or restored the copy, so the copy is vendored again, or found in step, by the one answer the restore read, and the fix's reference is asked for once (a list of another fix is never used). Its dry run asks the same question (one request, no download) and previews the copy vendored from that list, one `verified` event per patched build, in place of `wouldRedownload`. It refuses an entry that pins no digest for the gem or the gemspec (`vendor_prebuilt_integrity_mismatch`, before any download, with the tree left as it was), requires the download to be both the gem the patch registry lists and the one the entry pins and the stub gemspec to state the entry's name, version and platform, and checks the tree against the record the patch service serves for that platform's patch now. That is one reference request and one record per platform more than the builds' own references. The run reports the gem per platform gem, as hosted mode does: one counted `applied` event for each patched one (`purl` `pkg:gem/@?platform=`, `uuid` that platform's patch, `details.gemFix` the gem's patch, `details.platform`), likewise `skipped` / `already_vendored` on an in-sync re-run and `verified` / `vendor_check_ok` (or `failed` / `vendor_check_failed`) under `vendor --check`; a tree of upstream's gem is the advisory `skipped` / `gem_upstream_build_kept` event with no `uuid`, which `summary` does not count (under a failed `vendor --check` it shares the copy's `failed` event, so a copy that does not verify fails for every tree); human lines and totals count the gem as one package. `vex` attests each vendored patched platform gem under its own patch, from the committed ledger alone, and states a platform gem whose tree is upstream's gem `affected`, with an action statement that says the copy holds upstream's gem for that platform and that a later `scan --mode vendored` takes the patched build once it is published (the `gem_upstream_build_kept` event in its envelope). A ledger entry that still carries the key `gemPlatforms` (only development builds wrote it) is read with the key ignored, and `vendor --revert` and `rollback` restore the pair from its recorded originals. A dry run previews what the wet run does: `vendor --dry-run` goes through the backend, and `scan` / `get --mode vendored --dry-run` ask the patch service about each gem locked as platform gems (the gem patch's reference, then one request for the platform patches; nothing is downloaded), so a gem that would be vendored is reported as one `verified` event per patched platform gem (with the `gem_upstream_build_kept` event and the gem's line for a platform that gets upstream's gem) and a gem that cannot be vendored yet as the same one line and `skipped` event as the wet run, never as "would vendor". The dry run of a scan also asks the gem patch's reference for a gem already vendored as platform gems, as the wet run does, and reports the trees the wet run would put in place when the list names other builds. A plain ` ()` entry beside the platform ones (the `ruby` platform, which no platform tree serves), or a lock whose `BUNDLED WITH` is absent or older than Bundler 2.3 (the oldest the layout is verified on), is refused `platform_gem_unsupported` with nothing written. `vendor --check`, `vex` and `repair` cover every platform's tree with one rule, which a re-run's in-sync test applies too: a patched file the tree holds is the patched one; a patched file it lacks is no mismatch, even when it holds none of them (a platform gem need not ship what its extension was built from); and every file of the tree matches the ledger's file inventory, which is what vouches for such a tree once it is vendored (a file that is gone, changed or added is a mismatch, and the next run rebuilds the copy). Only an entry with no inventory needs a patched file in the tree: without one nothing vouches for it. On bundler 2.7+ (the lock's `BUNDLED WITH`), a `gem` line that follows a `gemspec` directive whose gemspec declares a development dependency on the same gem is refused `gemfile_declaration_not_editable` before any write: bundler merges the two requirements and then rejects even its own lock for a path gem under frozen mode, so the refusal names the remedy (declare the gem above `gemspec`, or use hosted mode). Hosted mode instead pins the merged requirement bundler writes: the gemspec's requirements plus `= `, in bundler's order (` (>= 0, = )!` for an unconstrained development dependency), and warns `redirect_gem_gemspec_dependency_unreadable` when the gemspec cannot be read (#985) | `bundle install` (normal **and** `BUNDLE_FROZEN=true`), byte-stable lock. Lock-only edits are a silent unpatch — hence the mandatory pair. Where a rules_ruby hub of the project's Bazel workspace reads the `Gemfile` or its lock, the gem is committed as its archive instead, `/gems/-.gem` with the `/.gitignore` and `.gitattributes` above, and the pair names it as hosted mode names a patch registry, with the relative URL `file:.socket/vendor/gem//` as the `source:` of the `gem` line and the `remote:` of a `GEM` section of the gem's own, the `DEPENDENCIES` entry source-pinned (`!`) and the `CHECKSUMS` line at the sha256 of the patched gem (`vendor_gem_bazel_file_source`); where that is not known to build the gem is refused `vendor_gem_bazel_hub` (**Experimental**, Bazel workspaces), and with `--allow-vendored-in-bazel` it is vendored by its path as above | | pypi / uv (uv.lock) | rebuilt wheel (canonical PEP 427 filename; RECORD regenerated) | `[tool.uv.sources] = {path}` in pyproject + surgical uv.lock rewrite; transitive deps via `[tool.uv] override-dependencies` | `uv sync --locked` / `--frozen --offline` (hash-verified, byte-stable lock). Where a rules_python hub of the project's Bazel workspace reads the `uv.lock` (`uv_lock`), or a requirements file beside it that names the package, the package is refused `vendor_pypi_bazel_hub` (**Experimental**, Bazel workspaces) unless the run has `--allow-vendored-in-bazel` | | pypi / poetry (poetry.lock: legacy `[metadata.hashes]`, lock 1.0/1.1 `[metadata.files]`, 2.x `files`) | (rebuilt wheel) | lock-only: the target `[[package]]` gets `[package.source] type="file"` (+ `reference = ""` on the 0.12/1.0 layouts, which read it unconditionally) and the single `{file, hash: sha256-of-our-wheel}` entry in whichever table the generation keeps it. pyproject + `metadata.content-hash` untouched; CRLF locks keep their line endings. A lock written by Poetry < 1.4 emits `pypi_poetry_integrity_unverified` (that installer verifies no local hashes and skips an already-installed version) | `poetry check --lock && poetry sync`, cold cache (hash fail-closed from Poetry 1.4; byte-stable lock) — see `docs/testing/poetry-compatibility.md` | | pypi / pdm (pdm.lock) | (rebuilt wheel) | lock-only: the `[[package]]` gains the local-file `path` + `files[]` hash. pyproject + `content_hash` untouched. Non-fixture `[metadata] strategy` / hash-less locks refused | `pdm sync` (+ `pdm install --check`), cold cache | @@ -2523,7 +2523,7 @@ command's integration tests check its output. | `vendor_maven_pin_would_move_module` | `skipped` (benign; exit 0) | vendor / scan / get `--mode vendored` (Maven reactor): the only poms that resolve the artifact at the patch's base version are parent poms above a module that resolves another version. A `` pin in the parent is inherited by that module and would move it, and Maven has no management that reaches a parent and not its children, so nothing is pinned and no file is written; the reason names the parent, the module and its version. When a sibling module does select the base version it is pinned and the same sentence is the `vendor_jvm_degraded` reason `pin_would_move_module`. | | `vendor_prebuilt_pending` / `vendor_prebuilt_unavailable` | `skipped` | vendor / scan / get `--mode vendored` (every ecosystem, #954, #1235): the package is already vendored at another patch uuid, and the patch service has no prebuilt artifact for the selected (superseding) uuid — still building (`pending_build`) / not served (`build_failed`, `not_found`, `withdrawn`, no usable artifact). Nothing is touched: the older patch's artifact, wiring and ledger entry stay in force, the detail names both uuids (`kept the vendored patch : prebuilt is still building for patch `, where `` is the backend's artifact kind: `artifact` for the npm family, `.gem`, `crate`, `module zip`, `dist zip`, `wheel`, `.jar`, `.nupkg`, …), and the run does not fail (exit 0), the way hosted mode keeps its pin and lists the upgrade in `redirect.skipped[]`. A re-run picks the new patch up once the service serves it. A gem locked as platform gems whose fix is still building is the skip `vendor_prebuilt_platform_pending` instead, vendored or not (below). A package with no vendored patch to keep still fails (`failed`, error `prebuilt is still building` / `prebuilt unavailable: `; outside the npm family under `vendor_prebuilt_required`), as does a request/transport failure. | | `vendor_prebuilt_replaced` | `failed` | repair (gem; a vendor / scan / get `--mode vendored` run that finds a platform gem's tree damaged is refused the exact restore the same way, and then vendors the copy again from the list instead of failing): the list of the gem's fix names another patch for that platform than the vendor ledger records, or no patched build, so the tree cannot be restored as it was vendored. The same for a tree the ledger records as upstream's own gem when the list names a patched build for its platform now, or lists no gem for it (`the copy of upstream's gem for () cannot be restored as it was vendored: …`); a `scan --mode vendored` then vendors what the list names now. Nothing is downloaded or unpacked. Only a list says so: when the fix's reference carries no list, or the service says the patch is not ready (the service has not read the version's gems, or is building one of them again), nothing is said of a replacement and nothing is changed. The restore fails as for any patch the service does not serve, with the detail `vendor_prebuilt_required: the patch service lists no builds for @ right now; run this again later` (under `vendor_artifact_redownload_failed` in `repair` and `vendor_redownload_failed` in a vendor run), and a run that vendors the lock's platforms is the skip `vendor_prebuilt_platform_pending`, whose line says which copy stays in force. The error names both patches and the remedy, the one command that works: run `socket-patch scan --mode vendored`, which vendors what the patch service serves now. | -| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, or an upstream gem did not unpack. Nothing of the copy was touched and it stays in force, which the run checks before it says so; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | +| `vendor_gem_list_not_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): an intact copy vendored as platform gems whose fix now lists another build for a locked platform (a patched build published since, or upstream's gem where the patched build was withdrawn) could not be vendored again from that list: a download failed, a build's gem failed its digest or its stub was not served, an upstream gem did not unpack, or git would not commit the new trees (`vendor_artifact_gitignored`, asked before they are moved in). Nothing of the copy was touched and it stays in force, which the run checks before it says so; the run reports the copy as it reports one in step (exit 0) and prints the reason as a note, `Note: @ could not be brought in step with the builds the patch registry lists (); its vendored copy stays in force as it is.` The next run tries again. | | `vendor_gem_list_followed` | `events[]` (`skipped`, NOT counted in `summary`) | vendor / scan / get `--mode vendored` (gem): the run vendored an intact copy again because its fix lists another build for a locked platform. JSON only: the gem's line says which platforms changed (`now also patched for …`, `upstream gem back for …`), and the builds' events carry `details.newlyPatched` / `details.withdrawn`. | | `vendor_prebuilt_platform_pending` | `skipped` | vendor / scan / get `--mode vendored` (gem): `Gemfile.lock` pins the gem as precompiled platform gems (`nokogiri (1.18.10-x86_64-linux-gnu)`) and the gem cannot be vendored for the locked platforms yet: no locked platform has a patched build (each is served as upstream's gem, `gemBuilds[].patchUuid` is null), or the list leaves a locked platform out, or the patch it names for one is not served; or the fix names no builds right now, which the service says in two ways that are one skip here: a reference that carries no list, or a patch that is not ready (`pending_build`). A lock with a patched build for at least one platform and upstream's gem for the rest is vendored, not skipped (see the gem row of the vendored layouts). Nothing is downloaded or written, the run does not fail (exit 0), and ONE line (stderr, no warning; one counted `skipped` event under the gem's purl) names the platforms without a patched build and the ones that have one (on a terminal it is wrapped like the hosted line of such a gem). With no locked platform patched: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin and x86_64-linux-gnu.` A platform whose patch is listed but not served yet (still being built) leaves the gem as it is, because the registry then lists neither a patched build that can be vendored nor upstream's gem for it: `nokogiri@1.19.3 is not vendored: no patched build yet for arm64-darwin (aarch64-linux-gnu and x86_64-linux-gnu have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; `scan --mode hosted` can patch the others now.` One whose patch the service does not grant (not found, withdrawn, a failed build) reads `no patched build available for ` (mixed: `no patched build yet for and none available for `). A platform the list leaves out is not one to wait for. The patch service lists every platform gem upstream publishes for the version, so it is a platform upstream does not publish, which hosted mode reports as `redirect_gem_platform_unlisted` and leaves alone as well. The line says that the registry does not list it and what settles that, and does not offer hosted mode: `nokogiri@1.19.3 is not vendored: the patch registry does not list java. Vendored mode needs a gem, patched or upstream's own, for every locked platform, and a re-run does not change what the registry lists: this is settled once the lockfile no longer names java (`bundle lock --remove-platform java`), or the registry lists a gem for every locked platform.` (beside a platform with no patched build: `… does not list java, and there is no patched build yet for arm64-darwin. Vendored mode needs …`). A fix that names no builds right now (the service has not read the version's gems, or is building one of them again) names no platform and says what to do, in the same words under `vendor`, `scan` and `get`: `nokogiri@1.19.3 is not vendored: the patch service lists no builds for it right now. Run this again later.` A copy that is already vendored stays in force and the line says so: `… was not brought up to date: no patched build yet for java (… have one). Vendored mode needs a gem, patched or upstream's own, for every locked platform; its vendored copy stays in force as it is.`, or `…; its vendored copy of an earlier patch stays in force as it is.` when the copy is of an older patch; for a fix that names no builds right now, `… was not brought up to date: the patch service lists no builds for it right now. Run this again later; its vendored copy stays in force as it is.` (or `…; its vendored copy of an earlier patch stays in force as it is.`). A gem pinned hosted (a takeover) stays hosted: `…; the gem stays hosted.` A re-run vendors the gem once the registry lists a gem for every locked platform, a patched build for at least one of them, and serves each patch it names. A newer patch that has no patched build for a platform the vendored copy of an earlier patch holds one for is this skip too: `… was not brought up to date: the newer fix has no patched build for x86_64-linux-gnu yet; its vendored copy of an earlier patch stays in force as it is.` Every line of a fix that names no builds says `Run this again later`, the failure below included (`… right now. Run this again later; its vendored copy is missing or damaged and cannot be rebuilt until then.`). Two cases stay failures (`vendor_prebuilt_required`): a copy the lock is already wired to that is missing or damaged and cannot be rebuilt, by a re-run or by `repair` (`…; its vendored copy is missing or damaged and cannot be rebuilt until then.`); and an eject of the gem's hosted pin (plain `vendor`), which is all-or-nothing and keeps the pin. | | `unsafe_coordinates` | `failed` | vendor: purl/uuid would escape `.socket/vendor/` (tampered manifest/state); refused before any write. | @@ -2614,9 +2614,9 @@ command's integration tests check its output. | `vendor_dep_manifest_unlocked` | refused | vendor (yarn classic): the patch rewrites the package's own `package.json` to depend on a descriptor (`name@range`) no `yarn.lock` block is keyed by — an added dependency, or an existing one moved to a new range. A descriptor every wired block's sub-map already names is not counted: yarn keys those blocks by the registry packument's ranges, which can differ from the tarball's `package.json` (#1578). yarn 1 builds its install graph from the lock, so the rewired block would name a dependency it never resolves: online frozen installs fetch it unpinned, `--offline` installs fail and every plain `yarn install` re-saves the lock (#591). Refused after staging and before any wiring is written (the staged uuid dir is removed); the detail names the descriptors. Remedy: lock them first (for example `yarn add `), then re-run. A dry run, which stages nothing, does not foresee it. Also `failed` on `repair` (and `vendor_check_failed` on `vendor --check`) for a lock an older release already vendored that way, with a block wired to the entry naming a descriptor no block locks and the recorded pre-vendor block did not (#1379); the lock is left as it is. Remedy: `yarn install` (without `--frozen-lockfile`) to lock them, then commit `yarn.lock`. | | `redirect_yarn_classic_dep_manifest_unlocked` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` depends on a descriptor no `yarn.lock` block is keyed by and that the sub-maps of the registry blocks being pinned don't already name (yarn keys those by the packument's ranges, #1578). yarn 1 installs only what the lock names, so a pin would install the patched package without that dependency (#591). The dep is not pinned and never confirmed; the lock is left as it was. The served tarball is read on every run, so a pin an earlier release wrote without this check (#1462) gets the same warning and is never confirmed either; it stays in the lock until the dependency is locked or the pin is rolled back. Same remedy as `vendor_dep_manifest_unlocked`. | | `redirect_yarn_classic_dep_manifest_rewritten` | `warnings[]` (warning) | scan/get `--mode hosted` (yarn classic): the served tarball's own `package.json` declares other dependencies than the pinned block's sub-maps, every descriptor already locked; the block's `dependencies:` / `optionalDependencies:` sub-maps are rewritten to match, in the shape yarn 1 writes for that manifest (#591, #1558). | -| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. A gem vendored as platform gems is asked about on every path that finishes its copy, not only when it is first vendored: a copy the lock already names is refused where it stands (it is not removed), git is then asked with its index, and a refusal that comes from the uuid directory's own `.gitignore` and `.gitattributes` not being writable names them and that remedy (see `vendor_gem_git_metadata_unwritten`). | +| `vendor_artifact_gitignored` | `failed` | vendor (vlt, the npm-family tarball flavors — npm, pnpm, bun, yarn classic, yarn berry — NuGet, every PyPI flavor, a gem vendored as platform gems, and the JVM trees of Maven, Gradle, sbt and scala-cli): inside a git work tree, `git check-ignore --no-index` reports the new artifact's uuid directory (JVM: its tree root, such as `.socket/vendor/maven2`) as ignored by a rule its own `.gitignore` cannot override (such as a root `.socket/` or `vendor/` rule; the detail names the rule). Remedy: drop that rule for `.socket/vendor/`. Refused before any write, dry run included. A file rule such as `*.tgz`, `*.nupkg`, `*.whl` or `*.jar` is overridden by the `!*` `.gitignore` vendoring writes into the uuid dir or tree root (PyPI's uuid dir also gets the `.gitattributes` that unsets a `*.whl filter=lfs` rule); if a written tarball, directory payload, nupkg or wheel still reads as ignored, the run refuses and removes the uuid dir it created. A gem vendored as platform gems is asked about wherever its trees are about to be placed (a first vendor, a rebuild of a wired copy, a restore), before they are moved in and without the index, in a dry run too: a refusal leaves what is on disk as it was, and one that comes from the uuid directory's own `.gitignore` and `.gitattributes` not being writable names them and that remedy (see `vendor_gem_git_metadata_unwritten`). A copy that is in step, or left in force, is asked about nothing. | | `vendor_artifact_gitignore_unchecked` | warning | vendor (vlt, the npm-family tarball flavors, NuGet and every PyPI flavor): git is installed but could not answer the ignore check for the written vendored directory (it failed to start, ran past 30 s, or `rev-parse` / `check-ignore` exited with an error); the package is vendored and the detail names what failed. Remedy: make sure no ignore rule covers `.socket/` before committing. Git absent, or a project outside any work tree, raises nothing. | -| `vendor_gem_git_metadata_unwritten` | warning | vendor / scan / get `--mode vendored` and `repair` (a gem vendored as platform gems): the `.gitignore` and `.gitattributes` of the copy's uuid directory could not be written. Those two files keep a project ignore rule or filter (such as `*.so`, or a Git LFS rule) off the vendored binaries; they are not part of the copy, so the trees are in place and correct and the run does not fail. The detail names the two files and the error. Remedy: make them writable and run again. Said by every path that puts the trees in place or leaves them in force, once per run (a skip that leaves the copy in force ends its line with it). Where git would then not commit a file of the copy, the run fails instead with `vendor_artifact_gitignored`, which names these files as the cause. | +| `vendor_gem_git_metadata_unwritten` | warning | vendor / scan / get `--mode vendored` and `repair` (a gem vendored as platform gems): the `.gitignore` and `.gitattributes` of the copy's uuid directory could not be written. Those two files keep a project ignore rule or filter (such as `*.so`, or a Git LFS rule) off the vendored binaries; they are not part of the copy, so the trees are in place and correct and the run does not fail. The detail names the two files and the error. Remedy: make them writable and run again. Said by every path that puts the trees in place or leaves them in force, once per run (a skip that leaves the copy in force ends its line with it). Where trees are about to be placed and git would then not commit a file of them, they are not placed: `vendor_artifact_gitignored` names these files as the cause. | | `vendor_ledger_gitignored` | top-level error (exit 1) | vendor / scan / get `--mode vendored` (every backend) and the hosted→vendored eject: inside a git work tree, `git check-ignore` reports the vendor ledger `.socket/vendor/state.json` as ignored by a file rule (such as `state.json`, `*.json` or `**/state.json`; the message names it), so the commit the run asks for would leave it out and no other checkout could `rollback`, `list` or `vendor --revert` the patches (#1638). A ledger git already tracks is never refused. Refused before any write, dry run included. Remedy: drop the rule or add `!.socket/vendor/state.json`. A rule that ignores `.socket/` or `.socket/vendor/` as a directory is `vendor_artifact_gitignored`: per package from the backends that check it themselves (the npm family, NuGet, PyPI, the JVM trees), and as this same run-level refusal when the run includes any other ecosystem. | | `vendor_ledger_entry_missing` | `failed` | vendor (vlt): the only installed copy is vlt's link to a committed vendored directory, but the vendor ledger has no entry for the package; restore `.socket/vendor/state.json` from version control (v5.0: `repair` no longer re-synthesizes it). Replaces the `package_not_installed` skip. | | `vendor_variant_ambiguous` | `failed` | vendor / scan / get `--mode vendored` (pypi, gem): the package is not installed and the manifest holds several release variants of it (`?artifact_id=` / `?platform=`), none of which the vendor ledger records, so nothing says which distribution to vendor; install the package or keep one release variant. A variant the ledger records (at any patch uuid) is taken as the wired one and its siblings are left out without an event. | diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6cd3779fbb..0cfa8de7e6 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5234,7 +5234,7 @@ How each mode gets the patched code running: | Mode | What happens | |---|---| | Hosted | Bundler installs the patched `.gem` from the patch registry, and RubyGems compiles it like any registry gem. A gem the lock pins as precompiled platform gems (`x86_64-linux-gnu`) is installed through the patch registry with nothing to compile: the patched platform gem where the platform has one, upstream's own gem where it has none yet. The gem moves as soon as one locked platform has a patched build, and the run names the platforms that are patched and the ones that keep upstream's gem. | -| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way: a single short attempt, which a patch service that is down cannot turn into a failure) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. A run that cannot write those two files says so and goes on (`vendor_gem_git_metadata_unwritten`: make them writable and run again); where git would then leave a binary out of the commit, the run fails and names them. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | +| Vendored | A gem `Gemfile.lock` pins as precompiled platform gems (one entry per platform, such as `nokogiri (1.18.10-x86_64-linux-gnu)`) is vendored from patched platform gems. Each platform has a patch of its own, and the vendored directory holds each platform's patched gem unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. The gem is vendored as soon as one platform in the lock has a patched build. A platform that has none yet gets upstream's own gem, unchanged, as hosted mode installs it: the scan downloads it from Socket's patch server (not from rubygems.org, and without following a redirect), checks it against the sha256 the patch registry lists, and unpacks it beside the patched ones. One line says which platforms run patched code: `nokogiri 1.18.10: patched for x86_64-linux-gnu; upstream gem kept for arm64-darwin (no patched build yet)`. In `--json` the patched builds are the counted `applied` events and the other platform is the advisory `gem_upstream_build_kept` event, and `vex` attests the patched builds and states the other platform `affected`. Only a socket-patch release that contains this support and the platform-gem vendoring it builds on reads such a copy. 5.1.0 and earlier have no platform-gem vendoring and do not read such a copy: on 5.1.0 `vendor --check` fails on it and `vex` leaves the gem out of the document. Attest a project vendored this way (`vex`, `vendor --check`) with the release that vendored it or a later one. A later scan asks the patch registry which builds it lists (one small request per gem vendored this way: a single short attempt, which a patch service that is down cannot turn into a failure) and follows it: it puts a patched build that was published since in place of upstream's gem (`now also patched for arm64-darwin`), and puts upstream's gem back where a patched build was withdrawn. It never moves to a newer patch that has no patched build for a platform the vendored copy holds one for. A vendored copy that is intact is never made worse by this: when the registry cannot be asked the copy is left as it is, and when a newly listed build cannot be vendored (a failed download, a digest that does not match) the copy stays in force, the run exits 0 and one note says so (`vendor_gem_list_not_followed`). The run checks that the copy still stands before it says that; a rebuild that fails after it changed the copy is reported as a failure, and the next scan vendors the copy again. A copy that is damaged after the registry's list changed is vendored again from the current list by the next scan. While no platform in the lock has a patched build, or the patch of one is listed but still being built, the gem is not vendored: one line (`vendor_prebuilt_platform_pending`) says so. A platform the patch registry does not list (one upstream does not publish) is named as such, with what settles it (`bundle lock --remove-platform`), and neither mode patches the gem until then. While the patch service lists no builds for the gem at all (it has not read the version's gems yet, or is building one of them again), the line names no platform and says to run again later. A dry run says the same. The run does not fail, nothing is written, a copy that is already vendored stays in place, and a later run vendors the gem once a platform has a patched build. A lock that also holds the plain `nokogiri (1.18.10)` entry of the `ruby` platform is refused with `platform_gem_unsupported`, and so is a lock written by a Bundler older than 2.3 (its `BUNDLED WITH`), the oldest version the layout is verified on. The vendored directory carries its own `.gitignore` and `.gitattributes`, so a project rule such as `*.so` or a Git LFS filter does not keep the binaries out of the commit or change their bytes. A run that cannot write those two files says so and goes on (`vendor_gem_git_metadata_unwritten`: make them writable and run again); where git would then leave a binary out of the commit, the new files are not put in place and the run names the two files. Git is asked only when files are about to be placed, never about a copy that is already there. Bundler cannot add a platform the vendored directory has no gem for: to add one later, revert the gem (`vendor --revert`), run `bundle lock --add-platform ` and vendor again. A gem with a native extension that is locked for the `ruby` platform alone is refused (`native_extensions_unsupported`, or `platform_gem_unsupported` when the installed copy is a precompiled one): Bundler builds no extensions for path-sourced gems. Use hosted or agent mode for that gem. | | Agent (`apply`) | The extension is rebuilt from the gem's source archive with the patch laid over it, using RubyGems' builder and the Ruby that owns the install, and the build is put where Ruby loads it: the extension directory of a gem RubyGems built, the prebuilt binary of a precompiled gem. | `apply` takes the source gem (`-.gem`) from the gem home's `cache/` directory, From 614513e7f2c59d185f1ddb0ee0264d5df50ce9f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 00:25:31 +0000 Subject: [PATCH 27/28] Say a wired copy's pending skip in a scan's dry run too A scan or get vendored dry run reported an intact platform-gem copy as already vendored when the fix's list had moved to a patched build the patch service does not serve yet. preview_locked_builds dropped that refusal, so ask_platform_gems kept the in-sync verdict, while the wet run skips the gem with vendor_prebuilt_platform_pending and says the copy stays in force (wired_copy_failed). The preview of a wired lock now returns the pending refusal, and the scan preview turns it into the wet run's skip line for an intact copy. Any other refusal still leaves the copy's verdict as it was. Assisted-by: Claude Code:claude-opus-5-5 --- .../src/commands/scan/vendor_flow.rs | 9 +++++++ crates/socket-patch-core/src/vendor/gem.rs | 25 +++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index 9fc7c34ede..4692e0645f 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -328,6 +328,15 @@ impl VendorPreview { row.gem_builds = builds; continue; } + // A patched build the list names is not served yet: the + // wet run skips the gem and leaves its intact copy in + // force as it is (`wired_copy_failed`). + Some(LockedBuildsPreview::Refused { code, detail }) + if vendored && code == VENDOR_PREBUILT_PLATFORM_PENDING => + { + let detail = format!("{detail}; its vendored copy stays in force as it is."); + (code, detail) + } // What the wet run leaves a vendored copy with is the // copy as it is. Some(LockedBuildsPreview::Refused { .. }) if vendored => continue, diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 3b3319aad0..62e0073226 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -3602,8 +3602,20 @@ pub async fn preview_locked_builds( let moved = moved_sources(project_root, service, uuid, name, copy_rel, &trees, None); let sources = moved.await?; let cfg = service.filter(|cfg| cfg.service_enabled())?; - let served = served_builds(cfg, name, &trees, &sources).await; - return served.is_ok().then(|| builds_of(sources)); + // A patched build the list names that is not served yet is the + // wet run's skip, with the copy left in force + // ([`wired_copy_failed`]): the caller says so of an intact copy. + return match served_builds(cfg, name, &trees, &sources).await { + Ok(_) => Some(builds_of(sources)), + Err(outcome) => match *outcome { + VendorOutcome::Refused { code, detail } + if code == super::VENDOR_PREBUILT_PLATFORM_PENDING => + { + Some(LockedBuildsPreview::Refused { code, detail }) + } + _ => None, + }, + }; } let standing = match hosted { true => Standing::Hosted, @@ -14497,6 +14509,15 @@ mod tests { "{detail}" ); assert_eq!(ts::tree_snapshot(&root), before); + // A scan's preview says the same skip, not a copy in step. + match preview_locked_builds(&root, NOKO, UUID, false, Some(&cfg)).await { + Some(LockedBuildsPreview::Refused { code, detail: said }) => { + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING); + assert!(detail.starts_with(&said), "{said} / {detail}"); + } + previewed => panic!("{previewed:?}"), + } + assert_eq!(ts::tree_snapshot(&root), before); // An entry that names no build of its trees (a development // build's ledger), over trees that hold the files of the gem's From 4b7a0b97ecd008dc6530f3e3cde1252ab315e4fa Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 29 Nov 2026 04:17:59 +0000 Subject: [PATCH 28/28] Expect the pending skip from a wired copy's preview in the no-record test 614513e made preview_locked_builds return the wet run's vendor_prebuilt_platform_pending refusal for a wired lock whose list names a patched build the service does not serve yet. The no-record preview test still expected None for that case, so the coverage leg failed. Assert the pending refusal instead, as the wired-copy test added in 614513e does. Assisted-by: Claude Code:claude-opus-5-5 --- crates/socket-patch-core/src/vendor/gem.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 62e0073226..f182fd3ad6 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -16196,10 +16196,14 @@ mod tests { assert_eq!(downloads(&withdrawn).await, Vec::::new()); let (_unserved, cfg) = service(UUID, &[unserved(DARWIN, "pending_build"), upstream(LINUX)]).await; - assert!( - preview(&root, &cfg).await.is_none(), - "the copy stays as it is, as in the wet run" - ); + // The wet run skips the gem and leaves the copy as it is; the + // preview says that skip rather than a copy in step. + match preview(&root, &cfg).await { + Some(LockedBuildsPreview::Refused { code, .. }) => { + assert_eq!(code, crate::vendor::VENDOR_PREBUILT_PLATFORM_PENDING) + } + other => panic!("the wet run's pending skip: {other:?}"), + } } /// The preview words a skip as the wet run does when the Gemfile