Skip to content

The agent that grows with you

fix(terminal): drain stdout with poll() to survive fd >= FD_SETSIZE

Anthony Holten9b6b243762f4
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 431ff6ea662..66ae1b063d4 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -13,7 +13,6 @@ import errno
import fcntl # windows-footgun: ok — POSIX-only module by design (see docstring)
import math
import os
-import select
import signal
import struct
import sys
@@ -168,11 +167,11 @@ class PtyBridge:
"""
if self._closed:
return None
- try:
- readable, _, _ = select.select([self._fd], [], [], timeout)
- except (OSError, ValueError):
+ from tools.environments.fd_wait import make_fd_waiter
+ wait = make_fd_waiter(self._fd)
+ if wait is None:
return None
- if not readable:
+ if not wait(int(timeout * 1000)):
return b""
try:
data = os.read(self._fd, 65536)
@@ -181,7 +180,7 @@ class PtyBridge:
if exc.errno in {errno.EIO, errno.EBADF}:
return None
# The fd is deliberately non-blocking. Readiness can disappear
- # between select() and os.read() when close/output races occur.
+ # between the readiness check and os.read() when close/output races occur.
if exc.errno in {errno.EAGAIN, errno.EWOULDBLOCK}:
return b""
raise
@@ -270,11 +269,15 @@ class PtyBridge:
# Exiting children flush their pending terminal output first; on macOS a process stays in
# exit (and a SIGHUP save outlasts the grace) until someone drains the master. The drain
# task no longer consumes the output, so read and drop while waiting.
+ from tools.environments.fd_wait import make_fd_waiter
+ wait = make_fd_waiter(self._fd)
+ if wait is None:
+ time.sleep(timeout)
+ return
try:
- readable, _, _ = select.select([self._fd], [], [], timeout)
- if readable and os.read(self._fd, 65536):
+ if wait(int(timeout * 1000)) and os.read(self._fd, 65536):
return
- except (OSError, ValueError):
+ except OSError:
pass
time.sleep(timeout) # nothing read, EOF (b"") or EIO: don't spin on a readable dead fd
diff --git a/tests/tools/test_drain_high_fd.py b/tests/tools/test_drain_high_fd.py
new file mode 100644
index 00000000000..86db73cd822
--- /dev/null
+++ b/tests/tools/test_drain_high_fd.py
@@ -0,0 +1,110 @@
+"""Regression: the POSIX stdout drain must not lose output when a command's
+pipe fd is at or above FD_SETSIZE (1024).
+
+A long-lived gateway/desktop process accumulates open fds over uptime. Once a
+command's stdout pipe fd reaches 1024, the drain's old ``select.select()`` call
+raises ``ValueError: filedescriptor out of range in select()``. That ValueError
+was caught and treated as "fd already closed", so ``terminal`` and ``read_file``
+returned an empty string with ``exit_code 0``; output silently discarded with
+no error signal (issue #94928). The drain now waits with ``select.poll()``,
+which has no FD_SETSIZE ceiling.
+"""
+
+import codecs
+import os
+from unittest.mock import MagicMock
+
+import pytest
+
+from tools.environments.base_output import _BoundedOutputCollector, _drain_fd_select
+
+# Enough held fds to push the next pipe fd past FD_SETSIZE (1024).
+_TARGET_LOW_FDS = 1100
+
+
+def _hold_high_fds():
+ """Best-effort raise the soft fd limit, then hold fds past FD_SETSIZE.
+
+ Returns the list of held fd ints, or None when the host cannot reach the
+ count; the caller skips rather than assert a false repro.
+ """
+ import resource # POSIX-only; this file is never imported on the Windows lane
+
+ want = _TARGET_LOW_FDS + 200
+ soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
+ if soft < want:
+ new_soft = want if hard == resource.RLIM_INFINITY else min(hard, want)
+ try:
+ resource.setrlimit(resource.RLIMIT_NOFILE, (new_soft, hard))
+ except (ValueError, OSError):
+ pass
+ soft, _ = resource.getrlimit(resource.RLIMIT_NOFILE)
+ if soft < want:
+ return None
+ held = []
+ while len(held) < _TARGET_LOW_FDS:
+ held.append(os.open(os.devnull, os.O_RDONLY))
+ if held[-1] < 1024:
+ for fd in held:
+ os.close(fd)
+ return None
+ return held
+
+
+def _release(held):
+ for fd in held:
+ try:
+ os.close(fd)
+ except OSError:
+ pass
+
+
+def test_drain_fd_select_captures_output_above_fd_setsize():
+ """The drain's readiness wait must not drop output when the pipe fd >= 1024."""
+ held = _hold_high_fds()
+ if held is None:
+ pytest.skip("fd limit too low to reproduce")
+ r, w = os.pipe()
+ try:
+ assert r >= 1024, "setup failed to push the pipe fd above FD_SETSIZE"
+ os.write(w, b"hello-high-fd\n")
+ os.close(w) # true EOF once drained
+
+ proc = MagicMock()
+ proc.poll.return_value = 0
+ output = _BoundedOutputCollector(1000)
+ decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
+
+ _drain_fd_select(proc, r, output, decoder)
+
+ assert "hello-high-fd" in output.render()
+ finally:
+ try:
+ os.close(r)
+ except OSError:
+ pass
+ _release(held)
+
+
+def test_terminal_output_survives_pipe_fd_above_fd_setsize(tmp_path):
+ """End-to-end: ``terminal`` still captures stdout once the pipe fd is >= 1024."""
+ held = _hold_high_fds()
+ if held is None:
+ pytest.skip("fd limit too low to reproduce")
+ try:
+ assert held[-1] >= 1024, "setup failed to push fds above FD_SETSIZE"
+
+ from tools.environments.local import LocalEnvironment
+
+ env = LocalEnvironment(cwd=str(tmp_path))
+ try:
+ result = env.execute("echo hello-high-fd")
+ finally:
+ env.cleanup()
+
+ assert result["returncode"] == 0
+ assert "hello-high-fd" in result["output"]
+ finally:
+ _release(held)
diff --git a/tools/environments/base_output.py b/tools/environments/base_output.py
index 050e5833c85..98d7d612bf7 100644
--- a/tools/environments/base_output.py
+++ b/tools/environments/base_output.py
@@ -7,7 +7,6 @@ stdout drain thread used by ``BaseEnvironment._wait_for_process``.
import codecs
import os
-import select
import subprocess
import threading
import time
@@ -16,6 +15,7 @@ from pathlib import Path
from typing import IO, Callable, Protocol
from hermes_constants import get_hermes_home
+from tools.environments.fd_wait import make_fd_waiter
from tools.tool_output_truncate import head_tail_split, truncation_notice
from hermes_cli._subprocess_compat import windows_hide_flags
@@ -395,17 +395,21 @@ def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: th
def _drain_fd_select(proc, fd: int, output: _BoundedOutputCollector, decoder, stop=None) -> None:
- """POSIX drain: select() poll, stopping ~300ms after bash exits with the pipe idle, or
- when *stop* is set (the pipe is being handed to another reader — yield-to-background)."""
+ """POSIX drain: poll() readiness, stopping ~300ms after bash exits with the pipe idle, or
+ when *stop* is set (the pipe is being handed to another reader — yield-to-background).
+
+ Readiness waits through :func:`make_fd_waiter` (poll(), no FD_SETSIZE ceiling) rather
+ than ``select.select()``, which raises ValueError once the pipe fd reaches 1024 and was
+ silently discarding all output (issue #94928).
+ """
idle_after_exit = 0
+ wait = make_fd_waiter(fd)
+ if wait is None:
+ return # fd already closed
while True:
if stop is not None and stop.is_set():
return
- try:
- ready, _, _ = select.select([fd], [], [], 0.1)
- except (ValueError, OSError):
- return # fd already closed
- if ready:
+ if wait(100):
try:
chunk = os.read(fd, 4096)
except (ValueError, OSError):
diff --git a/tools/environments/fd_wait.py b/tools/environments/fd_wait.py
new file mode 100644
index 00000000000..41e553f8281
--- /dev/null
+++ b/tools/environments/fd_wait.py
@@ -0,0 +1,30 @@
+"""POSIX fd-readiness helper shared by the stdout drains.
+
+``select.select()`` raises ``ValueError: filedescriptor out of range in select()``
+the moment a pipe fd reaches FD_SETSIZE (1024); a long-lived gateway/desktop
+process holds that many open fds, and both drains swallowed that ValueError as
+"fd already closed", silently discarding output with no error signal (issue
+#94928). ``poll()`` has no FD_SETSIZE ceiling, and POLLHUP/POLLERR count as
+readable so the caller's read observes the real EOF or broken descriptor.
+"""
+
+import select
+
+
+def make_fd_waiter(fd: int):
+ """Return a ``wait(timeout_ms) -> bool`` readability waiter for *fd*.
+
+ Returns None when *fd* is already closed and there is nothing to drain.
+ ``wait`` returns True as soon as *fd* is readable (POLLHUP/POLLERR included,
+ so the caller's read observes EOF), False when *timeout_ms* elapses idle.
+ """
+ poller = select.poll()
+ try:
+ poller.register(fd, select.POLLIN)
+ except (ValueError, OSError):
+ return None
+
+ def wait(timeout_ms: int) -> bool:
+ return bool(poller.poll(timeout_ms))
+
+ return wait
diff --git a/tools/process_registry.py b/tools/process_registry.py
index 3b41242a38b..0f24efd3aec 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -1359,19 +1359,19 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
if not (isinstance(fd, int) and fd >= 0):
fd = None
if fd is not None:
- import select as _select
+ from tools.environments.fd_wait import make_fd_waiter
session._reader_selectable = True
+ _wait = make_fd_waiter(fd)
+ else:
+ _wait = None
idle_after_exit = 0
drained_after_request = 0
while True:
- if fd is not None:
- try:
- # Once a finish is requested, read only what is already buffered: the exited
- # child's tail, never an orphaned grandchild's future writes.
- wait_s = 0 if session._reader_finish_requested.is_set() else 0.2
- ready, _, _ = _select.select([fd], [], [], wait_s)
- except (ValueError, OSError):
- break # fd already closed
+ if _wait is not None:
+ # Once a finish is requested, read only what is already buffered: the exited
+ # child's tail, never an orphaned grandchild's future writes.
+ wait_ms = 0 if session._reader_finish_requested.is_set() else 200
+ ready = _wait(wait_ms)
if not ready:
if session._reader_finish_requested.is_set():
break