← Back to Pull requests

sort: handle compression subprocess failures #14945

Open
mattsu2020 opened this pull request with 736 lines diff across 6 files
View on GitHub
mattsu2020 mattsu2020 commented on Sep 29, 2026 09:59 UTC
Author

Compression subprocesses that exit early can terminate sort with SIGPIPE, and intermediate merge write failures can return status 1 instead of 2. Handle broken pipes and buffered write errors, reject abnormal child exits, and wait for compression and decompression children on error paths. Restore child waiting when SIGCHLD is inherited as ignored, while preserving normal SIGPIPE behavior for stdout.

Adds regression tests for early exits, failures after consuming all input or producing output, signal termination, and intermediate merge failures. The sort regression tests pass on macOS and Linux. The GNU shell test itself has not been run.

The current CodSpeed comparison mixes Rust 1.98.1 and 1.99.0 between BASE and HEAD. Paired Linux/aarch64 runs using Rust 1.99.0 did not reproduce the reported large sort and split slowdowns; a matched-toolchain CodSpeed comparison is still needed.

Refs #14705 (sort/sort-compress-proc.sh).
Closes #14951

Diff: 736 lines (+714 / -22) across 6 files Reviewer: sylvestre Review duration: 95138m
All Vouch review confidence checks passed
Residual risk 0.06 = Change Risk (0.57) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.57 · 736 lines diff across 6 files
0.57
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.395
Real PR Conversation Timeline
31 items
github-actions[bot] github-actions[bot] commented on Sep 29, 2026 10:59 UTC
Bot

<!-- gnu-comment-bot -->
GNU testsuite comparison:

Skip an intermittent issue tests/misc/usage_vs_getopt (fails in this run but passes in the 'main' branch)
Congrats! The gnu test tests/pr/options is no longer failing!

xtqqczze xtqqczze commented on Sep 29, 2026 11:26 UTC
Contributor

@mattsu2020 You need to open an issue to prevent duplication of work.

sylvestre sylvestre commented on code on Oct 08, 2026 09:11 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -157,8 +163,12 @@ pub fn merge_with_file_limit<
 
             let mut tmp_file =
                 Tmp::create(tmp_dir.next_file()?, settings.compress_prog.as_deref())?;
