Skip to content

Handle BrokenPipe gracefully#64

Merged
leynos merged 2 commits intomainfrom
codex/handle-brokenpipe-errors-in-run_pr
Aug 12, 2025
Merged

Handle BrokenPipe gracefully#64
leynos merged 2 commits intomainfrom
codex/handle-brokenpipe-errors-in-run_pr

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Aug 10, 2025

Summary

  • avoid logging when review/thread output hits a BrokenPipe
  • write end banner via writeln! and surface write errors
  • add regression test ensuring vk pr exits cleanly when piped to a short-lived reader

Testing

  • make fmt
  • make lint
  • make test

https://chatgpt.com/codex/tasks/task_e_6898985477208322a5415a24d283ad2d

Summary by Sourcery

Gracefully handle BrokenPipe errors during review output and end banner printing, surface write errors via Result, and add a regression test to ensure clean exits when piping output into a reader that closes early

Enhancements:

  • Suppress logging and gracefully ignore BrokenPipe errors when printing reviews, threads, and end banner
  • Update print_end_banner to return a Result and use writeln! to propagate write errors

Documentation:

  • Add error documentation for print_end_banner

Tests:

  • Add end-to-end test to verify vk pr exits successfully when its output is piped to a short-lived reader

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Aug 10, 2025

Reviewer's Guide

The PR refactors end-of-output handling to detect and silently swallow BrokenPipe errors during printing, updates print_end_banner to return a Result and use writeln!, and adds an e2e regression test to verify clean exit when output is piped to a short-lived reader.

Sequence diagram for handling BrokenPipe during output in vk pr

sequenceDiagram
    participant vk_pr as vk pr (main)
    participant stdout as Stdout
    vk_pr->>stdout: print_reviews()
    alt BrokenPipe error
        vk_pr-->>vk_pr: Return Ok(()) (exit silently)
    else Other error
        vk_pr-->>vk_pr: Log error
    end
    vk_pr->>stdout: print_thread()
    alt BrokenPipe error
        vk_pr-->>vk_pr: Return Ok(()) (exit silently)
    else Other error
        vk_pr-->>vk_pr: Log error
    end
    vk_pr->>stdout: print_end_banner()
    alt BrokenPipe error
        vk_pr-->>vk_pr: Return Ok(()) (exit silently)
    else Other error
        vk_pr-->>vk_pr: Log error
    end
Loading

Class diagram for updated print_end_banner function

classDiagram
    class summary {
        +print_end_banner() std::io::Result<()>
    }
    summary : print_end_banner() uses writeln! to write to stdout
    summary : print_end_banner() returns error on write failure
Loading

File-Level Changes

Change Details Files
Graceful BrokenPipe detection in main output routines
  • Wrap print_reviews error handling to detect BrokenPipe and return Ok
  • Wrap print_thread error handling similarly
  • Handle BrokenPipe from print_end_banner Result and return Ok
src/main.rs
Refactor print_end_banner to return Result and use writeln!
  • Change signature to return std::io::Result<()>
  • Replace println! with writeln! using stdout lock
  • Add documentation and error propagation
src/summary.rs
Add regression test for BrokenPipe scenario
  • Introduce pr_exits_cleanly_on_broken_pipe async test
  • Spawn vk process piped into head to simulate broken pipe
  • Assert vk exits successfully
tests/e2e.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 10, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 2 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6c3e937 and 1f5188f.

📒 Files selected for processing (3)
  • src/main.rs (3 hunks)
  • src/summary.rs (2 hunks)
  • tests/e2e.rs (2 hunks)

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of broken pipe errors during output, preventing unnecessary error logs when the output stream is closed prematurely.
  • Tests

    • Added a new end-to-end test to verify the application exits cleanly when encountering a broken pipe scenario.
  • Documentation

    • Updated function documentation to clarify error behaviour and provide usage examples.

Walkthrough

Expand error handling for output operations in the run_pr function to gracefully handle broken pipe errors. Update the print_end_banner function to return a Result and propagate I/O errors. Add an end-to-end test to verify that the process exits cleanly when a broken pipe occurs during output.

Changes

Cohort / File(s) Change Summary
Broken pipe error handling in output
src/main.rs
Add explicit handling for ErrorKind::BrokenPipe in output operations within run_pr, returning early on broken pipes instead of logging errors.
End banner output refactor
src/summary.rs
Refactor print_end_banner to return std::io::Result<()>, use explicit locking and writing to stdout, and update documentation accordingly.
E2E test for broken pipe
tests/e2e.rs
Add async test pr_exits_cleanly_on_broken_pipe to verify clean process exit when output is piped and closed early. Adjust imports for process and timeout handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant vk (run_pr)
    participant OS Pipe

    User->>vk (run_pr): Start process, pipe output
    vk (run_pr)->>OS Pipe: Write output
    OS Pipe-->>vk (run_pr): BrokenPipe error (pipe closed)
    vk (run_pr)->>vk (run_pr): Detect BrokenPipe, return Ok(())
    vk (run_pr)-->>User: Exit cleanly
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

  • Add end-of-review banner #32: Adds initial banner printing functionality, which is now extended with error handling for broken pipe scenarios and a new return type.

Poem

