From 7620e5065d2a25975a9e59a76b6a8da59c2b7a11 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:26:27 +0000 Subject: [PATCH 1/4] Start fix for gem build failure hiding its cause Refs #2117. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeP49dwo2SCWb55mzyj From 8a4d906107c79882aaa38a9b0cf003979b35ed42 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:38:48 +0000 Subject: [PATCH 2/4] Test that a failed gem build shows its cause Two unit tests for the build-output filter and one end-to-end test with the stand-in Ruby, which now can fail a build the way a gem's extconf.rb does when a library is missing. All three fail on main: the error ends in mkmf's list of configuration options, points at an mkmf.log in the removed stage, names a compiler as the remedy and is printed twice. Refs #2117. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeP49dwo2SCWb55mzyj --- .../tests/e2e_gem_native_ext_build.rs | 140 ++++++++++++++++++ crates/socket-patch-core/src/patch/gem_ext.rs | 65 ++++++++ 2 files changed, 205 insertions(+) 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 c65adf6b7..1a93cb44b 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 @@ -662,6 +662,37 @@ hang() {{ wait exit 1 }} +# What RubyGems prints when a gem's extconf.rb gives up on a missing +# library, building into the extension dir $1: the cause, mkmf's list of +# configuration options, and where it left mkmf.log. +extconf_failure() {{ + echo "ERROR: Failed to build gem native extension." + echo + echo "checking for libsp.h... no" + echo "Can't find the 'libsp.h header" + echo "Please install libsp like so:" + echo " sudo apt install libsp-dev" + echo "*** extconf.rb failed ***" + echo "Could not create Makefile due to some reason, probably lack of necessary" + echo "libraries and/or headers. Check the mkmf.log file for more details. You may" + echo "need configuration options." + echo + echo "Provided configuration options:" + i=0 + while [ $i -lt 40 ]; do + printf '\t--with-opt-%s\n' $i + i=$((i+1)) + done + echo + echo "To see why this extension failed to compile, please check the mkmf.log which can be found here:" + echo + echo " $1/mkmf.log" + echo + echo "extconf failed, exit code 1" + echo + echo "Gem files will remain installed in /somewhere for inspection." + echo "Results logged to $1/gem_make.out" +}} # The Ruby this stands in for: 3.4, or 3.3 once the test says so. version=3.4.1 abi=3.4.0 @@ -698,6 +729,10 @@ stage_build) full=$(basename "$4" .gemspec) ext="$5/extensions/x86_64-linux/$abi/$full" [ -e "$state/hang" ] && hang + if [ -e "$state/fail-extconf" ]; then + extconf_failure "$ext" >&2 + exit 1 + fi if [ -e "$state/fail-stage-build" ]; then echo "sp_native.c:7: error: this is not C (in the stage)" >&2 exit 1 @@ -729,6 +764,10 @@ build) wait exit 1 fi + if [ -e "$state/fail-extconf" ]; then + extconf_failure "$ext" >&2 + exit 1 + fi if [ -e "$state/fail-build" ]; then echo "sp_native.c:7: error: this is not C (in place)" >&2 exit 1 @@ -788,6 +827,12 @@ esac std::fs::write(self.state.join("fail-build"), b"").unwrap(); } + /// Make every later build fail, staged or in place, the way a gem's + /// `extconf.rb` does when a library it builds against is missing. + fn fail_extconf(&self) { + std::fs::write(self.state.join("fail-extconf"), b"").unwrap(); + } + /// Stand in for Ruby 3.3 from now on (3.4 until then). fn become_ruby_33(&self) { std::fs::write(self.state.join("ruby-3.3"), b"").unwrap(); @@ -1887,6 +1932,101 @@ fn a_failed_staged_build_changes_nothing() { } } +/// A build that fails because the gem's `extconf.rb` misses a library +/// (#2117: a precompiled `pg` on a machine without `libpq-dev`) says so. +/// The error keeps the lines that name the cause and not mkmf's list of +/// configuration options that follows them, does not point at a log in the +/// stage (or the extension dir) the failed build was removed with, names +/// what the rebuild of a precompiled gem needs, and is printed once. +#[cfg(unix)] +#[test] +fn a_failed_extconf_shows_its_cause_once() { + for precompiled in [true, false] { + let case = format!("precompiled {precompiled}"); + let (_tmp, proj, _gem_dir) = if precompiled { + fake_precompiled_gem(true) + } else { + let fixture = fake_native_gem(true); + let cache = fixture.1.join("vendor/bundle/ruby/3.4.0/cache"); + std::fs::create_dir_all(&cache).unwrap(); + std::fs::write(cache.join("sp_native-1.0.0.gem"), b"the source gem").unwrap(); + fixture + }; + write_manifest(&proj.join(".socket"), &c_source(1), &c_source(2)); + let ruby = FakeRuby::new(); + ruby.serve_source_gem(&c_source(1)); + ruby.fail_extconf(); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--offline"], &[]); + assert_eq!(code, 1, "{case}: {stdout}\n{stderr}"); + assert!( + stderr.contains( + "Error: Failed to patch pkg:gem/sp_native@1.0.0: native_extension_build_failed:" + ), + "{case}: {stderr}" + ); + assert!( + stderr.contains("Can't find the 'libsp.h header") + && stderr.contains("sudo apt install libsp-dev"), + "{case}: the cause is shown: {stderr}" + ); + assert!( + !stderr.contains("--with-opt-") && !stderr.contains("Provided configuration options"), + "{case}: mkmf's option list is not: {stderr}" + ); + assert!( + !stderr.contains("mkmf.log which can be found") + && !stderr.contains("/mkmf.log") + && !stderr.contains("gem_make.out"), + "{case}: no pointer to a log that was removed: {stderr}" + ); + assert!( + !stderr.contains("Install a compiler toolchain and the Ruby headers and apply again"), + "{case}: the remedy does not assume the compiler is what is missing: {stderr}" + ); + if precompiled { + assert!( + stderr.contains("gem install sp_native --platform ruby") + && stderr.contains("the libraries the gem builds against"), + "{case}: the remedy says what a precompiled gem's rebuild needs: {stderr}" + ); + } else { + assert!( + stderr.contains("a library the gem builds against") + && stderr.contains("socket-patch scan --mode hosted"), + "{case}: {stderr}" + ); + } + assert_eq!( + stderr + .matches("did not build from the patched sources") + .count(), + 1, + "{case}: the failure is printed once: {stderr}" + ); + assert!(!stderr.contains("Warning:"), "{case}: {stderr}"); + assert_tree(&proj.join("vendor"), &tree_before, &case); + + // The machine channel keeps the failure as the package's error and + // as a coded warning. + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--json", "--offline"], &[]); + assert_eq!(code, 1, "{case}: {stdout}\n{stderr}"); + let envelope = parse_json_envelope(&stdout); + let warnings = envelope["warnings"].as_array().expect("warnings[]"); + assert!( + warnings.iter().any(|w| { + w["code"] == "native_extension_build_failed" + && w["detail"] + .as_str() + .is_some_and(|d| d.contains("Can't find the 'libsp.h header")) + }), + "{case}: {stdout}" + ); + assert_tree(&proj.join("vendor"), &tree_before, &case); + } +} + /// Whatever keeps a gem RubyGems built from being rebuilt from its source /// gem, before anything of the installed copy is written, leaves it the /// rebuild it had before there was a stage: from its own tree, in place. diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 77d855627..351582e4d 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -5507,6 +5507,71 @@ mod tests { ); } + /// #2117: for a failed `extconf.rb` the last lines of the output are + /// mkmf's list of configuration options and a pointer to an `mkmf.log` + /// that is removed with the failed build; the cause comes before both. + #[test] + fn stderr_tail_keeps_the_cause_of_a_failed_extconf() { + let mut text = String::from( + "ERROR: Failed to build gem native extension.\n\n\ + checking for libpq-fe.h... no\n\ + Can't find the 'libpq-fe.h header\n\ + \x20 sudo apt install libpq-dev\n\ + *** extconf.rb failed ***\n\ + Could not create Makefile due to some reason, probably lack of necessary\n\ + libraries and/or headers. Check the mkmf.log file for more details. You may\n\ + need configuration options.\n\n\ + Provided configuration options:\n", + ); + for i in 0..40 { + text.push_str(&format!("\t--with-opt-{i}\n")); + } + text.push_str( + "\nTo see why this extension failed to compile, please check the mkmf.log which \ + can be found here:\n\n /home/.socket-patch-build/pg-1.6.2/home/extensions/x/3.3.0/\ + pg-1.6.2/mkmf.log\n\nextconf failed, exit code 1\n\n\ + Gem files will remain installed in /x for inspection.\n\ + Results logged to /x/gem_make.out\n", + ); + let tail = stderr_tail(&text); + assert_eq!( + tail, + "ERROR: Failed to build gem native extension.\n\ + checking for libpq-fe.h... no\n\ + Can't find the 'libpq-fe.h header\n\ + \x20 sudo apt install libpq-dev\n\ + *** extconf.rb failed ***\n\ + Could not create Makefile due to some reason, probably lack of necessary\n\ + libraries and/or headers. Check the mkmf.log file for more details. You may\n\ + need configuration options.\n\ + extconf failed, exit code 1" + ); + } + + /// Only mkmf's own block is dropped: tab-indented lines elsewhere (a + /// Ruby backtrace, `make` output) stay, and so does a line after the + /// pointer that is not the log's path. + #[test] + fn stderr_tail_keeps_indented_lines_outside_the_option_list() { + let text = "extconf.rb:5:in `rename': No such file (Errno::ENOENT)\n\ + \tfrom extconf.rb:5:in `
'\n\ + Provided configuration options:\n\ + \t--with-opt-dir\n\ + make: *** [Makefile:245: pg.o] Error 1\n\ + \tcompilation terminated.\n\ + To see why this extension failed to compile, please check the mkmf.log \ + which can be found here:\n\ + make failed, exit code 2\n"; + assert_eq!( + stderr_tail(text), + "extconf.rb:5:in `rename': No such file (Errno::ENOENT)\n\ + \tfrom extconf.rb:5:in `
'\n\ + make: *** [Makefile:245: pg.o] Error 1\n\ + \tcompilation terminated.\n\ + make failed, exit code 2" + ); + } + #[test] fn probe_output_parses() { assert_eq!( From 547b56ab8428aeb67aca11859950655a3edf4d4d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:00:33 +0000 Subject: [PATCH 3/4] Show the cause of a failed gem extension build When agent apply rebuilds a gem's native extension and the build fails, the error carried the last 20 lines of the build's stderr. For a failed extconf.rb those are mkmf's list of configuration options, so the lines naming the cause (a missing libpq-fe.h for a precompiled pg) were cut off. The tail also pointed at an mkmf.log in the stage, which is removed before the error is printed. The diagnostic now drops mkmf's option list and its mkmf.log pointer before taking the tail, which grows to 30 lines. The remedy of a precompiled gem says that the rebuild needs what `gem install --platform ruby` needs, and the in-place one no longer assumes the compiler is what is missing. On the human path a failed gem refusal was printed twice, as the package's Error line and as a Warning with the same text. The warning is now kept for the JSON envelope only. A failed in-place build also no longer advises that `bundle install --redownload` reverts a patch it did not leave applied. Fixes #2117. Refs #2106. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeP49dwo2SCWb55mzyj --- crates/socket-patch-cli/CLI_CONTRACT.md | 2 +- crates/socket-patch-cli/src/commands/apply.rs | 22 +++++- .../tests/e2e_gem_native_ext_build.rs | 3 + crates/socket-patch-core/src/patch/gem_ext.rs | 78 +++++++++++++++---- docs/ecosystems.md | 9 ++- 5 files changed, 96 insertions(+), 18 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 74e5e02d1..7a13183d5 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1080,7 +1080,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, 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_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), at most 30 lines of each, without mkmf's list of configuration options or its pointer to the `mkmf.log` that was removed with the failed build. For a precompiled gem it says that the rebuild needs what `gem install --platform ruby` needs. On the human path the failure is printed once, as the package's `Error:` line; under `--json` it is the package's error and a `warnings[]` entry. | | `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-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 04bb6a828..5cd9a3322 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -1796,7 +1796,13 @@ pub(crate) async fn run_locked( // Sources-unavailable codes restate the staging layer's // own `Error:` diagnostic (already printed, even under // --silent); they exist for the JSON envelope. - if !is_stage_failure_code(&w.code) { + // + // So does the coded copy of a package's refusal (a gem + // whose native extension cannot be rebuilt): the + // package's own `Error: Failed to patch` line carries + // the same text, and a build failure's is many lines + // long (#2117). + if !is_stage_failure_code(&w.code) && !restates_a_failure(w, &results) { eprintln!("Warning: {}", w.detail); } } @@ -2267,6 +2273,20 @@ fn is_stage_failure_code(code: &str) -> bool { code == OFFLINE_MISSING_SOURCES || code == SOURCES_DOWNLOAD_FAILED } +/// Whether `warning` is the coded copy of a failed result's error (`: +/// `, how a gem refusal is carried for the JSON envelope): the +/// human path already printed that text as the package's `Error: Failed to +/// patch` line. +fn restates_a_failure(warning: &RunWarning, results: &[ApplyResult]) -> bool { + results.iter().filter(|r| !r.success).any(|r| { + r.error + .as_deref() + .and_then(|error| error.strip_prefix(warning.code.as_str())) + .and_then(|rest| rest.strip_prefix(": ")) + == Some(warning.detail.as_str()) + }) +} + /// Why nothing could be applied when the patch sources are unavailable — /// the `--json` envelope's only explanation for its empty, failing run /// (the staging layer's stderr diagnostic is muted under `--json`). 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 1a93cb44b..97e55b387 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 @@ -2005,6 +2005,8 @@ fn a_failed_extconf_shows_its_cause_once() { 1, "{case}: the failure is printed once: {stderr}" ); + // Nor is a copy that was put back advised about what reverts its + // patch. assert!(!stderr.contains("Warning:"), "{case}: {stderr}"); assert_tree(&proj.join("vendor"), &tree_before, &case); @@ -2023,6 +2025,7 @@ fn a_failed_extconf_shows_its_cause_once() { }), "{case}: {stdout}" ); + assert!(!stdout.contains("--redownload"), "{case}: {stdout}"); assert_tree(&proj.join("vendor"), &tree_before, &case); } } diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 351582e4d..78aae32e3 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -1467,19 +1467,55 @@ async fn run_ruby( } } -/// The useful end of a failed build's stderr: RubyGems' trailing -/// "Gem files will remain installed" boilerplate dropped, at most 20 lines. +/// How many lines of a failed build's output its error carries. +const DIAGNOSTIC_LINES: usize = 30; + +/// The line mkmf prints above every configuration option the failed +/// `extconf.rb` accepts, one tab-indented line each. +const MKMF_OPTIONS_HEADING: &str = "Provided configuration options:"; + +/// How RubyGems starts its pointer to the `mkmf.log` of a failed +/// `extconf.rb`; the log's path is the next line that is not blank. +const MKMF_LOG_POINTER: &str = "To see why this extension failed to compile, please check the"; + +/// The useful end of a failed build's stderr, at most [`DIAGNOSTIC_LINES`] +/// lines of it. Dropped first, as they say nothing about the failure and +/// are what RubyGems ends the output of a failed `extconf.rb` with: +/// +/// * its trailing "Gem files will remain installed" boilerplate; +/// * mkmf's list of configuration options, which is longer than the tail +/// for most gems, so the lines that name the cause, printed before it, +/// would be cut off; +/// * its pointer to the build's `mkmf.log`. Every build this module runs +/// is undone when it fails (the stage is removed, an in-place build's +/// extension dir is replaced with the one it had), and the log with it. fn stderr_tail(stderr: &str) -> String { let text = stderr .split("\nGem files will remain installed") .next() .unwrap_or(stderr); - let lines: Vec<&str> = text - .lines() - .map(str::trim_end) - .filter(|l| !l.is_empty()) - .collect(); - let start = lines.len().saturating_sub(20); + let mut lines: Vec<&str> = Vec::new(); + let (mut in_options, mut log_path_next) = (false, false); + for line in text.lines().map(str::trim_end) { + if line.is_empty() { + continue; + } + if std::mem::take(&mut in_options) && line.starts_with('\t') { + in_options = true; + continue; + } + if std::mem::take(&mut log_path_next) && line.ends_with("mkmf.log") { + continue; + } + if line == MKMF_OPTIONS_HEADING { + in_options = true; + } else if line.starts_with(MKMF_LOG_POINTER) { + log_path_next = true; + } else { + lines.push(line); + } + } + let start = lines.len().saturating_sub(DIAGNOSTIC_LINES); let tail = lines[start..].join("\n"); if tail.is_empty() { "the build exited with an error and no output".to_string() @@ -4467,6 +4503,9 @@ impl Job<'_> { result.success = false; result.files_patched.clear(); result.applied_via.clear(); + // What the written sources were advised about (`bundle install + // --redownload` reverts them) is not true of a copy put back. + result.sidecar = None; result.error = Some(format!("{BUILD_FAILED_CODE}: {detail}")); GemApplied { result, @@ -4858,8 +4897,14 @@ pub async fn apply_gem_package_patch( BUILD_FAILED_CODE, format!( "the native extension did not build from the patched sources ({inputs}); \ - nothing of the installed gem was changed. Install a compiler toolchain and \ - the Ruby headers and apply again.\n{diagnostic}" + nothing of the installed gem was changed. {} was installed precompiled, so \ + nothing of it was built on this machine before: the rebuild needs what `gem \ + install {} --platform ruby` needs, which is a compiler toolchain, the Ruby \ + headers and the libraries the gem builds against. The build output below \ + says what failed; install what it names as missing and apply again.\ + \n{diagnostic}", + copy.full_name, + gem_name_of(©.full_name) ), ), failure => needs_source_gem(source.as_ref(), failure.describe(), remedy.is_some()), @@ -4938,9 +4983,10 @@ async fn rebuild_in_place( }; let detail = format!( "the native extension did not build from the patched sources ({}); the \ - sources and the previous build were put back. Install a compiler toolchain \ - and the Ruby headers and apply again, or use `socket-patch scan --mode \ - hosted`.{both}\n{diagnostic}", + sources and the previous build were put back. The build output below says \ + what failed: when it is a missing compiler, the Ruby headers or a library \ + the gem builds against, install that and apply again; otherwise use \ + `socket-patch scan --mode hosted`.{both}\n{diagnostic}", job.inputs ); job.not_built(result, &originals, detail).await @@ -5499,8 +5545,12 @@ mod tests { let mut text: String = (0..30).map(|i| format!("line {i}\n")).collect(); text.push_str("\nGem files will remain installed in /x for inspection.\n"); let tail = stderr_tail(&text); - assert!(tail.starts_with("line 10")); + assert!(tail.starts_with("line 0\n")); assert!(tail.ends_with("line 29")); + let long: String = (0..45).map(|i| format!("line {i}\n")).collect(); + let tail = stderr_tail(&long); + assert!(tail.starts_with("line 15\n")); + assert!(tail.ends_with("line 44")); assert_eq!( stderr_tail(""), "the build exited with an error and no output" diff --git a/docs/ecosystems.md b/docs/ecosystems.md index 317516802..70a3286cc 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -2046,8 +2046,13 @@ touched until the build has finished. An agent-mode rebuild needs a compiler toolchain and the Ruby headers (`ruby-dev` / `ruby-devel` on Linux distributions, the Xcode command line tools on macOS), the same requirements as `gem install` for the ruby-platform gem. It takes as long as that install: about -a minute for nokogiri. When the build fails, the installed gem is left as it was and the package -fails with `native_extension_build_failed`, showing the tail of the build output. When it can't +a minute for nokogiri. A precompiled gem (`pg`, `nokogiri`, `ffi` and most others install that way) +was never built on your machine, so its rebuild is the first time the gem's own build dependencies +are needed: the libraries and headers it compiles against (`libpq-dev` for `pg`), which `bundle +install` did without. When the build fails, the installed gem is left as it was and the package +fails with `native_extension_build_failed`, showing the tail of the build output: the lines that +say what failed, without mkmf's list of configuration options or its pointer to an `mkmf.log`, +which is removed with the failed build. When it can't rebuild at all (a Bundler git checkout, no matching Ruby, no source gem for a precompiled gem), nothing is written and the package fails with `native_extensions_unsupported`. From f545e89705aab5f530df5ba9f5d18db2d461e0b9 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 14:19:08 +0000 Subject: [PATCH 4/4] Name the source gem and keep a prior advisory From the review of this branch: - The remedy of a precompiled gem's failed rebuild names the source gem by its name and version instead of a name derived from the installed directory. - Both remedies no longer promise build output that names what is missing: a build that timed out or could not start has none. - A failed in-place build keeps the `bundle install --redownload` advisory when an earlier run left a file of the record patched, which this run does not put back. - CLI_CONTRACT.md says for every native-extension refusal that it is printed once on the human path. Refs #2117. Assisted-by: Claude Code:claude-fable-5-2 Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_011f9aeP49dwo2SCWb55mzyj --- crates/socket-patch-cli/CLI_CONTRACT.md | 5 +- crates/socket-patch-cli/src/commands/apply.rs | 37 +++++++++++ .../tests/e2e_gem_native_ext_build.rs | 38 ++++++++++- crates/socket-patch-core/src/patch/gem_ext.rs | 63 ++++++++++++------- 4 files changed, 120 insertions(+), 23 deletions(-) diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 7a13183d5..6a0484d30 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -1080,11 +1080,14 @@ 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, 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), at most 30 lines of each, without mkmf's list of configuration options or its pointer to the `mkmf.log` that was removed with the failed build. For a precompiled gem it says that the rebuild needs what `gem install --platform ruby` needs. On the human path the failure is printed once, as the package's `Error:` line; under `--json` it is the package's error and a `warnings[]` entry. | +| `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), at most 30 lines of each, without mkmf's list of configuration options or its pointer to the `mkmf.log` that was removed with the failed build. For a precompiled gem it says that the rebuild needs what `gem install -v --platform ruby` needs. | | `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 `). | +A refusal is printed once on the human path, as the package's `Error: Failed to patch` line. Under +`--json` it is the package's error and, under its code, a `warnings[]` entry. + `vex` and `apply --check` attest such a copy only while its marker matches the record's patched sources and every artifact it lists, a precompiled gem's replaced binary included; otherwise the purl fails with `native_extension_not_rebuilt`. After `gem pristine` or a reinstall, run `apply` diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 5cd9a3322..0681686d7 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -4149,6 +4149,43 @@ mod tests { assert_eq!(expected_hash_label(&h), h); } + /// A gem refusal reaches the run as a failed result (`: + /// `) and as a coded warning with the same detail: only that + /// warning restates a failure the human path already printed. + #[test] + fn only_the_coded_copy_of_a_failed_result_restates_it() { + let warning = |code: &str, detail: &str| RunWarning { + code: code.to_string(), + detail: detail.to_string(), + }; + let mut failed = sample_applied(VerifyStatus::Ready); + failed.success = false; + failed.error = + Some("native_extension_build_failed: it did not build\nmake: Error 1".into()); + let mut advised = sample_applied(VerifyStatus::Ready); + advised.error = Some("native_extension_rebuilt: rebuilt".into()); + let results = [failed, advised, sample_applied(VerifyStatus::Ready)]; + + assert!(restates_a_failure( + &warning( + "native_extension_build_failed", + "it did not build\nmake: Error 1" + ), + &results + )); + // Another detail, another code, or a result that succeeded. + for other in [ + warning("native_extension_build_failed", "it did not build"), + warning( + "native_extensions_unsupported", + "it did not build\nmake: Error 1", + ), + warning("native_extension_rebuilt", "rebuilt"), + ] { + assert!(!restates_a_failure(&other, &results), "{}", other.detail); + } + } + /// Build a successful `ApplyResult` with one patched file and one /// verified file. Used as the base for action-routing tests. fn sample_applied(status: VerifyStatus) -> ApplyResult { 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 97e55b387..7e29451f9 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 @@ -1987,7 +1987,7 @@ fn a_failed_extconf_shows_its_cause_once() { ); if precompiled { assert!( - stderr.contains("gem install sp_native --platform ruby") + stderr.contains("`gem install sp_native -v 1.0.0 --platform ruby`") && stderr.contains("the libraries the gem builds against"), "{case}: the remedy says what a precompiled gem's rebuild needs: {stderr}" ); @@ -2030,6 +2030,42 @@ fn a_failed_extconf_shows_its_cause_once() { } } +/// A failed build puts back what this run wrote, and no more: a file an +/// earlier run left patched stays patched, so the copy is still advised +/// that `bundle install --redownload` reverts it. +#[cfg(unix)] +#[test] +fn a_failed_build_keeps_the_advisory_of_a_file_patched_before() { + let (_tmp, proj, gem_dir) = fake_native_gem(true); + let (before, after) = (c_source(1), c_source(2)); + let lib_after = format!("{LIB_RB}# patched\n"); + write_record( + &proj.join(".socket"), + PURL, + &[ + (C_KEY, Some(&before), &after), + ("lib/sp_native.rb", Some(LIB_RB), &lib_after), + ], + ); + std::fs::write(gem_dir.join("lib/sp_native.rb"), &lib_after).unwrap(); + let ruby = FakeRuby::new(); + ruby.fail_builds(); + let tree_before = walk_files(&proj.join("vendor")); + + let (code, stdout, stderr) = ruby.run(&proj, &["apply", "--offline"], &[]); + assert_eq!(code, 1, "{stdout}\n{stderr}"); + assert!( + stderr.contains("native_extension_build_failed:"), + "{stderr}" + ); + assert_eq!( + stderr.matches("bundle install --redownload").count(), + 1, + "{stderr}" + ); + assert_tree(&proj.join("vendor"), &tree_before, "after the failed build"); +} + /// Whatever keeps a gem RubyGems built from being rebuilt from its source /// gem, before anything of the installed copy is written, leaves it the /// rebuild it had before there was a stage: from its own tree, in place. diff --git a/crates/socket-patch-core/src/patch/gem_ext.rs b/crates/socket-patch-core/src/patch/gem_ext.rs index 78aae32e3..630d2759e 100644 --- a/crates/socket-patch-core/src/patch/gem_ext.rs +++ b/crates/socket-patch-core/src/patch/gem_ext.rs @@ -4504,8 +4504,16 @@ impl Job<'_> { result.files_patched.clear(); result.applied_via.clear(); // What the written sources were advised about (`bundle install - // --redownload` reverts them) is not true of a copy put back. - result.sidecar = None; + // --redownload` reverts them) is not true of a copy put back. It + // still is of one an earlier run left a patched file in, which + // this run did not write and so did not put back. + let patched_before = result + .files_verified + .iter() + .any(|v| v.status == crate::patch::apply::VerifyStatus::AlreadyPatched); + if !patched_before { + result.sidecar = None; + } result.error = Some(format!("{BUILD_FAILED_CODE}: {detail}")); GemApplied { result, @@ -4891,22 +4899,35 @@ pub async fn apply_gem_package_patch( failure if !precompiled => { rebuild_in_place(&job, &probe, &absent, &failure, remedy.as_deref()).await } - StageFailure::Build(diagnostic) => refusal( - package_key, - pkg_path, - BUILD_FAILED_CODE, - format!( - "the native extension did not build from the patched sources ({inputs}); \ - nothing of the installed gem was changed. {} was installed precompiled, so \ - nothing of it was built on this machine before: the rebuild needs what `gem \ - install {} --platform ruby` needs, which is a compiler toolchain, the Ruby \ - headers and the libraries the gem builds against. The build output below \ - says what failed; install what it names as missing and apply again.\ - \n{diagnostic}", - copy.full_name, - gem_name_of(©.full_name) - ), - ), + StageFailure::Build(diagnostic) => { + // The source gem the stage was built from, by name and + // version: what the same build is run with outside this tool. + let install = match &source { + Some(source) => format!( + "gem install {} -v {} --platform ruby", + source.name, source.version + ), + None => format!( + "gem install {} --platform ruby", + gem_name_of(©.full_name) + ), + }; + refusal( + package_key, + pkg_path, + BUILD_FAILED_CODE, + format!( + "the native extension did not build from the patched sources ({inputs}); \ + nothing of the installed gem was changed. {} was installed precompiled, \ + so nothing of it was built on this machine before: the rebuild needs \ + what `{install}` needs, which is a compiler toolchain, the Ruby headers \ + and the libraries the gem builds against. The lines below say what \ + failed; when they name something as missing, install it and apply \ + again.\n{diagnostic}", + copy.full_name + ), + ) + } failure => needs_source_gem(source.as_ref(), failure.describe(), remedy.is_some()), } } @@ -4983,9 +5004,9 @@ async fn rebuild_in_place( }; let detail = format!( "the native extension did not build from the patched sources ({}); the \ - sources and the previous build were put back. The build output below says \ - what failed: when it is a missing compiler, the Ruby headers or a library \ - the gem builds against, install that and apply again; otherwise use \ + sources and the previous build were put back. The lines below say what \ + failed: when it is a missing compiler, the Ruby headers or a library the \ + gem builds against, install that and apply again; otherwise use \ `socket-patch scan --mode hosted`.{both}\n{diagnostic}", job.inputs );