-            merger.write_all_to(settings, tmp_file.as_write(), || "write failed".into())?;
-            temporary_files.push(tmp_file.finished_writing()?);
+            let write_result = merger.write_all_to(settings, tmp_file.as_write(), |error| {

same block as above, could be dedup in a small helper, no?

sylvestre sylvestre commented on code on Oct 08, 2026 09:11 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -253,32 +272,45 @@ fn reader(
     settings: &GlobalSettings,
     separator: u8,
 ) -> UResult<()> {
-    for (file_idx, recycled_chunk) in recycled_receiver {
-        if let Some(ReaderFile {
-            file,
-            sender,
-            carry_over,
-        }) = &mut files[file_idx]
-        {
-            let should_continue = chunks::read(
+    let read_result: UResult<()> = (|| {

please extract that into a function rather than an immediately called closure

sylvestre sylvestre commented on code on Oct 08, 2026 09:11 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -454,9 +486,36 @@ impl FileMerger<'_> {
     }
 }
 
+/// Make compression children waitable even if the caller ignored SIGCHLD.
+#[cfg(unix)]
+pub fn prepare_child_wait() -> io::Result<()> {

could you please move this to uucore::signals and use nix like the other helpers there? it doesn't really belong in merge.rs

sylvestre sylvestre commented on code on Oct 08, 2026 09:12 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -566,6 +628,10 @@ impl WriteableTmpFile for WriteableCompressedTmpFile {
     type InnerWrite = BufWriter<ChildStdin>;
 
     fn create((file, path): (File, PathBuf), compress_prog: Option<&str>) -> UResult<Self> {
+        // A compressor can close stdin before we finish writing. Handle EPIPE as
+        // an ordinary write error instead of letting SIGPIPE terminate sort.
+        #[cfg(unix)]
+        let _ = disable_pipe_errors();

this ignores SIGPIPE for the whole process, so sort --compress-program=gzip big | head -1 now errors on stdout instead of dying quietly like GNU, no?
also gzip inherits the ignored SIGPIPE through exec

sylvestre sylvestre commented on code on Oct 08, 2026 09:12 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1726,6 +1792,95 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    at.write("input", input);
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "--compress-program=./compressor",
+            "-S",
+            buffer_size,
+            "--batch-size=2",
+            "input",
+        ])
+        .fails_with_code(2);

please also check stderr, only checking the exit code is weak

sylvestre sylvestre commented on code on Oct 08, 2026 09:12 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1726,6 +1792,95 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    at.write("input", input);
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "--compress-program=./compressor",
+            "-S",
+            buffer_size,
+            "--batch-size=2",
+            "input",
+        ])
+        .fails_with_code(2);
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_exits_before_reading() {
+    let input = compressor_input(30_000, 8, "xxxxxxxxxxxxxxxxxxxxxxxx");
+    run_with_compressor("#!/bin/sh\nexit 0\n", &input, "300k");
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_exits_during_intermediate_merge() {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", "#!/bin/sh\nexit 7\n");
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    // Exceed the pipe capacity so the failure occurs while merging, before
+    // finished_writing checks the compressor's exit status.
+    at.write("input", &"a long sorted input line\n".repeat(100_000));
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "-m",
+            "--batch-size=2",
+            "--compress-program=./compressor",
+            "input",
+            "input",
+            "input",
+        ])
+        .fails_with_code(2);
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_failure_after_input() {
+    let input = compressor_input(600, 4, "");
+    run_with_compressor(
+        "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nexit 7\n",

the sleep makes this timing dependent, do we need it?

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:40 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -157,8 +163,12 @@ pub fn merge_with_file_limit<
 
             let mut tmp_file =
                 Tmp::create(tmp_dir.next_file()?, settings.compress_prog.as_deref())?;
-            merger.write_all_to(settings, tmp_file.as_write(), || "write failed".into())?;
-            temporary_files.push(tmp_file.finished_writing()?);
+            let write_result = merger.write_all_to(settings, tmp_file.as_write(), |error| {

I'll take care of it.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:41 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -253,32 +272,45 @@ fn reader(
     settings: &GlobalSettings,
     separator: u8,
 ) -> UResult<()> {
-    for (file_idx, recycled_chunk) in recycled_receiver {
-        if let Some(ReaderFile {
-            file,
-            sender,
-            carry_over,
-        }) = &mut files[file_idx]
-        {
-            let should_continue = chunks::read(
+    let read_result: UResult<()> = (|| {

I'll fix that code.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:41 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -454,9 +486,36 @@ impl FileMerger<'_> {
     }
 }
 
+/// Make compression children waitable even if the caller ignored SIGCHLD.
+#[cfg(unix)]
+pub fn prepare_child_wait() -> io::Result<()> {

I'll move that code to uucore::signals.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:43 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -566,6 +628,10 @@ impl WriteableTmpFile for WriteableCompressedTmpFile {
     type InnerWrite = BufWriter<ChildStdin>;
 
     fn create((file, path): (File, PathBuf), compress_prog: Option<&str>) -> UResult<Self> {
+        // A compressor can close stdin before we finish writing. Handle EPIPE as
+        // an ordinary write error instead of letting SIGPIPE terminate sort.
+        #[cfg(unix)]
+        let _ = disable_pipe_errors();

I've updated the implementation to avoid ignoring SIGPIPE process-wide.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:45 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1726,6 +1792,95 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    at.write("input", input);
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "--compress-program=./compressor",
+            "-S",
+            buffer_size,
+            "--batch-size=2",
+            "input",
+        ])
+        .fails_with_code(2);

I've updated the code to check for errors.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 12:46 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1726,6 +1792,95 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    at.write("input", input);
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "--compress-program=./compressor",
+            "-S",
+            buffer_size,
+            "--batch-size=2",
+            "input",
+        ])
+        .fails_with_code(2);
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_exits_before_reading() {
+    let input = compressor_input(30_000, 8, "xxxxxxxxxxxxxxxxxxxxxxxx");
+    run_with_compressor("#!/bin/sh\nexit 0\n", &input, "300k");
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_exits_during_intermediate_merge() {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let (at, mut ucmd) = at_and_ucmd!();
+    at.write("compressor", "#!/bin/sh\nexit 7\n");
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+    // Exceed the pipe capacity so the failure occurs while merging, before
+    // finished_writing checks the compressor's exit status.
+    at.write("input", &"a long sorted input line\n".repeat(100_000));
+    ucmd.timeout(Duration::from_secs(30))
+        .args(&[
+            "-m",
+            "--batch-size=2",
+            "--compress-program=./compressor",
+            "input",
+            "input",
+            "input",
+        ])
+        .fails_with_code(2);
+}
+
+#[test]
+#[cfg(unix)]
+fn test_compressor_failure_after_input() {
+    let input = compressor_input(600, 4, "");
+    run_with_compressor(
+        "#!/bin/sh\ncat >/dev/null\nsleep 0.1\nexit 7\n",

I deleted it.

codspeed[bot] codspeed[bot] commented on Oct 08, 2026 12:57 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will degrade performance by 46.73%

<details>
<summary><b>2 warnings, 1 note</b></summary>

:warning: 127 benchmarks are dominated by system calls

> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

> Learn more about system calls

> See affected benchmarks

:warning: 3 benchmarks with a significant change ran on different hardware

> Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.

> Learn more about Macro Runners

> See affected benchmarks

:information_source: 1 benchmark has no flamegraph

> The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

> See affected benchmarks

</details>

⚡ 1 improved benchmark
❌ 2 regressed benchmarks
✅ 412 untouched benchmarks
⏩ 74 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | Memory | [` socket_addrs_direct[100000] ](https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Asort-compress-proc.sh?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Asocket_addrs_direct%255B100000%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 8.6 KB | 68 KB | -87.29% |
| ❌ | Memory | [
hostname_ip_lookup[100000] ](https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Asort-compress-proc.sh?uri=src%2Fuu%2Fhostname%2Fbenches%2Fhostname_bench.rs%3A%3Ahostname_ip_lookup%255B100000%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 100.9 KB | 160.3 KB | -37.06% |
| ⚡ | Memory |
timeout_enforced | 167.5 KB | 88.7 KB | +88.88% |

[!TIP]

Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>mattsu2020:sort-compress-proc.sh</code> (5e1fe6e) with <code>main</code> (ce58468)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Asort-compress-proc.sh?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 74 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>main</code> (f02ef8e) during the generation of this report, so ce58468 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

sylvestre sylvestre commented on Oct 08, 2026 13:22 UTC
Contributor

significant perf regressions here

sylvestre sylvestre commented on code on Oct 08, 2026 20:43 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -545,11 +597,29 @@ impl MergeInput for PlainTmpMergeInput {
     }
 }
 
+/// Protect compression pipe writes without changing the process's SIGPIPE handler.
+pub struct CompressionPipeWriter(ChildStdin);
+
+impl Write for CompressionPipeWriter {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        #[cfg(target_vendor = "apple")]
+        uucore::signals::disable_pipe_errors_for_fd(&self.0)?;

this does an fcntl on every write, could you please set it once in create() instead?

sylvestre sylvestre commented on code on Oct 08, 2026 20:43 UTC
Code Review
src/uucore/src/lib/features/signals.rs:1
@@ -614,6 +614,88 @@ pub fn disable_pipe_errors() -> Result<(), Errno> {
     unsafe { signal(SIGPIPE, SigIgn) }.map(|_| ())
 }
 
+/// Runs a pipe write with SIGPIPE blocked only on the calling thread.
+/// Consumes a newly generated SIGPIPE on EPIPE, preserving any already pending
+/// signal and restoring the original mask even if the operation panics.
+#[cfg(all(unix, not(target_vendor = "apple")))]
+pub fn with_sigpipe_blocked<T>(write: impl FnOnce() -> std::io::Result<T>) -> std::io::Result<T> {

that's 4+ syscalls per buffered write (mask swap, 2 sigpending, restore), could we block SIGPIPE once around the whole tmp file write instead?

sylvestre sylvestre commented on code on Oct 08, 2026 20:44 UTC
Code Review
src/uucore/src/lib/features/signals.rs:1
@@ -806,6 +888,123 @@ pub fn ensure_stdout_not_broken() -> std::io::Result<bool> {
     Ok(true)
 }
 
+#[test]
+#[cfg(all(unix, not(target_vendor = "apple")))]
+fn test_with_sigpipe_blocked() {

this test is quite long and complex for what it checks, could it be simplified?

sylvestre sylvestre commented on code on Oct 08, 2026 20:44 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1696,6 +1696,72 @@ fn test_compress_merge() {
         .stdout_only_fixture("merge_ints_interleaved.expected");
 }
 
+#[cfg(target_os = "linux")]
+fn sort_with_ignored_sigchld(ts: &TestScenario) -> uutests::util::UCommand {
+    let mut command = ts.cmd("bash");
+    command
+        .timeout(Duration::from_secs(30))
+        .args(&["-c", "trap '' CHLD; exec \"$@\"", "bash"])
+        .arg(&ts.bin_path)
+        .arg(&ts.util_name);
+    command
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+fn test_compress_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    let mut expected = String::new();
+    for i in 0..600 {
+        writeln!(&mut expected, "{i:04}").unwrap();
+    }
+    sort_with_ignored_sigchld(&ts)
+        .args(&["--compress-program=gzip", "-S", "1k", "input"])
+        .succeeds()
+        .stdout_only(&expected);
+
+    ts.fixtures.write("sorted", &expected);
+    sort_with_ignored_sigchld(&ts)
+        .args(&[
+            "-m",
+            "-u",
+            "--batch-size=2",
+            "--compress-program=gzip",
+            "sorted",
+            "sorted",
+            "sorted",
+        ])
+        .succeeds()
+        .stdout_only(&expected);
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+fn test_compress_failures_ignored_sigchld() {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    for script in [
+        "#!/bin/sh\ncat >/dev/null\nexit 7\n",
+        "#!/bin/sh\ncat >/dev/null\nkill -TERM $$\n",
+        "#!/bin/sh\ncat\nif [ \"$1\" = -d ]; then exit 7; fi\n",
+    ] {
+        ts.fixtures.write("compressor", script);
+        fs::set_permissions(
+            ts.fixtures.plus("compressor"),
+            fs::Permissions::from_mode(0o755),

write + chmod of the compressor script is repeated 4 times, could be a small helper, no?

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 23:00 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -545,11 +597,29 @@ impl MergeInput for PlainTmpMergeInput {
     }
 }
 
+/// Protect compression pipe writes without changing the process's SIGPIPE handler.
+pub struct CompressionPipeWriter(ChildStdin);
+
+impl Write for CompressionPipeWriter {
+    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+        #[cfg(target_vendor = "apple")]
+        uucore::signals::disable_pipe_errors_for_fd(&self.0)?;

Since changes can be made to “create,” I'll handle it.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 23:01 UTC
Code Review
src/uucore/src/lib/features/signals.rs:1
@@ -806,6 +888,123 @@ pub fn ensure_stdout_not_broken() -> std::io::Result<bool> {
     Ok(true)
 }
 
+#[test]
+#[cfg(all(unix, not(target_vendor = "apple")))]
+fn test_with_sigpipe_blocked() {

That code can be consolidated.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 23:01 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1696,6 +1696,72 @@ fn test_compress_merge() {
         .stdout_only_fixture("merge_ints_interleaved.expected");
 }
 
+#[cfg(target_os = "linux")]
+fn sort_with_ignored_sigchld(ts: &TestScenario) -> uutests::util::UCommand {
+    let mut command = ts.cmd("bash");
+    command
+        .timeout(Duration::from_secs(30))
+        .args(&["-c", "trap '' CHLD; exec \"$@\"", "bash"])
+        .arg(&ts.bin_path)
+        .arg(&ts.util_name);
+    command
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+fn test_compress_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    let mut expected = String::new();
+    for i in 0..600 {
+        writeln!(&mut expected, "{i:04}").unwrap();
+    }
+    sort_with_ignored_sigchld(&ts)
+        .args(&["--compress-program=gzip", "-S", "1k", "input"])
+        .succeeds()
+        .stdout_only(&expected);
+
+    ts.fixtures.write("sorted", &expected);
+    sort_with_ignored_sigchld(&ts)
+        .args(&[
+            "-m",
+            "-u",
+            "--batch-size=2",
+            "--compress-program=gzip",
+            "sorted",
+            "sorted",
+            "sorted",
+        ])
+        .succeeds()
+        .stdout_only(&expected);
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+fn test_compress_failures_ignored_sigchld() {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    for script in [
+        "#!/bin/sh\ncat >/dev/null\nexit 7\n",
+        "#!/bin/sh\ncat >/dev/null\nkill -TERM $$\n",
+        "#!/bin/sh\ncat\nif [ \"$1\" = -d ]; then exit 7; fi\n",
+    ] {
+        ts.fixtures.write("compressor", script);
+        fs::set_permissions(
+            ts.fixtures.plus("compressor"),
+            fs::Permissions::from_mode(0o755),

I think it's possible to keep it simple.

mattsu2020 mattsu2020 commented on code on Oct 08, 2026 23:04 UTC
Code Review
src/uucore/src/lib/features/signals.rs:1
@@ -614,6 +614,88 @@ pub fn disable_pipe_errors() -> Result<(), Errno> {
     unsafe { signal(SIGPIPE, SigIgn) }.map(|_| ())
 }
 
+/// Runs a pipe write with SIGPIPE blocked only on the calling thread.
+/// Consumes a newly generated SIGPIPE on EPIPE, preserving any already pending
+/// signal and restoring the original mask even if the operation panics.
+#[cfg(all(unix, not(target_vendor = "apple")))]
+pub fn with_sigpipe_blocked<T>(write: impl FnOnce() -> std::io::Result<T>) -> std::io::Result<T> {

I'll simplify the implementation

sylvestre sylvestre commented on code on Nov 23, 2026 09:06 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1940,6 +2000,115 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn write_compressor_script(at: &uutests::util::AtPath, script: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str, expected_error: &str) {

these #!/bin/sh scripts will break on android (no /bin/sh there), test_compress_fail is skipped on android for that, probably the Android CI failure, no?

sylvestre sylvestre commented on code on Nov 23, 2026 09:06 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1909,6 +1909,66 @@ fn test_compress_merge() {
         .stdout_only_fixture("merge_ints_interleaved.expected");
 }
 
+#[cfg(target_os = "linux")]
+fn sort_with_ignored_sigchld(ts: &TestScenario) -> uutests::util::UCommand {
+    let mut command = ts.cmd("bash");
+    command
+        .timeout(Duration::from_secs(30))
+        .args(&["-c", "trap '' CHLD; exec \"$@\"", "bash"])
+        .arg(&ts.bin_path)
+        .arg(&ts.util_name);
+    command
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+#[uutests::wasi_ignore(NoSubprocessSpawning)]
+fn test_compress_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    let mut expected = String::new();
+    for i in 0..600 {
+        writeln!(&mut expected, "{i:04}").unwrap();
+    }
+    sort_with_ignored_sigchld(&ts)
+        .args(&["--compress-program=gzip", "-S", "1k", "input"])
+        .succeeds()
+        .stdout_only(&expected);
+
+    ts.fixtures.write("sorted", &expected);
+    sort_with_ignored_sigchld(&ts)
+        .args(&[
+            "-m",
+            "-u",
+            "--batch-size=2",
+            "--compress-program=gzip",
+            "sorted",
+            "sorted",
+            "sorted",
+        ])
+        .succeeds()
+        .stdout_only(&expected);
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+#[uutests::wasi_ignore(NoSubprocessSpawning)]
+fn test_compress_failures_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    for script in [

same three scripts as test_compressor_failure_after_input / _terminated_by_signal / _failure_after_output, could be dedup, no?

sylvestre sylvestre commented on code on Nov 23, 2026 09:06 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -673,6 +760,75 @@ mod tests {
     use std::fs;
     use std::os::unix::fs::PermissionsExt;
 
+    #[test]
+    fn compression_pipe_final_flush_error() {

re-exec of the test binary, unwraps, env var modes... quite complex for a unit test, could it be an integration test in test_sort.rs instead?

mattsu2020 mattsu2020 commented on code on Nov 23, 2026 11:56 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1940,6 +2000,115 @@ fn test_compress_fail() {
     assert_eq!(result.stdout_str(), expected);
 }
 
+#[cfg(unix)]
+fn compressor_input(count: usize, width: usize, suffix: &str) -> String {
+    let mut input = String::new();
+    for i in (0..count).rev() {
+        writeln!(&mut input, "{i:0width$}{suffix}").unwrap();
+    }
+    input
+}
+
+#[cfg(unix)]
+fn write_compressor_script(at: &uutests::util::AtPath, script: &str) {
+    use std::fs;
+    use std::os::unix::fs::PermissionsExt;
+
+    at.write("compressor", script);
+    fs::set_permissions(at.plus("compressor"), fs::Permissions::from_mode(0o755)).unwrap();
+}
+
+#[cfg(unix)]
+fn run_with_compressor(script: &str, input: &str, buffer_size: &str, expected_error: &str) {

fixed it.
Changed /bin/sh handling for Android.

mattsu2020 mattsu2020 commented on code on Nov 23, 2026 12:00 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -1909,6 +1909,66 @@ fn test_compress_merge() {
         .stdout_only_fixture("merge_ints_interleaved.expected");
 }
 
+#[cfg(target_os = "linux")]
+fn sort_with_ignored_sigchld(ts: &TestScenario) -> uutests::util::UCommand {
+    let mut command = ts.cmd("bash");
+    command
+        .timeout(Duration::from_secs(30))
+        .args(&["-c", "trap '' CHLD; exec \"$@\"", "bash"])
+        .arg(&ts.bin_path)
+        .arg(&ts.util_name);
+    command
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+#[uutests::wasi_ignore(NoSubprocessSpawning)]
+fn test_compress_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    let mut expected = String::new();
+    for i in 0..600 {
+        writeln!(&mut expected, "{i:04}").unwrap();
+    }
+    sort_with_ignored_sigchld(&ts)
+        .args(&["--compress-program=gzip", "-S", "1k", "input"])
+        .succeeds()
+        .stdout_only(&expected);
+
+    ts.fixtures.write("sorted", &expected);
+    sort_with_ignored_sigchld(&ts)
+        .args(&[
+            "-m",
+            "-u",
+            "--batch-size=2",
+            "--compress-program=gzip",
+            "sorted",
+            "sorted",
+            "sorted",
+        ])
+        .succeeds()
+        .stdout_only(&expected);
+}
+
+#[test]
+#[cfg(target_os = "linux")]
+#[uutests::wasi_ignore(NoSubprocessSpawning)]
+fn test_compress_failures_ignored_sigchld() {
+    let ts = TestScenario::new("sort");
+    ts.fixtures.write("input", &compressor_input(600, 4, ""));
+    for script in [

Consolidated similar logic.

mattsu2020 mattsu2020 commented on code on Nov 23, 2026 12:05 UTC
Code Review
src/uu/sort/src/merge.rs:1
@@ -673,6 +760,75 @@ mod tests {
     use std::fs;
     use std::os::unix::fs::PermissionsExt;
 
+    #[test]
+    fn compression_pipe_final_flush_error() {

fixed it

Reviewers
Assignees
mattsu2020 mattsu2020
Labels
risk: low confidence: 89.3% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 56.8% (MEDIUM) · Higher = larger blast radius
56.8%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 89.3% · Lower = rushed or shallow review
89.3%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 6.1% · Safe to merge
6.1%