Skip to content

stop echoing captured output after any persistent write error - #18399

Merged
kevinushey merged 2 commits into
mainfrom
bugfix/output-capture-eio-log-loop
Jul 31, 2026
Merged

kevinushey merged 2 commits into
mainfrom
bugfix/output-capture-eio-log-loop

Conversation

@kevinushey

@kevinushey kevinushey commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

An rsession was found spinning at ~93% CPU for hours, flooding its log with system error 5 (Input/output error) entries microseconds apart, all from PosixOutputCapture.cpp:101. Full diagnosis in #18398; the short version:

  • Output capture echoes captured stdout/stderr back to dup()'d copies of the original descriptors, so output still reaches the launching terminal.
  • When that terminal's pty goes away, the echo write() fails with EIO. Only EPIPE/EBADF set the "skip further writes" flag; every other errno was logged on every failed write, and retried forever.
  • With log-stderr=1 set (as in the dev config), each logged error is written to fd 2 -- the redirected capture pipe -- so the capture thread reads its own error message, fails to echo it, and logs again: a self-sustaining loop at full CPU speed, with continuous log rotation churn on the side. log-stderr=1 is the sole trigger: the same option both enables the echo writes (it is passed as forwardOutputToOriginalDescriptors) and installs the stderr log destination, so the two halves of the loop always arrive together. A stderr logger configured via logging.conf alone cannot reproduce this, because without log-stderr there are no echo writes to fail.

Fix

Treat any non-transient write error (anything other than EAGAIN/EINTR) the way EPIPE/EBADF were already treated: disable further echo writes and log the error once. The errno-specific message text is folded into a single generic description; the underlying errno is still reported by systemError.

Trade-off: a theoretically recoverable errno (say, transient ENOSPC on a redirected file) now permanently disables the echo for the remainder of the session, same as a closed pipe always has. Given that the echo target is the launching terminal and the alternative is an unbounded logging loop, that seems like the right side to err on. Client-visible console output is unaffected -- it flows through the capture handlers, not the echo path.

Verified the edited file compiles with the project's real compile flags (-fsyntax-only via compile_commands.json). Manual verification of the full loop requires killing the launching pty out from under a session with stderr logging enabled.

Addresses #18398.

When the terminal that launched the session goes away, echoing captured
output to the saved stderr descriptor fails with EIO, which was logged on
every write and retried forever. With a stderr log destination active,
each logged error itself lands in the capture pipe, creating a feedback
loop that spins at 100% CPU. Treat any non-transient write error like
EPIPE/EBADF: disable the echo and log once.

Addresses #18398.
@kevinushey kevinushey added this to the 2026.08 (Yellow Yarrow) milestone Jul 30, 2026
@posit-snyk-bot

posit-snyk-bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

✅ Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
✅ Open Source Security 0 0 0 0 0 issues
✅ Licenses 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
1666 0 320 0
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ desktop-linux 250 0 34 0
✅ desktop-macos 469 0 94 0
✅ desktop-windows 479 0 89 0
✅ server-linux 450 0 103 0
✅ setup 18 0 0 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 62ded4f504e5be06d2c9ca0e3d428a6d74d2f3a3 - Run #401

@kevinushey
kevinushey requested a review from gtritchie July 30, 2026 16:57
@gtritchie

Copy link
Copy Markdown
Member

Code review findings

Actionable items from an automated multi-agent review.

The core fix checks out: the loop terminates (including the cross-stream stdout-fails-then-stderr-fails case, which bounds at two extra iterations), and console delivery is unaffected because handler(output) at PosixOutputCapture.cpp:81 runs before the skip-write guard. The findings below are about the surrounding details, not the classification change itself.

