Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### Fixed

- **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.
34 changes: 19 additions & 15 deletions dokimi/dokimi/harnesses/agent_sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,23 +234,27 @@ 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)
Comment thread
antonwolfy marked this conversation as resolved.
Resolved
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 OSError as 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:
Expand Down
3 changes: 2 additions & 1 deletion dokimi/dokimi/harnesses/docker_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@
default_forbidden,
operator_source_env,
probe_reward,
remove_tree,
run_probe,
solver_cli_flags,
)
Expand Down Expand Up @@ -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:
Expand Down
149 changes: 149 additions & 0 deletions dokimi/tests/test_docker_solver_rmtree.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# 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):
"""#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)
(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)


@_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)

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()
Loading