From 8782b39a989999acb3f81a027ed3127e5e5f2a25 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:29:20 +0000 Subject: [PATCH 1/4] Claim #2106: one-shot gem build scripts Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRso7kGGWRcMwXQpkz From 1860d66732117f224893a1fc7b75f25f62390783 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:33:01 +0000 Subject: [PATCH 2/4] Test a gem build script that uses up a file A build script can use up a file the gem ships: argon2's extconf.rb renames Makefile.real to Makefile. The installed tree then lacks the file, and the in-place rebuild of agent mode fails in the script. The first test fails on main (the apply ends in native_extension_build_failed). The second guards the fix: a build that fails leaves the gem exactly as installed. Refs #2106 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRso7kGGWRcMwXQpkz Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_gem_native_ext_build.rs | 133 +++++++++++++++++- 1 file changed, 132 insertions(+), 1 deletion(-) diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index 1a21534dd..e9c8357f9 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -3625,6 +3625,20 @@ end File.write("Makefile", "all:\n\ninstall:\n\nclean:\n\n") "##; +/// `sp_wrap` with a build script that uses up a file the gem ships, as +/// argon2's does (`File.rename('Makefile.real', 'Makefile')`): the +/// installed tree holds no `Makefile.real`, and the script cannot run +/// there a second time. +const ONE_SHOT_EXTCONF: &str = r##"require "rbconfig" +Dir.chdir(__dir__) +name = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "libsp_wrap.dylib" : "libsp_wrap.so" +cc = RbConfig::CONFIG["CC"].split +abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +File.rename("Makefile.real", "Makefile") +"##; +/// The file [`ONE_SHOT_EXTCONF`] uses up, relative to the gem dir. +const ONE_SHOT_FILE: &str = "ext/sp_wrap/Makefile.real"; + /// A project with `sp_wrap` (built by `extconf`) installed into /// `vendor/bundle/ruby/` by the real `gem`, its archive in the home's /// `cache/`, and a record that changes `SpWrap.value` from 1 to 2. @@ -3645,11 +3659,13 @@ impl WrapGem { std::fs::write(src.join("ext/sp_wrap/extconf.rb"), extconf).unwrap(); std::fs::write(src.join(WRAP_C_KEY), wrap_c(1)).unwrap(); std::fs::write(src.join("lib/sp_wrap.rb"), WRAP_LIB).unwrap(); + // Shipped with every variant; only `ONE_SHOT_EXTCONF` touches it. + std::fs::write(src.join(ONE_SHOT_FILE), "all:\n\ninstall:\n\nclean:\n\n").unwrap(); std::fs::write( src.join("sp_wrap.gemspec"), "Gem::Specification.new do |s|\n s.name = \"sp_wrap\"\n s.version = \"1.0.0\"\n \ s.summary = \"t\"\n s.authors = [\"t\"]\n \ - s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb}\"]\n \ + s.files = Dir[\"lib/**/*.rb\", \"ext/**/*.{c,rb,real}\"]\n \ s.extensions = [\"ext/sp_wrap/extconf.rb\"]\nend\n", ) .unwrap(); @@ -3838,6 +3854,121 @@ fn a_build_that_keeps_a_stale_library_is_made_to_rebuild_it() { assert_eq!(fx.c_file(), wrap_c(1)); } +/// A build script that uses up a file the gem ships cannot run a second +/// time over the installed tree (argon2's renames `Makefile.real`). The +/// source gem still holds the file, so it is put back for the in-place +/// build: the patch is built, and nothing is left in the tree that the +/// build did not leave there itself. `rollback` gives the installed tree +/// back, with or without the backup of the original build (#2106). +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_build_script_that_uses_up_a_shipped_file_is_given_it_back() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, ONE_SHOT_EXTCONF); + assert_eq!(fx.value(), "1"); + assert!( + !fx.gem_dir.join(ONE_SHOT_FILE).exists(), + "the install-time build used the file up" + ); + let installed = walk_files(&fx.gem_dir); + let extensions = walk_files(&fx.home.join("extensions")); + + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!( + fx.value(), + "2", + "Ruby must load the library built from the patched source:\n{stdout}" + ); + let mut changed: Vec = tree_diff(&installed, &walk_files(&fx.gem_dir)) + .into_iter() + .filter(|line| !line.contains(".socket-patch-native-")) + .collect(); + changed.sort(); + assert_eq!( + changed, + [format!("~{}", fx.library()), format!("~{WRAP_C_KEY}")], + "the patched source and the library built from it are all that changed" + ); + let (code, stdout, stderr) = fx.run(&["apply", "--check"]); + assert_eq!(code, 0, "a rebuilt patch checks clean:\n{stdout}\n{stderr}"); + assert!(vex_attests(|args| fx.run(args))); + + let (code, stdout, stderr) = fx.run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.value(), "1", "Ruby must load the original library again"); + assert_tree(&fx.gem_dir, &installed, "after rollback"); + assert_tree(&fx.home.join("extensions"), &extensions, "after rollback"); + + // A rollback that has lost the backup rebuilds from the restored + // source, with the same script. (The first rollback dropped the + // record.) + write_record( + &fx.proj.join(".socket"), + WRAP_PURL, + &[(WRAP_C_KEY, Some(&wrap_c(1)), &wrap_c(2))], + ); + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); + assert_eq!(fx.value(), "2"); + std::fs::remove_dir_all(fx.gem_dir.join(".socket-patch-native-orig")).unwrap(); + let (code, stdout, stderr) = fx.run(&["rollback", "--json", "--offline"]); + assert_eq!(code, 0, "rollback failed:\n{stdout}\n{stderr}"); + assert_eq!( + fx.value(), + "1", + "the library is rebuilt from the restored source:\n{stdout}" + ); + assert_eq!(fx.c_file(), wrap_c(1)); + assert!( + !fx.gem_dir.join(ONE_SHOT_FILE).exists(), + "the file put back for the build is not left behind" + ); +} + +/// A patched source that does not compile fails the in-place build after +/// the shipped file was put back for it: the file goes again with +/// everything else the build did, and the gem is exactly as installed +/// (#2106). +#[test] +#[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ + the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] +fn a_failed_build_takes_the_shipped_file_it_was_given_away_again() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, ONE_SHOT_EXTCONF); + write_record( + &fx.proj.join(".socket"), + WRAP_PURL, + &[(WRAP_C_KEY, Some(&wrap_c(1)), &broken_source())], + ); + let installed = walk_files(&fx.gem_dir); + let extensions = walk_files(&fx.home.join("extensions")); + + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_ne!(code, 0, "a broken source cannot apply:\n{stdout}\n{stderr}"); + let env = parse_json_envelope(&stdout); + let event = common::envelope::event_for(&env, WRAP_PURL); + assert!( + event["error"] + .as_str() + .is_some_and(|e| e.starts_with("native_extension_build_failed:")), + "{stdout}" + ); + assert_eq!(fx.value(), "1"); + assert_tree(&fx.gem_dir, &installed, "after the failed apply"); + assert_tree( + &fx.home.join("extensions"), + &extensions, + "after the failed apply", + ); + assert!(!fx.home.join(".socket-patch-build").exists()); +} + /// Without the source gem nothing says which files the build makes, so /// none can be removed for it. A build that then exits cleanly and leaves /// every library as it was has not built the patched source: the patch is From 7a001ace4a7ea1d0c08c82ec846c16d92f346269 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 13:53:52 +0000 Subject: [PATCH 3/4] Give a gem build the files its first run used up A gem that loads its library from its own tree is rebuilt in agent mode where it is installed. That build ran over the tree as the install left it, and a build script may use up a file the gem ships: argon2's extconf.rb renames Makefile.real to Makefile. Run again, the script fails, so every agent-mode patch to an argon2 build input ended in native_extension_build_failed. The staged build of the source gem already says the gem builds into its own tree. It now also keeps the files the source gem ships that the installed copy no longer holds, read before the staged build uses them up as well. The in-place build gets them back after the tree snapshot is taken, so the undo of a failed build removes them. After a build that finishes, those it left untouched are removed again: the tree then differs from the installed one by what the build made, and rollback gives the installed tree back byte for byte. A rollback that has lost its backup rebuilds the same way. Fixes #2106 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRso7kGGWRcMwXQpkz Assisted-by: Claude Code:claude-fable-5-2 --- crates/socket-patch-core/src/patch/gem_ext.rs | 402 ++++++++++++++++-- docs/ecosystems.md | 16 +- 2 files changed, 383 insertions(+), 35 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 4688c1a16..390bcc869 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -3243,10 +3243,15 @@ fn stale_build( } /// Rebuild `copy`'s extension from the sources on disk with `probe.ruby`, -/// in its installed tree. `stale` are files of that tree the gem's build is -/// known to make ([`StageFailure::InTree`]): they are taken out of the -/// build's way, as a fresh install has none of them, so a build that would -/// take them for current makes them again. +/// in its installed tree, as close to a fresh install's as `seen` (what +/// the build of its source gem showed, [`StageFailure::InTree`]) lets it +/// be made. The files of the tree that build is known to make are taken +/// out of the build's way, as a fresh install has none of them, so a build +/// that would take them for current makes them again. The files the gem +/// ships that the tree no longer holds are put back for it ([`give_back`]), +/// so a build script that uses one up can run again (#2106); those the +/// build leaves as they were are taken away after it, whether it finished +/// or not. /// /// The gem's own tree is snapshotted first ([`TreeSnapshot`]). What a /// finished build replaced or added there is backed up with the original @@ -3265,7 +3270,7 @@ async fn rebuild( files: &HashMap, env: &RubyEnv, back_up: bool, - stale: &[String], + seen: &SeenInStage, ) -> Result<(), NotRebuilt> { // A backup this rebuild made is dropped again when the build does not // land: the install-time build is back in place, so the copy is as it @@ -3281,8 +3286,9 @@ async fn rebuild( .keys() .map(|key| normalize_file_path(key).to_string()) .collect(); - let (aside, made_backup, snapshot, removed) = { - let (copy, probe, stale) = (copy.clone(), probe.clone(), stale.to_vec()); + let (aside, made_backup, snapshot, removed, given) = { + let (copy, probe) = (copy.clone(), probe.clone()); + let (stale, used_up) = (seen.created.clone(), seen.used_up.clone()); crate::utils::fs::run_blocking(move || { let made = if back_up { back_up_original(©, &probe, &[]) @@ -3311,8 +3317,14 @@ async fn rebuild( } Ok((snapshot, removed)) }); + // What is written here is in no snapshot: the undo of a failed + // build removes it. + let prepared = prepared.and_then(|(snapshot, removed)| { + let given = give_back(©, &snapshot, &used_up, &left)?; + Ok((snapshot, removed, given)) + }); match prepared { - Ok((snapshot, removed)) => Ok((aside, made, snapshot, removed)), + Ok((snapshot, removed, given)) => Ok((aside, made, snapshot, removed, given)), Err(e) => { // The parked build stays where it is when the tree // cannot be put back: the next run tries again. @@ -3368,6 +3380,9 @@ async fn rebuild( let unread = watch .as_ref() .and_then(|watch| unread_inputs(©.gem_dir, watch, &snapshot.dir)); + // What the build left of the files it was given is no + // change it made. + take_away(©, &given); let changes = tree_changes(©, &snapshot); let stale = stale_build(©, &probe, &removed, &snapshot, &changes); match (stale, unread) { @@ -3414,8 +3429,13 @@ async fn rebuild( // The gem's own tree first, while the parked build still says a // rebuild is under way: if it cannot be put back, the parked build // stays, and the next run tries again from the snapshot. - let undone = - restore_tree(©, &snapshot.dir).and_then(|()| put_back(©, &probe, aside)); + let undone = restore_tree(©, &snapshot.dir) + .map(|()| { + // The files went with the restore; the dirs made for them + // are left to go. + take_away(©, &given); + }) + .and_then(|()| put_back(©, &probe, aside)); match undone { Ok(()) => { drop_new_backup(©, made_backup); @@ -3657,12 +3677,185 @@ enum StageFailure { /// in for it. InTree { products: Vec, - /// Those of `products` the source gem does not ship: the build - /// made them, and a fresh install builds without them. - created: Vec, + /// What the staged build showed that a build of the installed + /// tree goes by. + seen: SeenInStage, }, } +/// A file the source gem ships that the installed copy does not hold. +#[derive(Debug, Clone, PartialEq, Eq)] +struct ShippedFile { + /// Its path in the gem dir, `/`-separated. + rel: String, + bytes: Vec, + permissions: std::fs::Permissions, +} + +/// What building a gem's source gem in a stage showed of its build, for a +/// build of the installed tree ([`rebuild`]) to go by. The default (no +/// staged build to learn from) changes nothing of that build. +#[derive(Debug, Default)] +struct SeenInStage { + /// The files Ruby loads that the build made in the gem's own tree and + /// the source gem does not ship ([`in_tree_products`]): a fresh + /// install builds without them. + created: Vec, + /// The files the source gem ships that the installed copy no longer + /// holds ([`used_up_files`]): a fresh install builds with them. + used_up: Vec, +} + +/// The most bytes of [`used_up_files`] a run keeps while the staged build +/// runs. A gem that ships more than this and installs without it is built +/// in place from the tree as it is. +const USED_UP_LIMIT: usize = 64 * 1024 * 1024; + +/// The files of the pristine source gem unpacked at `staged` that the +/// copy at `installed` does not hold, with their content. +/// +/// RubyGems installs every file of a gem, so one that is gone was taken +/// away after the install, as a rule by the gem's own build: a script that +/// renames a file it ships (argon2's `extconf.rb` makes `Makefile.real` +/// its `Makefile`), or one that deletes the sources it has compiled. That +/// build cannot run a second time over what it left, and the build of the +/// stage uses the staged files up the same way, so they are read before +/// it. All of them or none: a file that cannot be read, or more than +/// [`USED_UP_LIMIT`] in all, keeps nothing. +fn used_up_files(installed: &Path, staged: &Path) -> Vec { + let mut files = Vec::new(); + let mut total = 0usize; + for rel in tree_files(staged) { + if !is_safe_relative_subpath(&rel) || is_own_entry(&rel) { + continue; + } + // Only a file that is not there is one the copy does not hold. + if !matches!(try_entry_type(&installed.join(&rel)), Ok(None)) { + continue; + } + let path = staged.join(&rel); + let (Ok(bytes), Ok(meta)) = (read_regular_to_bytes_sync(&path), std::fs::metadata(&path)) + else { + return Vec::new(); + }; + total = total.saturating_add(bytes.len()); + if total > USED_UP_LIMIT { + return Vec::new(); + } + files.push(ShippedFile { + rel, + bytes, + permissions: meta.permissions(), + }); + } + files +} + +/// The files [`give_back`] wrote, and the dirs it made for them. +#[derive(Debug, Default)] +struct GivenBack { + /// Gem-dir path → git-sha256 of what was written. + files: Vec<(String, String)>, + /// Deepest first. + dirs: Vec, +} + +/// Write the files a fresh install of the gem would hold and `copy` does +/// not (`used_up`) into its tree, for an in-place build to find: after +/// `snapshot` was taken, so the undo of a failed build removes them +/// ([`restore_tree`]). A path the tree holds by now, one of the record's +/// (`left`), and one under a link in the gem dir (it would be written +/// through the link) are left alone. On `Err` nothing of it is left. +fn give_back( + copy: &GemCopy, + snapshot: &TreeSnapshot, + used_up: &[ShippedFile], + left: &[String], +) -> std::io::Result { + let mut given = GivenBack::default(); + let written = write_used_up(copy, snapshot, used_up, left, &mut given); + // Deepest first, each once. + given + .dirs + .sort_by_key(|dir| std::cmp::Reverse(dir.components().count())); + given.dirs.dedup(); + match written { + Ok(()) => Ok(given), + Err(e) => { + // Nothing has run since: every file listed is this call's, + // whole or not. + for (rel, _) in &given.files { + let _ = std::fs::remove_file(copy.gem_dir.join(rel)); + } + take_away(copy, &given); + Err(e) + } + } +} + +/// [`give_back`]'s writes, each listed in `given` before it is made. +fn write_used_up( + copy: &GemCopy, + snapshot: &TreeSnapshot, + used_up: &[ShippedFile], + left: &[String], + given: &mut GivenBack, +) -> std::io::Result<()> { + for file in used_up { + let rel = &file.rel; + if !is_safe_relative_subpath(rel) + || is_own_entry(rel) + || left.contains(rel) + || snapshot.files.contains_key(rel) + { + continue; + } + let path = copy.gem_dir.join(rel); + if crate::utils::containment::try_linked_level(©.gem_dir, &path)?.is_some() + || try_entry_type(&path)?.is_some() + { + continue; + } + // The dirs that are made for it, to take away again with it. + let mut made = Vec::new(); + let mut dir = path.parent(); + while let Some(parent) = dir.filter(|parent| *parent != copy.gem_dir) { + if try_entry_type(parent)?.is_some() { + break; + } + made.push(parent.to_path_buf()); + dir = parent.parent(); + } + given.dirs.extend(made); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + given + .files + .push((rel.clone(), compute_git_sha256_from_bytes(&file.bytes))); + std::fs::write(&path, &file.bytes)?; + std::fs::set_permissions(&path, file.permissions.clone())?; + } + Ok(()) +} + +/// Take away what [`give_back`] wrote and the build left as it was: a +/// file of the gem that the installed copy did not hold before the build +/// is not left in it after. A file the build changed is the build's, and +/// stays. So does a dir that still holds something. +fn take_away(copy: &GemCopy, given: &GivenBack) { + for (rel, hash) in &given.files { + let path = copy.gem_dir.join(rel); + if is_real_file(&path) && compute_file_git_sha256_sync(&path).ok().as_ref() == Some(hash) { + let _ = std::fs::remove_file(&path); + } + } + for dir in &given.dirs { + // Fails on a dir that is not empty, which is the point. + let _ = std::fs::remove_dir(dir); + } +} + impl StageFailure { /// The failure as a clause of a message. fn describe(&self) -> String { @@ -4122,6 +4315,14 @@ async fn build_in_stage( .await .map_err(StageFailure::NotOwnSource)?; } + // What the installed copy's build used up of the gem, while the stage + // still holds it: only a copy RubyGems built is ever built in place. + let used_up = if source.full_name() == copy.full_name { + let (installed, unpacked) = (copy.gem_dir.clone(), staged.gem_dir.clone()); + crate::utils::fs::run_blocking(move || used_up_files(&installed, &unpacked)).await + } else { + Vec::new() + }; // The record over the pristine source gem, before anything runs. if let Some(record) = record { let blobs = stage_blobs(record.pkg_path, record.files, record.sources).await; @@ -4219,7 +4420,10 @@ async fn build_in_stage( .await }; if !products.is_empty() { - return Err(StageFailure::InTree { products, created }); + return Err(StageFailure::InTree { + products, + seen: SeenInStage { created, used_up }, + }); } Ok(built) } @@ -5416,12 +5620,13 @@ async fn rebuild_in_place( warning: None, }; } - // What the source gem's build was seen to make in the gem's own tree. - let stale: &[String] = match staged { - StageFailure::InTree { created, .. } => created, - _ => &[], + // What the source gem's build showed of this gem's build. + let nothing = SeenInStage::default(); + let seen = match staged { + StageFailure::InTree { seen, .. } => seen, + _ => ¬hing, }; - match rebuild(job.copy, probe, job.scope, job.files, job.env, true, stale).await { + match rebuild(job.copy, probe, job.scope, job.files, job.env, true, seen).await { Ok(()) => job.built(result), // The previous build is back, and the sources stay written. Err(NotRebuilt::NotOfPatch(why)) => { @@ -5686,9 +5891,9 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result rebuilt, - Err(stale) => { + Err(seen) => { let scope = NativeScope::default(); - rebuild(©, &probe, &scope, &HashMap::new(), env, false, &stale) + rebuild(©, &probe, &scope, &HashMap::new(), env, false, &seen) .await .map_err(NotRebuilt::into_detail) } @@ -5708,32 +5913,32 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result Result, Vec> { +) -> Result, SeenInStage> { let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) .await - .map_err(|_| Vec::new())?; + .map_err(|_| SeenInStage::default())?; let facts = SpecFacts::of(&spec_text, ©.full_name); let source = facts .release .filter(|_| facts.extensions.declared) - .ok_or_else(Vec::new)?; + .ok_or_else(SeenInStage::default)?; let gems = GemSource::of(&env.cwd, env.offline).await; let archive = gems .archive(©.home, &source) .await - .map_err(|_| Vec::new())?; + .map_err(|_| SeenInStage::default())?; let (stage, built) = match build_from_source_gem(copy, probe, &source, archive, &gems, env, None).await { Ok(staged) => staged, Err(StageFailure::Busy(why)) => return Ok(Err(why)), - Err(StageFailure::InTree { created, .. }) => return Err(created), - Err(_) => return Err(Vec::new()), + Err(StageFailure::InTree { seen, .. }) => return Err(seen), + Err(_) => return Err(SeenInStage::default()), }; let moved_in = { let (copy, probe) = (copy.clone(), probe.clone()); @@ -8520,6 +8725,145 @@ mod tests { ); } + /// The source gem of [`in_tree_gem`], unpacked: what the installed + /// copy holds of it, a Makefile its build script renames and a dir of + /// sources its build deletes. + fn source_gem_of(copy: &GemCopy, at: &Path) -> PathBuf { + let staged = at.join("staged"); + for (rel, bytes) in [ + ("ext/a/a.c", "patched source"), + ("ext/a/Makefile.real", "the makefile"), + ("ext/a/vendor/src/b.c", "packed source"), + ("lib/a.rb", "ruby"), + (MARKER_FILE, "not the gem's"), + ] { + let path = staged.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + assert!(!copy.gem_dir.join("ext/a/Makefile.real").exists()); + staged + } + + fn rels(files: &[ShippedFile]) -> Vec<&str> { + files.iter().map(|file| file.rel.as_str()).collect() + } + + /// The files a fresh install would hold and the copy does not are the + /// ones its build used up: they are read from the pristine source gem, + /// with nothing of this module's among them (#2106). + #[test] + fn the_files_a_build_used_up_are_read_from_the_source_gem() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, _probe) = in_tree_gem(tmp.path()); + let staged = source_gem_of(©, tmp.path()); + let used_up = used_up_files(©.gem_dir, &staged); + assert_eq!( + rels(&used_up), + ["ext/a/Makefile.real", "ext/a/vendor/src/b.c"] + ); + assert_eq!(used_up[0].bytes, b"the makefile"); + } + + /// The used-up files are put back for the in-place build, after the + /// snapshot: a failed build's undo removes them, and after a finished + /// one those the build left alone go again, with the dirs made for + /// them. One the build wrote to is the build's (#2106). + #[test] + fn used_up_files_are_given_back_for_the_build_and_taken_away_after() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let staged = source_gem_of(©, tmp.path()); + let used_up = used_up_files(©.gem_dir, &staged); + let installed = tree_bytes(©.gem_dir); + let dirs = |copy: &GemCopy| copy.gem_dir.join("ext/a/vendor").exists(); + + // A build that fails: the snapshot's undo, then the dirs. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + assert_eq!( + std::fs::read(copy.gem_dir.join("ext/a/Makefile.real")).unwrap(), + b"the makefile" + ); + assert!(copy.gem_dir.join("ext/a/vendor/src/b.c").is_file()); + build_in_tree(©, &probe); + restore_tree(©, &snapshot.dir).unwrap(); + take_away(©, &given); + assert_eq!(tree_bytes(©.gem_dir), installed); + assert!(!dirs(©), "the dirs made for the files go with them"); + + // A build that finishes, having renamed one file as argon2's + // script does and left the other: neither is a change it made. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + std::fs::rename( + copy.gem_dir.join("ext/a/Makefile.real"), + copy.gem_dir.join("ext/a/Makefile"), + ) + .unwrap(); + take_away(©, &given); + assert!(!dirs(©)); + assert_eq!( + tree_changes(©, &snapshot), + TreeChanges { + replaced: vec!["ext/a/Makefile".to_string()], + created: vec![], + } + ); + restore_tree(©, &snapshot.dir).unwrap(); + + // A file the build wrote to stays, and is one it created. + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/vendor/src/b.c"), b"generated").unwrap(); + take_away(©, &given); + assert_eq!( + tree_changes(©, &snapshot).created, + ["ext/a/vendor/src/b.c"] + ); + restore_tree(©, &snapshot.dir).unwrap(); + take_away(©, &given); + assert_eq!(tree_bytes(©.gem_dir), installed); + } + + /// Nothing is written over a file the tree holds, in place of a file + /// of the record, or through a link in the gem dir (#2106). + #[test] + fn a_used_up_file_is_only_written_where_the_tree_has_none() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let shipped = |rel: &str| ShippedFile { + rel: rel.to_string(), + bytes: b"shipped".to_vec(), + permissions: std::fs::metadata(copy.gem_dir.join("lib/a.rb")) + .unwrap() + .permissions(), + }; + #[cfg_attr(not(unix), allow(unused_mut))] + let mut used_up = vec![ + shipped("ext/a/Makefile"), + shipped("ext/a/a.c"), + shipped("../outside"), + shipped(MARKER_FILE), + ]; + let outside = tmp.path().join("elsewhere"); + #[cfg(unix)] + { + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, copy.gem_dir.join("linked")).unwrap(); + used_up.push(shipped("linked/planted")); + } + // The record's file is gone from the tree (a patch may delete one). + std::fs::remove_file(copy.gem_dir.join("ext/a/a.c")).unwrap(); + let installed = tree_bytes(©.gem_dir); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let given = give_back(©, &snapshot, &used_up, &record_paths()).unwrap(); + assert!(given.files.is_empty(), "{given:?}"); + assert_eq!(tree_bytes(©.gem_dir), installed); + assert!(!outside.join("planted").exists()); + assert!(!tmp.path().join("gems/outside").exists()); + } + /// A build that fails part-way has already written into the gem's own /// tree. The snapshot puts every file back, and goes. #[test] diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 2e0c021f6..94bfd223e 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2198,12 +2198,16 @@ are never printed. The JRuby (`-java`) build of a gem ships jars and is always refused for such a patch. A gem that builds a library into its own directory and loads it from there (an FFI gem such as -scrypt, a Rakefile build such as digest-crc) is always rebuilt from its installed tree. The -libraries the gem's build makes there are removed first, as a fresh install has none of them, so -a build script that would take an existing library for current compiles the patched source. When -`apply` can't tell which files those are (no source gem to compare with) and the build exits -without changing any compiled code, the package fails with `native_extension_build_failed` -instead of being reported as patched. +scrypt or argon2, a Rakefile build such as digest-crc) is always rebuilt from its installed tree. +The libraries the gem's build makes there are removed first, as a fresh install has none of them, +so a build script that would take an existing library for current compiles the patched source. +The files the gem ships that its first build used up are put back from the source gem for the +build, so a build script that can only run once (argon2's renames a file it ships) runs again; +those the build leaves untouched are removed again afterwards. When `apply` has no source gem to +compare with, it can do neither: a build script that needs a file that is gone fails, and a build +that exits without changing any compiled code is not taken for one. Either way the package fails +with `native_extension_build_failed` instead of being reported as patched, and the gem is left as +it was. Ruby files are never build inputs outside `ext/` and a build script's directory: a patch that only changes `.rb` or `.rbs` files needs no compiler, wherever the gem keeps them. From 48c82f84c1a001cde065d39a0c516cc40ce37119 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 14:11:19 +0000 Subject: [PATCH 4/4] Give used-up gem files back with their own times Review fixes for the in-place build of a gem with a one-shot build script. A file given back kept the time it was written, which is after the patched sources were. A build that makes one from the other (a parser the gem ships generated) would take the shipped file for current. It now keeps the time the stage's copy was written, which is before the record's files are written anywhere. The size of a file is checked against the limit before it is read. Files that cannot be given back (a full disk) no longer fail the rebuild: it runs over the tree as it is, as it did before. The end-to-end test of a failed build broke the patched source, which fails the staged build first, so nothing was ever given back in it. Its build now fails only in the installed tree, after it used the shipped file up. Refs #2106 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeRso7kGGWRcMwXQpkz Assisted-by: Claude Code:claude-fable-5-2 --- .../tests/e2e_gem_native_ext_build.rs | 39 ++++++----- crates/socket-patch-core/src/patch/gem_ext.rs | 67 ++++++++++++++++--- 2 files changed, 82 insertions(+), 24 deletions(-) diff --git a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs index e9c8357f9..633f7296f 100644 --- a/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs +++ b/crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs @@ -3636,6 +3636,18 @@ cc = RbConfig::CONFIG["CC"].split abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") File.rename("Makefile.real", "Makefile") "##; +/// [`ONE_SHOT_EXTCONF`] with a build that only a fresh tree lets finish: +/// run over an installed one it compiles the library, uses the shipped +/// file up and then fails. +const ONCE_ONLY_EXTCONF: &str = r##"require "rbconfig" +Dir.chdir(__dir__) +name = RbConfig::CONFIG["host_os"] =~ /darwin/ ? "libsp_wrap.dylib" : "libsp_wrap.so" +cc = RbConfig::CONFIG["CC"].split +installed = File.exist?("Makefile") +abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +File.rename("Makefile.real", "Makefile") +abort "this tree was built before" if installed +"##; /// The file [`ONE_SHOT_EXTCONF`] uses up, relative to the gem dir. const ONE_SHOT_FILE: &str = "ext/sp_wrap/Makefile.real"; @@ -3929,10 +3941,10 @@ fn a_build_script_that_uses_up_a_shipped_file_is_given_it_back() { ); } -/// A patched source that does not compile fails the in-place build after -/// the shipped file was put back for it: the file goes again with -/// everything else the build did, and the gem is exactly as installed -/// (#2106). +/// A build that fails in the installed tree after it was given the +/// shipped file back, and after it compiled the patched library and used +/// the file up: the undo takes everything the build did with it, and the +/// gem is exactly as installed (#2106). #[test] #[ignore = "host capstone: compiles a C extension with the real ruby/gem toolchain; \ the unpinned `test` job skips it, the pinned-Ruby e2e leg runs it via --ignored"] @@ -3940,24 +3952,20 @@ fn a_failed_build_takes_the_shipped_file_it_was_given_away_again() { let Some(abi) = toolchain() else { return; }; - let fx = WrapGem::new(&abi, ONE_SHOT_EXTCONF); - write_record( - &fx.proj.join(".socket"), - WRAP_PURL, - &[(WRAP_C_KEY, Some(&wrap_c(1)), &broken_source())], - ); + let fx = WrapGem::new(&abi, ONCE_ONLY_EXTCONF); let installed = walk_files(&fx.gem_dir); let extensions = walk_files(&fx.home.join("extensions")); let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); - assert_ne!(code, 0, "a broken source cannot apply:\n{stdout}\n{stderr}"); + assert_ne!(code, 0, "the in-place build fails:\n{stdout}\n{stderr}"); let env = parse_json_envelope(&stdout); let event = common::envelope::event_for(&env, WRAP_PURL); assert!( - event["error"] - .as_str() - .is_some_and(|e| e.starts_with("native_extension_build_failed:")), - "{stdout}" + event["error"].as_str().is_some_and(|e| { + e.starts_with("native_extension_build_failed:") + && e.contains("this tree was built before") + }), + "the build got as far as the script's last line, so it was given the file:\n{stdout}" ); assert_eq!(fx.value(), "1"); assert_tree(&fx.gem_dir, &installed, "after the failed apply"); @@ -3967,6 +3975,7 @@ fn a_failed_build_takes_the_shipped_file_it_was_given_away_again() { "after the failed apply", ); assert!(!fx.home.join(".socket-patch-build").exists()); + assert!(!vex_attests(|args| fx.run(args))); } /// Without the source gem nothing says which files the build makes, so diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 390bcc869..ba70434df 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -3318,10 +3318,12 @@ async fn rebuild( Ok((snapshot, removed)) }); // What is written here is in no snapshot: the undo of a failed - // build removes it. - let prepared = prepared.and_then(|(snapshot, removed)| { - let given = give_back(©, &snapshot, &used_up, &left)?; - Ok((snapshot, removed, given)) + // build removes it. Files that cannot be written (a full + // disk) leave the tree as it is, which is what the build ran + // over before there was anything to give it. + let prepared = prepared.map(|(snapshot, removed)| { + let given = give_back(©, &snapshot, &used_up, &left).unwrap_or_default(); + (snapshot, removed, given) }); match prepared { Ok((snapshot, removed, given)) => Ok((aside, made, snapshot, removed, given)), @@ -3690,6 +3692,9 @@ struct ShippedFile { rel: String, bytes: Vec, permissions: std::fs::Permissions, + /// When the stage's copy was written: before the record's files were, + /// in the stage and in the installed copy. + modified: Option, } /// What building a gem's source gem in a stage showed of its build, for a @@ -3709,7 +3714,7 @@ struct SeenInStage { /// The most bytes of [`used_up_files`] a run keeps while the staged build /// runs. A gem that ships more than this and installs without it is built /// in place from the tree as it is. -const USED_UP_LIMIT: usize = 64 * 1024 * 1024; +const USED_UP_LIMIT: u64 = 64 * 1024 * 1024; /// The files of the pristine source gem unpacked at `staged` that the /// copy at `installed` does not hold, with their content. @@ -3722,9 +3727,15 @@ const USED_UP_LIMIT: usize = 64 * 1024 * 1024; /// stage uses the staged files up the same way, so they are read before /// it. All of them or none: a file that cannot be read, or more than /// [`USED_UP_LIMIT`] in all, keeps nothing. +/// +/// Each keeps the time the stage's copy was written, which is before the +/// record's files are written anywhere. A file given back with the time +/// of its writing would be newer than the patched sources, and a build +/// that makes one from the other (a parser the gem ships generated) would +/// take the shipped one for current. fn used_up_files(installed: &Path, staged: &Path) -> Vec { let mut files = Vec::new(); - let mut total = 0usize; + let mut total = 0u64; for rel in tree_files(staged) { if !is_safe_relative_subpath(&rel) || is_own_entry(&rel) { continue; @@ -3734,18 +3745,23 @@ fn used_up_files(installed: &Path, staged: &Path) -> Vec { continue; } let path = staged.join(&rel); - let (Ok(bytes), Ok(meta)) = (read_regular_to_bytes_sync(&path), std::fs::metadata(&path)) - else { + // Its size before its bytes: one that is over the limit is not + // read to find that out. + let Ok(meta) = std::fs::symlink_metadata(&path) else { return Vec::new(); }; - total = total.saturating_add(bytes.len()); + total = total.saturating_add(meta.len()); if total > USED_UP_LIMIT { return Vec::new(); } + let Ok(bytes) = read_regular_to_bytes_sync(&path) else { + return Vec::new(); + }; files.push(ShippedFile { rel, bytes, permissions: meta.permissions(), + modified: meta.modified().ok(), }); } files @@ -3834,6 +3850,13 @@ fn write_used_up( .files .push((rel.clone(), compute_git_sha256_from_bytes(&file.bytes))); std::fs::write(&path, &file.bytes)?; + if let Some(modified) = file.modified { + // Before the permissions, which may not let it be opened. + std::fs::OpenOptions::new() + .write(true) + .open(&path)? + .set_modified(modified)?; + } std::fs::set_permissions(&path, file.permissions.clone())?; } Ok(()) @@ -8763,6 +8786,13 @@ mod tests { ["ext/a/Makefile.real", "ext/a/vendor/src/b.c"] ); assert_eq!(used_up[0].bytes, b"the makefile"); + assert_eq!( + used_up[0].modified, + std::fs::metadata(staged.join("ext/a/Makefile.real")) + .unwrap() + .modified() + .ok() + ); } /// The used-up files are put back for the in-place build, after the @@ -8774,6 +8804,14 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let (copy, probe) = in_tree_gem(tmp.path()); let staged = source_gem_of(©, tmp.path()); + // The stage was unpacked before the patched sources were written. + let unpacked = std::time::SystemTime::now() - Duration::from_secs(3600); + std::fs::File::options() + .write(true) + .open(staged.join("ext/a/Makefile.real")) + .unwrap() + .set_modified(unpacked) + .unwrap(); let used_up = used_up_files(©.gem_dir, &staged); let installed = tree_bytes(©.gem_dir); let dirs = |copy: &GemCopy| copy.gem_dir.join("ext/a/vendor").exists(); @@ -8786,6 +8824,16 @@ mod tests { b"the makefile" ); assert!(copy.gem_dir.join("ext/a/vendor/src/b.c").is_file()); + // Not newer than the patched source: a build that makes one from + // the other would take the file given back for current. + let written = |rel: &str| { + std::fs::metadata(copy.gem_dir.join(rel)) + .unwrap() + .modified() + .unwrap() + }; + assert_eq!(Some(written("ext/a/Makefile.real")), used_up[0].modified); + assert!(written("ext/a/Makefile.real") < written("ext/a/a.c")); build_in_tree(©, &probe); restore_tree(©, &snapshot.dir).unwrap(); take_away(©, &given); @@ -8838,6 +8886,7 @@ mod tests { permissions: std::fs::metadata(copy.gem_dir.join("lib/a.rb")) .unwrap() .permissions(), + modified: None, }; #[cfg_attr(not(unix), allow(unused_mut))] let mut used_up = vec![