termmate icon indicating copy to clipboard operation
termmate copied to clipboard

Agent stderr readers can stop draining and block the CLI

Open thiblizz opened this issue 4 months ago • 0 comments

Summary

Claude and Pi decode stderr with strict UTF-8. A malformed byte raises UnicodeDecodeError, and the broad exception handler silently ends the reader. All three providers also use StreamReader.readline(), which can raise when a newline-free record exceeds the stream limit:

Once the reader has stopped, the child can fill the stderr pipe and block before it writes the response to stdout.

Steps to reproduce

This fixture does not contact a provider.

  1. Save this as fake_claude.py in a temporary directory:
#!/usr/bin/env python3
import os
import sys

def write_stderr(data):
    remaining = memoryview(data)
    while remaining:
        remaining = remaining[os.write(sys.stderr.fileno(), remaining):]

with open(os.environ["TERMMATE_REPRO_PID"], "w", encoding="ascii") as file:
    file.write(str(os.getpid()))

mode = os.environ.get("TERMMATE_STDERR_MODE", "invalid")
if mode == "invalid":
    write_stderr(b"\xff\n")
else:
    write_stderr(b"x" * (128 * 1024) + b"\n")

write_stderr(b"x" * (4 * 1024 * 1024))
os.write(sys.stdout.fileno(), b'{"type":"result","result":"ok"}\n')
  1. Make it executable on Linux/macOS. On Windows, create fake_claude.cmd beside it containing @py -3 "%~dp0fake_claude.py" %*.
  2. Set claude_command to the absolute script or wrapper path. Add TERMMATE_REPRO_PID and TERMMATE_STDERR_MODE to TermMate's env setting.
  3. Set TERMMATE_STDERR_MODE to invalid, start a Claude chat, and wait five seconds.
  4. Close the chat, set TERMMATE_STDERR_MODE to long, and repeat.

In both cases, the ok result does not appear and the recorded process remains alive. Check it with kill -0 <pid> on POSIX or Get-Process -Id <pid> in PowerShell.

Close the chat, terminate only the recorded PID if necessary, and restore the previous settings after each test.

Expected behavior

Malformed bytes and long newline-free stderr do not stop the reader. Stderr is drained with bounded memory, and the child can finish writing its stdout response and exit.

Actual behavior

The stderr task silently ends after malformed UTF-8 or an overlong newline-free record. The child then blocks when the pipe fills.

Suggested fix

Read stderr in bounded chunks instead of using readline(). Use an incremental UTF-8 decoder with replacement for malformed bytes so valid characters split across reads are preserved. If line-oriented logging is retained, bound that buffer and the amount written to the log.

If the stderr reader fails unexpectedly, report one bounded error and terminate and await the subprocess instead of leaving it able to block.

Add tests for malformed bytes, newline-free output above the stream limit, split UTF-8, output above pipe capacity, EOF, cancellation, and bounded logging.

thiblizz avatar Jul 26 '26 21:07 thiblizz