From 61755e232f95f0b26527bb7cb01b3fa36df8d9e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:22:49 +0000 Subject: [PATCH 1/5] Start fix for in-tree gem build products Claim commit for #2104 and #2105: the in-place rebuild of a gem's native extension neither backs up nor records the libraries the build leaves in the gem's own tree. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePpTeM1ZTDzN1jcpr1 From 1d18d1ed6382b33f2110a10a23a5d251cf767ccf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:31:36 +0000 Subject: [PATCH 2/5] Test in-tree gem build products end to end Three host capstones over a gem that builds its library into its own tree and loads it from there. Each fails on main: - rollback leaves the patched library in place, and nothing records it (#2104) - a build that takes the old library for current passes for a rebuild, with and without the source gem to compare (#2105) Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePpTeM1ZTDzN1jcpr1 --- .../tests/e2e_gem_native_ext_build.rs | 294 +++++++++++++----- 1 file changed, 218 insertions(+), 76 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 b981ecb6c..3f61aa547 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 @@ -2918,60 +2918,89 @@ fn wrap_c(value: u32) -> String { format!("int sp_wrap_value(void) {{ return {value}; }}\n") } -/// A gem that loads its library from its own tree is not left running the -/// old one: a build staged elsewhere cannot stand in for a library the -/// installed copy loads from where it was built, so the staged build is -/// set aside and the gem is rebuilt where it is installed. -#[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_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { - let Some(abi) = toolchain() else { - return; - }; - let tmp = tempfile::tempdir().unwrap(); - let scratch = tmp.path().to_path_buf(); - let src = scratch.join("sp_wrap"); - std::fs::create_dir_all(src.join("ext/sp_wrap")).unwrap(); - std::fs::create_dir_all(src.join("lib")).unwrap(); - std::fs::write(src.join("ext/sp_wrap/extconf.rb"), WRAP_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(); - 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.extensions = [\"ext/sp_wrap/extconf.rb\"]\nend\n", - ) - .unwrap(); - gem(&scratch, &src, &["build", "sp_wrap.gemspec"], &[]); - let proj = scratch.join("proj"); - let home = proj.join("vendor/bundle/ruby").join(&abi); - std::fs::create_dir_all(&home).unwrap(); - std::fs::write( - proj.join("Gemfile"), - "source \"https://rubygems.org\"\ngem \"sp_wrap\"\n", - ) - .unwrap(); - gem( - &scratch, - &scratch, - &[ - "install", - "--local", - "--no-document", - "--install-dir", - home.to_str().unwrap(), - src.join("sp_wrap-1.0.0.gem").to_str().unwrap(), - ], - &[], - ); - let gem_dir = home.join("gems/sp_wrap-1.0.0"); - let value = || { +/// `sp_wrap` with a build that takes a library it finds for current, as a +/// Rakefile whose library task does not depend on the C sources does +/// (digest-crc): run again over an installed tree, it compiles nothing. +const STALE_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 +unless File.exist?(name) + abort "could not build #{name}" unless system(*cc, "-shared", "-fPIC", "-o", name, "wrap.c") +end +File.write("Makefile", "all:\n\ninstall:\n\nclean:\n\n") +"##; + +/// 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. +struct WrapGem { + _tmp: tempfile::TempDir, + proj: PathBuf, + home: PathBuf, + gem_dir: PathBuf, +} + +impl WrapGem { + fn new(abi: &str, extconf: &str) -> WrapGem { + let tmp = tempfile::tempdir().unwrap(); + let scratch = tmp.path().to_path_buf(); + let src = scratch.join("sp_wrap"); + std::fs::create_dir_all(src.join("ext/sp_wrap")).unwrap(); + std::fs::create_dir_all(src.join("lib")).unwrap(); + 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(); + 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.extensions = [\"ext/sp_wrap/extconf.rb\"]\nend\n", + ) + .unwrap(); + gem(&scratch, &src, &["build", "sp_wrap.gemspec"], &[]); + let proj = scratch.join("proj"); + let home = proj.join("vendor/bundle/ruby").join(abi); + std::fs::create_dir_all(&home).unwrap(); + std::fs::write( + proj.join("Gemfile"), + "source \"https://rubygems.org\"\ngem \"sp_wrap\"\n", + ) + .unwrap(); + gem( + &scratch, + &scratch, + &[ + "install", + "--local", + "--no-document", + "--install-dir", + home.to_str().unwrap(), + src.join("sp_wrap-1.0.0.gem").to_str().unwrap(), + ], + &[], + ); + assert!(home.join("cache/sp_wrap-1.0.0.gem").is_file()); + write_record( + &proj.join(".socket"), + WRAP_PURL, + &[(WRAP_C_KEY, Some(&wrap_c(1)), &wrap_c(2))], + ); + let gem_dir = home.join("gems/sp_wrap-1.0.0"); + WrapGem { + _tmp: tmp, + proj, + home, + gem_dir, + } + } + + /// `SpWrap.value` as the installed gem's Ruby loads it. + fn value(&self) -> String { let out = Command::new("ruby") .args(["-W0", "-e", "require 'sp_wrap'; print SpWrap.value"]) - .env("GEM_PATH", &home) + .env("GEM_PATH", &self.home) .env_remove("GEM_HOME") .env_remove("RUBYOPT") .output() @@ -2982,43 +3011,156 @@ fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { String::from_utf8_lossy(&out.stderr) ); String::from_utf8_lossy(&out.stdout).into_owned() + } + + fn c_file(&self) -> String { + std::fs::read_to_string(self.gem_dir.join(WRAP_C_KEY)).unwrap() + } + + /// The library the gem loads, relative to the gem dir. + fn library(&self) -> String { + ["libsp_wrap.so", "libsp_wrap.dylib"] + .iter() + .map(|name| format!("ext/sp_wrap/{name}")) + .find(|rel| self.gem_dir.join(rel).is_file()) + .expect("the gem's library is in its own tree") + } + + fn run(&self, args: &[&str]) -> (i32, String, String) { + common::run_with_env(&self.proj, args, &[("SOCKET_RUBYGEMS_URL", NO_REGISTRY)]) + } +} + +/// A gem that loads its library from its own tree is not left running the +/// old one: a build staged elsewhere cannot stand in for a library the +/// installed copy loads from where it was built, so the staged build is +/// set aside and the gem is rebuilt where it is installed. The library +/// that build replaces is backed up and recorded like one in the extension +/// dir: `apply --check` notices it changing, and `rollback` gives the +/// original back byte for byte (#2104). +#[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_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { + let Some(abi) = toolchain() else { + return; }; - assert_eq!(value(), "1"); - assert!(home.join("cache/sp_wrap-1.0.0.gem").is_file()); - let (before, after) = (wrap_c(1), wrap_c(2)); - write_record( - &proj.join(".socket"), - WRAP_PURL, - &[(WRAP_C_KEY, Some(&before), &after)], - ); - let run = - |args: &[&str]| common::run_with_env(&proj, args, &[("SOCKET_RUBYGEMS_URL", NO_REGISTRY)]); + let fx = WrapGem::new(&abi, WRAP_EXTCONF); + assert_eq!(fx.value(), "1"); + let installed = walk_files(&fx.gem_dir); + let library = fx.library(); - let (code, stdout, stderr) = run(&["apply", "--json", "--offline"]); + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!( - value(), + fx.value(), "2", "Ruby must load the library built from the patched source:\n{stdout}" ); - assert_eq!( - std::fs::read_to_string(gem_dir.join(WRAP_C_KEY)).unwrap(), - after + assert_eq!(fx.c_file(), wrap_c(2)); + assert!(!fx.home.join(".socket-patch-build").exists()); + assert!(!fx.gem_dir.join(".socket-patch-native-tree").exists()); + let marker: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(fx.gem_dir.join(".socket-patch-native-build.json")).unwrap(), + ) + .unwrap(); + assert!( + marker["libArtifacts"][&library].is_string(), + "the build record names the library built in the gem's tree: {marker}" ); - assert!(gem_dir.join(".socket-patch-native-build.json").is_file()); - assert!(!home.join(".socket-patch-build").exists()); - let (code, stdout, stderr) = run(&["apply", "--check"]); + 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))); - // (Rollback restores the sources and the extension dir. The library in - // the gem's own tree is no part of what an in-place rebuild backs up, - // here as before the stage existed.) - let (code, stdout, stderr) = run(&["rollback", "--json", "--offline"]); + // A library that is no longer the one that was built is not attested. + let built = std::fs::read(fx.gem_dir.join(&library)).unwrap(); + std::fs::write(fx.gem_dir.join(&library), b"not the build").unwrap(); + let (code, stdout, stderr) = fx.run(&["apply", "--check"]); + assert_ne!( + code, 0, + "a replaced library must not check clean:\n{stdout}\n{stderr}" + ); + assert!(!vex_attests(|args| fx.run(args))); + std::fs::write(fx.gem_dir.join(&library), built).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", "Ruby must load the original library again"); + assert_tree(&fx.gem_dir, &installed, "after rollback"); +} + +/// A build that takes the library it finds in the gem's tree for current +/// compiles nothing when it runs over an installed copy. The products the +/// source gem's build was seen to make are removed first, as a fresh +/// install starts without them, so the library is built from the patched +/// source (#2105). +#[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_that_keeps_a_stale_library_is_made_to_rebuild_it() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, STALE_EXTCONF); + assert_eq!(fx.value(), "1"); + let installed = walk_files(&fx.gem_dir); + + let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); + assert_eq!(code, 0, "apply failed:\n{stdout}\n{stderr}"); assert_eq!( - std::fs::read_to_string(gem_dir.join(WRAP_C_KEY)).unwrap(), - before + fx.value(), + "2", + "Ruby must load the library built from the patched source:\n{stdout}" + ); + 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"); +} + +/// 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 +/// refused, the gem is left exactly as it was, and nothing attests it +/// (#2105). +#[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_that_compiles_nothing_is_refused_and_not_attested() { + let Some(abi) = toolchain() else { + return; + }; + let fx = WrapGem::new(&abi, STALE_EXTCONF); + std::fs::remove_file(fx.home.join("cache/sp_wrap-1.0.0.gem")).unwrap(); + 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 build that compiled nothing must not pass for a rebuild:\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:") && e.contains("compiled nothing") + }), + "the refusal says the build compiled nothing:\n{stdout}" + ); + assert_eq!(fx.value(), "1"); + assert_eq!(fx.c_file(), wrap_c(1), "the source is put back"); + assert_tree(&fx.gem_dir, &installed, "after the refused apply"); + assert_tree( + &fx.home.join("extensions"), + &extensions, + "after the refused apply", ); + assert!(!vex_attests(|args| fx.run(args))); } /// A precompiled gem ships one binary per Ruby minor, and a graft replaces From 70367e4ff6060ea91ffde48d0df90999a849f137 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:57:09 +0000 Subject: [PATCH 3/5] Track in-tree products of in-place gem builds A gem that builds a library into its own tree and loads it from there (scrypt, digest-crc) has no artifact in the RubyGems extension dir, which is all the in-place rebuild backed up, recorded and put back. The rebuild now snapshots the gem's tree before the build. What a finished build replaced or added there is backed up with the original build and attested by the marker, so rollback restores it byte for byte and vex notices it changing (#2104). A failed or interrupted build is undone from the snapshot. The products the source gem's build was seen to make are removed before the in-place build, as a fresh install has none, so a build script that takes an existing library for current compiles the patched source. With none known, a build of a changed input that leaves no compiled code changed fails instead of passing for a rebuild (#2105). Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePpTeM1ZTDzN1jcpr1 --- crates/socket-patch-cli/CLI_CONTRACT.md | 10 +- crates/socket-patch-core/src/patch/gem_ext.rs | 716 +++++++++++++++++- docs/ecosystems.md | 10 +- 3 files changed, 703 insertions(+), 33 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 11ff110b6..836af5c76 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1022,11 +1022,13 @@ Ruby inside the project is never run, and every run goes without the Socket cred The first rebuild of a copy backs up the original compiled code to `.socket-patch-native-orig/` in the gem directory (the install-time extension directory and `lib/` copies; a precompiled gem's -prebuilt binaries, each when it is first replaced), and every rebuild records +prebuilt binaries, each when it is first replaced; every file of the gem's own tree an in-place +rebuild replaced, with the names of those it added), and every rebuild records `.socket-patch-native-build.json` there: the source hashes it was built from and the hash of every artifact it put in place (`"grafted": true` for a precompiled gem's replaced binaries, whose paths -name the Ruby minors they were built for). A record whose sources are patched and whose marker -matches is `already_patched`; sources an earlier release patched without a rebuild are rebuilt, +name the Ruby minors they were built for; for an in-place rebuild, `libArtifacts` also lists what +the build left in the gem's own tree for Ruby to load). A record whose sources are patched and +whose marker matches is `already_patched`; sources an earlier release patched without a rebuild are rebuilt, with a `native_extension_rebuilt` warning. `rollback` (and `remove`) puts the backed-up build back with the sources, bytes and file mode; without a backup it rebuilds a gem RubyGems built from the restored sources, and fails a precompiled gem with `native_extension_restore_failed` (`gem @@ -1067,7 +1069,7 @@ a file the copy does not hold is not written: the record fails on it as on any m | Code | Run result | Meaning | |---|---|---| | `native_extensions_unsupported` | refused, exit 1 | The record changes build inputs that cannot be rebuilt here: the copy is not a RubyGems install with a `specifications/` entry (a Bundler git checkout); the gem neither declares extensions nor is a platform gem; it is the JRuby (`java`) build; no Ruby that owns the install was found; a precompiled gem cannot be built from its source gem (the archive is neither in the home's `cache/` nor downloadable, is not the copy's own source, the record does not apply to it, a gem its build needs could not be staged, its build leaves a library in the gem's own tree, or the build has no counterpart among the gem's prebuilt binaries); a record changes an input a build removed and the source gem cannot be built. Nothing is written. Also: another run is rebuilding the same gem right now, or an interrupted rebuild could not be undone (the error says which). | -| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail (of the build from the source gem and of the in-place one, when both ran). | +| `native_extension_build_failed` | refused, exit 1 | The extension did not build from the patched sources (no compiler or Ruby headers, a build error, an in-place build that exited cleanly without compiling anything), or the finished build could not be moved into place. The installed copy is as it was before the run; the error carries the build output's tail (of the build from the source gem and of the in-place one, when both ran). | | `native_extension_rebuilt` | warning | The sources were already patched (by a release before #1996, with `--no-gem-native-rebuild`, or by `apply` under another Ruby version of a precompiled gem) and the extension was rebuilt from them. Under `--dry-run`: the rebuild a real `apply` would run; no Ruby is started and nothing is downloaded to check that it can. | | `native_extension_not_rebuilt` | warning | `--no-gem-native-rebuild`: the sources were written without a rebuild; Ruby loads the old build until the caller compiles it. | | `native_extension_restore_failed` | rollback: that copy fails | The sources were restored, but the original compiled extension could not be put back. Run `gem pristine --extensions` (a precompiled gem: `gem pristine `). | diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index c2327a774..9185ad4c9 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -80,8 +80,12 @@ //! to 5) leaves a gem RubyGems built the rebuild it always had: in place, //! from its own tree (`rebuild`). The patched sources are written, the //! current build is moved aside, and RubyGems builds into a fresh -//! extension dir; a failed build puts the old build and the original -//! sources back, and its error names both failures. (The one exception: +//! extension dir. That build writes into the gem's own tree too, so the +//! tree is snapshotted first (`TreeSnapshot`): what the build replaced or +//! added there is backed up and attested with the extension dir's +//! artifacts, and a build that compiled nothing is a failed one +//! (`stale_build`). A failed build puts the old build, the gem's tree and +//! the original sources back, and its error names both failures. (The one exception: //! another run building the same gem right now.) A precompiled gem has no //! such fallback and is refused, with what it needs: network access to the //! registry once, or the source gem in the home's `cache/`. @@ -225,6 +229,12 @@ pub const MARKER_FILE: &str = ".socket-patch-native-build.json"; pub const BACKUP_DIR: &str = ".socket-patch-native-orig"; /// The backup's description file, inside [`BACKUP_DIR`]. const BACKUP_INFO: &str = "backup.json"; +/// The gem's own tree as it was before an in-place build, in the gem dir +/// for as long as that build runs (see [`TreeSnapshot`]). +const TREE_SNAPSHOT_DIR: &str = ".socket-patch-native-tree"; +/// What every entry this module keeps in a gem dir starts with: the +/// marker, the backup, the tree snapshot and their stages. +const OWN_ENTRY_PREFIX: &str = ".socket-patch-native"; /// The stage a rebuild from the source gem builds in, inside the gem home /// (the same filesystem as the build it replaces, so the finished extension @@ -1587,8 +1597,20 @@ fn recover_interrupted_rebuild_sync( format!("{} is a symlink, not an extension dir", ext.display()), )); } + // An in-place build was under way: the gem's own tree goes back to + // what it was before it ([`TreeSnapshot`]), whichever way the + // extension dir is settled, since no marker speaks for what the + // build left there. + let snapshot = copy.gem_dir.join(TREE_SNAPSHOT_DIR); + let in_place = is_real_dir(&snapshot); + if in_place { + restore_tree(copy, &snapshot)?; + } if ext.join(BUILD_COMPLETE).is_file() { remove_dir_if_exists(&parked)?; + if let Some(require_path) = require_path.filter(|_| in_place) { + realign_lib_copies(copy, &ext, require_path); + } } else { remove_dir_if_exists(&ext)?; std::fs::rename(&parked, &ext)?; @@ -1598,6 +1620,8 @@ fn recover_interrupted_rebuild_sync( } recovered = true; } + // No rebuild is under way now, so a snapshot that is left is nobody's. + drop_stale_tree_snapshot(copy); Ok(recovered) } @@ -2092,8 +2116,15 @@ struct BackupInfo { extension_dir: String, /// The extension dir existed (its tree is under `ext/`). had_extension_dir: bool, - /// The lib copies backed up under `lib/` (paths relative to the gem dir). + /// The files of the gem dir backed up under `lib/` (paths relative to + /// the gem dir): the lib copies of the extension dir's artifacts, and + /// every file of the gem's own tree an in-place build replaced or + /// removed ([`back_up_tree_changes`]). lib_files: Vec, + /// The files an in-place build added to the gem's own tree (paths + /// relative to the gem dir): `rollback` removes them. + #[serde(default)] + created_files: Vec, /// The backup is of a precompiled copy: `lib_files` are the prebuilt /// binaries a build of the source gem replaced, and there is no /// extension dir. @@ -2321,6 +2352,7 @@ fn commit_build( scope: &NativeScope, files: &HashMap, aside: &Aside, + in_tree: &[String], ) -> std::io::Result<()> { let ext = &probe.extension_dir; let mut marker = BuildMarker { @@ -2345,6 +2377,12 @@ fn commit_build( } marker.ext_artifacts.insert(rel, hash); } + // What the build left in the gem's own tree for Ruby to load is + // attested like the copies RubyGems makes there. + for rel in in_tree { + let hash = compute_file_git_sha256_sync(©.gem_dir.join(rel))?; + marker.lib_artifacts.insert(rel.clone(), hash); + } write_marker(copy, &marker)?; if let Some(old) = &aside.old_ext { let _ = remove_dir_if_exists(old); @@ -2366,9 +2404,313 @@ fn write_marker(copy: &GemCopy, marker: &BuildMarker) -> std::io::Result<()> { written } -/// Rebuild `copy`'s extension from the sources on disk with `probe.ruby`. -/// On failure every build product is put back as it was; `Err` is the -/// build's diagnostic. +/// Whether a gem-dir path is one of this module's own entries there +/// ([`OWN_ENTRY_PREFIX`]): never part of the gem's tree. +fn is_own_entry(rel: &str) -> bool { + rel.split('/') + .next() + .is_some_and(|top| top.starts_with(OWN_ENTRY_PREFIX)) +} + +/// The files of the gem's own tree ([`tree_files`]), this module's entries +/// aside. +fn gem_tree_files(gem_dir: &Path) -> Vec { + tree_files(gem_dir) + .into_iter() + .filter(|rel| !is_own_entry(rel)) + .collect() +} + +/// The gem's own tree as it was before an in-place build: a copy of every +/// file, in [`TREE_SNAPSHOT_DIR`] inside the gem dir. +/// +/// A build run in the installed tree writes there too: its objects and +/// Makefiles, and for a gem that loads its library from its own tree (an +/// FFI gem built with `ffi-compiler`, a Rakefile build), the compiled code +/// itself. Nothing says ahead of the build which files those are, so the +/// whole tree is kept until the build is committed or undone: a failed +/// build is undone from it ([`restore_tree`]), and a finished one backs up +/// what it replaced from it ([`back_up_tree_changes`]). +/// +/// The record's own files are no part of it: the patch writes them and +/// `rollback` puts them back, before or after a build is undone, and a +/// snapshot that held them would undo that with it. Their paths are kept +/// beside the copies ([`SNAPSHOT_LEFT`]), so a later run knows them too. +/// +/// It is taken while the parked build is locked and dropped before that +/// lock is, so one that is found without a parked build belongs to no run +/// ([`recover_interrupted_rebuild`]). +struct TreeSnapshot { + dir: PathBuf, + /// Gem-dir path → git-sha256, for every file copied. + files: BTreeMap, + /// The record's files (gem-dir paths), left as they are. + left: Vec, +} + +/// The copies of a [`TreeSnapshot`], inside its dir. +const SNAPSHOT_TREE: &str = "tree"; +/// The paths a [`TreeSnapshot`] leaves alone, inside its dir: a JSON list. +const SNAPSHOT_LEFT: &str = "left.json"; + +/// What a build did to the gem's own tree, against its [`TreeSnapshot`]. +#[derive(Debug, Default, PartialEq, Eq)] +struct TreeChanges { + /// Files the tree held that the build replaced or removed. + replaced: Vec, + /// Files the build added. + created: Vec, +} + +/// Copy `from` to `to` with its mode, creating `to`'s directory. +fn copy_file_with_mode(from: &Path, to: &Path) -> std::io::Result<()> { + if let Some(parent) = to.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(to, read_regular_to_bytes_sync(from)?)?; + std::fs::set_permissions(to, std::fs::metadata(from)?.permissions()) +} + +/// Take the [`TreeSnapshot`] of `copy`, leaving the paths `left` out: +/// staged and renamed into place, so a snapshot dir is always whole. +fn snapshot_tree(copy: &GemCopy, left: &[String]) -> std::io::Result { + let dir = copy.gem_dir.join(TREE_SNAPSHOT_DIR); + let stage = copy.gem_dir.join(format!("{TREE_SNAPSHOT_DIR}.tmp")); + remove_dir_if_exists(&dir)?; + remove_dir_if_exists(&stage)?; + std::fs::create_dir_all(&stage)?; + let taken = (|| { + let mut files = BTreeMap::new(); + for rel in gem_tree_files(©.gem_dir) { + if left.contains(&rel) { + continue; + } + let src = copy.gem_dir.join(&rel); + copy_file_with_mode(&src, &stage.join(SNAPSHOT_TREE).join(&rel))?; + files.insert(rel, compute_file_git_sha256_sync(&src)?); + } + std::fs::write( + stage.join(SNAPSHOT_LEFT), + serde_json::to_vec(left).map_err(std::io::Error::other)?, + )?; + std::fs::rename(&stage, &dir)?; + Ok(files) + })(); + match taken { + Ok(files) => Ok(TreeSnapshot { + dir, + files, + left: left.to_vec(), + }), + Err(e) => { + let _ = remove_dir_if_exists(&stage); + Err(e) + } + } +} + +/// The [`TreeChanges`] of `copy` since `snapshot` was taken. +fn tree_changes(copy: &GemCopy, snapshot: &TreeSnapshot) -> TreeChanges { + let now: BTreeMap> = gem_tree_files(©.gem_dir) + .into_iter() + .filter(|rel| !snapshot.left.contains(rel)) + .map(|rel| { + let hash = compute_file_git_sha256_sync(©.gem_dir.join(&rel)).ok(); + (rel, hash) + }) + .collect(); + TreeChanges { + replaced: snapshot + .files + .iter() + .filter(|(rel, hash)| now.get(*rel).and_then(Option::as_ref) != Some(*hash)) + .map(|(rel, _)| rel.clone()) + .collect(), + created: now + .into_keys() + .filter(|rel| !snapshot.files.contains_key(rel)) + .collect(), + } +} + +/// Put the gem's own tree back as the snapshot at `snapshot_dir` holds it: +/// files that are not in it go, files that differ from it or are gone come +/// back (through [`replace_file`]), and the snapshot is dropped. A file +/// that is as it was is not written, and the paths the snapshot left out +/// are not touched. A snapshot that does not say which those are is not +/// used: `Err`, with the tree as it is. +fn restore_tree(copy: &GemCopy, snapshot_dir: &Path) -> std::io::Result<()> { + let left: Vec = serde_json::from_slice(&read_regular_to_bytes_sync( + &snapshot_dir.join(SNAPSHOT_LEFT), + )?) + .map_err(std::io::Error::other)?; + let saved_tree = snapshot_dir.join(SNAPSHOT_TREE); + let kept: std::collections::BTreeSet = tree_files(&saved_tree).into_iter().collect(); + for rel in gem_tree_files(©.gem_dir) { + if !kept.contains(&rel) && !left.contains(&rel) { + std::fs::remove_file(copy.gem_dir.join(&rel))?; + } + } + for rel in &kept { + let (saved, path) = (saved_tree.join(rel), copy.gem_dir.join(rel)); + let same = std::fs::symlink_metadata(&path).is_ok_and(|meta| meta.is_file()) + && compute_file_git_sha256_sync(&path).ok() + == compute_file_git_sha256_sync(&saved).ok(); + if !same { + replace_with_file(&saved, &path, None)?; + } + } + remove_dir_if_exists(snapshot_dir) +} + +/// Drop what a run that died left of a [`TreeSnapshot`] in `copy`, once no +/// parked build says a rebuild was under way: the tree it was taken of is +/// either untouched or the committed build's. +fn drop_stale_tree_snapshot(copy: &GemCopy) { + for name in [ + TREE_SNAPSHOT_DIR.to_string(), + format!("{TREE_SNAPSHOT_DIR}.tmp"), + ] { + let dir = copy.gem_dir.join(name); + if is_real_dir(&dir) { + let _ = remove_dir_if_exists(&dir); + } + } +} + +/// Add what an in-place build did to the gem's own tree (`changes`) to the +/// backup of the original build, so `rollback` undoes it +/// ([`restore_backup`]): the content each replaced file had before the +/// build, from `snapshot`, and the names of the files it added. A file the +/// backup already holds, or already lists as added by an earlier build, is +/// left as recorded: that is the original, and this build ran over +/// socket-patch's own. Without a backup of a build RubyGems made there is +/// nothing to add to (the original is gone, and `rollback` rebuilds). +fn back_up_tree_changes( + copy: &GemCopy, + snapshot: &TreeSnapshot, + changes: &TreeChanges, +) -> std::io::Result<()> { + let backup = copy.gem_dir.join(BACKUP_DIR); + let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let Some(mut info) = known.filter(|info| !info.grafted && is_real_dir(&backup)) else { + return Ok(()); + }; + let before = (info.lib_files.len(), info.created_files.len()); + let recorded = |info: &BackupInfo, rel: &String| { + info.lib_files.contains(rel) || info.created_files.contains(rel) + }; + for rel in &changes.replaced { + if !recorded(&info, rel) { + let saved = snapshot.dir.join(SNAPSHOT_TREE).join(rel); + copy_file_with_mode(&saved, &backup.join("lib").join(rel))?; + info.lib_files.push(rel.clone()); + } + } + for rel in &changes.created { + if !recorded(&info, rel) { + info.created_files.push(rel.clone()); + } + } + if before != (info.lib_files.len(), info.created_files.len()) { + write_backup_info(&backup, &info)?; + } + Ok(()) +} + +/// The files an in-place build left in the gem's own tree for Ruby to load +/// (under a require path, or a shared library by name: [`loadable_files`]), +/// to attest in its marker: those of `changes`, and those the backup says +/// an earlier build of socket-patch's replaced or added, which a build +/// that writes the same bytes again does not change. +fn in_tree_artifacts(copy: &GemCopy, probe: &Probe, changes: &TreeChanges) -> Vec { + let dlext = probe.facts.as_ref().map(|facts| facts.dlext.as_str()); + let recorded = read_regular_to_bytes_sync(©.gem_dir.join(BACKUP_DIR).join(BACKUP_INFO)) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|info| !info.grafted) + .map(|info| [info.lib_files, info.created_files].concat()) + .unwrap_or_default(); + let mut rels: Vec = changes + .replaced + .iter() + .chain(&changes.created) + .chain(&recorded) + .filter(|rel| is_safe_relative_subpath(rel) && !is_own_entry(rel)) + .filter(|rel| { + under_require_path(rel, &probe.require_paths) || is_library_name(leaf_of(rel), dlext) + }) + .filter(|rel| { + std::fs::symlink_metadata(copy.gem_dir.join(rel)).is_ok_and(|meta| meta.is_file()) + }) + .cloned() + .collect(); + rels.sort(); + rels.dedup(); + rels +} + +/// Why a build that exited cleanly is not one of the patched sources, when +/// that shows in the files it left: `None` when nothing does. +/// +/// A build run over an installed tree finds the products of the install +/// there, and one that takes them for current compiles nothing (a Rakefile +/// whose library task does not depend on the C sources). `removed` are the +/// products taken out of its way beforehand, each of which it must have +/// made again. With none known, a record that changes a build input must +/// leave compiled code somewhere: an artifact in the extension dir, or a +/// changed file in the gem's tree that Ruby could load. +fn stale_build( + copy: &GemCopy, + probe: &Probe, + scope: &NativeScope, + removed: &[String], + changes: &TreeChanges, +) -> Option { + let missing: Vec<&str> = removed + .iter() + .filter(|rel| !copy.gem_dir.join(rel).is_file()) + .map(String::as_str) + .collect(); + if !missing.is_empty() { + return Some(format!( + "the build exited cleanly but did not make {} again, which the gem's build from \ + its source gem leaves in the gem's own tree", + missing.join(", ") + )); + } + if scope.inputs.is_empty() || !removed.is_empty() { + return None; + } + let dlext = probe.facts.as_ref().map(|facts| facts.dlext.as_str()); + let compiled = !artifact_rels(&probe.extension_dir).is_empty() + || changes.replaced.iter().chain(&changes.created).any(|rel| { + under_require_path(rel, &probe.require_paths) || is_library_name(leaf_of(rel), dlext) + }); + (!compiled).then(|| { + "the build exited cleanly but compiled nothing: it left no artifact in the extension \ + dir and changed no file of the gem's own tree that Ruby loads, so the gem still runs \ + its previous build (a build script that takes the library it finds for current \ + does this)" + .to_string() + }) +} + +/// 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. +/// +/// The gem's own tree is snapshotted first ([`TreeSnapshot`]). What a +/// finished build replaced or added there is backed up with the original +/// build and attested by the marker like the extension dir's artifacts. +/// On failure every build product, in the extension dir and in the gem's +/// tree, is put back as it was; `Err` is the build's diagnostic. A build +/// that exits cleanly without building the sources fails too +/// ([`stale_build`]). async fn rebuild( copy: &GemCopy, probe: &Probe, @@ -2376,6 +2718,7 @@ async fn rebuild( files: &HashMap, env: &RubyEnv, back_up: bool, + stale: &[String], ) -> Result<(), String> { // 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 @@ -2385,8 +2728,14 @@ async fn rebuild( let _ = remove_dir_if_exists(©.gem_dir.join(BACKUP_DIR)); } }; - let (aside, made_backup) = { - let (copy, probe) = (copy.clone(), probe.clone()); + // The record's files are the patch's to write and put back, not the + // build's. + let left: Vec = files + .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()); crate::utils::fs::run_blocking(move || { let made = if back_up { back_up_original(©, &probe, &[]) @@ -2394,12 +2743,42 @@ async fn rebuild( } else { false }; - match set_aside(©, &probe) { - Ok(aside) => Ok((aside, made)), + let aside = match set_aside(©, &probe) { + Ok(aside) => aside, Err(e) => { drop_new_backup(©, made); - Err(format!( + return Err(format!( "could not move the current extension build aside: {e}" + )); + } + }; + // Under the parked build's lock, and only files the snapshot + // holds are removed: each can be put back. + let prepared = snapshot_tree(©, &left).and_then(|snapshot| { + let mut removed = Vec::new(); + for rel in stale { + if snapshot.files.contains_key(&rel) { + std::fs::remove_file(copy.gem_dir.join(&rel))?; + removed.push(rel); + } + } + Ok((snapshot, removed)) + }); + match prepared { + Ok((snapshot, removed)) => Ok((aside, made, snapshot, removed)), + Err(e) => { + let snapshot_dir = copy.gem_dir.join(TREE_SNAPSHOT_DIR); + let undone = if is_real_dir(&snapshot_dir) { + restore_tree(©, &snapshot_dir) + } else { + Ok(()) + }; + let undone = undone.and(put_back(©, &probe, aside)); + if undone.is_ok() { + drop_new_backup(©, made); + } + Err(format!( + "could not keep a copy of the gem's files to build over: {e}" )) } } @@ -2413,18 +2792,44 @@ async fn rebuild( // one: an unrecorded build would never be attested, and the caller // puts the original sources back. So is one that exits cleanly // without an extension dir: the old one was moved aside for it. - let diagnostic = match built { - Ok(_) if !probe.extension_dir.is_dir() => format!( + let committed = match built { + Ok(_) if !probe.extension_dir.is_dir() => Err(format!( "the build exited cleanly but left no extension in {}", probe.extension_dir.display() - ), - Ok(_) => match commit_build(©, &probe, &scope, &files, &aside) { - Ok(()) => return Ok(()), - Err(e) => format!("the extension built, but its build record could not be written: {e}"), - }, + )), + Ok(_) => { + let changes = tree_changes(©, &snapshot); + match stale_build(©, &probe, &scope, &removed, &changes) { + Some(why) => Err(why), + // The backup learns of the tree's changes before the + // marker says the build is done: a run that dies in + // between is undone from the snapshot. + None => back_up_tree_changes(©, &snapshot, &changes) + .and_then(|()| { + let in_tree = in_tree_artifacts(©, &probe, &changes); + commit_build(©, &probe, &scope, &files, &aside, &in_tree) + }) + .map_err(|e| { + format!( + "the extension built, but its build record could not be \ + written: {e}" + ) + }), + } + } + Err(diagnostic) => Err(diagnostic), + }; + let diagnostic = match committed { + Ok(()) => { + let _ = remove_dir_if_exists(&snapshot.dir); + return Ok(()); + } Err(diagnostic) => diagnostic, }; - match put_back(©, &probe, aside) { + // The gem's own tree first, while the parked build still says a + // rebuild is under way. + let undone = restore_tree(©, &snapshot.dir).and(put_back(©, &probe, aside)); + match undone { Ok(()) => { drop_new_backup(©, made_backup); Err(diagnostic) @@ -2660,7 +3065,12 @@ enum StageFailure { /// The build leaves what Ruby loads in the gem's own tree /// ([`in_tree_products`]), where a build staged elsewhere cannot stand /// in for it. - InTree(Vec), + 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, + }, } impl StageFailure { @@ -2681,7 +3091,7 @@ impl StageFailure { StageFailure::Build(diagnostic) => { format!("the source gem did not build:\n{diagnostic}") } - StageFailure::InTree(products) => format!( + StageFailure::InTree { products, .. } => format!( "the source gem's build leaves {} in the gem's own tree, which is where it is \ loaded from, and a build staged elsewhere cannot take its place", products.join(", ") @@ -3168,12 +3578,21 @@ async fn build_in_stage( extension_dir, label, }; - let products = { + let (products, created) = { let (built, probe) = (built.clone(), probe.clone()); - crate::utils::fs::run_blocking(move || in_tree_products(&built, &before, &probe)).await + crate::utils::fs::run_blocking(move || { + let products = in_tree_products(&built, &before, &probe); + let created = products + .iter() + .filter(|rel| !before.contains_key(*rel)) + .cloned() + .collect(); + (products, created) + }) + .await }; if !products.is_empty() { - return Err(StageFailure::InTree(products)); + return Err(StageFailure::InTree { products, created }); } Ok(built) } @@ -3273,7 +3692,7 @@ fn install_staged_build( )?; } } - commit_build(copy, probe, scope, files, &aside) + commit_build(copy, probe, scope, files, &aside, &[]) })(); let Err(error) = moved_in else { return Ok(()); @@ -4280,7 +4699,12 @@ async fn rebuild_in_place( warning: None, }; } - match rebuild(job.copy, probe, job.scope, job.files, job.env, true).await { + // 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, + _ => &[], + }; + match rebuild(job.copy, probe, job.scope, job.files, job.env, true, stale).await { Ok(()) => job.built(result), Err(diagnostic) => { // An installed tree may no longer hold what its build needs @@ -4532,7 +4956,7 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result rebuilt, None => { let scope = NativeScope::default(); - rebuild(©, &probe, &scope, &HashMap::new(), env, false).await + rebuild(©, &probe, &scope, &HashMap::new(), env, false, &[]).await } }; rebuilt.map_err(|diagnostic| { @@ -4628,6 +5052,12 @@ fn restore_backup(copy: &GemCopy, marker: Option<&BuildMarker>) -> std::io::Resu let _ = std::fs::remove_file(copy.gem_dir.join(lib)); } } + // So does what an in-place build added to the gem's own tree. + for created in &info.created_files { + if is_safe_relative_subpath(created) && !is_own_entry(created) { + let _ = std::fs::remove_file(copy.gem_dir.join(created)); + } + } remove_dir_if_exists(&ext_dir)?; if info.had_extension_dir { copy_tree_sync(&backup.join("ext"), &ext_dir)?; @@ -6857,4 +7287,236 @@ mod tests { assert!(!names_platform(other, "x86_64-linux"), "{other}"); } } + + // ── an in-place build over the gem's own tree ─────────────────────── + + /// A gem that builds a library into its own tree and loads it from + /// there (scrypt, digest-crc): its extension dir holds no artifact. + fn in_tree_gem(home: &Path) -> (GemCopy, Probe) { + let copy = installed_gem(home, "lib"); + let probe = probe_for(©, "3.4.10"); + std::fs::write(probe.extension_dir.join(BUILD_COMPLETE), b"").unwrap(); + for (rel, bytes) in [ + ("ext/a/a.c", "patched source"), + ("ext/a/liba.bundle", "original library"), + ("ext/a/a.o", "original object"), + ("ext/a/Makefile", "makefile"), + ("lib/a.rb", "ruby"), + ] { + let path = copy.gem_dir.join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + (copy, probe) + } + + /// Every file under `dir`, with its bytes. + fn tree_bytes(dir: &Path) -> BTreeMap> { + tree_files(dir) + .into_iter() + .map(|rel| { + let bytes = std::fs::read(dir.join(&rel)).unwrap(); + (rel, bytes) + }) + .collect() + } + + /// What a build run in the installed tree does there: a library and an + /// object replaced, a file removed, a file added, and a fresh + /// extension dir with no artifact in it. + fn build_in_tree(copy: &GemCopy, probe: &Probe) { + std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"built library").unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/a.o"), b"built object").unwrap(); + std::fs::remove_file(copy.gem_dir.join("ext/a/Makefile")).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log").unwrap(); + std::fs::create_dir_all(&probe.extension_dir).unwrap(); + std::fs::write(probe.extension_dir.join(BUILD_COMPLETE), b"").unwrap(); + } + + /// The record's files, as a snapshot leaves them out. + fn record_paths() -> Vec { + vec!["ext/a/a.c".to_string()] + } + + fn in_tree_scope() -> (NativeScope, HashMap) { + let scope = NativeScope { + inputs: vec!["ext/a/a.c".into()], + builds_extensions: true, + ..NativeScope::default() + }; + (scope, files(&["ext/a/a.c"])) + } + + /// The library an in-place build replaces in the gem's own tree is + /// backed up, attested by the marker, and put back by the restore with + /// everything else the build did there (#2104). + #[test] + fn an_in_place_build_of_the_gems_own_tree_is_recorded_and_restored() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let (scope, record) = in_tree_scope(); + let installed = (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)); + + assert!(back_up_original(©, &probe, &[]).unwrap()); + let aside = set_aside(©, &probe).unwrap(); + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + build_in_tree(©, &probe); + let changes = tree_changes(©, &snapshot); + assert_eq!( + changes, + TreeChanges { + replaced: vec![ + "ext/a/Makefile".to_string(), + "ext/a/a.o".to_string(), + "ext/a/liba.bundle".to_string(), + ], + created: vec!["ext/a/mkmf.log".to_string()], + } + ); + assert_eq!(stale_build(©, &probe, &scope, &[], &changes), None); + back_up_tree_changes(©, &snapshot, &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &changes); + assert_eq!(in_tree, ["ext/a/liba.bundle"]); + commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); + remove_dir_if_exists(&snapshot.dir).unwrap(); + + let marker = read_marker_sync(©.gem_dir).unwrap(); + assert_eq!( + marker.lib_artifacts.keys().collect::>(), + ["ext/a/liba.bundle"] + ); + assert!(marker_holds(&marker, ©, &scope, &record)); + std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"another").unwrap(); + assert!( + !marker_holds(&marker, ©, &scope, &record), + "a library that is not the built one is not attested" + ); + + // A second build over socket-patch's own: the backup keeps the + // original of what the first replaced, and the file the first + // added still goes with the restore. + let aside = set_aside(©, &probe).unwrap(); + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"built again").unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log 2").unwrap(); + std::fs::create_dir_all(&probe.extension_dir).unwrap(); + std::fs::write(probe.extension_dir.join(BUILD_COMPLETE), b"").unwrap(); + let changes = tree_changes(©, &snapshot); + back_up_tree_changes(©, &snapshot, &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &changes); + commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); + remove_dir_if_exists(&snapshot.dir).unwrap(); + + let marker = read_marker_sync(©.gem_dir); + restore_backup(©, marker.as_ref()).unwrap(); + assert_eq!( + (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)), + installed, + "the gem is as `gem install` left it" + ); + } + + /// A build that fails part-way has already written into the gem's own + /// tree. The snapshot puts every file back, and goes. + #[test] + fn a_failed_in_place_build_leaves_the_gems_own_tree_as_it_was() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let installed = tree_bytes(©.gem_dir); + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + build_in_tree(©, &probe); + restore_tree(©, &snapshot.dir).unwrap(); + assert_eq!(tree_bytes(©.gem_dir), installed); + + // A snapshot that does not say which files it left out is not + // used: it would take the record's files for the build's. + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + std::fs::remove_file(snapshot.dir.join(SNAPSHOT_LEFT)).unwrap(); + build_in_tree(©, &probe); + assert!(restore_tree(©, &snapshot.dir).is_err()); + assert!(copy.gem_dir.join("ext/a/a.c").is_file()); + assert!(copy.gem_dir.join("ext/a/mkmf.log").is_file()); + } + + /// A build that exits cleanly and compiles nothing is not a rebuild of + /// a changed build input, and neither is one that leaves a product it + /// was made to build again unbuilt (#2105). + #[test] + fn a_build_that_leaves_no_compiled_code_is_stale() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let (scope, _) = in_tree_scope(); + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + + // Nothing changed, or only what Ruby does not load. + let nothing = tree_changes(©, &snapshot); + assert_eq!(nothing, TreeChanges::default()); + let why = stale_build(©, &probe, &scope, &[], ¬hing).unwrap(); + assert!(why.contains("compiled nothing"), "{why}"); + std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log").unwrap(); + let log_only = tree_changes(©, &snapshot); + assert!(stale_build(©, &probe, &scope, &[], &log_only).is_some()); + // A rebuild of no changed input (a rollback's) has nothing to show. + let unpatched = NativeScope { + inputs: Vec::new(), + ..scope.clone() + }; + assert_eq!(stale_build(©, &probe, &unpatched, &[], ¬hing), None); + // An artifact in the extension dir is compiled code. + std::fs::create_dir_all(probe.extension_dir.join("a")).unwrap(); + std::fs::write(probe.extension_dir.join("a/a.bundle"), b"built").unwrap(); + assert_eq!(stale_build(©, &probe, &scope, &[], ¬hing), None); + std::fs::remove_dir_all(probe.extension_dir.join("a")).unwrap(); + + // A product taken out of the build's way must be there again. + let removed = ["ext/a/liba.bundle".to_string()]; + assert_eq!( + stale_build(©, &probe, &scope, &removed, ¬hing), + None, + "made again, with the same bytes or not" + ); + std::fs::remove_file(copy.gem_dir.join("ext/a/liba.bundle")).unwrap(); + let gone = tree_changes(©, &snapshot); + let why = stale_build(©, &probe, &scope, &removed, &gone).unwrap(); + assert!(why.contains("ext/a/liba.bundle"), "{why}"); + } + + /// A run that died during an in-place build left the gem's own tree + /// half-built beside its snapshot. The next run puts the tree back + /// with the parked build, and leaves the record's files as it finds + /// them: a `rollback` has put the original source back by then. A + /// snapshot with no parked build is nobody's: it goes, and the tree + /// stays. + #[test] + fn an_interrupted_in_place_build_gets_its_tree_back() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let mut installed = (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)); + let aside = set_aside(©, &probe).unwrap(); + let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"half").unwrap(); + std::fs::remove_file(copy.gem_dir.join("ext/a/a.o")).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log").unwrap(); + drop(aside); + std::fs::write(copy.gem_dir.join("ext/a/a.c"), b"original source").unwrap(); + installed + .0 + .insert("ext/a/a.c".to_string(), b"original source".to_vec()); + + assert!(recover_interrupted_rebuild_sync(©, Some("lib")).unwrap()); + assert_eq!( + (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)), + installed + ); + assert!(!snapshot.dir.exists()); + + let stale = snapshot_tree(©, &record_paths()).unwrap(); + std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"committed").unwrap(); + assert!(!recover_interrupted_rebuild_sync(©, Some("lib")).unwrap()); + assert!(!stale.dir.exists()); + assert_eq!( + std::fs::read(copy.gem_dir.join("ext/a/liba.bundle")).unwrap(), + b"committed" + ); + } } diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 6de6d91b6..01119053c 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2014,7 +2014,12 @@ mirror of rubygems.org, set `SOCKET_RUBYGEMS_URL` to it. The JRuby (`-java`) bui 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 -argon2) is always rebuilt from its installed tree. +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. 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. @@ -2043,7 +2048,8 @@ passes `--no-gem-native-rebuild` (or `SOCKET_NO_GEM_NATIVE_REBUILD=1`): the sour without a rebuild, with a `native_extension_not_rebuilt` warning, and `vex` does not attest them. `apply` keeps the original compiled code in `.socket-patch-native-orig/` inside the gem -directory (the install-time build, or a precompiled gem's prebuilt binary), so `rollback` +directory (the install-time build, a precompiled gem's prebuilt binary, and every file a rebuild +in the installed tree replaced there), so `rollback` restores it byte for byte without recompiling, and records what it built in `.socket-patch-native-build.json`. `vex` attests the patch only while that record matches the installed binary: after `gem pristine` or a reinstall, run `apply` again. From f8e88d029ce05c8046d73129e9141efa60d15068 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:27:30 +0000 Subject: [PATCH 4/5] Harden the in-place gem build snapshot From the review of the previous commit: - Keep the tree snapshot beside the parked extension dir, not in the gem dir, where a build script that globs for sources would find a second copy of them. - Leave the parked build in place when the tree cannot be put back, so the next run retries from the snapshot instead of dropping it. - Refuse a build that compiled nothing only for a gem that keeps a library in its own tree. A gem with no library anywhere compiles nothing on this platform, and passes as before. - Hand the products the source gem's build makes to a rollback's in-place rebuild too, and hold that rebuild to the same check. - Attest and back up a product that was rebuilt with the bytes it had, so the restore does not take it for one to remove. - Hash a snapshotted file from the bytes already read. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePpTeM1ZTDzN1jcpr1 --- .../tests/e2e_gem_native_ext_build.rs | 24 +- crates/socket-patch-core/src/patch/gem_ext.rs | 332 +++++++++++------- 2 files changed, 234 insertions(+), 122 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 3f61aa547..b2cb9acd2 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 @@ -3048,6 +3048,7 @@ fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { let fx = WrapGem::new(&abi, WRAP_EXTCONF); assert_eq!(fx.value(), "1"); let installed = walk_files(&fx.gem_dir); + let extensions = walk_files(&fx.home.join("extensions")); let library = fx.library(); let (code, stdout, stderr) = fx.run(&["apply", "--json", "--offline"]); @@ -3059,7 +3060,6 @@ fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { ); assert_eq!(fx.c_file(), wrap_c(2)); assert!(!fx.home.join(".socket-patch-build").exists()); - assert!(!fx.gem_dir.join(".socket-patch-native-tree").exists()); let marker: serde_json::Value = serde_json::from_str( &std::fs::read_to_string(fx.gem_dir.join(".socket-patch-native-build.json")).unwrap(), ) @@ -3087,6 +3087,7 @@ fn a_gem_that_loads_its_library_from_its_own_tree_is_rebuilt_in_place() { 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 build that takes the library it finds in the gem's tree for current @@ -3120,6 +3121,27 @@ fn a_build_that_keeps_a_stale_library_is_made_to_rebuild_it() { 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"); + + // A rollback that has lost the backup rebuilds from the restored + // source, and that build must not take the patched library for + // current either. (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)); } /// 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 9185ad4c9..e87f9671e 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -229,11 +229,8 @@ pub const MARKER_FILE: &str = ".socket-patch-native-build.json"; pub const BACKUP_DIR: &str = ".socket-patch-native-orig"; /// The backup's description file, inside [`BACKUP_DIR`]. const BACKUP_INFO: &str = "backup.json"; -/// The gem's own tree as it was before an in-place build, in the gem dir -/// for as long as that build runs (see [`TreeSnapshot`]). -const TREE_SNAPSHOT_DIR: &str = ".socket-patch-native-tree"; /// What every entry this module keeps in a gem dir starts with: the -/// marker, the backup, the tree snapshot and their stages. +/// marker, the backup and their stages. const OWN_ENTRY_PREFIX: &str = ".socket-patch-native"; /// The stage a rebuild from the source gem builds in, inside the gem home @@ -1505,6 +1502,26 @@ fn parked_build_path(ext: &Path) -> PathBuf { ext.with_file_name(format!(".{leaf}.socket-patch-old")) } +/// Where an in-place rebuild keeps the gem's own tree as it was before the +/// build ([`TreeSnapshot`]): beside the parked build of the extension dir +/// `ext`, outside the gem dir, where the gem's build scripts do not look +/// for sources. +fn tree_snapshot_path(ext: &Path) -> PathBuf { + let leaf = ext + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + ext.with_file_name(format!(".{leaf}.socket-patch-tree")) +} + +/// Where the snapshot at `snapshot` ([`tree_snapshot_path`]) is staged +/// while it is taken. +fn tree_snapshot_stage(snapshot: &Path) -> PathBuf { + let mut name = snapshot.as_os_str().to_os_string(); + name.push(".tmp"); + PathBuf::from(name) +} + /// Take the rebuild lock of a build dir (an extension dir about to be /// parked, or a parked one): an exclusive advisory lock on the directory /// itself. It follows the directory through its renames and goes when the @@ -1601,7 +1618,7 @@ fn recover_interrupted_rebuild_sync( // what it was before it ([`TreeSnapshot`]), whichever way the // extension dir is settled, since no marker speaks for what the // build left there. - let snapshot = copy.gem_dir.join(TREE_SNAPSHOT_DIR); + let snapshot = tree_snapshot_path(&ext); let in_place = is_real_dir(&snapshot); if in_place { restore_tree(copy, &snapshot)?; @@ -1621,7 +1638,7 @@ fn recover_interrupted_rebuild_sync( recovered = true; } // No rebuild is under way now, so a snapshot that is left is nobody's. - drop_stale_tree_snapshot(copy); + drop_stale_tree_snapshots(copy); Ok(recovered) } @@ -2219,6 +2236,12 @@ fn back_up_original(copy: &GemCopy, probe: &Probe, absent: &[String]) -> std::io Ok(true) } +/// The description of the backup dir `backup`, when it has a readable one. +fn read_backup_info(backup: &Path) -> Option { + let bytes = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)).ok()?; + serde_json::from_slice(&bytes).ok() +} + /// Write a backup's description into `dir`: staged beside its place and /// renamed, so it is always whole. fn write_backup_info(dir: &Path, info: &BackupInfo) -> std::io::Result<()> { @@ -2237,10 +2260,7 @@ fn note_absent_files(backup: &Path, absent: &[String]) -> std::io::Result<()> { if absent.is_empty() || !is_real_dir(backup) { return Ok(()); } - let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); - let Some(mut info) = known else { + let Some(mut info) = read_backup_info(backup) else { return Ok(()); }; let before = info.absent_files.len(); @@ -2422,7 +2442,7 @@ fn gem_tree_files(gem_dir: &Path) -> Vec { } /// The gem's own tree as it was before an in-place build: a copy of every -/// file, in [`TREE_SNAPSHOT_DIR`] inside the gem dir. +/// file, beside the parked build ([`tree_snapshot_path`]). /// /// A build run in the installed tree writes there too: its objects and /// Makefiles, and for a gem that loads its library from its own tree (an @@ -2463,19 +2483,23 @@ struct TreeChanges { } /// Copy `from` to `to` with its mode, creating `to`'s directory. -fn copy_file_with_mode(from: &Path, to: &Path) -> std::io::Result<()> { +/// The git-sha256 of what was copied. +fn copy_file_with_mode(from: &Path, to: &Path) -> std::io::Result { if let Some(parent) = to.parent() { std::fs::create_dir_all(parent)?; } - std::fs::write(to, read_regular_to_bytes_sync(from)?)?; - std::fs::set_permissions(to, std::fs::metadata(from)?.permissions()) + let bytes = read_regular_to_bytes_sync(from)?; + std::fs::write(to, &bytes)?; + std::fs::set_permissions(to, std::fs::metadata(from)?.permissions())?; + Ok(compute_git_sha256_from_bytes(&bytes)) } -/// Take the [`TreeSnapshot`] of `copy`, leaving the paths `left` out: -/// staged and renamed into place, so a snapshot dir is always whole. -fn snapshot_tree(copy: &GemCopy, left: &[String]) -> std::io::Result { - let dir = copy.gem_dir.join(TREE_SNAPSHOT_DIR); - let stage = copy.gem_dir.join(format!("{TREE_SNAPSHOT_DIR}.tmp")); +/// Take the [`TreeSnapshot`] of `copy` beside its extension dir `ext`, +/// leaving the paths `left` out: staged and renamed into place, so a +/// snapshot dir is always whole. +fn snapshot_tree(copy: &GemCopy, ext: &Path, left: &[String]) -> std::io::Result { + let dir = tree_snapshot_path(ext); + let stage = tree_snapshot_stage(&dir); remove_dir_if_exists(&dir)?; remove_dir_if_exists(&stage)?; std::fs::create_dir_all(&stage)?; @@ -2486,8 +2510,8 @@ fn snapshot_tree(copy: &GemCopy, left: &[String]) -> std::io::Result std::io::Result<()> { } for rel in &kept { let (saved, path) = (saved_tree.join(rel), copy.gem_dir.join(rel)); - let same = std::fs::symlink_metadata(&path).is_ok_and(|meta| meta.is_file()) + let same = is_real_file(&path) && compute_file_git_sha256_sync(&path).ok() == compute_file_git_sha256_sync(&saved).ok(); if !same { @@ -2563,17 +2587,16 @@ fn restore_tree(copy: &GemCopy, snapshot_dir: &Path) -> std::io::Result<()> { remove_dir_if_exists(snapshot_dir) } -/// Drop what a run that died left of a [`TreeSnapshot`] in `copy`, once no +/// Drop what a run that died left of a [`TreeSnapshot`] of `copy`, once no /// parked build says a rebuild was under way: the tree it was taken of is /// either untouched or the committed build's. -fn drop_stale_tree_snapshot(copy: &GemCopy) { - for name in [ - TREE_SNAPSHOT_DIR.to_string(), - format!("{TREE_SNAPSHOT_DIR}.tmp"), - ] { - let dir = copy.gem_dir.join(name); - if is_real_dir(&dir) { - let _ = remove_dir_if_exists(&dir); +fn drop_stale_tree_snapshots(copy: &GemCopy) { + for ext in extension_dir_slots(copy) { + let snapshot = tree_snapshot_path(&ext); + for dir in [tree_snapshot_stage(&snapshot), snapshot] { + if is_real_dir(&dir) { + let _ = remove_dir_if_exists(&dir); + } } } } @@ -2581,7 +2604,11 @@ fn drop_stale_tree_snapshot(copy: &GemCopy) { /// Add what an in-place build did to the gem's own tree (`changes`) to the /// backup of the original build, so `rollback` undoes it /// ([`restore_backup`]): the content each replaced file had before the -/// build, from `snapshot`, and the names of the files it added. A file the +/// build, from `snapshot`, and the names of the files it added. The +/// products taken out of the build's way (`removed`) count as replaced +/// whether or not they came back with other bytes: the marker lists them, +/// and the restore removes whatever a marker lists that the backup does +/// not hold. A file the /// backup already holds, or already lists as added by an earlier build, is /// left as recorded: that is the original, and this build ran over /// socket-patch's own. Without a backup of a build RubyGems made there is @@ -2589,20 +2616,19 @@ fn drop_stale_tree_snapshot(copy: &GemCopy) { fn back_up_tree_changes( copy: &GemCopy, snapshot: &TreeSnapshot, + removed: &[String], changes: &TreeChanges, ) -> std::io::Result<()> { let backup = copy.gem_dir.join(BACKUP_DIR); - let known = read_regular_to_bytes_sync(&backup.join(BACKUP_INFO)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); - let Some(mut info) = known.filter(|info| !info.grafted && is_real_dir(&backup)) else { + let known = read_backup_info(&backup).filter(|info| !info.grafted && is_real_dir(&backup)); + let Some(mut info) = known else { return Ok(()); }; let before = (info.lib_files.len(), info.created_files.len()); let recorded = |info: &BackupInfo, rel: &String| { info.lib_files.contains(rel) || info.created_files.contains(rel) }; - for rel in &changes.replaced { + for rel in changes.replaced.iter().chain(removed) { if !recorded(&info, rel) { let saved = snapshot.dir.join(SNAPSHOT_TREE).join(rel); copy_file_with_mode(&saved, &backup.join("lib").join(rel))?; @@ -2621,15 +2647,18 @@ fn back_up_tree_changes( } /// The files an in-place build left in the gem's own tree for Ruby to load -/// (under a require path, or a shared library by name: [`loadable_files`]), -/// to attest in its marker: those of `changes`, and those the backup says -/// an earlier build of socket-patch's replaced or added, which a build -/// that writes the same bytes again does not change. -fn in_tree_artifacts(copy: &GemCopy, probe: &Probe, changes: &TreeChanges) -> Vec { +/// ([`is_loadable`]), to attest in its marker: those of `changes`, the +/// products it was made to build again (`removed`), and those the backup +/// says an earlier build of socket-patch's replaced or added. A build that +/// writes the same bytes again changes none of the last two. +fn in_tree_artifacts( + copy: &GemCopy, + probe: &Probe, + removed: &[String], + changes: &TreeChanges, +) -> Vec { let dlext = probe.facts.as_ref().map(|facts| facts.dlext.as_str()); - let recorded = read_regular_to_bytes_sync(©.gem_dir.join(BACKUP_DIR).join(BACKUP_INFO)) - .ok() - .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + let recorded = read_backup_info(©.gem_dir.join(BACKUP_DIR)) .filter(|info| !info.grafted) .map(|info| [info.lib_files, info.created_files].concat()) .unwrap_or_default(); @@ -2637,14 +2666,11 @@ fn in_tree_artifacts(copy: &GemCopy, probe: &Probe, changes: &TreeChanges) -> Ve .replaced .iter() .chain(&changes.created) + .chain(removed) .chain(&recorded) .filter(|rel| is_safe_relative_subpath(rel) && !is_own_entry(rel)) - .filter(|rel| { - under_require_path(rel, &probe.require_paths) || is_library_name(leaf_of(rel), dlext) - }) - .filter(|rel| { - std::fs::symlink_metadata(copy.gem_dir.join(rel)).is_ok_and(|meta| meta.is_file()) - }) + .filter(|rel| is_loadable(rel, &probe.require_paths, dlext)) + .filter(|rel| is_real_file(©.gem_dir.join(rel))) .cloned() .collect(); rels.sort(); @@ -2652,26 +2678,28 @@ fn in_tree_artifacts(copy: &GemCopy, probe: &Probe, changes: &TreeChanges) -> Ve rels } -/// Why a build that exited cleanly is not one of the patched sources, when +/// Why a build that exited cleanly is not one of the sources on disk, when /// that shows in the files it left: `None` when nothing does. /// /// A build run over an installed tree finds the products of the install /// there, and one that takes them for current compiles nothing (a Rakefile /// whose library task does not depend on the C sources). `removed` are the /// products taken out of its way beforehand, each of which it must have -/// made again. With none known, a record that changes a build input must -/// leave compiled code somewhere: an artifact in the extension dir, or a -/// changed file in the gem's tree that Ruby could load. +/// made again. With none known, a gem that keeps a shared library in its +/// own tree must show compiled code from the build: an artifact in the +/// extension dir, or a changed file in the tree that Ruby could load. (A +/// gem with no library in its tree and none in its extension dir compiles +/// nothing on this platform, and there is nothing stale for Ruby to load.) fn stale_build( copy: &GemCopy, probe: &Probe, - scope: &NativeScope, removed: &[String], + snapshot: &TreeSnapshot, changes: &TreeChanges, ) -> Option { let missing: Vec<&str> = removed .iter() - .filter(|rel| !copy.gem_dir.join(rel).is_file()) + .filter(|rel| !is_real_file(©.gem_dir.join(rel))) .map(String::as_str) .collect(); if !missing.is_empty() { @@ -2681,19 +2709,25 @@ fn stale_build( missing.join(", ") )); } - if scope.inputs.is_empty() || !removed.is_empty() { + if !removed.is_empty() { return None; } let dlext = probe.facts.as_ref().map(|facts| facts.dlext.as_str()); + let keeps_library = snapshot + .files + .keys() + .any(|rel| is_library_name(leaf_of(rel), dlext)); let compiled = !artifact_rels(&probe.extension_dir).is_empty() - || changes.replaced.iter().chain(&changes.created).any(|rel| { - under_require_path(rel, &probe.require_paths) || is_library_name(leaf_of(rel), dlext) - }); - (!compiled).then(|| { + || changes + .replaced + .iter() + .chain(&changes.created) + .any(|rel| is_loadable(rel, &probe.require_paths, dlext)); + (keeps_library && !compiled).then(|| { "the build exited cleanly but compiled nothing: it left no artifact in the extension \ dir and changed no file of the gem's own tree that Ruby loads, so the gem still runs \ - its previous build (a build script that takes the library it finds for current \ - does this)" + the library that was there (a build script that takes the library it finds for \ + current does this)" .to_string() }) } @@ -2710,7 +2744,8 @@ fn stale_build( /// On failure every build product, in the extension dir and in the gem's /// tree, is put back as it was; `Err` is the build's diagnostic. A build /// that exits cleanly without building the sources fails too -/// ([`stale_build`]). +/// ([`stale_build`]): that holds for a rollback's rebuild of the restored +/// sources as for a patch's. async fn rebuild( copy: &GemCopy, probe: &Probe, @@ -2754,7 +2789,7 @@ async fn rebuild( }; // Under the parked build's lock, and only files the snapshot // holds are removed: each can be put back. - let prepared = snapshot_tree(©, &left).and_then(|snapshot| { + let prepared = snapshot_tree(©, &probe.extension_dir, &left).and_then(|snapshot| { let mut removed = Vec::new(); for rel in stale { if snapshot.files.contains_key(&rel) { @@ -2767,13 +2802,15 @@ async fn rebuild( match prepared { Ok((snapshot, removed)) => Ok((aside, made, snapshot, removed)), Err(e) => { - let snapshot_dir = copy.gem_dir.join(TREE_SNAPSHOT_DIR); + // The parked build stays where it is when the tree + // cannot be put back: the next run tries again. + let snapshot_dir = tree_snapshot_path(&probe.extension_dir); let undone = if is_real_dir(&snapshot_dir) { restore_tree(©, &snapshot_dir) } else { Ok(()) }; - let undone = undone.and(put_back(©, &probe, aside)); + let undone = undone.and_then(|()| put_back(©, &probe, aside)); if undone.is_ok() { drop_new_backup(©, made); } @@ -2799,14 +2836,14 @@ async fn rebuild( )), Ok(_) => { let changes = tree_changes(©, &snapshot); - match stale_build(©, &probe, &scope, &removed, &changes) { + match stale_build(©, &probe, &removed, &snapshot, &changes) { Some(why) => Err(why), // The backup learns of the tree's changes before the // marker says the build is done: a run that dies in // between is undone from the snapshot. - None => back_up_tree_changes(©, &snapshot, &changes) + None => back_up_tree_changes(©, &snapshot, &removed, &changes) .and_then(|()| { - let in_tree = in_tree_artifacts(©, &probe, &changes); + let in_tree = in_tree_artifacts(©, &probe, &removed, &changes); commit_build(©, &probe, &scope, &files, &aside, &in_tree) }) .map_err(|e| { @@ -2827,8 +2864,10 @@ async fn rebuild( Err(diagnostic) => diagnostic, }; // The gem's own tree first, while the parked build still says a - // rebuild is under way. - let undone = restore_tree(©, &snapshot.dir).and(put_back(©, &probe, aside)); + // 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)); match undone { Ok(()) => { drop_new_backup(©, made_backup); @@ -3385,9 +3424,14 @@ fn is_library_name(leaf: &str, dlext: Option<&str>) -> bool { }) } -/// The files of the gem tree at `gem_dir` that Ruby could load, each with -/// its git-sha256: every file under a require path, and every shared -/// library by name wherever it sits. +/// Whether Ruby could load the gem file `rel`: it is under a require path, +/// or a shared library by name wherever it sits. +fn is_loadable(rel: &str, require_paths: &[String], dlext: Option<&str>) -> bool { + under_require_path(rel, require_paths) || is_library_name(leaf_of(rel), dlext) +} + +/// The files of the gem tree at `gem_dir` that Ruby could load +/// ([`is_loadable`]), each with its git-sha256. fn loadable_files( gem_dir: &Path, require_paths: &[String], @@ -3395,9 +3439,7 @@ fn loadable_files( ) -> BTreeMap { tree_files(gem_dir) .into_iter() - .filter(|rel| { - under_require_path(rel, require_paths) || is_library_name(leaf_of(rel), dlext) - }) + .filter(|rel| is_loadable(rel, require_paths, dlext)) .filter_map(|rel| { let hash = compute_file_git_sha256_sync(&gem_dir.join(&rel)).ok()?; Some((rel, hash)) @@ -4953,10 +4995,10 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result rebuilt, - None => { + Ok(rebuilt) => rebuilt, + Err(stale) => { let scope = NativeScope::default(); - rebuild(©, &probe, &scope, &HashMap::new(), env, false, &[]).await + rebuild(©, &probe, &scope, &HashMap::new(), env, false, &stale).await } }; rebuilt.map_err(|diagnostic| { @@ -4972,25 +5014,34 @@ pub async fn restore_original_build(pkg_path: &Path, env: &RubyEnv) -> Result Option> { +) -> Result, Vec> { let spec_text = crate::utils::fs::read_regular_to_string(©.spec_path) .await - .ok()?; + .map_err(|_| Vec::new())?; let facts = SpecFacts::of(&spec_text, ©.full_name); - let source = facts.release.filter(|_| facts.extensions.declared)?; + let source = facts + .release + .filter(|_| facts.extensions.declared) + .ok_or_else(Vec::new)?; let gems = GemSource::of(&env.cwd, env.offline).await; - let archive = gems.archive(©.home, &source).await.ok()?; + let archive = gems + .archive(©.home, &source) + .await + .map_err(|_| Vec::new())?; let (stage, built) = match build_from_source_gem(copy, probe, &source, archive, &gems, env, None).await { Ok(staged) => staged, - Err(StageFailure::Busy(why)) => return Some(Err(why)), - Err(_) => return None, + Err(StageFailure::Busy(why)) => return Ok(Err(why)), + Err(StageFailure::InTree { created, .. }) => return Err(created), + Err(_) => return Err(Vec::new()), }; let moved_in = { let (copy, probe) = (copy.clone(), probe.clone()); @@ -5001,7 +5052,7 @@ async fn rebuild_unpatched_from_source_gem( .await }; close_stage(stage, copy).await; - Some(moved_in) + Ok(moved_in) } /// Put the backed-up original build back over socket-patch's build, then @@ -7359,7 +7410,7 @@ mod tests { assert!(back_up_original(©, &probe, &[]).unwrap()); let aside = set_aside(©, &probe).unwrap(); - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); build_in_tree(©, &probe); let changes = tree_changes(©, &snapshot); assert_eq!( @@ -7373,9 +7424,9 @@ mod tests { created: vec!["ext/a/mkmf.log".to_string()], } ); - assert_eq!(stale_build(©, &probe, &scope, &[], &changes), None); - back_up_tree_changes(©, &snapshot, &changes).unwrap(); - let in_tree = in_tree_artifacts(©, &probe, &changes); + assert_eq!(stale_build(©, &probe, &[], &snapshot, &changes), None); + back_up_tree_changes(©, &snapshot, &[], &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &[], &changes); assert_eq!(in_tree, ["ext/a/liba.bundle"]); commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); remove_dir_if_exists(&snapshot.dir).unwrap(); @@ -7396,14 +7447,14 @@ mod tests { // original of what the first replaced, and the file the first // added still goes with the restore. let aside = set_aside(©, &probe).unwrap(); - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"built again").unwrap(); std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log 2").unwrap(); std::fs::create_dir_all(&probe.extension_dir).unwrap(); std::fs::write(probe.extension_dir.join(BUILD_COMPLETE), b"").unwrap(); let changes = tree_changes(©, &snapshot); - back_up_tree_changes(©, &snapshot, &changes).unwrap(); - let in_tree = in_tree_artifacts(©, &probe, &changes); + back_up_tree_changes(©, &snapshot, &[], &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &[], &changes); commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); remove_dir_if_exists(&snapshot.dir).unwrap(); @@ -7416,6 +7467,41 @@ mod tests { ); } + /// A product taken out of the build's way and made again with the + /// bytes it had is attested like one that changed, so the backup holds + /// it too: the restore removes what a marker lists and the backup + /// does not, and this file is the gem's own. + #[test] + fn a_product_rebuilt_with_the_same_bytes_survives_the_restore() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let (scope, record) = in_tree_scope(); + let installed = (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)); + let removed = ["ext/a/liba.bundle".to_string()]; + + assert!(back_up_original(©, &probe, &[]).unwrap()); + let aside = set_aside(©, &probe).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + std::fs::remove_file(copy.gem_dir.join(&removed[0])).unwrap(); + std::fs::write(copy.gem_dir.join(&removed[0]), b"original library").unwrap(); + std::fs::create_dir_all(&probe.extension_dir).unwrap(); + std::fs::write(probe.extension_dir.join(BUILD_COMPLETE), b"").unwrap(); + let changes = tree_changes(©, &snapshot); + assert_eq!(changes, TreeChanges::default()); + back_up_tree_changes(©, &snapshot, &removed, &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &removed, &changes); + assert_eq!(in_tree, removed); + commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); + remove_dir_if_exists(&snapshot.dir).unwrap(); + + let marker = read_marker_sync(©.gem_dir); + restore_backup(©, marker.as_ref()).unwrap(); + assert_eq!( + (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)), + installed + ); + } + /// A build that fails part-way has already written into the gem's own /// tree. The snapshot puts every file back, and goes. #[test] @@ -7423,14 +7509,14 @@ mod tests { let tmp = tempfile::tempdir().unwrap(); let (copy, probe) = in_tree_gem(tmp.path()); let installed = tree_bytes(©.gem_dir); - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); build_in_tree(©, &probe); restore_tree(©, &snapshot.dir).unwrap(); assert_eq!(tree_bytes(©.gem_dir), installed); // A snapshot that does not say which files it left out is not // used: it would take the record's files for the build's. - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); std::fs::remove_file(snapshot.dir.join(SNAPSHOT_LEFT)).unwrap(); build_in_tree(©, &probe); assert!(restore_tree(©, &snapshot.dir).is_err()); @@ -7438,47 +7524,51 @@ mod tests { assert!(copy.gem_dir.join("ext/a/mkmf.log").is_file()); } - /// A build that exits cleanly and compiles nothing is not a rebuild of - /// a changed build input, and neither is one that leaves a product it - /// was made to build again unbuilt (#2105). + /// A build that exits cleanly and compiles nothing, over a tree that + /// keeps a library, has left Ruby the library that was there. So has + /// one that leaves a product it was made to build again unbuilt + /// (#2105). A gem with no library anywhere compiles nothing here, and + /// that is not stale. #[test] fn a_build_that_leaves_no_compiled_code_is_stale() { let tmp = tempfile::tempdir().unwrap(); let (copy, probe) = in_tree_gem(tmp.path()); - let (scope, _) = in_tree_scope(); - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); // Nothing changed, or only what Ruby does not load. let nothing = tree_changes(©, &snapshot); assert_eq!(nothing, TreeChanges::default()); - let why = stale_build(©, &probe, &scope, &[], ¬hing).unwrap(); + let why = stale_build(©, &probe, &[], &snapshot, ¬hing).unwrap(); assert!(why.contains("compiled nothing"), "{why}"); std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log").unwrap(); let log_only = tree_changes(©, &snapshot); - assert!(stale_build(©, &probe, &scope, &[], &log_only).is_some()); - // A rebuild of no changed input (a rollback's) has nothing to show. - let unpatched = NativeScope { - inputs: Vec::new(), - ..scope.clone() - }; - assert_eq!(stale_build(©, &probe, &unpatched, &[], ¬hing), None); + assert!(stale_build(©, &probe, &[], &snapshot, &log_only).is_some()); // An artifact in the extension dir is compiled code. std::fs::create_dir_all(probe.extension_dir.join("a")).unwrap(); std::fs::write(probe.extension_dir.join("a/a.bundle"), b"built").unwrap(); - assert_eq!(stale_build(©, &probe, &scope, &[], ¬hing), None); + assert_eq!(stale_build(©, &probe, &[], &snapshot, ¬hing), None); std::fs::remove_dir_all(probe.extension_dir.join("a")).unwrap(); - // A product taken out of the build's way must be there again. + // A product taken out of the build's way must be there again, and + // is attested though its bytes are the ones it had. let removed = ["ext/a/liba.bundle".to_string()]; assert_eq!( - stale_build(©, &probe, &scope, &removed, ¬hing), - None, - "made again, with the same bytes or not" + stale_build(©, &probe, &removed, &snapshot, ¬hing), + None + ); + assert_eq!( + in_tree_artifacts(©, &probe, &removed, ¬hing), + removed ); std::fs::remove_file(copy.gem_dir.join("ext/a/liba.bundle")).unwrap(); let gone = tree_changes(©, &snapshot); - let why = stale_build(©, &probe, &scope, &removed, &gone).unwrap(); + let why = stale_build(©, &probe, &removed, &snapshot, &gone).unwrap(); assert!(why.contains("ext/a/liba.bundle"), "{why}"); + + // No library in the tree and none built: nothing for Ruby to load. + let plain = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + let nothing = tree_changes(©, &plain); + assert_eq!(stale_build(©, &probe, &[], &plain, ¬hing), None); } /// A run that died during an in-place build left the gem's own tree @@ -7493,7 +7583,7 @@ mod tests { let (copy, probe) = in_tree_gem(tmp.path()); let mut installed = (tree_bytes(©.gem_dir), tree_bytes(&probe.extension_dir)); let aside = set_aside(©, &probe).unwrap(); - let snapshot = snapshot_tree(©, &record_paths()).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"half").unwrap(); std::fs::remove_file(copy.gem_dir.join("ext/a/a.o")).unwrap(); std::fs::write(copy.gem_dir.join("ext/a/mkmf.log"), b"log").unwrap(); @@ -7510,7 +7600,7 @@ mod tests { ); assert!(!snapshot.dir.exists()); - let stale = snapshot_tree(©, &record_paths()).unwrap(); + let stale = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); std::fs::write(copy.gem_dir.join("ext/a/liba.bundle"), b"committed").unwrap(); assert!(!recover_interrupted_rebuild_sync(©, Some("lib")).unwrap()); assert!(!stale.dir.exists()); From 82ed2bfeade56f166274aac8938889be7f83061c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 06:40:20 +0000 Subject: [PATCH 5/5] Keep a committed in-place gem build on recovery A run that died after it wrote the marker of an in-place build, before it dropped the parked build and the tree snapshot, left all three on disk. The next run restored the gem's tree from the snapshot, putting the old in-tree library back under a finished build. Recovery now tells that state apart: the extension dir is a finished build, and the marker was written after the snapshot was taken and matches the tree. Such a build stands, and the snapshot is dropped. Found by Cursor Bugbot on the PR. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aePpTeM1ZTDzN1jcpr1 --- crates/socket-patch-core/src/patch/gem_ext.rs | 62 ++++++++++++++++++- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index e87f9671e..72c3874b9 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1617,9 +1617,11 @@ fn recover_interrupted_rebuild_sync( // An in-place build was under way: the gem's own tree goes back to // what it was before it ([`TreeSnapshot`]), whichever way the // extension dir is settled, since no marker speaks for what the - // build left there. + // build left there. Unless one does: a run that died after it + // recorded the build, before it dropped the parked one, left a + // finished build that stands with its tree. let snapshot = tree_snapshot_path(&ext); - let in_place = is_real_dir(&snapshot); + let in_place = is_real_dir(&snapshot) && !build_committed_since(copy, &ext, &snapshot); if in_place { restore_tree(copy, &snapshot)?; } @@ -2587,6 +2589,30 @@ fn restore_tree(copy: &GemCopy, snapshot_dir: &Path) -> std::io::Result<()> { remove_dir_if_exists(snapshot_dir) } +/// Whether the in-place build that took the snapshot at `snapshot` was +/// committed: the extension dir `ext` is a finished build, and the copy's +/// marker was written after the snapshot was taken and still names, hash +/// for hash, what is in the gem's tree. ([`commit_build`] writes the +/// marker before it drops the parked build, and the snapshot goes after +/// both.) +fn build_committed_since(copy: &GemCopy, ext: &Path, snapshot: &Path) -> bool { + let written = |path: &Path| std::fs::symlink_metadata(path).and_then(|meta| meta.modified()); + let (Ok(marked), Ok(taken)) = (written(©.gem_dir.join(MARKER_FILE)), written(snapshot)) + else { + return false; + }; + ext.join(BUILD_COMPLETE).is_file() + && marked >= taken + && read_marker_sync(©.gem_dir).is_some_and(|marker| { + !marker.grafted + && marker.lib_artifacts.iter().all(|(rel, hash)| { + is_safe_relative_subpath(rel) + && compute_file_git_sha256_sync(©.gem_dir.join(rel)) + .is_ok_and(|now| &now == hash) + }) + }) +} + /// Drop what a run that died left of a [`TreeSnapshot`] of `copy`, once no /// parked build says a rebuild was under way: the tree it was taken of is /// either untouched or the committed build's. @@ -7467,6 +7493,38 @@ mod tests { ); } + /// A run that died after it recorded an in-place build, before it + /// dropped the parked one and the snapshot, left a finished build. The + /// next run keeps it with its tree: putting the old library back + /// under the new marker would leave the gem running unpatched code. + #[test] + fn a_committed_in_place_build_is_not_undone_by_the_next_run() { + let tmp = tempfile::tempdir().unwrap(); + let (copy, probe) = in_tree_gem(tmp.path()); + let (scope, record) = in_tree_scope(); + let parked = parked_build_path(&probe.extension_dir); + + assert!(back_up_original(©, &probe, &[]).unwrap()); + let aside = set_aside(©, &probe).unwrap(); + let snapshot = snapshot_tree(©, &probe.extension_dir, &record_paths()).unwrap(); + build_in_tree(©, &probe); + let changes = tree_changes(©, &snapshot); + back_up_tree_changes(©, &snapshot, &[], &changes).unwrap(); + let in_tree = in_tree_artifacts(©, &probe, &[], &changes); + commit_build(©, &probe, &scope, &record, &aside, &in_tree).unwrap(); + drop(aside); + // As the run that died left it: the parked build still there. + std::fs::create_dir_all(&parked).unwrap(); + let built = tree_bytes(©.gem_dir); + + assert!(recover_interrupted_rebuild_sync(©, Some("lib")).unwrap()); + assert_eq!(tree_bytes(©.gem_dir), built); + assert!(!parked.exists()); + assert!(!snapshot.dir.exists()); + let marker = read_marker_sync(©.gem_dir).unwrap(); + assert!(marker_holds(&marker, ©, &scope, &record)); + } + /// A product taken out of the build's way and made again with the /// bytes it had is attested like one that changed, so the backup holds /// it too: the restore removes what a marker lists and the backup