Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
| `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 <name> -v <version> --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 <gem> --extensions` (a precompiled gem: `gem pristine <gem>`). |

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`
Expand Down
59 changes: 58 additions & 1 deletion crates/socket-patch-cli/src/commands/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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 (`<code>:
/// <detail>`, 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`).
Expand Down Expand Up @@ -4129,6 +4149,43 @@ mod tests {
assert_eq!(expected_hash_label(&h), h);
}

/// A gem refusal reaches the run as a failed result (`<code>:
/// <detail>`) 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 {
Expand Down
179 changes: 179 additions & 0 deletions crates/socket-patch-cli/tests/e2e_gem_native_ext_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -1887,6 +1932,140 @@ 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 -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}"
);
} 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}"
);
// 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);

// 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!(!stdout.contains("--redownload"), "{case}: {stdout}");
assert_tree(&proj.join("vendor"), &tree_before, &case);
}
}

/// 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.
Expand Down
Loading
Loading