From 8b681f70ea505959cf7721be40d9dad8f3d33c8f Mon Sep 17 00:00:00 2001 From: Adolanium <94890352+Adolanium@users.noreply.github.com> Date: Sat, 22 Aug 2026 12:29:48 +0300 Subject: [PATCH] perf(process): poll sandbox job logs for new bytes only The background-process poller for non-local backends ran `cat` on the whole log file every two seconds, then threw away everything except the part it had not seen yet. The offset it needed was already tracked one line below, so the full read was pure waste. Cost of one poll grew with the total output so far, which makes the cost of a run grow with the square of its length. A job writing 10 MB over an hour moved about 9 GB across the docker or SSH channel to deliver 10 MB of output. The poller now asks the shell for the file size and the bytes after the offset in one command. Reading the size first and cutting the tail at that same size keeps the two in step, so a file that grows mid-command never sends a byte twice. A file that shrank was rotated or truncated, so the offset drops back to 0 and the buffer is dropped. The output buffer is now appended to rather than replaced, matching the local reader loops, and the offset is counted in bytes because the shell counts bytes. --- tests/tools/test_process_registry.py | 146 ++++++++++++++++++++++++++- tools/process_registry.py | 70 ++++++++++--- 2 files changed, 202 insertions(+), 14 deletions(-) diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py index ae97defcfe..6b4f18ee4e 100644 --- a/tests/tools/test_process_registry.py +++ b/tests/tools/test_process_registry.py @@ -781,7 +781,7 @@ class TestSpawnEnvSanitization: def __init__(self): self.commands = [] self._responses = iter([ - {"output": "hello\n"}, + {"output": "6 0\nhello\n"}, {"output": "1\n"}, {"output": "0\n"}, ]) @@ -802,11 +802,153 @@ class TestSpawnEnvSanitization: "/path with spaces/hermes_bg.exit", ) - assert env.commands[0][0] == "cat '/path with spaces/hermes_bg.log' 2>/dev/null" + assert "'/path with spaces/hermes_bg.log'" in env.commands[0][0] + assert "cat '/path with spaces/hermes_bg.log'" not in env.commands[0][0] assert env.commands[1][0] == "kill -0 \"$(cat '/path with spaces/hermes_bg.pid' 2>/dev/null)\" 2>/dev/null; echo $?" assert env.commands[2][0] == "cat '/path with spaces/hermes_bg.exit' 2>/dev/null" +class TestEnvPollerIncrementalRead: + """The sandbox log poller must read only new bytes, not the whole file. + + Reading the whole file every poll made one poll cost grow with the total + output so far, so a long noisy job re-sent all of its output over the + docker or SSH channel every two seconds. + """ + + @staticmethod + def _run_poller(registry, session, responses): + """Drive one poll cycle and hand back the commands the env saw.""" + + class FakeEnv: + def __init__(self): + self.commands = [] + self._responses = iter(responses) + + def execute(self, command, **kwargs): + self.commands.append(command) + return next(self._responses) + + env = FakeEnv() + with patch("tools.process_registry.time.sleep", return_value=None), \ + patch.object(registry, "_move_to_finished"): + registry._env_poller_loop( + session, env, "/tmp/bg.log", "/tmp/bg.pid", "/tmp/bg.exit" + ) + return env.commands + + def test_read_command_asks_only_for_new_bytes(self): + cmd = ProcessRegistry._log_delta_command("'/tmp/bg.log'", 4096) + # The offset is carried into the command, and the file is opened with + # tail rather than cat. + assert "O=4096" in cmd + assert "tail -c +$((O+1)) '/tmp/bg.log'" in cmd + assert "cat '/tmp/bg.log'" not in cmd + + def test_read_command_starts_from_zero_on_first_poll(self): + cmd = ProcessRegistry._log_delta_command("'/tmp/bg.log'", 0) + assert "O=0" in cmd + + def test_first_poll_reads_from_the_start(self, registry): + session = _make_session(sid="proc_delta") + session.exited = False + commands = self._run_poller( + registry, + session, + [ + {"output": "11 0\nfirst chunk"}, + {"output": "1\n"}, + {"output": "0\n"}, + ], + ) + assert "O=0" in commands[0] + assert session.output_buffer == "first chunk" + + def test_delta_is_appended_not_replaced(self, registry): + session = _make_session(sid="proc_append", output="already here ") + session.exited = False + self._run_poller( + registry, + session, + [ + {"output": "8 0\nand new"}, + {"output": "1\n"}, + {"output": "0\n"}, + ], + ) + assert session.output_buffer == "already here and new" + + def test_second_poll_asks_from_where_the_first_one_stopped(self, registry): + session = _make_session(sid="proc_two_polls") + session.exited = False + commands = self._run_poller( + registry, + session, + [ + {"output": "11 0\nfirst chunk"}, + {"output": "0\n"}, # still running, poll again + {"output": "17 11\n and more"}, + {"output": "1\n"}, # gone now + {"output": "0\n"}, + ], + ) + assert "O=0" in commands[0] + # The second read starts at byte 11, so the first chunk is not sent + # a second time. + assert "O=11" in commands[2] + assert session.output_buffer == "first chunk and more" + + def test_truncated_log_drops_the_stale_buffer(self, registry): + session = _make_session(sid="proc_rotate") + session.exited = False + # The second read reports offset 0 even though the first one left off + # at byte 11. The file no longer reaches that byte, so it was rotated + # or truncated and the buffer we hold no longer matches it. + self._run_poller( + registry, + session, + [ + {"output": "11 0\nfirst chunk"}, + {"output": "0\n"}, # still running, poll again + {"output": "5 0\nfresh"}, + {"output": "1\n"}, + {"output": "0\n"}, + ], + ) + assert session.output_buffer == "fresh" + + def test_unreadable_header_leaves_the_buffer_alone(self, registry): + session = _make_session(sid="proc_bad", output="keep me") + session.exited = False + # No header at all, for example when the shell is missing one of the + # tools the command needs. + self._run_poller( + registry, + session, + [ + {"output": ""}, + {"output": "1\n"}, + {"output": "0\n"}, + ], + ) + assert session.output_buffer == "keep me" + + def test_buffer_stays_within_the_cap(self, registry): + session = _make_session(sid="proc_cap") + session.exited = False + session.max_output_chars = 10 + self._run_poller( + registry, + session, + [ + {"output": "20 0\n" + "x" * 20}, + {"output": "1\n"}, + {"output": "0\n"}, + ], + ) + assert session.output_buffer == "x" * 10 + + # ========================================================================= # Popen leak prevention # ========================================================================= diff --git a/tools/process_registry.py b/tools/process_registry.py index a2314ee47e..70495b05b6 100644 --- a/tools/process_registry.py +++ b/tools/process_registry.py @@ -1522,6 +1522,32 @@ class ProcessRegistry: session.completion_reason = "exited" self._move_to_finished(session) + @staticmethod + def _log_delta_command(quoted_log_path: str, offset: int) -> str: + """Build the shell command that reads only new bytes from a log file. + + The old version ran ``cat`` on the whole file every poll, so a job + that keeps writing pays for its entire output again and again. Over a + long run that turns into a lot of wasted traffic on the docker/SSH + channel, since only the new part is ever used. + + The command prints one header line, ``" "``, then the + bytes between ``offset`` and ``size``. Reading the size first and + cutting the tail at that same size keeps the two numbers in step, so + a file that grows while the command runs never sends a byte twice. + A file that shrank was rotated or truncated, so the offset drops back + to 0 and the reader starts over. + """ + return ( + f"O={offset}; " + f"S=$({{ wc -c < {quoted_log_path}; }} 2>/dev/null | tr -dc '0-9'); " + f"S=${{S:-0}}; " + f'if [ "$S" -lt "$O" ]; then O=0; fi; ' + f'echo "$S $O"; ' + f'if [ "$S" -gt "$O" ]; then ' + f"tail -c +$((O+1)) {quoted_log_path} 2>/dev/null | head -c $((S-O)); fi" + ) + def _env_poller_loop( self, session: ProcessSession, env: Any, log_path: str, pid_path: str, exit_path: str ): @@ -1529,24 +1555,44 @@ class ProcessRegistry: quoted_log_path = shlex.quote(log_path) quoted_pid_path = shlex.quote(pid_path) quoted_exit_path = shlex.quote(exit_path) - prev_output_len = 0 # track delta for watch pattern scanning + # Byte offset already read from the log. Bytes, not characters: the + # shell counts bytes, and a log with non-ASCII text has more bytes + # than characters. + prev_output_bytes = 0 while not session.exited: time.sleep(2) # Poll every 2 seconds try: - # Read new output from the log file - result = env.execute(f"cat {quoted_log_path} 2>/dev/null", timeout=10) - new_output = result.get("output", "") - if new_output: - # Compute delta for watch pattern scanning - delta = new_output[prev_output_len:] if len(new_output) > prev_output_len else "" - prev_output_len = len(new_output) + # Read only the bytes written since the last poll. + result = env.execute( + self._log_delta_command(quoted_log_path, prev_output_bytes), + timeout=10, + ) + raw = result.get("output", "") + header, _, delta = raw.partition("\n") + try: + size_str, offset_str = header.split() + new_size = int(size_str) + used_offset = int(offset_str) + except ValueError: + # No usable header (command failed, shell missing a tool). + # Skip this poll rather than act on a half-read value. + new_size = None + used_offset = None + delta = "" + if new_size is not None: + if used_offset < prev_output_bytes: + # The log was rotated or truncated, so what we hold no + # longer lines up with the file. Drop it and restart. + with session._lock: + session.output_buffer = "" + prev_output_bytes = new_size + if delta: with session._lock: - session.output_buffer = new_output + session.output_buffer += delta if len(session.output_buffer) > session.max_output_chars: session.output_buffer = session.output_buffer[-session.max_output_chars:] - if delta: - self._check_watch_patterns(session, delta) - self._emit_output(session, delta) + self._check_watch_patterns(session, delta) + self._emit_output(session, delta) # Check if process is still running check = env.execute(