Handle broken pipe errors on stdout gracefully (#932)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Replace `println!` calls on the results paths with `writeln!` on `io::stdout()` and propagate the `io::Error` to `main`, where `ErrorKind::BrokenPipe` is turned into a quiet `exit(0)`. This matches the conventional behavior of command-line tools when their output pipe is closed early (e.g. `hyperfine ... | head -n 0`), and fixes panics in all run-output paths: the per-benchmark header and results, the speed comparison summary, and `-`-style exports to stdout. The warnings and "Note" outputs to stderr are converted the same way. ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Mathjk <Mathjk@users.noreply.github.com>
- Co-authored-by: David Peter <mail@david-peter.de>
Diff stats
7 files+118 added−30 removed
- tests:+42 added−1 removed
- other:+76 added−29 removed
Provenance
- Commit
c0b3834- Tree
28125db- Author
jk <1835947594@qq.com>- Committer
GitHub <noreply@github.com>- Parent
4d073e0
7 files changed+118 added−30 removed
modified:src/benchmark/mod.rs+19 added-11 removed
3 unmodified lines4 pub mod scheduler;5 pub mod timing_result;6 7 use std::cmp;8+use std::io::{self, Write};9 10 use crate::benchmark::executor::BenchmarkIteration;11 use crate::command::Command;12 use crate::options::{13 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,14 };15 use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};16+use crate::output::console_writeln;17 use crate::output::format::{format_duration, format_duration_unit};18 use crate::output::progress_bar::get_progress_bar;19 use crate::output::warnings::{OutlierWarningOptions, Warnings};20 use crate::parameter::ParameterNameAndValue;120 unmodified lines141 142 /// Run the benchmark for a single command143 pub fn run(&self) -> Result<BenchmarkResult> {144 if self.options.output_style != OutputStyleOption::Disabled {143- println!(145+ console_writeln!(146+ io::stdout(),147 "{}{}: {}",148 "Benchmark ".bold(),149 (self.number + 1).to_string().bold(),150 self.command.get_name_with_unused_parameters(),148- );151+ )?;152 }153 154 let mut times_real: Vec<Second> = vec![];155 let mut times_user: Vec<Second> = vec![];204 unmodified lines360 let user_str = format_duration(user_mean, Some(time_unit));361 let system_str = format_duration(system_mean, Some(time_unit));362 363 if self.options.output_style != OutputStyleOption::Disabled {364+ let mut stdout = io::stdout().lock();365 if times_real.len() == 1 {362- println!(366+ console_writeln!(367+ stdout,368 " Time ({} ≡): {:>8} {:>8} [User: {}, System: {}]",369 "abs".green().bold(),370 mean_str.green().bold(),371 " ", // alignment372 user_str.blue(),373 system_str.blue()369- );374+ )?;375 } else {376 let stddev_str = format_duration(t_stddev.unwrap(), Some(time_unit));377 373- println!(378+ console_writeln!(379+ stdout,380 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",381 "mean".green().bold(),382 "σ".green(),383 mean_str.green().bold(),384 stddev_str.green(),385 user_str.blue(),386 system_str.blue()381- );387+ )?;388 383- println!(389+ console_writeln!(390+ stdout,391 " Range ({} … {}): {:>8} … {:>8} {}",392 "min".cyan(),393 "max".purple(),394 min_str.cyan(),395 max_str.purple(),396 num_str.dimmed()390- );397+ )?;398 }399 }400 401 // Warnings34 unmodified lines436 warnings.push(Warnings::OutliersDetected(outlier_warning_options));437 }438 439 if !warnings.is_empty() {433- eprintln!(" ");440+ let mut stderr = io::stderr().lock();441+ console_writeln!(stderr, " ")?;442 443 for warning in &warnings {436- eprintln!(" {}: {}", "Warning".yellow(), warning);444+ console_writeln!(stderr, " {}: {}", "Warning".yellow(), warning)?;445 }446 }447 448 if self.options.output_style != OutputStyleOption::Disabled {441- println!(" ");449+ console_writeln!(io::stdout(), " ")?;450 }451 452 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;453 22 unmodified linesmodified:src/benchmark/scheduler.rs+22 added-13 removed
1 unmodified line2 use super::executor::{Executor, MockExecutor, RawExecutor, ShellExecutor};3 use super::{relative_speed, Benchmark};4 use colored::*;5 use std::cmp::Ordering;6+use std::io::{self, Write};7 8 use crate::command::{Command, Commands};9 use crate::export::ExportManager;10 use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder};11+use crate::output::console_writeln;12 13 use anyhow::Result;14 15 pub struct Scheduler<'a> {43 unmodified lines59 60 Ok(())61 }62 61- pub fn print_relative_speed_comparison(&self) {63+ pub fn print_relative_speed_comparison(&self) -> Result<()> {64 if self.options.output_style == OutputStyleOption::Disabled {63- return;65+ return Ok(());66 }67 68 if self.results.len() < 2 {67- return;69+ return Ok(());70 }71 72 let reference = self73 .options6 unmodified lines80 &self.results,81 reference,82 self.options.sort_order_speed_comparison,83 ) {84+ let mut stdout = io::stdout().lock();85 match self.options.sort_order_speed_comparison {86 SortOrder::MeanTime => {84- println!("{}", "Summary".bold());87+ console_writeln!(stdout, "{}", "Summary".bold())?;88 89 let reference = annotated_results.iter().find(|r| r.is_reference).unwrap();90 let others = annotated_results.iter().filter(|r| !r.is_reference);91 89- println!(92+ console_writeln!(93+ stdout,94 " {} ran",95 reference.result.command_with_unused_parameters.cyan()92- );96+ )?;97 98 for item in others {99 let stddev = if let Some(stddev) = item.relative_speed_stddev {100 format!(" ± {}", format!("{:.2}", stddev).green())16 unmodified lines117 format!("{:.2}", item.relative_speed).bold().green(),118 stddev119 ),120 };117- println!(121+ console_writeln!(122+ stdout,123 "{} {}",124 comparator,125 item.result.command_with_unused_parameters.magenta()121- );126+ )?;127 }128 }129 SortOrder::Command => {125- println!("{}", "Relative speed comparison".bold());130+ console_writeln!(stdout, "{}", "Relative speed comparison".bold())?;131 132 for item in annotated_results {128- println!(133+ console_writeln!(134+ stdout,135 " {}{} {}",136 format!("{:10.2}", item.relative_speed).bold().green(),137 if item.is_reference {138 " ".into()2 unmodified lines141 } else {142 " ".into()143 },144 item.result.command_with_unused_parameters,139- );145+ )?;146 }147 }148 }149 } else {144- eprintln!(150+ console_writeln!(151+ io::stderr(),152 "{}: The benchmark comparison could not be computed as some benchmark times are zero. \153 This could be caused by background interference during the initial calibration phase \154 of hyperfine, in combination with very fast commands (faster than a few milliseconds). \155 Try to re-run the benchmark on a quiet system. If you did not do so already, try the \156 --shell=none/-N option. If it does not help either, you command is most likely too fast \157 to be accurately benchmarked by hyperfine.",158 "Note".bold().red()152- );159+ )?;160 }161+162+ Ok(())163 }164 165 pub fn final_export(&self) -> Result<()> {166 self.export_manager.write_results(&self.results, false)71 unmodified linesmodified:src/export/mod.rs+5 added-3 removed
1 use std::fs::{File, OpenOptions};2-use std::io::Write;2+use std::io::{self, Write};3 4 mod asciidoc;5 mod csv;6 mod json;10 unmodified lines17 use self::orgmode::OrgmodeExporter;18 19 use crate::benchmark::benchmark_result::BenchmarkResult;20 use crate::options::SortOrder;21+use crate::output::console_writeln;22 use crate::util::units::Unit;23 24 use anyhow::{Context, Result};25 use clap::ArgMatches;118 unmodified lines144 }145 }146 ExportTarget::Stdout => {147 if !intermediate {147- println!();148- println!("{}", String::from_utf8(content()?).unwrap());148+ let mut stdout = io::stdout().lock();149+ console_writeln!(stdout)?;150+ console_writeln!(stdout, "{}", String::from_utf8(content()?).unwrap())?;151 }152 }153 }154 }10 unmodified linesmodified:src/output/mod.rs+10 added
1 pub mod format;2 pub mod progress_bar;3 pub mod warnings;4+5+/// Mark console write errors so broken pipes can be handled separately from file errors.6+macro_rules! console_writeln {7+ ($writer:expr $(, $($args:tt)*)?) => {8+ writeln!($writer $(, $($args)*)?)9+ .map_err($crate::error::ConsoleOutputError)10+ };11+}12+13+pub(crate) use console_writeln;modified:src/error.rs+4 added
2 unmodified lines3 use rust_decimal::Error as DecimalError;4 use thiserror::Error;5 6 #[derive(Debug, Error)]7+#[error(transparent)]8+pub struct ConsoleOutputError(pub std::io::Error);9+10+#[derive(Debug, Error)]11 pub enum ParameterScanError {12 #[error("Error while parsing parameter scan arguments ({0})")]13 ParseIntError(num::ParseIntError),14 #[error("Error while parsing parameter scan arguments ({0})")]48 unmodified linesmodified:src/main.rs+16 added-2 removed
2 unmodified lines3 feature(windows_process_extensions_main_thread_handle)4 )]5 6 use std::env;7+use std::io::{self, Write};8 9 use benchmark::scheduler::Scheduler;10 use cli::get_cli_arguments;11 use command::Commands;12+use error::ConsoleOutputError;13 use export::ExportManager;14 use options::Options;15 16 use anyhow::Result;28 unmodified lines45 options.validate_against_command_list(&commands)?;46 47 let mut scheduler = Scheduler::new(&commands, &options, &export_manager);48 scheduler.run_benchmarks()?;47- scheduler.print_relative_speed_comparison();49+ scheduler.print_relative_speed_comparison()?;50 scheduler.final_export()?;51 52 Ok(())53 }54 55+fn caused_by_broken_console_pipe(error: &anyhow::Error) -> bool {56+ error57+ .downcast_ref::<ConsoleOutputError>()58+ .is_some_and(|e| e.0.kind() == io::ErrorKind::BrokenPipe)59+}60+61 fn main() {62 match run() {63 Ok(_) => {}64 Err(e) => {57- eprintln!("{} {:#}", "Error:".red(), e);65+ // Exit quietly when a reader stops consuming console output early.66+ if caused_by_broken_console_pipe(&e) {67+ std::process::exit(0);68+ }69+ // The write to stderr can itself fail if stderr is closed; the70+ // error message cannot be shown in that case anyway.71+ let _ = writeln!(io::stderr(), "{} {:#}", "Error:".red(), e);72 std::process::exit(1);73 }74 }75 }modified:tests/integration_tests.rs+42 added-1 removed
1 mod common;2-use common::hyperfine;2+use common::{hyperfine, hyperfine_raw_command};3 4 use predicates::prelude::*;5 6 /// Platform-specific I/O utility.25 unmodified lines32 .assert()33 .success();34 }35 36+/// Regression test: hyperfine must not panic when writing to a closed37+/// stdout pipe (e.g. `hyperfine ... | head -n 1` or a downstream process38+/// that terminates early). A `BrokenPipe` error should result in a quiet39+/// exit with code 0 instead of a `println!` panic.40 #[test]41+fn exits_quietly_when_stdout_is_closed() {42+ use std::process::Stdio;43+44+ for args in [45+ vec!["--runs=1", "echo dummy benchmark"],46+ vec!["--runs=1", "--export-json=-", "echo dummy benchmark"],47+ vec!["--runs=1", "echo dummy benchmark", "echo second benchmark"],48+ ] {49+ // A pipe whose read end has been closed before hyperfine is even50+ // started: every write to it will fail with `BrokenPipe`.51+ let (reader, writer) = std::io::pipe().expect("failed to create pipe");52+ drop(reader);53+54+ let output = hyperfine_raw_command()55+ .args(&args)56+ .stdout(writer)57+ .stderr(Stdio::piped())58+ .spawn()59+ .expect("failed to spawn hyperfine")60+ .wait_with_output()61+ .expect("failed to wait for hyperfine");62+ let stderr = String::from_utf8_lossy(&output.stderr);63+64+ assert!(65+ !stderr.contains("panicked"),66+ "hyperfine panicked while writing to a closed pipe:\n{}",67+ stderr68+ );69+ assert!(70+ output.status.success(),71+ "hyperfine did not exit cleanly; stderr:\n{}",72+ stderr73+ );74+ }75+}76+77+#[test]78 fn can_run_commands_without_a_shell() {79 hyperfine()80 .arg("--runs=1")81 .arg("--show-output")684 unmodified lines