Skip to content

The agent that grows with you

fix(terminal): wait on a selector so PTY reads stay correct on macOS

Teknium355910814abf
diff --git a/hermes_cli/pty_bridge.py b/hermes_cli/pty_bridge.py
index 66ae1b063d4..26acca60331 100644
--- a/hermes_cli/pty_bridge.py
+++ b/hermes_cli/pty_bridge.py
@@ -107,6 +107,8 @@ class PtyBridge:
WebSocket task, never the dashboard event loop.
"""
+ _waiter = None # FdWaiter for the master; None until __init__ registers it
+
def __init__(self, proc: ptyprocess.PtyProcess): # type: ignore[name-defined]
self._proc = proc
self._fd: int = proc.fd
@@ -118,6 +120,11 @@ class PtyBridge:
except OSError:
self._pgid = None
os.set_blocking(self._fd, False)
+ # A selector, never select.select() (ValueError at fd >= FD_SETSIZE, #94928) or poll()
+ # (macOS poll() reports a PTY master as POLLNVAL, so read() would spin).
+ from tools.environments.fd_wait import open_fd_waiter
+
+ self._waiter = open_fd_waiter(self._fd)
@classmethod
def is_available(cls) -> bool:
@@ -165,13 +172,13 @@ class PtyBridge:
``b""`` = nothing yet; ``None`` = EOF / closed (also after :meth:`close`).
"""
- if self._closed:
+ if self._closed or self._waiter is None:
return None
- from tools.environments.fd_wait import make_fd_waiter
- wait = make_fd_waiter(self._fd)
- if wait is None:
+ try:
+ readable = self._waiter.wait(timeout)
+ except (OSError, ValueError): # close() raced this read
return None
- if not wait(int(timeout * 1000)):
+ if not readable:
return b""
try:
data = os.read(self._fd, 65536)
@@ -269,15 +276,10 @@ 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:
- if wait(int(timeout * 1000)) and os.read(self._fd, 65536):
+ if self._waiter is not None and self._waiter.wait(timeout) and os.read(self._fd, 65536):
return
- except OSError:
+ except (OSError, ValueError):
pass
time.sleep(timeout) # nothing read, EOF (b"") or EIO: don't spin on a readable dead fd
@@ -376,6 +378,11 @@ class PtyBridge:
self._proc.close(force=True)
except Exception:
pass
+ self._close_waiter()
+
+ def _close_waiter(self) -> None:
+ if self._waiter is not None:
+ self._waiter.close()
def __enter__(self) -> PtyBridge:
return self
diff --git a/tests/hermes_cli/test_pty_bridge.py b/tests/hermes_cli/test_pty_bridge.py
index 7b88d7805e0..5363e9dcdb9 100644
--- a/tests/hermes_cli/test_pty_bridge.py
+++ b/tests/hermes_cli/test_pty_bridge.py
@@ -9,7 +9,6 @@ from __future__ import annotations
import asyncio
import errno
import os
-import select
import shutil
import signal
import subprocess
@@ -138,7 +137,11 @@ class TestPtyBridgeIO:
bridge._fd = 123
bridge._closed = False
- monkeypatch.setattr(select, "select", lambda *_args: ([123], [], []))
+ class _AlwaysReady:
+ def wait(self, _timeout):
+ return True
+
+ bridge._waiter = _AlwaysReady()
def would_block(_fd, _size):
raise BlockingIOError(errno.EAGAIN, "try again")
diff --git a/tests/tools/test_drain_high_fd.py b/tests/tools/test_drain_high_fd.py
index 86db73cd822..dc81bcdb9d6 100644
--- a/tests/tools/test_drain_high_fd.py
+++ b/tests/tools/test_drain_high_fd.py
@@ -1,33 +1,30 @@
-"""Regression: the POSIX stdout drain must not lose output when a command's
-pipe fd is at or above FD_SETSIZE (1024).
+"""Regression for #94928: no output reader may lose output once its 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.
+command's pipe fd reached 1024, ``select.select()`` raised ``ValueError:
+filedescriptor out of range in select()``; the foreground drain, the background
+reader and the PTY bridge all caught it as "fd already closed", so ``terminal``
+returned an empty string with ``exit_code 0``. Readiness now goes through a
+selector (epoll/kqueue). The PTY case also pins that an idle read really waits:
+macOS ``poll()`` reports a PTY master as POLLNVAL ("ready" at once), which would
+turn the dashboard terminal's read loop into a busy spin.
"""
-import codecs
import os
-from unittest.mock import MagicMock
+import time
import pytest
-from tools.environments.base_output import _BoundedOutputCollector, _drain_fd_select
+from tests.waiting import wait_until
# 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.
- """
+def high_fds():
+ """Raise the soft fd limit, then hold fds so every new fd lands above FD_SETSIZE."""
import resource # POSIX-only; this file is never imported on the Windows lane
want = _TARGET_LOW_FDS + 200
@@ -38,73 +35,57 @@ def _hold_high_fds():
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:
+ if resource.getrlimit(resource.RLIMIT_NOFILE)[0] < want:
+ pytest.skip("fd limit too low to reproduce")
+ held = [os.open(os.devnull, os.O_RDONLY) for _ in range(_TARGET_LOW_FDS)]
+ try:
+ assert held[-1] >= 1024, "setup failed to push fds above FD_SETSIZE"
+ yield
+ finally:
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
@pytest.mark.platforms("posix")
-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")
+def test_command_output_survives_pipe_fd_above_fd_setsize(high_fds, tmp_path):
+ """Foreground ``terminal`` drain and the background-process reader both keep output."""
+ from tools.environments.local import LocalEnvironment
+ from tools.process_registry import ProcessRegistry
- _drain_fd_select(proc, r, output, decoder)
-
- assert "hello-high-fd" in output.render()
+ env = LocalEnvironment(cwd=str(tmp_path))
+ try:
+ result = env.execute("echo hello-high-fd")
finally:
- try:
- os.close(r)
- except OSError:
- pass
- _release(held)
+ env.cleanup()
+ assert result["returncode"] == 0
+ assert "hello-high-fd" in result["output"]
+ registry = ProcessRegistry()
+ session = registry.spawn_local("echo bg-high-fd", cwd=str(tmp_path), task_id="high-fd")
+ wait_until(lambda: session.exited, timeout=10, what="background process exit")
+ wait_until(lambda: "bg-high-fd" in session.output_buffer, timeout=5,
+ what=f"background output (got {session.output_buffer!r})")
-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()
+def test_pty_bridge_reads_and_waits_above_fd_setsize(high_fds):
+ """The PTY bridge delivers output at a high fd, and an idle read blocks for its timeout."""
+ pytest.importorskip("ptyprocess")
+ from hermes_cli.pty_bridge import PtyBridge
- assert result["returncode"] == 0
- assert "hello-high-fd" in result["output"]
+ bridge = PtyBridge.spawn(["/bin/sh", "-c", "echo pty-high-fd; exec sleep 30"])
+ try:
+ assert bridge._fd >= 1024
+ buf = bytearray()
+ deadline = time.monotonic() + 5
+ while b"pty-high-fd" not in buf and time.monotonic() < deadline:
+ chunk = bridge.read(timeout=0.2)
+ assert chunk is not None, f"PTY reported EOF before output (got {bytes(buf)!r})"
+ buf.extend(chunk)
+ assert b"pty-high-fd" in buf
+
+ started = time.monotonic()
+ assert bridge.read(timeout=0.5) == b""
+ assert time.monotonic() - started >= 0.3, "idle PTY read returned without waiting"
finally:
- _release(held)
+ bridge.close()
diff --git a/tools/environments/base_output.py b/tools/environments/base_output.py
index 85b8fb570f1..7c7c5db8c26 100644
--- a/tools/environments/base_output.py
+++ b/tools/environments/base_output.py
@@ -15,7 +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.environments.fd_wait import open_fd_waiter
from tools.tool_output_truncate import head_tail_split, truncation_notice
from hermes_cli._subprocess_compat import windows_hide_flags
@@ -395,21 +395,24 @@ def _drain_stdout(proc: ProcessHandle, output: _BoundedOutputCollector, stop: th
def _drain_fd_select(proc, fd: int, output: _BoundedOutputCollector, decoder, stop=None) -> None:
- """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).
+ """POSIX drain: selector readiness (no FD_SETSIZE ceiling, #94928), 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)."""
+ waiter = open_fd_waiter(fd)
+ if waiter is None:
+ return # fd already closed
+ try:
+ _drain_fd_waiter(proc, fd, waiter, output, decoder, stop)
+ finally:
+ waiter.close()
- 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).
- """
+
+def _drain_fd_waiter(proc, fd: int, waiter, output: _BoundedOutputCollector, decoder, stop) -> None:
idle_after_exit = 0
- wait = make_fd_waiter(fd)
- if wait is None:
- return # fd cannot be registered (closed or invalid)
while True:
if stop is not None and stop.is_set():
return
- if wait(100):
+ if waiter.wait(0.1):
try:
chunk = os.read(fd, 4096)
except (ValueError, OSError):
diff --git a/tools/environments/fd_wait.py b/tools/environments/fd_wait.py
index 41e553f8281..dd301d9f384 100644
--- a/tools/environments/fd_wait.py
+++ b/tools/environments/fd_wait.py
@@ -1,30 +1,44 @@
-"""POSIX fd-readiness helper shared by the stdout drains.
+"""POSIX fd-readiness helper shared by the stdout drains and the PTY bridge.
``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.
+once an fd reaches FD_SETSIZE (1024). A long-lived gateway/desktop process holds
+that many open fds, and every drain swallowed that ValueError as "fd already
+closed", silently discarding output (issue #94928).
+
+``selectors.DefaultSelector`` (epoll on Linux, kqueue on macOS) has no FD_SETSIZE
+ceiling. ``poll()`` is not a substitute: macOS ``poll()`` does not support device
+fds and reports a PTY master as POLLNVAL, i.e. "ready" at once, so a PTY read loop
+would spin a core.
"""
-import select
+import selectors
+
+
+class FdWaiter:
+ """Readability wait on one fd. Owns a selector (itself one fd): create it once
+ per reader lifetime and ``close()`` it when the reader is done."""
+
+ def __init__(self, fd: int):
+ self._selector = selectors.DefaultSelector()
+ try:
+ self._selector.register(fd, selectors.EVENT_READ)
+ except BaseException:
+ self._selector.close()
+ raise
+ def wait(self, timeout_s: float) -> bool:
+ """True as soon as the fd is readable (EOF and hangup included), False when
+ *timeout_s* elapses idle."""
+ return bool(self._selector.select(max(timeout_s, 0)))
-def make_fd_waiter(fd: int):
- """Return a ``wait(timeout_ms) -> bool`` readability waiter for *fd*.
+ def close(self) -> None:
+ self._selector.close()
- 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()
+
+def open_fd_waiter(fd: int):
+ """Return an :class:`FdWaiter` for *fd*, or None when *fd* cannot be watched
+ (already closed / invalid) and there is nothing to drain."""
try:
- poller.register(fd, select.POLLIN)
+ return FdWaiter(fd)
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 0f24efd3aec..af1257ac88c 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -1319,8 +1319,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
blocks until EOF, landing "live" output in one burst at exit. Orphaned-pipe
guard: a backgrounded grandchild (``node server.js &``) inherits our pipe's write
end so EOF never arrives while it lives, which would park this thread and never
- fire ``notify_on_complete``; on POSIX we ``select()`` and stop draining shortly
- after the direct child exits (mirrors ``environments/base.py::_wait_for_process``).
+ fire ``notify_on_complete``; on POSIX we wait on an ``fd_wait`` selector (no FD_SETSIZE
+ cap, #94928) and stop draining shortly after the direct child exits.
Windows pipes lack select(), so the lazy ``_reconcile_local_exit`` is the net (#68915, #8340).
"""
# ``bash -lic`` without a tty writes its startup warnings one write() per line, so the
@@ -1337,6 +1337,7 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
chunk = self._clean_shell_noise(chunk)
head_noise = not chunk.strip()
self._ingest_output(session, chunk)
+ _waiter = None
try:
proc = session.process
if proc is None or proc.stdout is None:
@@ -1358,20 +1359,17 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
fd = None
if not (isinstance(fd, int) and fd >= 0):
fd = None
- if fd is not None:
- from tools.environments.fd_wait import make_fd_waiter
- session._reader_selectable = True
- _wait = make_fd_waiter(fd)
- else:
- _wait = None
+ from tools.environments.fd_wait import open_fd_waiter
+ _waiter = open_fd_waiter(fd) if fd is not None else None
+ session._reader_selectable = _waiter is not None
idle_after_exit = 0
drained_after_request = 0
while True:
- if _wait is not None:
+ if _waiter 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)
+ wait_s = 0 if session._reader_finish_requested.is_set() else 0.2
+ ready = _waiter.wait(wait_s)
if not ready:
if session._reader_finish_requested.is_set():
break
@@ -1399,6 +1397,8 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
except Exception as e:
logger.debug("Process stdout reader ended: %s", e)
finally:
+ if _waiter is not None:
+ _waiter.close()
self._finish_reader(
session, decoder, _append_chunk, "Process",
session.process.wait, lambda: session.process.returncode)