Skip to content

The agent that grows with you

fix(docker): teardown workers of reaper-detached containers are drained at exit (#86317)

PRATHAMESH7584b70e473e36
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index c53ca663ccc..6ef7e611232 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -16,6 +16,7 @@ import shutil
import subprocess
import sys
import threading
+import time
import uuid
from pathlib import Path
from typing import Optional
@@ -291,6 +292,11 @@ _RUN_TMPFS_EXEC = "--tmpfs", "/run:rw,exec,nosuid,size=64m"
# back. Skipped when --user is passed: the container already starts unprivileged.
_PRIVDROP_CAP_ARGS = ["--cap-add", "SETUID", "--cap-add", "SETGID"]
+# Every ``cleanup()`` worker, independent of terminal_tool's active-env registry (see
+# ``wait_for_all_teardowns``).
+_TEARDOWN_THREADS: set[threading.Thread] = set()
+_TEARDOWN_LOCK = threading.Lock()
+
_S6_INIT_ENTRYPOINTS = ("/init", "/package/admin/s6-overlay/command/init")
@@ -1035,6 +1041,8 @@ class DockerEnvironment(BaseEnvironment):
logger.warning(fail_msg, log_id, e)
t = threading.Thread(target=_do_cleanup, daemon=True, name=f"hermes-cleanup-{log_id}")
+ with _TEARDOWN_LOCK:
+ _TEARDOWN_THREADS.add(t)
t.start()
self._cleanup_thread = t
self._container_id = None
@@ -1044,6 +1052,24 @@ class DockerEnvironment(BaseEnvironment):
if not self._persistent:
self._remove_bind_dirs()
+ @staticmethod
+ def wait_for_all_teardowns(timeout: float = 15.0) -> bool:
+ """Join every in-flight teardown worker, including those of envs the idle reaper already
+ popped out of the active registry (their handles are otherwise unreachable at exit, so
+ ``docker rm`` died with the interpreter and left a stopped container behind — #86317).
+ Re-snapshots each pass: the reaper may start a worker while the drain runs."""
+ deadline = time.monotonic() + timeout
+ while True:
+ with _TEARDOWN_LOCK:
+ _TEARDOWN_THREADS.difference_update({t for t in _TEARDOWN_THREADS if not t.is_alive()})
+ pending = list(_TEARDOWN_THREADS)
+ if not pending:
+ return True
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ pending[0].join(timeout=remaining)
+
def wait_for_cleanup(self, timeout: float = 30.0) -> bool:
"""Block up to *timeout* seconds for the cleanup thread (atexit hook). True if it
finished or none was started, False on timeout."""
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 6aed41dc62e..713c5bdf237 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -21,6 +21,7 @@ import/patch target): ``terminal_tool_config`` (TERMINAL_* reads, ``_quiet``),
import json
import logging
import os
+import sys
import time
import threading
import atexit
@@ -715,6 +716,10 @@ def _atexit_cleanup():
if wait_fn is not None:
with _quiet("wait_for_cleanup raised on exit"): # never block shutdown on a bad backend
wait_fn(timeout=15.0)
+ # Workers of envs the idle reaper already detached are not in the registry (#86317).
+ if "tools.environments.docker" in sys.modules:
+ with _quiet("teardown drain raised on exit"):
+ sys.modules["tools.environments.docker"].DockerEnvironment.wait_for_all_teardowns(timeout=15.0)
atexit.register(_atexit_cleanup)