Skip to content
Myr

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. ---------

authored by jk · committed by GitHub · parent 4d073e0 · Browse files · 7 files+118 added−30 removed
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

7 files+118 added−30 removed

modified:src/benchmark/mod.rs+19 added-11 removed
3 unmodified lines
4pub mod scheduler;5pub mod timing_result;67use std::cmp;8use std::io::{self, Write};910use crate::benchmark::executor::BenchmarkIteration;11use crate::command::Command;12use crate::options::{13 CmdFailureAction, CommandOutputPolicy, ExecutorKind, Options, OutputStyleOption,14};15use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};16use crate::output::console_writeln;17use crate::output::format::{format_duration, format_duration_unit};18use crate::output::progress_bar::get_progress_bar;19use crate::output::warnings::{OutlierWarningOptions, Warnings};20use crate::parameter::ParameterNameAndValue;
120 unmodified lines
141142 /// 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 }153154 let mut times_real: Vec<Second> = vec![];155 let mut times_user: Vec<Second> = vec![];
204 unmodified lines
360 let user_str = format_duration(user_mean, Some(time_unit));361 let system_str = format_duration(system_mean, Some(time_unit));362363 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));377373 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 )?;388383 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 }400401 // Warnings
34 unmodified lines
436 warnings.push(Warnings::OutliersDetected(outlier_warning_options));437 }438439 if !warnings.is_empty() {433 eprintln!(" ");440 let mut stderr = io::stderr().lock();441 console_writeln!(stderr, " ")?;442443 for warning in &warnings {436 eprintln!(" {}: {}", "Warning".yellow(), warning);444 console_writeln!(stderr, " {}: {}", "Warning".yellow(), warning)?;445 }446 }447448 if self.options.output_style != OutputStyleOption::Disabled {441 println!(" ");449 console_writeln!(io::stdout(), " ")?;450 }451452 self.run_cleanup_command(self.command.get_parameters().iter().cloned(), output_policy)?;453
22 unmodified lines
modified:src/benchmark/scheduler.rs+22 added-13 removed
1 unmodified line
2use super::executor::{Executor, MockExecutor, RawExecutor, ShellExecutor};3use super::{relative_speed, Benchmark};4use colored::*;5use std::cmp::Ordering;6use std::io::{self, Write};78use crate::command::{Command, Commands};9use crate::export::ExportManager;10use crate::options::{ExecutorKind, Options, OutputStyleOption, SortOrder};11use crate::output::console_writeln;1213use anyhow::Result;1415pub struct Scheduler<'a> {
43 unmodified lines
5960 Ok(())61 }6261 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 }6768 if self.results.len() < 2 {67 return;69 return Ok(());70 }7172 let reference = self73 .options
6 unmodified lines
80 &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())?;8889 let reference = annotated_results.iter().find(|r| r.is_reference).unwrap();90 let others = annotated_results.iter().filter(|r| !r.is_reference);9189 println!(92 console_writeln!(93 stdout,94 " {} ran",95 reference.result.command_with_unused_parameters.cyan()92 );96 )?;9798 for item in others {99 let stddev = if let Some(stddev) = item.relative_speed_stddev {100 format!(" ± {}", format!("{:.2}", stddev).green())
16 unmodified lines
117 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())?;131132 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 lines
141 } 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 }161162 Ok(())163 }164165 pub fn final_export(&self) -> Result<()> {166 self.export_manager.write_results(&self.results, false)
71 unmodified lines
modified:src/export/mod.rs+5 added-3 removed
1use std::fs::{File, OpenOptions};2use std::io::Write;2use std::io::{self, Write};34mod asciidoc;5mod csv;6mod json;
10 unmodified lines
17use self::orgmode::OrgmodeExporter;1819use crate::benchmark::benchmark_result::BenchmarkResult;20use crate::options::SortOrder;21use crate::output::console_writeln;22use crate::util::units::Unit;2324use anyhow::{Context, Result};25use clap::ArgMatches;
118 unmodified lines
144 }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 lines
modified:src/output/mod.rs+10 added
1pub mod format;2pub mod progress_bar;3pub mod warnings;45/// Mark console write errors so broken pipes can be handled separately from file errors.6macro_rules! console_writeln {7 ($writer:expr $(, $($args:tt)*)?) => {8 writeln!($writer $(, $($args)*)?)9 .map_err($crate::error::ConsoleOutputError)10 };11}1213pub(crate) use console_writeln;
modified:src/error.rs+4 added
2 unmodified lines
3use rust_decimal::Error as DecimalError;4use thiserror::Error;56#[derive(Debug, Error)]7#[error(transparent)]8pub struct ConsoleOutputError(pub std::io::Error);910#[derive(Debug, Error)]11pub 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 lines
modified:src/main.rs+16 added-2 removed
2 unmodified lines
3 feature(windows_process_extensions_main_thread_handle)4)]56use std::env;7use std::io::{self, Write};89use benchmark::scheduler::Scheduler;10use cli::get_cli_arguments;11use command::Commands;12use error::ConsoleOutputError;13use export::ExportManager;14use options::Options;1516use anyhow::Result;
28 unmodified lines
45 options.validate_against_command_list(&commands)?;4647 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()?;5152 Ok(())53}5455fn 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}6061fn 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
1mod common;2use common::hyperfine;2use common::{hyperfine, hyperfine_raw_command};34use predicates::prelude::*;56/// Platform-specific I/O utility.
25 unmodified lines
32 .assert()33 .success();34}3536/// 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]41fn exits_quietly_when_stdout_is_closed() {42 use std::process::Stdio;4344 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);5354 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);6364 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}7677#[test]78fn can_run_commands_without_a_shell() {79 hyperfine()80 .arg("--runs=1")81 .arg("--show-output")
684 unmodified lines