When pipes are broken, don’t despair,
The process exits with gentle care.
No noisy logs, no needless fright,
Just silent endings, clean and right.
A banner prints, a test is run,
Robustness grows—well done, well done!
🛠️✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/handle-brokenpipe-errors-in-run_pr

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @leynos - I've reviewed your changes - here's some feedback:

  • The .chain().any(|c| c.downcast_ref::<io::Error>().map_or(false, |io| io.kind() == ErrorKind::BrokenPipe)) logic is repeated in several spots – consider extracting it into a helper like is_broken_pipe(err: &Error) -> bool to DRY up the code.
  • Instead of checking for BrokenPipe after each individual print call, you could wrap the entire printing flow in a single writer that gracefully ignores BrokenPipe to keep the top-level logic simpler.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The `.chain().any(|c| c.downcast_ref::<io::Error>().map_or(false, |io| io.kind() == ErrorKind::BrokenPipe))` logic is repeated in several spots – consider extracting it into a helper like `is_broken_pipe(err: &Error) -> bool` to DRY up the code.
- Instead of checking for BrokenPipe after each individual print call, you could wrap the entire printing flow in a single writer that gracefully ignores `BrokenPipe` to keep the top-level logic simpler.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Greptile Summary

This PR implements graceful handling of BrokenPipe errors in the vk pr command to improve the user experience when piping output to utilities that may terminate early (like head, grep, etc.). The changes address a common CLI tool issue where error messages are logged when downstream processes close their input before consuming all output.

The implementation adds BrokenPipe detection at three critical output stages in the run_pr() function: when printing reviews, printing threads, and printing the end banner. Each error handler now checks if the error chain contains a BrokenPipe IO error and returns Ok(()) instead of logging an error message. The print_end_banner() function was refactored from using println! to writeln! with explicit error handling, allowing the caller to detect and handle BrokenPipe scenarios consistently.

The changes integrate well with the existing error handling patterns in the codebase, maintaining the use of anyhow::Error for most operations while specifically handling the std::io::Error cases where BrokenPipe detection is needed. A comprehensive regression test ensures the functionality works end-to-end by spawning vk pr piped to head -n 1 and verifying clean exit behavior.

Important Files Changed

File Changes
Filename Score Overview
src/main.rs 5/5 Added BrokenPipe error detection and graceful handling in three output stages of run_pr()
src/summary.rs 5/5 Converted print_end_banner() from println! to writeln! with proper error propagation
tests/e2e.rs 4/5 Added regression test for BrokenPipe handling using process pipeline with head -n 1

Confidence score: 5/5

  • This PR is safe to merge with minimal risk as it only improves error handling for a specific edge case
  • Score reflects well-structured error handling with appropriate fallback behavior and comprehensive test coverage
  • No files require special attention as all changes follow established patterns and include proper testing

3 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0aed9fb and 6c3e937.

📒 Files selected for processing (3)
  • src/main.rs (2 hunks)
  • src/summary.rs (2 hunks)
  • tests/e2e.rs (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit Inference Engine (AGENTS.md)

**/*.rs: Every module must begin with a module level (//!) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Place function attributes after doc comments.
Do not use return in single-line functions.
Use predicate functions for conditional criteria with more than two branches.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type instead of panicking where feasible.
Prefer semantic error enums: Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary: Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library: Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.
Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Avoid unsafe code unless absolutely necessary and document any usage clearly.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.

Files:

  • src/main.rs
  • src/summary.rs
  • tests/e2e.rs

⚙️ CodeRabbit Configuration File

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.

Files:

  • src/main.rs
  • src/summary.rs
  • tests/e2e.rs
🔍 MCP Research (1 server)

Deepwiki:

  • Issue ENG-2040: The run_pr function in src/main.rs handles output errors during printing of reviews, threads, and the end banner. It now specifically checks for ErrorKind::BrokenPipe and returns Ok(()) immediately to avoid logging errors when the output stream is closed prematurely. Other errors continue to be logged as warnings. This improves robustness in output handling and prevents unnecessary error logs related to broken pipe scenarios. (ENG-2040)

  • Document [End-to-End Testing]: The tests/e2e.rs file includes an async Tokio test pr_exits_cleanly_on_broken_pipe that runs the vk pr command piped into head -n 1 to simulate a broken pipe scenario. The test asserts that the vk process exits successfully within 5 seconds, verifying that the application handles broken pipe errors gracefully without crashing or logging errors. (tests/e2e.rs)

  • Document [Supporting Components and Utilities]: The printing functions in src/main.rs and related modules now propagate I/O errors including broken pipe detection, improving error handling in output rendering. (src/main.rs)

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-test
🔇 Additional comments (5)
src/summary.rs (1)

7-7: Trait import is appropriate for writeln! usage.

Keep this; writeln! on a locked stdout handle requires std::io::Write in scope.

src/main.rs (2)

45-45: Import for ErrorKind is correct and scoped.

This supports BrokenPipe detection without broadening imports.


162-167: Confirm minimum supported Rust version for Option::is_some_and usage.

No explicit MSRV declaration found in Cargo.toml or rust-toolchain files. Ensure this project’s MSRV is at least 1.62 (when Option::is_some_and stabilised) before keeping the current code. Otherwise replace the call to avoid bumping MSRV.

• Search CI configs or docs for an MSRV specification.
• If MSRV < 1.62, replace the snippet at lines 162–167 (and 173–178) with:

if e.chain().any(|c| {
    c.downcast_ref::<std::io::Error>()
        .map(|io| io.kind() == ErrorKind::BrokenPipe)
        .unwrap_or(false)
}) {
    return Ok(());
}
tests/e2e.rs (2)

12-13: Add imports for binary path lookup.

These are needed for the new end-to-end test.


17-18: Add process and timing imports.

These are appropriate for spawning child processes and timeouts.

Comment thread src/main.rs Outdated
Comment thread src/main.rs Outdated
Comment thread src/main.rs
Comment thread src/summary.rs
Comment thread tests/e2e.rs
Copy link
Copy Markdown

@greptile-apps greptile-apps Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 files reviewed, no comments

Edit Code Review Bot Settings | Greptile

@leynos leynos merged commit 5043f02 into main Aug 12, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant