Agent stderr readers can stop draining and block the CLI
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.
- Save this as
fake_claude.pyin 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')
- Make it executable on Linux/macOS. On Windows, create
fake_claude.cmdbeside it containing@py -3 "%~dp0fake_claude.py" %*. - Set
claude_commandto the absolute script or wrapper path. AddTERMMATE_REPRO_PIDandTERMMATE_STDERR_MODEto TermMate'senvsetting. - Set
TERMMATE_STDERR_MODEtoinvalid, start a Claude chat, and wait five seconds. - Close the chat, set
TERMMATE_STDERR_MODEtolong, 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.