From 4e4d0adc41a31fe0cc5952a52bd83daebccbbd15 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 16:08:03 +0000 Subject: [PATCH 1/3] fix(harnesses): docker solver removes a kept work tree with an unlistable directory (#1511) docker_solver._rmtree was shutil.rmtree(path, ignore_errors=True). A directory the agent left at mode 0o111, 0o555 or 0o000 made the removal fail silently, so the previous run's kept tree under output_dir/work stayed and the shutil.copytree that follows merged the new tree into it. On Linux as a non-root user, a work/sub at 0o111 left ['sub'] after _rmtree(work), for each of the three modes and for a nested directory. The body of AgentWorkspace.cleanup (make each directory searchable and writable through a descriptor opened with O_NOFOLLOW, then remove, never raise, log the path when the tree stays) moves into a module-level remove_tree(path) in agent_sandbox.py. AgentWorkspace.cleanup calls it with self.root and _rmtree calls it too, so there is one copy of the logic. The warning now reads "tree %s was not removed: %s", since both callers use it. Where the repair cannot run, removal is plain and a tree that stays is logged instead of silent. The existing cleanup tests pass unchanged: the one that patches shutil.rmtree patches the shared module attribute, which remove_tree calls. Signed-off-by: Anton Volkov --- ..._100000_docker-solver-rmtree-unlistable.md | 8 ++ dokimi/dokimi/harnesses/agent_sandbox.py | 35 ++--- dokimi/dokimi/harnesses/docker_solver.py | 3 +- dokimi/tests/test_docker_solver_rmtree.py | 125 ++++++++++++++++++ 4 files changed, 155 insertions(+), 16 deletions(-) create mode 100644 dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md create mode 100644 dokimi/tests/test_docker_solver_rmtree.py diff --git a/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md b/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md new file mode 100644 index 000000000..ee9a7fe80 --- /dev/null +++ b/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A kept agent work tree is replaced, not merged into, when the agent made a directory unlistable** — the docker solver cleared a previous run's `work` directory (and a staged directory) with `shutil.rmtree(..., ignore_errors=True)`, so a `chmod 111`, `555` or `000` directory left the old tree in place silently and the new tree was copied into it. It now removes the tree the way `AgentWorkspace.cleanup` does (the shared `remove_tree`): each directory is made searchable and writable first, and a tree that still stays is logged with its path and the reason; it still never raises. diff --git a/dokimi/dokimi/harnesses/agent_sandbox.py b/dokimi/dokimi/harnesses/agent_sandbox.py index c348dfb34..c6f679a3c 100644 --- a/dokimi/dokimi/harnesses/agent_sandbox.py +++ b/dokimi/dokimi/harnesses/agent_sandbox.py @@ -234,23 +234,28 @@ def edited_since(self, before: frozenset[tuple[str, int, int]]) -> tuple[bool, O return True, exc def cleanup(self) -> None: - """Remove the root, never raising (it runs in ``finally`` paths): a directory the agent made unlistable or - read-only is made searchable and writable first; a tree that is still there is logged with the reason.""" - if _can_unlock(): - try: - root = _open_searchable(str(self.root), None) - try: - _unlock_below(root) - finally: - os.close(root) - except (OSError, RecursionError): # gone, or not ours to change: rmtree below reports what stays - pass + """Remove the root, never raising (it runs in ``finally`` paths): see :func:`remove_tree`.""" + remove_tree(self.root) + + +def remove_tree(path: Path) -> None: + """Remove the tree at *path*, never raising (it runs in cleanup paths): a directory the agent made unlistable or + read-only is made searchable and writable first; a tree that is still there is logged with the reason.""" + if _can_unlock(): try: - shutil.rmtree(self.root) - except FileNotFoundError: + root = _open_searchable(str(path), None) + try: + _unlock_below(root) + finally: + os.close(root) + except (OSError, RecursionError): # gone, or not ours to change: rmtree below reports what stays pass - except OSError as exc: - _LOG.warning("work tree %s was not removed: %s", self.root, exc) + try: + shutil.rmtree(path) + except FileNotFoundError: + pass + except OSError as exc: + _LOG.warning("tree %s was not removed: %s", path, exc) def _can_unlock() -> bool: diff --git a/dokimi/dokimi/harnesses/docker_solver.py b/dokimi/dokimi/harnesses/docker_solver.py index a3b558673..bbd69fd92 100644 --- a/dokimi/dokimi/harnesses/docker_solver.py +++ b/dokimi/dokimi/harnesses/docker_solver.py @@ -68,6 +68,7 @@ default_forbidden, operator_source_env, probe_reward, + remove_tree, run_probe, solver_cli_flags, ) @@ -776,7 +777,7 @@ def _docker(args: list[str], log, *, check: bool = True, timeout: Optional[float def _rmtree(path: Path) -> None: - shutil.rmtree(path, ignore_errors=True) + remove_tree(path) def _host_plugin_dir(workspace: AgentWorkspace) -> Path: diff --git a/dokimi/tests/test_docker_solver_rmtree.py b/dokimi/tests/test_docker_solver_rmtree.py new file mode 100644 index 000000000..8c8f71e4c --- /dev/null +++ b/dokimi/tests/test_docker_solver_rmtree.py @@ -0,0 +1,125 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""docker_solver._rmtree removes a kept agent tree the agent made unlistable (#1511).""" + +from __future__ import annotations + +import os +import shutil +from pathlib import Path + +import pytest + +import dokimi.harnesses.agent_sandbox as sandbox +from dokimi.harnesses import docker_solver + +_NOT_ROOT = pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +_CAN_UNLOCK = pytest.mark.skipif(not sandbox._can_unlock(), reason="the repair needs O_NOFOLLOW, O_DIRECTORY and /proc/self/fd") + + +def _tree(base: Path, mode: int, *, nested: bool) -> Path: + work = base / "work" + (work / "sub" / "deep").mkdir(parents=True) + (work / "sub" / "a.txt").write_text("old a", encoding="utf-8") + (work / "sub" / "deep" / "b.txt").write_text("old b", encoding="utf-8") + if nested: + (work / "sub" / "deep").chmod(mode) + (work / "sub").chmod(mode) + return work + + +def _unlock(work: Path) -> None: + for sub in (work / "sub", work / "sub" / "deep"): + if sub.exists(): + sub.chmod(0o700) + + +@_NOT_ROOT +@_CAN_UNLOCK +@pytest.mark.parametrize("nested", [False, True]) +@pytest.mark.parametrize("mode", [0o111, 0o555, 0o000]) +def test_rmtree_removes_a_tree_with_an_unlistable_directory(tmp_path, mode, nested): + work = _tree(tmp_path, mode, nested=nested) + try: + docker_solver._rmtree(work) + assert not work.exists() + finally: + if work.exists(): + _unlock(work) + + +@_NOT_ROOT +@_CAN_UNLOCK +def test_the_new_tree_copied_after_rmtree_holds_only_the_new_files(tmp_path): + """The merge #1511 names: the kept tree stayed and ``copytree`` wrote the new tree into it.""" + work = _tree(tmp_path, 0o111, nested=True) + fresh = tmp_path / "fresh" + (fresh / "sub").mkdir(parents=True) + (fresh / "sub" / "new.txt").write_text("new", encoding="utf-8") + try: + docker_solver._rmtree(work) + shutil.copytree(fresh, work, symlinks=True) + found = sorted(str(p.relative_to(work)) for p in work.rglob("*")) + assert found == ["sub", os.path.join("sub", "new.txt")] + finally: + if work.exists(): + _unlock(work) + + +@_NOT_ROOT +@_CAN_UNLOCK +def test_rmtree_leaves_the_target_of_a_link_out_of_the_tree_alone(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (outside / "keep.txt").write_text("k", encoding="utf-8") + outside.chmod(0o555) + work = _tree(tmp_path, 0o111, nested=False) + (work / "link").symlink_to(outside, target_is_directory=True) + try: + docker_solver._rmtree(work) + assert not work.exists() + assert (outside.stat().st_mode & 0o777) == 0o555 + assert (outside / "keep.txt").read_text(encoding="utf-8") == "k" + finally: + outside.chmod(0o700) + if work.exists(): + _unlock(work) + + +def test_rmtree_of_a_path_that_does_not_exist_is_no_error_and_no_warning(tmp_path, caplog): + with caplog.at_level("WARNING", logger=sandbox._LOG.name): + docker_solver._rmtree(tmp_path / "absent") + assert not [r for r in caplog.records if r.name == sandbox._LOG.name] + + +def test_rmtree_that_cannot_remove_the_tree_logs_its_path_and_does_not_raise(tmp_path, monkeypatch, caplog): + work = _tree(tmp_path, 0o700, nested=False) + + def refuse(path, *args, **kwargs): + raise PermissionError(13, "Permission denied", str(path)) + + monkeypatch.setattr(shutil, "rmtree", refuse) + with caplog.at_level("WARNING", logger=sandbox._LOG.name): + docker_solver._rmtree(work) + monkeypatch.undo() + assert work.exists() + (record,) = [r for r in caplog.records if r.name == sandbox._LOG.name] + assert str(work) in record.getMessage() and "Permission denied" in record.getMessage() + + +@_NOT_ROOT +def test_rmtree_without_the_repair_keeps_plain_removal_and_logs_what_stayed(tmp_path, monkeypatch, caplog): + real_isdir = os.path.isdir + monkeypatch.setattr(sandbox.os.path, "isdir", lambda p: False if p == "/proc/self/fd" else real_isdir(p)) + assert not sandbox._can_unlock() + work = _tree(tmp_path, 0o111, nested=False) + try: + with caplog.at_level("WARNING", logger=sandbox._LOG.name): + docker_solver._rmtree(work) + assert work.exists() + finally: + monkeypatch.undo() + _unlock(work) + (record,) = [r for r in caplog.records if r.name == sandbox._LOG.name] + assert str(work) in record.getMessage() From cbce4e3590ce40245fca9e76a0e64c8002b2f91d Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 09:33:01 +0000 Subject: [PATCH 2/3] docs(harnesses): say the stale tree made the snapshot copy fail, not merge Settles the review point on the changelog fragment and the test docstring: `shutil.copytree` without `dirs_exist_ok` rejects an existing destination with `FileExistsError`, which the solver logs, so the old snapshot was kept without the new files. The fragment and the test docstring now say that instead of a merge. Signed-off-by: Anton Volkov --- .../20261204_100000_docker-solver-rmtree-unlistable.md | 2 +- dokimi/tests/test_docker_solver_rmtree.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md b/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md index ee9a7fe80..e9b03c028 100644 --- a/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md +++ b/dokimi/changelog.d/20261204_100000_docker-solver-rmtree-unlistable.md @@ -5,4 +5,4 @@ SPDX-License-Identifier: Apache-2.0 ### Fixed -- **A kept agent work tree is replaced, not merged into, when the agent made a directory unlistable** — the docker solver cleared a previous run's `work` directory (and a staged directory) with `shutil.rmtree(..., ignore_errors=True)`, so a `chmod 111`, `555` or `000` directory left the old tree in place silently and the new tree was copied into it. It now removes the tree the way `AgentWorkspace.cleanup` does (the shared `remove_tree`): each directory is made searchable and writable first, and a tree that still stays is logged with its path and the reason; it still never raises. +- **A kept agent work tree is replaced when the previous one has a directory the agent made unlistable** — the docker solver cleared a previous run's `work` directory (and a staged directory) with `shutil.rmtree(..., ignore_errors=True)`, so a `chmod 111`, `555` or `000` directory left the old tree in place silently; the `shutil.copytree` that follows then failed with `FileExistsError`, which the solver logged, and the old snapshot was kept without the new files. It now removes the tree the way `AgentWorkspace.cleanup` does (the shared `remove_tree`): each directory is made searchable and writable first, and a tree that still stays is logged with its path and the reason; it still never raises. diff --git a/dokimi/tests/test_docker_solver_rmtree.py b/dokimi/tests/test_docker_solver_rmtree.py index 8c8f71e4c..ed8e9cfa4 100644 --- a/dokimi/tests/test_docker_solver_rmtree.py +++ b/dokimi/tests/test_docker_solver_rmtree.py @@ -52,7 +52,7 @@ def test_rmtree_removes_a_tree_with_an_unlistable_directory(tmp_path, mode, nest @_NOT_ROOT @_CAN_UNLOCK def test_the_new_tree_copied_after_rmtree_holds_only_the_new_files(tmp_path): - """The merge #1511 names: the kept tree stayed and ``copytree`` wrote the new tree into it.""" + """#1511: a kept tree that stayed made ``copytree`` fail with ``FileExistsError``, so the old snapshot was kept.""" work = _tree(tmp_path, 0o111, nested=True) fresh = tmp_path / "fresh" (fresh / "sub").mkdir(parents=True) From 4a99ec5775ccae595ec77bf839f5f6dd892a611d Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 12:20:44 +0000 Subject: [PATCH 3/3] fix(harnesses): remove_tree closes its descriptors under test and logs a dangling link that stays Settles two review points. The first: deleting os.close(root) in remove_tree left every test passing, so a new test compares the entries of /proc/self/fd before and after removing a tree with unlistable nested directories. The second: a dangling symlink at the tree's path stayed with no warning, because shutil.rmtree raises FileNotFoundError for it and that was read as "gone". remove_tree now treats FileNotFoundError as gone only when the path is not a link, and logs the link otherwise; a test covers it. Signed-off-by: Anton Volkov --- dokimi/dokimi/harnesses/agent_sandbox.py | 5 ++--- dokimi/tests/test_docker_solver_rmtree.py | 24 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/dokimi/dokimi/harnesses/agent_sandbox.py b/dokimi/dokimi/harnesses/agent_sandbox.py index c6f679a3c..fa7359a16 100644 --- a/dokimi/dokimi/harnesses/agent_sandbox.py +++ b/dokimi/dokimi/harnesses/agent_sandbox.py @@ -252,10 +252,9 @@ def remove_tree(path: Path) -> None: pass try: shutil.rmtree(path) - except FileNotFoundError: - pass except OSError as exc: - _LOG.warning("tree %s was not removed: %s", path, exc) + if not (isinstance(exc, FileNotFoundError) and not path.is_symlink()): # a dangling link stays: not "gone" + _LOG.warning("tree %s was not removed: %s", path, exc) def _can_unlock() -> bool: diff --git a/dokimi/tests/test_docker_solver_rmtree.py b/dokimi/tests/test_docker_solver_rmtree.py index ed8e9cfa4..4bbf3dd83 100644 --- a/dokimi/tests/test_docker_solver_rmtree.py +++ b/dokimi/tests/test_docker_solver_rmtree.py @@ -87,12 +87,36 @@ def test_rmtree_leaves_the_target_of_a_link_out_of_the_tree_alone(tmp_path): _unlock(work) +@_NOT_ROOT +@_CAN_UNLOCK +def test_rmtree_closes_the_descriptors_it_opens(tmp_path): + work = _tree(tmp_path, 0o111, nested=True) + before = set(os.listdir("/proc/self/fd")) + try: + docker_solver._rmtree(work) + assert not work.exists() + assert set(os.listdir("/proc/self/fd")) == before + finally: + if work.exists(): + _unlock(work) + + def test_rmtree_of_a_path_that_does_not_exist_is_no_error_and_no_warning(tmp_path, caplog): with caplog.at_level("WARNING", logger=sandbox._LOG.name): docker_solver._rmtree(tmp_path / "absent") assert not [r for r in caplog.records if r.name == sandbox._LOG.name] +def test_rmtree_of_a_dangling_link_logs_that_it_stayed(tmp_path, caplog): + link = tmp_path / "work" + link.symlink_to(tmp_path / "nowhere") + with caplog.at_level("WARNING", logger=sandbox._LOG.name): + docker_solver._rmtree(link) + assert link.is_symlink() + (record,) = [r for r in caplog.records if r.name == sandbox._LOG.name] + assert str(link) in record.getMessage() + + def test_rmtree_that_cannot_remove_the_tree_logs_its_path_and_does_not_raise(tmp_path, monkeypatch, caplog): work = _tree(tmp_path, 0o700, nested=False)