DEV Community

Ace Meridian
Ace Meridian

Posted on Originally published at Medium

subprocess.run text=True Ran My Agent's Command 3 Times

If an agent's shell tool calls subprocess.run(..., text=True), one non-UTF-8 byte in the output raises UnicodeDecodeError after the command has already finished and changed things, so the agent sees an error and runs it again. Capture bytes and decode them yourself with errors="backslashreplace", and the tool always returns the exit code and output, whatever bytes the command printed.

This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux with a UTF-8 locale, and the main script ran twice with identical output.

This is the shell tool I use now:

import json, subprocess
def run_shell(cmd: str, timeout: float = 30) -> str:
    p = subprocess.run(cmd, shell=True, capture_output=True, timeout=timeout)
    out = p.stdout.decode("utf-8", errors="backslashreplace")
    err = p.stderr.decode("utf-8", errors="backslashreplace")
    return json.dumps({"rc": p.returncode, "stdout": out[-4000:], "stderr": err[-2000:]})
Enter fullscreen mode Exit fullscreen mode

The rest of this post shows what text=True did instead, and why the error arrives too late to be useful.

The bug in one command

In the last few posts I looked at agent tools that outlive their timeout: subprocess.run orphans, ThreadPoolExecutor threads, asyncio.gather siblings, and a NaN timeout. This one is smaller and more common. The command works, and the tool still reports failure.

Linux filenames are bytes, not text. A file copied from an old Windows share or an unpacked zip can be called caf\xe9.txt, which is Latin-1 for "café" and not valid UTF-8. Any command that prints that name, such as ls, find, git status or mv -v, writes one invalid byte to stdout.

text=True tells subprocess.run to decode stdout and stderr with the locale encoding, using strict error handling. Decoding happens inside communicate(), after the child has exited. So the exception reports a decode problem but hides the fact that the command already ran.

What the agent saw

My test tool wraps subprocess.run(cmd, shell=True, capture_output=True, text=True) and returns the error string to the model, which is what most agent frameworks do with a tool exception. The command appends one line to a log file (the side effect) and then prints a filename with byte 0xe9. A simple retry loop stands in for the model trying again:

ls text=True: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
attempt 1: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 1
attempt 2: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 2
attempt 3: {"error": "UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 17: invali | side effects so far: 3
bytes mode rc: 0 stdout: b'moved 1 file: caf\xe9.txt\n'
Enter fullscreen mode Exit fullscreen mode

Three attempts, three side effects, zero successful tool results. The same call without text=True returned exit code 0 and the full output. If the side effect is mv, git commit or a curl -X POST, the retry is the real damage. The error message also points the model in the wrong direction: it says nothing about the command having worked, so the obvious next step is to try again.

It does not have to be stdout

The tool also failed when stdout was clean and only stderr had a bad byte:

bad stderr only: UnicodeDecodeError, stdout 'ok' lost: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
Enter fullscreen mode Exit fullscreen mode

ok was printed and the exit code was 0, but the caller received neither. Progress bars, compiler warnings and curl writing binary to stderr can all trigger this.

The timeout path behaved differently. With timeout=1 and a child that printed \xff before sleeping, I got a normal TimeoutExpired after 1.00 s, and e.stdout was raw bytes (b'\xff'), not text. So code that handles a timeout should expect bytes on that attribute even when text=True is set.

Streaming tools are worse

Some tools stream output line by line with Popen(..., stdout=PIPE, text=True). In that case the error ends the loop early and the child keeps running:

stream: UnicodeDecodeError after 0.00s, lines read=[], child poll()=None
0.5 s later child poll(): None
child exited rc=0 at 3.01s
Enter fullscreen mode Exit fullscreen mode

The bad byte was on line 3, but the reader had buffered it together with lines 1 and 2, so even those were lost. The child kept running for another 3 seconds with nobody reading its pipe. I did not test it, but a child that writes more than the pipe buffer holds would then block on write and never finish.

Locale settings do not save you

I expected LC_ALL=C to change things. It did not, because Python 3.7 and later switch the C locale to UTF-8 mode (utf8_mode: 1 in my run), and every line after the version line was identical. A truly Latin-1 locale would decode every byte without error, but then valid UTF-8 output turns into mojibake. The locale only changes which output breaks.

Picking an error handler

Once you capture bytes, choose how to decode them:

errors=backslashreplace: 0 'moved 1 file: caf\\xe9.txt\n'
errors=replace: 0 'moved 1 file: caf�.txt\n'
surrogateescape: 'caf\udce9.txt' | back to bytes: b'caf\xe9.txt'
Enter fullscreen mode Exit fullscreen mode

For text sent back to a model I use backslashreplace. It stays readable and shows exactly which byte was there. replace loses that byte. surrogateescape is the right choice when the string goes back into the filesystem, since os.fsencode restores the original name, but lone surrogates can break JSON encoders and model APIs later. Running the tool above on both failing commands returned {"rc": 0, "stdout": "moved 1 file: caf\\xe9.txt\n", ...} and {"rc": 0, "stdout": "ok\n", "stderr": "\\xff"}.

Takeaways

  • text=True decodes strictly after the command has finished, so a UnicodeDecodeError means the side effects already happened.
  • An agent that receives that error will usually retry. In my test, three retries ran the command three times.
  • One bad byte on stderr also discards a clean stdout and a 0 exit code.
  • With Popen(text=True) streaming, the reader stops and the child keeps running.
  • Capture bytes and decode with errors="backslashreplace" for model-facing output, or surrogateescape when the text goes back into the filesystem.

Top comments (1)

Collapse
 
paragonaimag profile image
Paragon •

That caf\xe9.txt example is the one that'll stick with me — one bad byte and subprocess.run throws away a perfectly good stdout along with a clean exit code 0. We've been poking at the Netflix Prize's 100,480,507 ratings on our side lately, and it's the same lesson at the other end of the scale: the data's only as trustworthy as the pipeline that carried it. errors="surrogateescape" feels like the right default to reach for first.