From 60193d1d322faddd531b573fc35ef371b917b583 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:25:32 +0000 Subject: [PATCH 1/4] Start fix for gem revert after a removed platform Refs #2283. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRdzAqnWS27Kgayqvw From 5534752296ad85a749f78b0a04bb9bc83457b733 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:35:04 +0000 Subject: [PATCH 2/4] Test gem revert after a platform is removed Three tests for a gem vendored as platform gems whose lock lost a platform to `bundle lock --remove-platform`. Two fail today: the revert of the wired pair, and the revert of a pair that is already back on the registry. The third pins what stays as it is. Refs #2283. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRdzAqnWS27Kgayqvw Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/vendor/gem.rs | 122 +++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index bf81f0a35a..1dfee11ed2 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -13238,5 +13238,127 @@ mod tests { assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); } + + /// `lock` as `bundle lock --remove-platform x86_64-linux-gnu` + /// leaves it: the platform, its spec block and its CHECKSUMS line + /// are gone (bundler 4.0.18 on a registry lock and on a vendored + /// one, #2283). + fn without_linux(lock: &str) -> String { + let block = " nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n"; + assert!(lock.contains(block), "{lock}"); + let mut out = String::new(); + for line in lock.replace(block, "").split_inclusive('\n') { + let checksum = line.starts_with(" nokogiri (1.18.10-x86_64-linux-gnu)"); + if line != " x86_64-linux-gnu\n" && !checksum { + out.push_str(line); + } + } + out + } + + /// A platform bundler removed from the lock after the gem was + /// vendored has nothing to restore: the revert puts back the + /// entries of the platforms still locked, which is the lock bundler + /// writes for the same removal on the registry lock (#2283). + #[tokio::test] + async fn a_platform_removed_from_the_lock_reverts_without_it() { + for registry in [None, Some(checksums(&sha('a'), &sha('b')))] { + let lock_before = lock(registry.as_deref()); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let removed = without_linux(&text(root.join(GEMFILE_LOCK)).await); + tokio::fs::write(root.join(GEMFILE_LOCK), &removed) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!( + text(root.join(GEMFILE_LOCK)).await, + without_linux(&lock_before) + ); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + } + } + + /// The same removal on a pair that is already back on the registry + /// (a hand restore, or a regenerated lock) has converged: nothing + /// is written and the copy goes. + #[tokio::test] + async fn a_restored_lock_without_a_removed_platform_has_converged() { + for registry in [None, Some(checksums(&sha('a'), &sha('b')))] { + let lock_before = lock(registry.as_deref()); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let restored = without_linux(&lock_before); + tokio::fs::write(root.join(GEMFILE_LOCK), &restored) + .await + .unwrap(); + tokio::fs::write(root.join(GEMFILE), GEMFILE_NOKO) + .await + .unwrap(); + + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, restored); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + assert!(!root.join(format!(".socket/vendor/gem/{UUID}")).exists()); + } + } + + /// Only the removal bundler makes counts as one. With the spec + /// entry gone and the bare CHECKSUMS line vendor wrote still there, + /// the platform is restored with the others. With a line vendor + /// did not write in its place the record has drifted, and neither + /// file is written. + #[tokio::test] + async fn a_half_removed_platform_is_restored_or_drift() { + let lock_before = lock(Some(&checksums(&sha('a'), &sha('b')))); + let (_tmp, root, record) = project(&lock_before).await; + let (_server, cfg) = service(UUID, &[served(DARWIN), served(LINUX)]).await; + let entry = vendor_and_persist(&root, &record, &cfg).await; + let wired = text(root.join(GEMFILE_LOCK)).await; + let gemfile = text(root.join(GEMFILE)).await; + let block = " nokogiri (1.18.10-x86_64-linux-gnu)\n racc (~> 1.4)\n"; + let spec_only = wired.replace(block, ""); + let other_line = spec_only.replace( + " nokogiri (1.18.10-x86_64-linux-gnu)\n", + &format!(" nokogiri (1.18.10-x86_64-linux-gnu){}\n", sha('e')), + ); + assert_ne!(other_line, spec_only); + tokio::fs::write(root.join(GEMFILE_LOCK), &other_line) + .await + .unwrap(); + let outcome = revert_gem(&entry, &root, false).await; + assert!( + outcome + .warnings + .iter() + .any(|w| w.code == "vendor_lock_entry_drifted"), + "{:?}", + outcome.warnings + ); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, other_line); + assert_eq!(text(root.join(GEMFILE)).await, gemfile); + assert!(root.join(rel(UUID)).is_dir(), "the copy is kept on drift"); + + assert_ne!(spec_only, wired); + tokio::fs::write(root.join(GEMFILE_LOCK), &spec_only) + .await + .unwrap(); + tokio::fs::write(root.join(GEMFILE), &gemfile) + .await + .unwrap(); + let outcome = revert_gem(&entry, &root, false).await; + assert!(outcome.success, "{:?}", outcome.error); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, lock_before); + assert_eq!(text(root.join(GEMFILE)).await, GEMFILE_NOKO); + } } } From 2da8904e76536aeb96c7571a18c635bdd7cfb660 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:56:21 +0000 Subject: [PATCH 3/4] Fix gem revert after a platform is removed A gem vendored as platform gems records one spec block and one CHECKSUMS line per platform the lock held. `bundle lock --remove-platform` drops a platform's spec and its CHECKSUMS line together, and the revert read the missing line as drift: rollback, remove and `vendor --revert` kept the gem wired, and the remedy they name (a re-scan) changed nothing. A platform the lock holds nothing of any more now has nothing to restore. The lock record puts back the blocks of the platforms still locked, the checksum record skips the removed platform's line, and a pair that is already back on the registry without the platform has converged. The reverted lock is the one bundler writes for the same removal on the registry lock. A lock that keeps the platform's spec or a CHECKSUMS line for it is judged as before. The platform-gem capstone drops a platform from a copy of the vendored project with the real bundler and compares the rollback with bundler's own lock for that removal. Fixes #2283. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRdzAqnWS27Kgayqvw Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- .../tests/e2e_vendor_gem_build.rs | 72 +++++++++++++++++ crates/socket-patch-core/src/vendor/gem.rs | 81 +++++++++++++++---- docs/ecosystems.md | 2 +- 4 files changed, 138 insertions(+), 19 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 10b3aecec0..73fc854d48 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1775,7 +1775,7 @@ worse, lets a warm cache silently serve unpatched bytes): | npm / pnpm | `packages[].resolution.integrity` (sha512) | recomputed from the tarball; the versioned `pnpm.overrides` selector pins exactly the patched version | | npm / bun | the packages-entry trailing `sha512-…` | recomputed from the tarball; tamper fails the frozen install on Bun ≥ 1.3.10 (URL/local tarball tuples are verified from 1.3.10, registry 4-tuples from 1.2.0 — so on 1.1.39–1.3.9 a hosted or vendored rewrite removes digest enforcement for the patched package; see `docs/testing/bun-compatibility.md`) | | npm / vlt | node slot [2] (sha512), slot [3] (resolved) | a `file` node carries none: the committed directory is the artifact, verified against the ledger's file inventory (`vendor_inventory_mismatch` on a planted, removed or changed file); integrity-less by vlt's design, like every `file:` directory dependency | -| gem | `CHECKSUMS` section (bundler ≥ 2.6 opt-in) | the vendored gem's entry rewritten to bundler's own path-gem form (bare `name (ver)`, sha256 token stripped) so re-locks stay byte-stable; original line in the ledger. A gem vendored as platform gems has one entry per platform (`name (ver-platform)`): each is made bare, and each original line is in the ledger | +| gem | `CHECKSUMS` section (bundler ≥ 2.6 opt-in) | the vendored gem's entry rewritten to bundler's own path-gem form (bare `name (ver)`, sha256 token stripped) so re-locks stay byte-stable; original line in the ledger. A gem vendored as platform gems has one entry per platform (`name (ver-platform)`): each is made bare, and each original line is in the ledger. A platform removed from the lock after vendoring (`bundle lock --remove-platform ` drops its spec entry and its `CHECKSUMS` line) is not drift: the revert puts back the entries of the platforms still locked and nothing of the removed one, which is the lock Bundler writes for that removal on the registry lock | | pypi / uv | `wheels[].hash`, `sdist.hash`, requires-dist specifiers | single `{filename, hash: sha256-of-our-wheel}`; sdist dropped; dropped specifiers ledgered for revert | | pypi / poetry | `files = [{file, hash}]` (2.x) / `[metadata.files]` entry (1.0/1.1) / `[metadata.hashes]` entry (0.12) | replaced with a single `{file, hash: sha256-of-our-wheel}` (or the bare hash for 0.12) in the generation's own table (Poetry ≥ 1.4 verifies the artifact against one listed hash; older writers are flagged `pypi_poetry_integrity_unverified`; stale registry hashes removed) | | pypi / pdm | `[[package]].files[]` hashes | replaced with our wheel's sha256; hash-less locks refused (`pypi_pdm_lock_no_hashes`) | 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 14ffd294ac..0c654c0f70 100644 --- a/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs +++ b/crates/socket-patch-cli/tests/e2e_vendor_gem_build.rs @@ -2948,6 +2948,11 @@ async fn service_requests(server: &MockServer) -> usize { /// 7. `vendor --revert` restores the Gemfile and the lock byte for byte /// (the registry CHECKSUMS tokens included) and removes the trees. /// +/// Before the revert, a copy of the vendored project drops one platform +/// with `bundle lock --remove-platform`: it still installs frozen, and +/// `rollback` restores the lock bundler writes for that removal on the +/// registry lock (#2283). +/// /// Run for a gem the Gemfile declares, and for one it only reaches through /// another gem (wired by the managed block). #[tokio::test(flavor = "multi_thread")] @@ -3451,6 +3456,73 @@ async fn platform_gems_capstone(bundler: &bundler_e2e::Bundler, declared: &str) drop(update); std::fs::write(&manifest_path, manifest).unwrap(); + // A platform the project drops after the gem is vendored (#2283): + // `bundle lock --remove-platform` takes it out of the wired lock, + // which still installs frozen, and `rollback` then gives back the lock + // the same bundler writes for that removal on the registry lock. + let dropped = foreign[1].as_str(); + let dropped_entry = format!("{PLAT} ({PLAT_VERSION}-{dropped})"); + let remove_platform = |root: &Path| { + let out = bundle(root, &["lock", "--remove-platform", dropped], false); + assert!( + out.status.success(), + "`bundle lock --remove-platform {dropped}` failed in {}:\n{}", + root.display(), + String::from_utf8_lossy(&out.stderr) + ); + std::fs::read_to_string(root.join("Gemfile.lock")).unwrap() + }; + let registry = base.join("registry-removed"); + std::fs::create_dir_all(®istry).unwrap(); + std::fs::write(registry.join("Gemfile"), &gemfile_before).unwrap(); + std::fs::write(registry.join("Gemfile.lock"), &lock_before).unwrap(); + common::fs_tree::copy_tree(&proj.join(".bundle"), ®istry.join(".bundle")); + let lock_removed = remove_platform(®istry); + let removed = base.join("vendored-removed"); + common::fs_tree::copy_tree(&proj, &removed); + // Bundler 2.5 and later drop the platform's spec entries with it; an + // older one keeps them, in the registry lock and in the wired one + // alike, and the rollback then restores every entry as before. + let wired_removed = remove_platform(&removed); + assert!( + wired_removed.starts_with(&format!("PATH\n remote: {copy_rel}\n")) + && wired_removed.contains(&dropped_entry) == lock_removed.contains(&dropped_entry), + "the wired lock loses what the registry lock loses (test premise):\n{wired_removed}" + ); + let ci = bundle(&removed, &["install"], true); + assert!( + ci.status.success(), + "the vendored pair must install frozen without the removed platform.\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&ci.stdout), + String::from_utf8_lossy(&ci.stderr), + ); + let (code, stdout, stderr) = run_socket( + &removed, + &[ + "rollback", + "--yes", + "--json", + "--offline", + "--cwd", + removed.to_str().unwrap(), + ], + ); + assert_eq!( + code, 0, + "rollback after a removed platform failed.\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + assert_eq!( + std::fs::read_to_string(removed.join("Gemfile.lock")).unwrap(), + lock_removed, + "rollback must give back the registry lock without the removed platform" + ); + assert_eq!( + std::fs::read(removed.join("Gemfile")).unwrap(), + gemfile_before, + "rollback must restore the Gemfile byte for byte" + ); + assert!(!removed.join(".socket/vendor").exists()); + // 7. Revert: both files byte for byte, every tree gone. let (code, stdout, stderr) = run_socket( &proj, diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 1dfee11ed2..5ece34654b 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -4035,7 +4035,8 @@ async fn revert_lock_record( /// True when the lock already holds the record's reverted state: no PATH /// section carries vendor's `remote:` line and every spec-block line of the -/// pre-vendor original is present. +/// pre-vendor original is present, but for the blocks of platforms bundler +/// has since removed from the lock ([`platform_removed`]). fn lock_record_converged(text: &str, original_lines: &[String], new_lines: &[String]) -> bool { // A record whose `new` lost its `remote:` line is malformed, never // converged (the tampered-ledger matrix pins it as drift). @@ -4050,13 +4051,53 @@ fn lock_record_converged(text: &str, original_lines: &[String], new_lines: &[Str return false; }; let gem = &lines[gs..ge]; - let mut spec_block = original_lines.iter().filter(|l| l.starts_with(" ")); - let mut any = false; - let all_present = spec_block.all(|l| { - any = true; - gem.contains(l) - }); - any && all_present + let spec_block = locked_spec_block(&lines, original_lines); + !spec_block.is_empty() && spec_block.iter().all(|l| gem.contains(l)) +} + +/// The spec-block lines of a `gemfile_lock_spec` record's pre-vendor +/// `original` that a revert restores to the lock `lines`: all of them, but +/// for the blocks of platforms bundler has since removed from the lock +/// ([`platform_removed`]). All of them as well when that would leave none: +/// a lock that names no build of the gem is not one a removal made. +fn locked_spec_block<'a>(lines: &[String], original_lines: &'a [String]) -> Vec<&'a String> { + let spec_block: Vec<&String> = original_lines + .iter() + .filter(|l| l.starts_with(" ")) + .collect(); + let mut locked = Vec::with_capacity(spec_block.len()); + // Whether the block being read (an entry and its dependency lines) is + // one of a platform the lock no longer holds. + let mut removed = false; + for &line in &spec_block { + if at_indent(line, 4).is_some() { + removed = spec_entry(line).is_some_and(|entry| platform_removed(lines, entry)); + } + if !removed { + locked.push(line); + } + } + if locked.is_empty() { + spec_block + } else { + locked + } +} + +/// True when the lock `lines` hold nothing of the platform build `entry` +/// (`(name, "-")`) of a gem vendored as platform gems: +/// no spec entry in any section, and no CHECKSUMS line. That is what +/// `bundle lock --remove-platform` leaves of a platform (it drops the +/// platform's spec and its CHECKSUMS line together, #2283), so a revert +/// has nothing of that platform to put back. A lock that keeps either one +/// is not that removal. Never true of a plain `name (version)` entry (a +/// RubyGems version holds no `-`). +fn platform_removed(lines: &[String], entry: (&str, &str)) -> bool { + entry.1.contains('-') + && !lines.iter().any(|l| spec_entry(l) == Some(entry)) + && !section_span(lines, "CHECKSUMS").is_some_and(|(start, end)| { + (start + 1..end).any(|i| checksum_entry(&lines[i]) == Some(entry)) + }) } fn wiring_string_array(v: Option<&Value>) -> Option> { @@ -4075,7 +4116,8 @@ fn wiring_string_array(v: Option<&Value>) -> Option> { /// pair). The search is confined to the CHECKSUMS section so a coincidental /// identical line elsewhere (e.g. a DEPENDENCIES entry) is never clobbered. /// The line vendor wrote being gone is drift — unless the registry line it -/// replaced is already back (convergence), left alone either way. +/// replaced is already back, or bundler removed the line's platform from +/// the lock (convergence), left alone either way. async fn revert_lock_checksum_record( files: &mut RevertFiles<'_>, w: &WiringRecord, @@ -4129,6 +4171,12 @@ async fn revert_lock_checksum_record( if original.is_some_and(|orig| (ck_start + 1..ck_end).any(|i| lines[i] == orig)) { continue; } + // ALREADY CONVERGED: bundler removed the platform from the lock + // (`bundle lock --remove-platform`), spec and CHECKSUMS line + // together, and the lock record restores no spec of it (#2283). + if checksum_entry(written).is_some_and(|entry| platform_removed(&lines, entry)) { + continue; + } return Ok(RecordRevert::Drifted); }; let Some(original) = original else { @@ -4154,26 +4202,25 @@ async fn revert_lock_checksum_record( /// Pure splice reversing [`edit_lock`]: drop the PATH section vendor emitted, /// move the spec block back into GEM/specs at its sorted position, and -/// restore (or delete) the DEPENDENCIES entry. All preconditions are checked -/// BEFORE any mutation so drift never yields a half-restored lock; `None` -/// means "drifted, leave the lock alone". +/// restore (or delete) the DEPENDENCIES entry. The block of a platform +/// bundler has since removed from the lock stays out ([`platform_removed`]). +/// All preconditions are checked BEFORE any mutation so drift never yields a +/// half-restored lock; `None` means "drifted, leave the lock alone". fn revert_lock_text(text: &str, original_lines: &[String], new_lines: &[String]) -> Option { let (new_dep_line, path_lines) = new_lines.split_last()?; let remote_line = path_lines.get(1)?; if !remote_line.starts_with(" remote: ") { return None; } - let spec_block: Vec<&String> = original_lines - .iter() - .filter(|l| l.starts_with(" ")) - .collect(); let source_remote = record_source_remote(original_lines); let old_dep_line = original_lines .iter() .find(|l| l.starts_with(" ") && !l[2..].starts_with(' ') && !l.starts_with(" remote: ")); - let our_name = spec_entry_name(spec_block.first()?)?.to_string(); let mut lines: Vec = text.split('\n').map(str::to_string).collect(); + // Read off the lock as found: the drain below takes the entries with it. + let spec_block = locked_spec_block(&lines, original_lines); + let our_name = spec_entry_name(spec_block.first()?)?.to_string(); // Preconditions on the untouched lines. let (path_start, path_end) = find_path_section(&lines, remote_line)?; diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 14dfbf8b6e..67c6116da5 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -5101,7 +5101,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 from the patched platform gem the registry serves for that platform, with nothing to compile; it is skipped with `redirect_gem_platform_unsupported` only while the patch has no patched build for one of the locked platforms. | -| 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 prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. 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 prebuilt 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 prebuilt patched platform gems. The patch service builds one for each platform, and the vendored directory holds each of them unpacked (`-//`), so Bundler loads the one for the platform it runs on and builds nothing. Every platform in the lock needs one. While the patch service has none for one of them the gem is skipped with `vendor_prebuilt_platform_pending`, which names the platforms that have none: the run does not fail, nothing is written, a patch that is already vendored stays in place, and a later run vendors the gem once every platform has one. 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 prebuilt 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. Removing one needs no revert: after `bundle lock --remove-platform ` the gem stays vendored for the platforms that remain, and `rollback`, `remove` and `vendor --revert` restore the lock without the removed platform. 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 2343c184d4a264066a53e3994c3d6bc42bacca5d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 22:16:07 +0000 Subject: [PATCH 4/4] Judge a removed gem platform by the whole record Review of the previous commit found three locks it read as a removed platform that are not one: another build of the gem in the removed one's place (a respelled platform), a lock with no build of the gem left, and lines of the gem the entry grammar does not read. Each made the revert drop a spec or leave a CHECKSUMS line behind and report success. One decision now serves the lock record and the checksum record. A platform counts as removed only when every spec entry and CHECKSUMS line of the gem in the lock is one the record names, and the lock still holds a spec entry of the record. Anything else is judged as before this fix. The three locks are pinned as drift. Refs #2283. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRdzAqnWS27Kgayqvw Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/vendor/gem.rs | 177 +++++++++++++++------ 1 file changed, 128 insertions(+), 49 deletions(-) diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 5ece34654b..17216db9bb 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -4036,7 +4036,7 @@ async fn revert_lock_record( /// True when the lock already holds the record's reverted state: no PATH /// section carries vendor's `remote:` line and every spec-block line of the /// pre-vendor original is present, but for the blocks of platforms bundler -/// has since removed from the lock ([`platform_removed`]). +/// has since removed from the lock ([`removed_platforms`]). fn lock_record_converged(text: &str, original_lines: &[String], new_lines: &[String]) -> bool { // A record whose `new` lost its `remote:` line is malformed, never // converged (the tampered-ledger matrix pins it as drift). @@ -4058,46 +4058,90 @@ fn lock_record_converged(text: &str, original_lines: &[String], new_lines: &[Str /// The spec-block lines of a `gemfile_lock_spec` record's pre-vendor /// `original` that a revert restores to the lock `lines`: all of them, but /// for the blocks of platforms bundler has since removed from the lock -/// ([`platform_removed`]). All of them as well when that would leave none: -/// a lock that names no build of the gem is not one a removal made. +/// ([`removed_platforms`]). fn locked_spec_block<'a>(lines: &[String], original_lines: &'a [String]) -> Vec<&'a String> { - let spec_block: Vec<&String> = original_lines - .iter() - .filter(|l| l.starts_with(" ")) - .collect(); - let mut locked = Vec::with_capacity(spec_block.len()); + let removed = removed_platforms(lines, original_lines); + let mut locked = Vec::new(); // Whether the block being read (an entry and its dependency lines) is // one of a platform the lock no longer holds. - let mut removed = false; - for &line in &spec_block { + let mut skip = false; + for line in original_lines.iter().filter(|l| l.starts_with(" ")) { if at_indent(line, 4).is_some() { - removed = spec_entry(line).is_some_and(|entry| platform_removed(lines, entry)); + skip = spec_entry(line) + .is_some_and(|(name, token)| removed.iter().any(|(n, t)| n == name && t == token)); } - if !removed { + if !skip { locked.push(line); } } - if locked.is_empty() { - spec_block - } else { - locked - } + locked } -/// True when the lock `lines` hold nothing of the platform build `entry` -/// (`(name, "-")`) of a gem vendored as platform gems: -/// no spec entry in any section, and no CHECKSUMS line. That is what -/// `bundle lock --remove-platform` leaves of a platform (it drops the -/// platform's spec and its CHECKSUMS line together, #2283), so a revert -/// has nothing of that platform to put back. A lock that keeps either one -/// is not that removal. Never true of a plain `name (version)` entry (a -/// RubyGems version holds no `-`). -fn platform_removed(lines: &[String], entry: (&str, &str)) -> bool { - entry.1.contains('-') - && !lines.iter().any(|l| spec_entry(l) == Some(entry)) - && !section_span(lines, "CHECKSUMS").is_some_and(|(start, end)| { - (start + 1..end).any(|i| checksum_entry(&lines[i]) == Some(entry)) - }) +/// The platform builds (`(name, "-")`) of a gem +/// vendored as platform gems that bundler has removed from the lock `lines` +/// since: the entries of the `gemfile_lock_spec` record's pre-vendor +/// `original_lines` the lock holds nothing of, neither a spec entry in any +/// section nor a CHECKSUMS line. That is what `bundle lock +/// --remove-platform` leaves of a platform (it drops the platform's spec +/// and its CHECKSUMS line together, #2283), so a revert has nothing of that +/// platform to put back. +/// +/// Empty unless the lock is what such a removal leaves of the record: +/// +/// * the record is of platform builds (a RubyGems version holds no `-`, so +/// a plain `name (version)` entry is never one); +/// * every spec entry and CHECKSUMS line of the gem in the lock is an entry +/// the record names. Another build in their place (a platform respelled +/// by a re-lock, a hand edit) or a line that names the gem and does not +/// parse is not a removal, and the records are judged as they stand; +/// * the lock still holds a spec entry of the record. A lock that names no +/// build of it lost more than a platform. +fn removed_platforms(lines: &[String], original_lines: &[String]) -> Vec<(String, String)> { + let recorded: Vec<(&str, &str)> = original_lines + .iter() + .filter_map(|l| spec_entry(l)) + .collect(); + let Some(&(name, _)) = recorded.first() else { + return Vec::new(); + }; + if recorded.iter().any(|(_, token)| !token.contains('-')) { + return Vec::new(); + } + let names_gem = |entry: &str| { + entry + .strip_prefix(name) + .is_some_and(|rest| rest.starts_with(" (")) + }; + let checksums = section_span(lines, "CHECKSUMS"); + let mut spec_held: Vec<(&str, &str)> = Vec::new(); + let mut checksum_held: Vec<(&str, &str)> = Vec::new(); + for (i, line) in lines.iter().enumerate() { + let in_checksums = checksums.is_some_and(|(start, end)| (start + 1..end).contains(&i)); + let (entry, held) = if in_checksums { + (at_indent(line, 2), &mut checksum_held) + } else { + (at_indent(line, 4), &mut spec_held) + }; + if !entry.is_some_and(names_gem) { + continue; + } + let parsed = match in_checksums { + true => checksum_entry(line), + false => spec_entry(line), + }; + match parsed.filter(|entry| recorded.contains(entry)) { + Some(entry) => held.push(entry), + None => return Vec::new(), + } + } + if spec_held.is_empty() { + return Vec::new(); + } + recorded + .into_iter() + .filter(|entry| !spec_held.contains(entry) && !checksum_held.contains(entry)) + .map(|(name, token)| (name.to_string(), token.to_string())) + .collect() } fn wiring_string_array(v: Option<&Value>) -> Option> { @@ -4161,6 +4205,17 @@ async fn revert_lock_checksum_record( // checksum for the gem at all, so there is no line left to restore. return Ok(RecordRevert::Done); }; + // The platforms bundler removed from the lock since, by the lock + // record's own reading of it (the checksum record holds only the lines + // vendor rewrote, not every build the lock held). + let removed = own + .entry + .wiring + .iter() + .find(|record| record.kind == LOCK_WIRING_KIND) + .and_then(|record| wiring_string_array(record.original.as_ref())) + .map(|original_lines| removed_platforms(&lines, &original_lines)) + .unwrap_or_default(); // Every pair is judged before the lock text is replaced, so one drifted // line leaves the others as found. let mut restored = false; @@ -4174,7 +4229,9 @@ async fn revert_lock_checksum_record( // ALREADY CONVERGED: bundler removed the platform from the lock // (`bundle lock --remove-platform`), spec and CHECKSUMS line // together, and the lock record restores no spec of it (#2283). - if checksum_entry(written).is_some_and(|entry| platform_removed(&lines, entry)) { + if checksum_entry(written) + .is_some_and(|(name, token)| removed.iter().any(|(n, t)| n == name && t == token)) + { continue; } return Ok(RecordRevert::Drifted); @@ -4203,7 +4260,7 @@ async fn revert_lock_checksum_record( /// Pure splice reversing [`edit_lock`]: drop the PATH section vendor emitted, /// move the spec block back into GEM/specs at its sorted position, and /// restore (or delete) the DEPENDENCIES entry. The block of a platform -/// bundler has since removed from the lock stays out ([`platform_removed`]). +/// bundler has since removed from the lock stays out ([`removed_platforms`]). /// All preconditions are checked BEFORE any mutation so drift never yields a /// half-restored lock; `None` means "drifted, leave the lock alone". fn revert_lock_text(text: &str, original_lines: &[String], new_lines: &[String]) -> Option { @@ -13361,8 +13418,10 @@ mod tests { /// Only the removal bundler makes counts as one. With the spec /// entry gone and the bare CHECKSUMS line vendor wrote still there, /// the platform is restored with the others. With a line vendor - /// did not write in its place the record has drifted, and neither - /// file is written. + /// did not write in its place, another build of the gem in its + /// place, no build of the gem left, or lines the entry grammar + /// does not read, the record has drifted and neither file is + /// written. #[tokio::test] async fn a_half_removed_platform_is_restored_or_drift() { let lock_before = lock(Some(&checksums(&sha('a'), &sha('b')))); @@ -13378,21 +13437,41 @@ mod tests { &format!(" nokogiri (1.18.10-x86_64-linux-gnu){}\n", sha('e')), ); assert_ne!(other_line, spec_only); - tokio::fs::write(root.join(GEMFILE_LOCK), &other_line) - .await - .unwrap(); - let outcome = revert_gem(&entry, &root, false).await; - assert!( - outcome - .warnings - .iter() - .any(|w| w.code == "vendor_lock_entry_drifted"), - "{:?}", - outcome.warnings + // The platform respelled (a re-lock, a hand edit): another + // build of the gem stands in its place. + let respelled = wired.replace("1.18.10-x86_64-linux-gnu)", "1.18.10-x86_64-linux)"); + // Every build gone, CHECKSUMS lines and all. + let none_left = without_linux(&wired) + .replace( + " nokogiri (1.18.10-arm64-darwin)\n racc (~> 1.4)\n", + "", + ) + .replace(" nokogiri (1.18.10-arm64-darwin)\n", ""); + assert!(!none_left.contains("nokogiri (1.18.10-"), "{none_left}"); + // The platform's lines in a line ending of their own, which + // the entry grammar does not read. + let unparsed = wired.replace( + "1.18.10-x86_64-linux-gnu)\n", + "1.18.10-x86_64-linux-gnu)\r\n", ); - assert_eq!(text(root.join(GEMFILE_LOCK)).await, other_line); - assert_eq!(text(root.join(GEMFILE)).await, gemfile); - assert!(root.join(rel(UUID)).is_dir(), "the copy is kept on drift"); + for drifted in [other_line, respelled, none_left, unparsed] { + assert_ne!(drifted, wired); + tokio::fs::write(root.join(GEMFILE_LOCK), &drifted) + .await + .unwrap(); + let outcome = revert_gem(&entry, &root, false).await; + assert!( + outcome + .warnings + .iter() + .any(|w| w.code == "vendor_lock_entry_drifted"), + "{drifted}: {:?}", + outcome.warnings + ); + assert_eq!(text(root.join(GEMFILE_LOCK)).await, drifted); + assert_eq!(text(root.join(GEMFILE)).await, gemfile); + assert!(root.join(rel(UUID)).is_dir(), "the copy is kept on drift"); + } assert_ne!(spec_only, wired); tokio::fs::write(root.join(GEMFILE_LOCK), &spec_only)