# OSError [Errno 24] After 338 asyncio wait_for Timeouts

> Source: <https://dev.to/acemeridian/oserror-errno-24-after-338-asyncio-waitfor-timeouts-124a>
> Published: 2026-11-26 05:08:23+00:00

**Recommendation:** In any agent shell tool, kill and await the child process in the timeout branch so its pipes and pidfd are released, rather than only cancelling communicate().
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

In my test, an agent's shell tool died with `OSError: [Errno 24] Too many open files`, raised from `File "/usr/lib/python3.14/subprocess.py", line 1886, in _execute_child`, and the real cause was 338 earlier calls to `asyncio.wait_for(proc.communicate(), timeout)` that timed out and left their child processes running. The fix is two lines in the `except TimeoutError` branch, `proc.kill()` then `await proc.wait()`, and with them 300 timed-out calls under a 256-descriptor limit ended with 7 open descriptors and 0 live children instead of a crash at call 83.

This story was written with the assistance of an AI writing program. Every number below comes from CPython 3.14.4 on Linux, and the main scripts ran twice with the same counts.

This is the tool runner I use now:

``` python
import asyncio
async def run_tool(*cmd, timeout=30.0):
    proc = await asyncio.create_subprocess_exec(
        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
    try:
        async with asyncio.timeout(timeout):
            out, err = await proc.communicate()
    except TimeoutError:
        proc.kill()          # the child does not die on its own
        await proc.wait()    # reap it; this closes the pipes and the pidfd
        raise
    return proc.returncode, out, err
```

The rest of this post shows what the short version leaks, and why it takes hundreds of calls before anything breaks.

This is what the shell tool looked like before:

```
proc = await asyncio.create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE)
try:
    out, err = await asyncio.wait_for(proc.communicate(), timeout)
except TimeoutError:
    return "tool timed out"
```

The timeout works in the sense that the caller gets control back on time. What it does not do is touch the child. `wait_for` cancels the `communicate()` coroutine, and cancelling a coroutine that reads pipes stops the reading. The process on the other end keeps running, and the event loop keeps its pipes open so it can still report the exit code later.

This is the same family of bug as my earlier posts on `subprocess.run` orphans and `ThreadPoolExecutor` threads: the caller stops waiting and assumes the work stopped too.

The fake tool is `sleep 30` with stdout and stderr piped, called with a 0.05 s timeout in a loop. After each run the script counts entries in `/proc/self/fd` and checks `/proc/<pid>/stat` for every child it started. I lowered `RLIMIT_NOFILE` with `resource.setrlimit` so the failure shows up in seconds instead of hours.

```
python 3.14.4 RLIMIT_NOFILE soft=256
naive wait_for(communicate): calls=82 timed_out=82 fds_before=7 fds_after=253 children_alive=82 elapsed=4.34s
naive wait_for(communicate): call 83 raised OSError: [Errno 24] Too many open files
python 3.14.4 RLIMIT_NOFILE soft=256
fixed kill+wait: calls=300 timed_out=300 fds_before=7 fds_after=7 children_alive=0 elapsed=16.23s
```

With a 1024 limit, the usual default soft limit on many Linux machines, the naive loop got through 338 calls and failed on call 339 with 1021 descriptors open and 338 `sleep` processes still alive. Every call returned "tool timed out" on schedule. Nothing in the logs pointed at the leak until call 339 failed inside `subprocess.py` with an error that says nothing about timeouts.

I counted what kinds of descriptor were piling up after 10 timed-out calls:

```
before {'anon_inode:[eventpoll]': 1, 'file': 3, 'socket': 2}
after 10 timeouts {'anon_inode:[eventpoll]': 1, 'anon_inode:[pidfd]': 10, 'file': 3, 'pipe': 20, 'socket': 2}
after gc.collect() {'anon_inode:[eventpoll]': 1, 'anon_inode:[pidfd]': 10, 'file': 3, 'pipe': 20, 'socket': 2}
after children killed {'anon_inode:[eventpoll]': 1, 'file': 3, 'socket': 2}
```

Each call holds two pipe ends (stdout, stderr) and one pidfd that the event loop uses to watch for the child's exit. That is 3 per call, which matches the numbers: (1024 - 7) / 3 is 339.

`gc.collect()` changed nothing. My script dropped every `proc` object after the call, but the loop still references the transport while it waits for the child to exit, so nothing is garbage. Once I killed the children, all 30 descriptors closed on their own within 0.5 s. The leak lasts as long as the child does. With `sleep 30` that is 30 seconds. With a hung `curl`, a `tail -f` or a REPL waiting on stdin, it lasts until the agent process restarts.

I ran 5 leaking calls in a script that then exited, and checked a second later: 0 `sleep 30` processes left. When `asyncio.run()` closes the loop, it closes each subprocess transport, and `BaseSubprocessTransport.close()` in `asyncio/base_subprocess.py` kills a child that is still running. So a unit test or a one-off CLI run cleans up after itself and passes.

A long-lived agent server, a Discord bot, or a notebook kernel never closes its loop. That is where the leak builds up until it hits the limit.

`proc.kill()` sends SIGKILL to the child. `await proc.wait()` waits for the loop to see the exit, after which it closes the pipes and the pidfd. I also tried `kill()` without the `wait()`: 300 sequential calls did not crash, but 10 descriptors were still open right after the loop and only dropped to 7 half a second later. The cleanup happens later in the background, so I keep the `wait()` and get a known state when the function returns. Re-raising keeps the `TimeoutError` visible to the caller. If your tool runs `sh -c`, the shell's children survive SIGKILL to the shell, so add `start_new_session=True` and kill the process group with `os.killpg`, as in my `subprocess.run` post.

I ran the snippet at the top as written: one `echo ok` call, then 100 timed-out `sleep 30` calls, and it finished with 7 open descriptors and no `sleep` processes left.

`communicate()` stops your wait, not the child. Kill the child yourself.`proc.kill()`, `await proc.wait()`. The pipes and the pidfd are closed only after the exit is seen, and waiting makes that happen before you return.`Errno 24`.` gc.collect()` will not save you, and neither will tests that exit, because `asyncio.run()` hides the bug at shutdown.`len(os.listdir("/proc/self/fd"))` in long-running agents. It is a cheap health metric.
I did not test macOS or Windows, which use different child watchers, and I did not test Python versions before 3.14.
