Skip to content

The agent that grows with you

perf(file-ops): native read_file fast path on local POSIX environments

Alex Jiad3275acf80a0
diff --git a/tests/tools/test_file_ops_single_roundtrip.py b/tests/tools/test_file_ops_single_roundtrip.py
index f10d50f7a37..b5bef568d9a 100644
--- a/tests/tools/test_file_ops_single_roundtrip.py
+++ b/tests/tools/test_file_ops_single_roundtrip.py
@@ -23,21 +23,43 @@ pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell pro
READ_PROBE_MARK = "__HERMES_RF_"
[email protected](scope="module")
+def _local_env(tmp_path_factory):
+ """One real LocalEnvironment per module; constructing one costs ~0.8 s."""
+ return LocalEnvironment(cwd=str(tmp_path_factory.mktemp("file-ops")))
+
+
@pytest.fixture
-def shell(tmp_path, monkeypatch):
- """(ops, calls): file ops over a real local shell, every execute recorded."""
- # Pin the shell path even where a native fast path exists.
- monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
- env = LocalEnvironment(cwd=str(tmp_path))
+def _ops(_local_env, tmp_path):
+ """(ops, calls): file ops over the real local shell, every execute recorded."""
+ env = _local_env
+ env.cwd = str(tmp_path)
calls = []
- real_execute = env.execute
+ real_execute = type(env).execute.__get__(env, type(env))
def spy(command, *args, **kwargs):
calls.append(command)
return real_execute(command, *args, **kwargs)
env.execute = spy
- return ShellFileOperations(env, cwd=str(tmp_path)), calls
+ try:
+ yield ShellFileOperations(env, cwd=str(tmp_path)), calls
+ finally:
+ env.__dict__.pop("execute", None)
+
+
+def shell(_ops, monkeypatch):
+ """Pin the shell path even where a native fast path exists."""
+ monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
+ return _ops
+
+
+def native(_ops, monkeypatch):
+ """Same wiring with the native fast path on."""
+ monkeypatch.delenv("HERMES_NATIVE_FILE_READ", raising=False)
+ return _ops
def _write(tmp_path, name, data: bytes):
@@ -258,6 +280,130 @@ class TestWriteFileRoundTrips:
assert p.read_bytes() == b"x\r\ny\r\n"
+class TestNativeRead:
+ def test_native_read_makes_no_shell_call(self, native, tmp_path):
+ ops, calls = native
+ r = ops.read_file(_write(tmp_path, "a.txt", b"one\ntwo\n"))
+ assert calls == []
+ assert r.error is None and r.content == "1|one\n2|two\n3|"
+ assert (r.total_lines, r.file_size) == (2, 8)
+
+ def test_kill_switch_routes_to_the_shell(self, native, tmp_path, monkeypatch):
+ ops, calls = native
+ p = _write(tmp_path, "a.txt", b"one\n")
+ monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
+ ops.read_file(p)
+ assert len(calls) == 1 and READ_PROBE_MARK in calls[0]
+
+ def test_non_local_environment_keeps_the_shell_path(self):
+ from unittest.mock import MagicMock
+
+ env = MagicMock()
+ env.cwd = "/tmp"
+ assert ShellFileOperations(env)._native_read_enabled() is False
+
+ def test_tilde_still_expands_through_the_shell(self, native):
+ ops, calls = native
+ r = ops.read_file("~/hermes-no-such-file-7f3a.txt")
+ assert calls[0] == "echo $HOME"
+ assert r.error and "File not found" in r.error
+
+ def test_injection_lookalike_path_is_never_expanded(self, native, tmp_path):
+ ops, calls = native
+ marker = tmp_path / "pwned"
+ r = ops.read_file(f"~; echo PWNED > {marker}")
+ assert r.error and not marker.exists()
+ # The text reaches the shell only single-quoted, inside the missing-
+ # file recovery's directory listing; the tilde probe is a fixed
+ # ``echo $HOME`` that never embeds the path. Nothing else runs.
+ for c in calls:
+ assert c == "echo $HOME" or c.startswith("ls -1 '~; echo PWNED"), c
+
+ @pytest.mark.linux_only
+ def test_fifo_refused_without_a_shell_and_without_blocking(self, native, tmp_path):
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("no mkfifo")
+ ops, calls = native
+ fifo = tmp_path / "pipe"
+ os.mkfifo(fifo)
+ box = {}
+
+ def run():
+ box["r"] = ops.read_file(str(fifo))
+
+ t = threading.Thread(target=run, daemon=True)
+ t.start()
+ t.join(20)
+ assert not t.is_alive(), "native read_file blocked on a writer-less FIFO"
+ assert "not a regular file" in box["r"].error
+ assert calls == []
+
+
+PARITY_CASES = [
+ ("plain", b"one\ntwo\nthree\n", {}),
+ ("no_trailing_newline", b"a\nb", {}),
+ ("blank_tail", b"a\n\n", {}),
+ ("crlf", b"x\r\ny\r\n", {}),
+ ("lone_cr", b"a\rb\n", {}),
+ ("bom", "hello\n".encode("utf-8"), {}),
+ ("empty", b"", {}),
+ ("single_no_newline", b"solo", {}),
+ ("only_newline", b"\n", {}),
+ ("unicode", "héllo wörld\n汉字\n".encode("utf-8"), {}),
+ ("long_line", b"a" * 9000 + b"\nshort\n", {}),
+ ("multibyte_long_line", ("汉" * 4000 + "\nx\n").encode("utf-8"), {}),
+ ("multi_chunk_line", b"b" * 3_000_000 + b"\nz\n", {}),
+ ("window", b"".join(b"l%d\n" % i for i in range(1, 11)), {"offset": 3, "limit": 2}),
+ ("window_reaches_eof", b"".join(b"l%d\n" % i for i in range(1, 11)), {"offset": 9, "limit": 5}),
+ ("past_eof", b"".join(b"l%d\n" % i for i in range(1, 6)), {"offset": 50}),
+ ("nul_binary", b"\x00\x01\x02" * 20, {}),
+ ("latin1_tail", b"caf\xe9\n", {}),
+ ("sentinel_lookalike", b"x\n__HERMES_RF_" + b"ab" * 16 + b"__\ny\n", {}),
+]
+
+
+class TestNativeReadParity:
+ """The native path must be indistinguishable from the shell path."""
+
+ @pytest.mark.parametrize("name,data,kwargs", PARITY_CASES, ids=[c[0] for c in PARITY_CASES])
+ def test_shell_and_native_agree(self, native, tmp_path, monkeypatch, name, data, kwargs):
+ ops, calls = native
+ p = _write(tmp_path, f"{name}.txt", data)
+ monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
+ via_shell = ops.read_file(p, **kwargs).to_dict()
+ assert calls and READ_PROBE_MARK in calls[0]
+ calls.clear()
+ monkeypatch.delenv("HERMES_NATIVE_FILE_READ")
+ via_native = ops.read_file(p, **kwargs).to_dict()
+ assert via_native == via_shell
+ # The native path touches the shell only for the UTF-16 rescue of binaries.
+ assert not any(READ_PROBE_MARK in c for c in calls)
+
+ def test_special_paths_agree(self, native, tmp_path, monkeypatch):
+ ops, calls = native
+ _write(tmp_path, "real.txt", b"target\n")
+ os.symlink(tmp_path / "real.txt", tmp_path / "link.txt")
+ os.symlink(tmp_path / "gone", tmp_path / "dangling.txt")
+ (tmp_path / "sub").mkdir()
+ _write(tmp_path, "pic.png", b"\x89PNG\r\n")
+ _write(tmp_path, "notes.txt", b"n\n")
+ for p in (
+ str(tmp_path / "link.txt"),
+ str(tmp_path / "dangling.txt"),
+ str(tmp_path / "sub"),
+ str(tmp_path / "pic.png"),
+ str(tmp_path / "note.txt"), # missing → similar-file suggestions
+ "real.txt", # relative to env.cwd
+ ):
+ monkeypatch.setenv("HERMES_NATIVE_FILE_READ", "0")
+ via_shell = ops.read_file(p).to_dict()
+ monkeypatch.delenv("HERMES_NATIVE_FILE_READ")
+ calls.clear()
+ via_native = ops.read_file(p).to_dict()
+ assert via_native == via_shell, p
+ assert not any(READ_PROBE_MARK in c for c in calls), p
+
+
class TestCompoundFallback:
def test_unparseable_reply_falls_back_to_sequential_probes(self, shell, tmp_path):
ops, calls = shell
diff --git a/tools/file_operations.py b/tools/file_operations.py
index ec10336b6df..0440d08deb8 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1562,13 +1562,18 @@ class ShellFileOperations(FileOperations):
existence, size, binary sample, the page, line count, trailing
newline (see ``_read_probe_cmd``). A reply that cannot be parsed
falls back to ``_read_file_sequential``, the one-probe-per-call
- form, so an exotic shell can never do worse than before.
+ form, so an exotic shell can never do worse than before. On a local
+ POSIX environment the read never touches the shell at all; see
+ ``_read_file_native``.
"""
# Expand ~ and other shell paths
path = self._expand_path(path)
offset, limit = normalize_read_pagination(offset, limit)
+ if self._native_read_enabled():
+ return self._read_file_native(path, offset, limit)
+
# Images and known-binary extensions never inline content; the
# sequential path stops at the probes for them, so nothing is gained
# by streaming their bytes through the page pipeline.
@@ -1646,6 +1651,137 @@ class ShellFileOperations(FileOperations):
file_ends_with_newline=file_ends_with_newline,
)
+ def _native_read_enabled(self) -> bool:
+ """Whether ``read_file`` may bypass the shell and read from this host.
+
+ Only on POSIX with a ``LocalEnvironment``: the file is on this
+ machine and the path is already in native form. Windows keeps the
+ shell path, since file_operations holds Git-Bash-style paths there.
+ ``HERMES_NATIVE_FILE_READ=0`` turns the fast path off.
+ """
+ flag = os.environ.get("HERMES_NATIVE_FILE_READ", "1").strip().lower()
+ if flag in ("0", "false", "no", "off"):
+ return False
+ cached = getattr(self, "_native_read_ok", None)
+ if cached is not None:
+ return cached
+ ok = False
+ if sys.platform != "win32":
+ env = getattr(self, "env", None)
+ if env is not None:
+ try:
+ from tools.environments.local import LocalEnvironment
+ ok = isinstance(env, LocalEnvironment)
+ except Exception: # noqa: BLE001 - never let an import problem break a read
+ ok = False
+ self._native_read_ok = ok
+ return ok
+
+ def _read_file_native(self, path: str, offset: int, limit: int) -> ReadResult:
+ """``read_file`` without a shell: the file lives on this host.
+
+ Same contract as the shell path, byte for byte. ``os.stat`` is the
+ ``[ -f ]`` guard (a stat, never an open, so FIFOs and devices are
+ refused before anything touches their contents); the first 1000
+ bytes drive the byte-layer binary check; the page is produced
+ exactly as ``sed -n 'a,bp' | cut -b1-N`` prints it (every line
+ clamped to N bytes and newline-terminated), then decoded with
+ errors="replace" like the terminal transport. One chunked pass
+ counts lines and collects the page, so neither the file nor a
+ single pathological line is ever held in memory whole.
+
+ ``path`` is already expanded and ``offset``/``limit`` normalized.
+ Anything unexpected from the OS hands over to the shell path.
+ """
+ import stat as _stat
+
+ full = path if os.path.isabs(path) else os.path.join(
+ getattr(self.env, "cwd", None) or self.cwd, path
+ )
+ try:
+ st = os.stat(full)
+ except (FileNotFoundError, NotADirectoryError):
+ return self._read_file_missing(path, offset, limit)
+ except OSError:
+ return self._read_file_sequential(path, offset, limit)
+ if not _stat.S_ISREG(st.st_mode):
+ return self._not_regular_error(path)
+ file_size = st.st_size
+
+ # Images are never inlined: redirect to the vision tool
+ if self._is_image(path):
+ return self._image_redirect_result(file_size)
+
+ from tools.tool_output_limits import get_max_line_length
+ clamp = 4 * get_max_line_length() + 1
+ end_line = offset + limit - 1
+
+ page: List[bytes] = []
+ total_lines = 0
+ lineno = 1 # the line currently being scanned
+ kept = bytearray() # first ``clamp`` bytes of that line
+ have_partial = False # that line has bytes but no newline yet
+ last_byte = b""
+ try:
+ with open(full, "rb") as fh:
+ sample = fh.read(1000)
+ ext_binary = os.path.splitext(path)[1].lower() in BINARY_EXTENSIONS
+ if ext_binary or self._is_likely_binary_bytes(sample):
+ return self._read_binary_file(path, offset, limit, file_size, sample)
+ fh.seek(0)
+ while True:
+ chunk = fh.read(1 << 20)
+ if not chunk:
+ break
+ last_byte = chunk[-1:]
+ pos, n = 0, len(chunk)
+ while pos < n:
+ nl = chunk.find(b"\n", pos)
+ in_page = offset <= lineno <= end_line
+ if nl < 0:
+ if in_page and len(kept) < clamp:
+ kept += chunk[pos:pos + (clamp - len(kept))]
+ have_partial = True
+ break
+ if in_page:
+ if len(kept) < clamp:
+ kept += chunk[pos:min(nl, pos + (clamp - len(kept)))]
+ page.append(bytes(kept) + b"\n")
+ kept = bytearray()
+ have_partial = False
+ total_lines += 1
+ lineno += 1
+ pos = nl + 1
+ except OSError:
+ return self._read_file_sequential(path, offset, limit)
+ if have_partial and offset <= lineno <= end_line:
+ # ``sed`` prints a final line that lacks a newline; ``cut`` adds one.
+ page.append(bytes(kept) + b"\n")
+
+ read_output = _strip_terminal_fence_leaks(
+ b"".join(page).decode("utf-8", errors="replace")
+ )
+ return self._assemble_read_result(
+ read_output,
+ offset=offset,
+ end_line=end_line,
+ total_lines=total_lines,
+ file_size=file_size,
+ file_ends_with_newline=(last_byte == b"\n") if file_size else None,
+ )
+
+ @staticmethod
+ def _image_redirect_result(file_size: int) -> ReadResult:
+ return ReadResult(
+ is_image=True,
+ is_binary=True,
+ file_size=file_size,
+ hint=(
+ "Image file detected. Automatically redirected to vision_analyze tool. "
+ "Use vision_analyze with this file path to inspect the image contents."
+ ),
+ )
+
def _read_probe_cmd(self, path: str, offset: int, end_line: int,
line_clamp_bytes: int, sentinel: str) -> str:
"""One shell command answering every question ``read_file`` asks.
@@ -1749,15 +1885,7 @@ class ShellFileOperations(FileOperations):
# Images are never inlined — redirect to the vision tool
if self._is_image(path):
- return ReadResult(
- is_image=True,
- is_binary=True,
- file_size=file_size,
- hint=(
- "Image file detected. Automatically redirected to vision_analyze tool. "
- "Use vision_analyze with this file path to inspect the image contents."
- ),
- )
+ return self._image_redirect_result(file_size)
# Read a sample to check for binary content — at the byte layer when
# the transport allows, falling back to the legacy text heuristic.