The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(docker): stop caching transient capability-probe failures as unsupported
beardthelion504e79d0d581
diff --git a/tests/tools/test_docker_cgroup_limits.py b/tests/tools/test_docker_cgroup_limits.pyindex a111a8eef88..970f99ef2de 100644--- a/tests/tools/test_docker_cgroup_limits.py+++ b/tests/tools/test_docker_cgroup_limits.py@@ -15,10 +15,12 @@ import tools.environments.docker as docker_env@pytest.fixture(autouse=True)def _reset_cgroup_cache():- """The probe result is cached in a module-level global; reset per test."""+ """The probe results are cached in module-level globals; reset per test."""docker_env._cgroup_limits_ok = None+ docker_env._storage_opt_ok = Noneyielddocker_env._cgroup_limits_ok = None+ docker_env._storage_opt_ok = Nonedef test_pids_limit_not_in_base_security_args():@@ -59,3 +61,192 @@ def test_probe_result_is_cached(monkeypatch):docker_env._cgroup_limits_available("img")docker_env._cgroup_limits_available("img")assert len(calls) == 1 # probe runs once, then cached+++def test_probe_timeout_is_not_cached_and_retried(monkeypatch):+ """A transient probe failure (auto-pull of an uncached image exceeding the+ 60s timeout, daemon cold-start) must not disable resource limits for the+ process lifetime. The spawn degrades but the next spawn re-probes."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []++ def _run(cmd, *a, **k):+ calls.append(cmd)+ if len(calls) == 1:+ raise subprocess.TimeoutExpired(cmd, 60)+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(docker_env.subprocess, "run", _run)+ assert docker_env._cgroup_limits_available("img") is False+ assert docker_env._cgroup_limits_available("img") is True+ assert len(calls) == 2+++def test_probe_non_cgroup_failure_is_not_cached(monkeypatch):+ """A nonzero probe exit for reasons unrelated to cgroups (manifest/pull+ error, daemon error) is not a definitive negative, so it is retried on the+ next spawn."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []++ def _run(cmd, *a, **k):+ calls.append(cmd)+ if len(calls) == 1:+ return subprocess.CompletedProcess(+ cmd, 125, stdout="", stderr="docker: Error response from daemon: "+ "manifest for hermes-agent:latest not found: manifest unknown")+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(docker_env.subprocess, "run", _run)+ assert docker_env._cgroup_limits_available("img") is False+ assert docker_env._cgroup_limits_available("img") is True+ assert len(calls) == 2+++def test_probe_pull_error_naming_cgroup_is_not_cached(monkeypatch):+ """An image whose NAME contains 'cgroup' produces a pull error mentioning it;+ that must not be read as a definitive cgroup rejection."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []++ def _run(cmd, *a, **k):+ calls.append(cmd)+ if len(calls) == 1:+ return subprocess.CompletedProcess(+ cmd, 125, stdout="", stderr="docker: Error response from daemon: "+ "pull access denied for cgroup-tools, repository does not exist")+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(docker_env.subprocess, "run", _run)+ assert docker_env._cgroup_limits_available("cgroup-tools") is False+ assert docker_env._cgroup_limits_available("cgroup-tools") is True+ assert len(calls) == 2+++def test_probe_definitive_cgroup_failure_is_cached(monkeypatch):+ """A daemon rejection that names cgroups IS a host property; caching it is+ the point of the probe, so subsequent spawns do not pay it again."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []++ def _run(cmd, *a, **k):+ calls.append(cmd)+ return subprocess.CompletedProcess(+ cmd, 126, stdout="", stderr="docker: Error response from daemon: failed to "+ "create task for container: OCI runtime create failed: error setting cgroup "+ "config for procHooks process: permission denied")++ monkeypatch.setattr(docker_env.subprocess, "run", _run)+ assert docker_env._cgroup_limits_available("img") is False+ assert docker_env._cgroup_limits_available("img") is False+ assert len(calls) == 1+++def test_missing_docker_is_not_cached(monkeypatch):+ """find_docker() missing says nothing about cgroup support, so it is not cached."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: None)+ assert docker_env._cgroup_limits_available("img") is False++ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ monkeypatch.setattr(docker_env.subprocess, "run",+ lambda cmd, *a, **k: subprocess.CompletedProcess(cmd, 0, stdout="", stderr=""))+ assert docker_env._cgroup_limits_available("img") is True+++class TestStorageOptProbeCaching:+ """``_storage_opt_supported`` has the same transient-vs-definitive contract:+ only a real answer (driver name, or a daemon rejection naming storage) may+ be cached process-wide; timeouts and pull/daemon failures must retry."""++ def _fake_run(self, calls, info=None, create=None, info_exc=None):+ def _run(cmd, *a, **k):+ calls.append(cmd)+ sub = cmd[1] if isinstance(cmd, list) and len(cmd) > 1 else ""+ if sub == "info":+ if info_exc:+ raise info_exc+ rc, stdout, stderr = info+ return subprocess.CompletedProcess(cmd, rc, stdout=stdout, stderr=stderr)+ if sub == "create":+ rc, stdout, stderr = create+ return subprocess.CompletedProcess(cmd, rc, stdout=stdout, stderr=stderr)+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ return _run++ def test_info_failure_not_cached(self, monkeypatch):+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []+ monkeypatch.setattr(docker_env.subprocess, "run", self._fake_run(+ calls, info=(1, "", "Cannot connect to the Docker daemon")))++ assert docker_env.DockerEnvironment._storage_opt_supported() is False+ monkeypatch.setattr(docker_env.subprocess, "run", self._fake_run(+ calls, info=(0, "overlay2\n", ""), create=(0, "cid123\n", "")))+ assert docker_env.DockerEnvironment._storage_opt_supported() is True++ def test_info_exception_not_cached(self, monkeypatch):+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []+ monkeypatch.setattr(docker_env.subprocess, "run", self._fake_run(+ calls, info_exc=subprocess.TimeoutExpired("docker", 10)))+ assert docker_env.DockerEnvironment._storage_opt_supported() is False+ assert docker_env._storage_opt_ok is None++ def test_unsupported_create_error_cached(self, monkeypatch):+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []+ monkeypatch.setattr(docker_env.subprocess, "run", self._fake_run(+ calls, info=(0, "overlay2\n", ""),+ create=(125, "", "Error response from daemon: --storage-opt is "+ "supported only for overlay2 with pquota")))+ assert docker_env.DockerEnvironment._storage_opt_supported() is False+ assert docker_env.DockerEnvironment._storage_opt_supported() is False+ assert len(calls) == 2 # info + create once; cached thereafter++ def test_create_pull_failure_not_cached(self, monkeypatch):+ """A create-probe failure that never reached the storage check (image+ pull error) is transient; retried, not latched."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls = []+ monkeypatch.setattr(docker_env.subprocess, "run", self._fake_run(+ calls, info=(0, "overlay2\n", ""),+ create=(125, "", "Unable to find image 'hello-world:latest'")))+ assert docker_env.DockerEnvironment._storage_opt_supported() is False+ assert docker_env._storage_opt_ok is None+++def test_transient_probe_failure_recovers_on_next_spawn(monkeypatch):+ """E2e through DockerEnvironment: the probe timing out on spawn one (auto-pull+ past the 60s timeout, daemon cold-start) leaves THAT container unlimited but+ must not disable limits process-wide. Spawn two re-probes, succeeds, and its+ docker run argv carries --cpus/--memory/--pids-limit."""+ monkeypatch.setattr(docker_env, "find_docker", lambda: "/usr/bin/docker")+ calls, probe_calls = [], []++ def _run(cmd, *a, **k):+ calls.append(cmd)+ if isinstance(cmd, list) and len(cmd) > 1 and cmd[1] == "run" and "--rm" in cmd:+ # the throwaway cgroup probe (`run --rm ... sleep 0`), not the real `run -d`+ probe_calls.append(cmd)+ if len(probe_calls) == 1:+ raise subprocess.TimeoutExpired(cmd, 60)+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")+ if isinstance(cmd, list) and len(cmd) > 1 and cmd[1] == "version":+ return subprocess.CompletedProcess(cmd, 0, stdout="Docker version", stderr="")+ if isinstance(cmd, list) and len(cmd) > 1 and cmd[1] == "run" and "-d" in cmd:+ return subprocess.CompletedProcess(cmd, 0, stdout="fake-container-id\n", stderr="")+ return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")++ monkeypatch.setattr(docker_env.subprocess, "run", _run)+ docker_env.DockerEnvironment(image="img", cpu=1.0, memory=512, task_id="t1")+ docker_env.DockerEnvironment(image="img", cpu=1.0, memory=512, task_id="t2")++ run_argvs = [c for c in calls+ if isinstance(c, list) and len(c) > 1 and c[1] == "run" and "-d" in c]+ assert len(run_argvs) == 2+ assert "--cpus" not in run_argvs[0] and "--memory" not in run_argvs[0]+ assert "--cpus" in run_argvs[1] and "1.0" in run_argvs[1]+ assert "--memory" in run_argvs[1] and "512m" in run_argvs[1]+ assert "--pids-limit" in run_argvs[1]+ assert len(probe_calls) == 2 # re-probed, not latched off the timeoutdiff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex 2d53f3e3d93..b1bb2bb8ffd 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -365,38 +365,63 @@ def _resolve_host_user_spec() -> Optional[str]:_storage_opt_ok: Optional[bool] = None # cached result across instances_cgroup_limits_ok: Optional[bool] = None # cached result across instances+# stderr fragments meaning the probe container/image never ran, so the failure says+# nothing about the capability being probed. Checked BEFORE capability keywords: an+# image named e.g. "cgroup-tools" produces a pull error mentioning "cgroup", which+# must not be read as a cgroup rejection.+_PROBE_NONDETERMINATE_STDERR = (+ "unable to find image", "manifest", "pull access denied", "pulling fs layer",+ "toomanyrequests", "failed to resolve reference", "error pulling",+ "cannot connect to the docker daemon", "connection refused", "context deadline exceeded")+++def _probe_stderr_indeterminate(stderr: str) -> bool:+ return any(s in stderr for s in _PROBE_NONDETERMINATE_STDERR)+def _cgroup_limits_available(image: str) -> bool:"""Probe once per process whether ``--cpus``/``--memory``/``--pids-limit`` work here, via athrowaway ``sleep 0`` container from *image* (no extra pull). Without delegated cgroupcontrollers (unprivileged LXCs, rootless) these flags fail every start with exit 126;- the result is host-wide, so it is cached."""+ the result is host-wide, so it is cached. Only DEFINITIVE answers are cached: a probe+ that could not run (auto-pull past the timeout, daemon cold-start, manifest/pull error)+ says nothing about cgroup support, so it degrades this spawn and is retried on the next."""global _cgroup_limits_okif _cgroup_limits_ok is not None:return _cgroup_limits_okdocker_exe = find_docker()if not docker_exe or not image:- _cgroup_limits_ok = False- return False+ return False # not cached: docker may appear later in this processtry:result = run_capture([docker_exe, "run", "--rm", "--cpus", "0.5", "--memory", "64m", "--pids-limit", "32",image, "sleep", "0"],timeout=60)- _cgroup_limits_ok = result.returncode == 0- if not _cgroup_limits_ok:- logger.warning(- "Cgroup resource limits (--cpus/--memory/--pids-limit) not "- "available in this environment. Containers will run without "- "CPU, memory or PID limits. To enable, delegate the cpu, "- "memory and pids cgroup controllers to this container. Probe stderr: %s",- (result.stderr or "").strip()[:500])except Exception as e:+ logger.warning("Cgroup limit probe failed; containers run without "+ "CPU/memory/PID limits until a probe succeeds: %s", e)+ return False+ if result.returncode == 0:+ _cgroup_limits_ok = True+ return True+ stderr = (result.stderr or "").strip()+ stderr_l = stderr.lower()+ if "cgroup" in stderr_l and not _probe_stderr_indeterminate(stderr_l):_cgroup_limits_ok = False- logger.warning("Cgroup limit probe failed; disabling resource limits: %s", e)- return _cgroup_limits_ok+ logger.warning(+ "Cgroup resource limits (--cpus/--memory/--pids-limit) not "+ "available in this environment. Containers will run without "+ "CPU, memory or PID limits. To enable, delegate the cpu, "+ "memory and pids cgroup controllers to this container. Probe stderr: %s",+ stderr[:500])+ else:+ logger.warning(+ "Cgroup limit probe could not determine support (docker exited %d: %s). "+ "Containers run without CPU/memory/PID limits until a probe succeeds.",+ result.returncode, stderr[:500])+ return _cgroup_limits_ok or Falsedef _docker_unavailable(log_msg: str, *log_args, error: str, hint: str, exc_info: bool = False):@@ -953,26 +978,36 @@ class DockerEnvironment(BaseEnvironment):@staticmethoddef _storage_opt_supported() -> bool:- """Whether ``--storage-opt size=`` works (only overlay2 on XFS with pquota; ext4 errors out)."""+ """Whether ``--storage-opt size=`` works (only overlay2 on XFS with pquota; ext4 errors out).+ Only definitive answers are cached: a probe that could not run (daemon cold-start,+ hello-world pull timeout) says nothing about pquota support and is retried next spawn."""global _storage_opt_okif _storage_opt_ok is not None:return _storage_opt_oktry:docker = find_docker() or "docker"result = run_capture([docker, "info", "--format", "{{.Driver}}"], timeout=10)+ if result.returncode != 0:+ return False # daemon unreachable etc. is transient; retry next spawnif result.stdout.strip().lower() != "overlay2":- _storage_opt_ok = False+ _storage_opt_ok = False # storage driver is a host propertyreturn False# Probe with a real create — the fastest reliable check.probe = run_capture([docker, "create", "--storage-opt", "size=1m", "hello-world"], timeout=15)- _storage_opt_ok = probe.returncode == 0- if _storage_opt_ok and probe.stdout.strip():- subprocess.run([docker, "rm", probe.stdout.strip()],- capture_output=True, timeout=5, stdin=subprocess.DEVNULL)+ if probe.returncode == 0:+ _storage_opt_ok = True+ if probe.stdout.strip():+ subprocess.run([docker, "rm", probe.stdout.strip()],+ capture_output=True, timeout=5, stdin=subprocess.DEVNULL)+ elif not _probe_stderr_indeterminate((probe.stderr or "").lower()) and \+ any(s in (probe.stderr or "").lower()+ for s in ("storage", "quota", "overlay2")):+ _storage_opt_ok = False # daemon said storage-opt is unsupported; host property+ # else: pull/daemon failure unrelated to storage-opt; not cached, retried next spawnexcept Exception:- _storage_opt_ok = False+ return False # TimeoutExpired, missing binary; transient, retried next spawnlogger.debug("Docker --storage-opt support: %s", _storage_opt_ok)- return _storage_opt_ok+ return _storage_opt_ok or Falsedef _container_network_mode(self, container_id: str) -> Optional[str]:"""``HostConfig.NetworkMode`` of a container, or ``None`` when inspection fails (callers