Important

  1. src/cpp/core/system/PosixOutputCapture.cpp:100 — the message says "Output will no longer be redirected.", but redirection is exactly what continues: handler(output) at :81 runs before the !*pSkipWrite check at :83, so output still reaches the pipe and the IDE console. Only the echo to the saved original descriptor stops. This string was pre-existing but is rewritten here, and it is now the only signal emitted for this condition (previously log volume made it self-evident), so a reader concluding that session output capture has died will file a false bug. Fix: " is no longer writable. Output will no longer be echoed to the original " + descriptorType + "."

  2. src/cpp/core/system/PosixOutputCapture.cpp:98-102 — errno is read at :102, after description is built at :98-100. safe_convert::numberToString constructs a std::ostringstream and calls imbue(std::locale::classic()) (shared_core/include/shared_core/SafeConvert.hpp:176-186), and library functions are permitted to set errno even on success. Before this change the EIO path read errno immediately (LOG_ERROR(systemError(errno, ERROR_LOCATION)) with no string building), so this is a small regression in the reliability of the one errno value that now gets reported. The classification at :87 is safe — it happens before any string work; only the logged value is at risk. Fix: int errorNumber = errno; immediately after the failed write(), then use it in both places.

  3. src/cpp/core/system/PosixOutputCapture.cpp:87-96 — disabling the write is broader than what breaks the loop, and the trade-off named in the PR description is avoidable. The feedback loop is driven by logging (the log write re-enters the capture pipe), not by the failed write: a log-once flag alone terminates it, since a failed echo write that logs nothing produces no new pipe input. Splitting the one flag into "already logged" and "stop writing" would keep the loop fixed while preserving recovery for the genuinely transient errnos the PR body flags (ENOSPC, plus EDQUOT/ENOBUFS/ENOMEM); the residual cost is one doomed write() syscall per output chunk, bounded by output volume rather than spinning. Relatedly, the comment's "non-transient" framing overstates what the code guarantees: EAGAIN is effectively unreachable because dupFd comes from ::dup() at :186 and shares the original file description's blocking flags (only the pipe read ends get O_NONBLOCK, :170-172), and EINTR is effectively unreachable because the thread is created under SignalBlocker::blockAll() (:254-257). So in practice the first write failure of any kind permanently disables the echo. If the symmetric handling is deliberate, saying so beats implying the errnos are all permanent.

Suggestions

  1. src/cpp/core/system/Win32OutputCapture.cpp:62-75 — the Windows echo path has the same bug, in a worse form: a failed WriteFile to the CONOUT$ handle calls LOG_ERROR on every failure with no skip flag at all, closing the identical log → std::cerr → redirected pipe → capture thread → failed write cycle. :78-83 additionally logs a ReadFile failure inside while(true) with no break or backoff. Reachability is lower (Desktop mode has no console, so CreateFile("CONOUT$") fails once at :160-174 and hOrigStdHandle stays null — the caller does initialize it to nullptr at :203-204, so that path is safe), which is why this needn't block here. Worth a follow-up issue if the intent is to fix the class of bug rather than the Posix instance.

  2. NEWS.md:45 and the PR description — the stated trigger is looser than the code. The echo path exists only when forwardOutputToOriginalDescriptors is true, and the sole caller passes options().logStderr() (src/cpp/session/modules/SessionConsole.cpp:103). So log-stderr=1 is necessary: enabling stderr logging via logging.conf alone cannot produce this, because without log-stderr there is no echo write and therefore no EIO. In-tree only src/cpp/conf/rsession-dev.conf:21 sets it. That also means log-stderr=1 is sufficient, since SessionMain.cpp:2382-2387 installs the stderr destination under the same flag — the two halves of the loop are enabled together, which is worth stating in the comment as the reason this is guaranteed rather than incidental.

  3. src/cpp/core/system/PosixOutputCapture.cpp:89-95 — three precision issues in the new comment. "the stream was closed" reads as stdout/stderr, but what died is dupFd, the saved dup() of the original descriptor; the process's own fd 1/2 point at the capture pipe and stay writable. That two-descriptor distinction is the non-obvious fact about this lambda and is worth naming explicitly. "echoed right back here" holds only for the stderr instantiation — std::cerr feeds errHandler, never outHandler, and there is no stdout log destination. And :92 ("mark that we should skip the write, and only log this error once") narrates the two statements directly below it, which the project's comment guidance asks to drop in favor of the why the last sentence already supplies.

  4. src/cpp/core/system/PosixOutputCapture.cpp:56-60 and :148-151 — the same unbounded-log shape survives in this function: a persistent read() error logs once per pass then returns straight to select(), and select() returning -1 with a permanent errno logs every iteration with no blocking call in the loop at all. Both look unreachable today (the pipe read fds are never closed and redirectToPipe never closes pipe[1], so neither EOF nor EBADF arises), so this is context for anyone revisiting the file rather than a change to make now.

  5. No tests, which is proportionate — the changed logic is a lambda inside an anonymous-namespace function whose thread runs forever with no shutdown, and there is no existing coverage for output capture anywhere. If a cheap guardrail is wanted, the classification is the only new logic and would unit-test directly as a bool isTransientWriteError(int) free function.

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Feedback posted, mostly seems to be nice-to-have at most.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants