diff --git a/dokimi/changelog.d/20261128_150000_unlistable-run-trees.md b/dokimi/changelog.d/20261128_150000_unlistable-run-trees.md new file mode 100644 index 0000000000..ea37c93ee0 --- /dev/null +++ b/dokimi/changelog.d/20261128_150000_unlistable-run-trees.md @@ -0,0 +1,10 @@ + + +### Fixed + +- **A host solve whose work tree has a directory that cannot be listed is a run error** โ€” `AgentWorkspace.state` walked the agent's work tree with `os.walk` and no `onerror`, which skips a directory it cannot list (mode `0o111`), and skipped a file it could not `lstat` (a directory without the x bit, mode `0o644`), so a file written under a directory the agent then made unlistable was missing from the state after the run. The walk and the `lstat` now re-raise the `OSError` (a file gone since the listing is still skipped), and `docker-claude-host` records it as the cell's error (`metrics.error` is `PermissionError: ...` naming the directory, `returncode` 1, no reward) after saving the solver stream and the cost, instead of scoring the run on a smaller tree. The state of a tree that can be listed is unchanged. +- **The `dokimi:typecheck` grader refuses a directory it cannot list** โ€” `_reachable` walked the graded workspace with no `onerror`, so a stub or a silencing comment under a directory it cannot list was never checked, and the oracle's `rglob` over `reference/` skipped such a directory, so a link inside it passed the link check and `shutil.copytree` failed with a `shutil.Error`. The workspace walk now raises the `OSError` (the run is not graded, with the error in `grade.json`), and the oracle raises a `ValueError` naming the `reference/` directory, as it does for a link. A dot directory the grader prunes (`.venv`, `.git`) is still not walked, so one it cannot list is no error. +- **The held-guidance link table raises when a workspace directory cannot be listed** โ€” `HeldGuidance._walk` used `os.walk` with no `onerror`, and `os.path.islink`, which reads a failed `lstat` as no link, so a link inside a directory it could not list or stat was missing from the table and its alias was not followed, while the directory itself was still recorded. The walk now raises the `OSError` naming the directory, and the link check uses `os.lstat`, so it raises too. `repo run` records it as the cell's error (`PermissionError: ...`, as for any other `OSError` of a cell), and `repo security` refuses the batch with it. diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index 6c3be5fea6..5bba62d394 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -955,7 +955,9 @@ own code has both, and the grader cannot read the base to tell them from the age report only the `assert False` kind, along with the repository's own unreachable branches. A task that needs these guarded checks them in its own `grade` entry point. `reference/` is optional. The task's `oracle` copies its `reference/` directory, when it has one, over the -workspace, so a reference repair is what gets graded; its answer is empty. Without `reference/` the grade +workspace, so a reference repair is what gets graded; its answer is empty. A directory of `reference/` that +cannot be listed makes the `oracle` fail with a `ValueError` naming it, and a directory of the workspace that +cannot be listed leaves the run not graded (the error is in `grade.json`), not read as a smaller tree. Without `reference/` the grade reads the listed files as they are, and the self-check (ยง4.3) runs the null step only: the untouched listed files must fail, since there is no reference repair for the oracle step to pass. It runs mypy in-process in the grading container, so the image's `python3` diff --git a/dokimi/dokimi/harnesses/agent_sandbox.py b/dokimi/dokimi/harnesses/agent_sandbox.py index 045e6acba9..619fdb2d7c 100644 --- a/dokimi/dokimi/harnesses/agent_sandbox.py +++ b/dokimi/dokimi/harnesses/agent_sandbox.py @@ -207,19 +207,32 @@ def isolation(self) -> dict[str, str]: def state(self) -> frozenset[tuple[str, int, int]]: """``(path, size, mtime_ns)`` of every file in the work tree. - Two states differ if the agent wrote, created or deleted a file between them. + Two states differ if the agent wrote, created or deleted a file between them. A directory that cannot be + listed raises its OSError: a state without the files under it would read as a run that left them alone. """ out = set() - for dirpath, _dirnames, filenames in os.walk(self.work): + + def unlistable(error: OSError) -> None: + raise error + + for dirpath, _dirnames, filenames in os.walk(self.work, onerror=unlistable): for name in filenames: path = os.path.join(dirpath, name) try: st = os.lstat(path) - except OSError: + except FileNotFoundError: # gone since the listing; a directory without x raises here continue out.add((os.path.relpath(path, self.work), st.st_size, st.st_mtime_ns)) return frozenset(out) + def edited_since(self, before: frozenset[tuple[str, int, int]]) -> tuple[bool, Optional[OSError]]: + """Whether the work tree differs from the ``state`` *before*, and the error of a listing that failed (then + True: nothing says the tree is untouched).""" + try: + return self.state() != before, None + except OSError as exc: + return True, exc + def cleanup(self) -> None: shutil.rmtree(self.root, ignore_errors=True) diff --git a/dokimi/dokimi/harnesses/docker_solver.py b/dokimi/dokimi/harnesses/docker_solver.py index 2b8f27661a..ff5bca2bfe 100644 --- a/dokimi/dokimi/harnesses/docker_solver.py +++ b/dokimi/dokimi/harnesses/docker_solver.py @@ -415,9 +415,11 @@ def _solve_claude( secrets = credential_values(env) proc = run_solver(cmd, output_dir, extra_metrics, treatment, secrets, cwd=str(work), timeout=timeout, env=env, runner=self.runner) + edited, unlisted = workspace.edited_since(before) usage = record_solver(proc, task.name, model, time.time() - t0, output_dir, - operations, log, extra_metrics, treatment, secrets, - edited=workspace.state() != before) + operations, log, extra_metrics, treatment, secrets, edited=edited) + if unlisted is not None: # raised once the stream and the cost are kept: no score on a smaller state + raise unlisted # The agent sees all of /app but writes back only its working tree: a # read-only baseline beside it (/app/baseline) stays the image's. back = work / posixpath.relpath(workdir, _AGENT_TREE) diff --git a/dokimi/dokimi/repos/graders/typecheck.py b/dokimi/dokimi/repos/graders/typecheck.py index aad5eb394a..7a4612435e 100644 --- a/dokimi/dokimi/repos/graders/typecheck.py +++ b/dokimi/dokimi/repos/graders/typecheck.py @@ -232,11 +232,16 @@ def _shadows(module: str, workspace: Path) -> bool: return not dists or not all(_installed_from(d, workspace) for d in dists) +def _unlistable(error: OSError) -> None: + """``os.walk``'s ``onerror``: a directory that cannot be listed is an error, not a tree without its files.""" + raise error + + def _reachable(workspace: Path, listed: list[str]): """``os.walk`` of the workspace without a dot directory (``.venv``, ``.git``) that holds no listed file: no import - names a dot directory, so mypy reads nothing under it.""" + names a dot directory, so mypy reads nothing under it. A directory it walks and cannot list raises its OSError.""" keep = [workspace / p for p in listed] - for dirpath, dirnames, filenames in os.walk(workspace): + for dirpath, dirnames, filenames in os.walk(workspace, onerror=_unlistable): dirnames[:] = [d for d in dirnames if not d.startswith(".") or any(k.is_relative_to(Path(dirpath, d)) for k in keep)] yield dirpath, dirnames, filenames @@ -372,21 +377,30 @@ def oracle(task: dict[str, Any], task_dir: Path, run_dir: Path | None = None) -> """No reference answer: the grade reads the workspace only. A task with a ``reference/`` directory has its files copied over the workspace first, so the reference repair is what gets graded. A destination reached through a symbolic link in the workspace is refused before anything is copied. A symbolic link in the - reference is refused too: copytree would follow it, and the entries behind it are not walked here.""" + reference is refused too: copytree would follow it, and the entries behind it are not walked here. A directory + of the reference that cannot be listed is refused the same way (a ValueError), so no link behind it goes unseen.""" reference = task_dir / REFERENCE_DIR if reference.is_dir() and run_dir is not None: workspace = Path(run_dir) / "workspace" # checked even for an empty reference: copytree still copies the mode onto a linked root if _linked_on_the_way(workspace, workspace): raise ValueError("the workspace is a symbolic link; the reference would be written through it") - for source in reference.rglob("*"): # directories too: copytree creates an empty one through a link - if source.is_symlink(): - raise ValueError(f"reference/{source.relative_to(reference).as_posix()} is a symbolic link; " - "the reference is copied without links") - dest = workspace / source.relative_to(reference) - if _linked_on_the_way(workspace, dest): - raise ValueError(f"{dest.relative_to(workspace).as_posix()} would be written through a " - "symbolic link in the workspace") + + def refuse(error: OSError) -> None: + where = Path(str(error.filename)).relative_to(reference).as_posix() + raise ValueError(f"{REFERENCE_DIR}{'' if where == '.' else '/' + where} cannot be listed: " + f"{error.strerror}") from error + + for top, dirs, names in os.walk(reference, onerror=refuse): # directories too: copytree makes one through a link + for name in (*dirs, *names): + source = Path(top, name) + if source.is_symlink(): + raise ValueError(f"reference/{source.relative_to(reference).as_posix()} is a symbolic link; " + "the reference is copied without links") + dest = workspace / source.relative_to(reference) + if _linked_on_the_way(workspace, dest): + raise ValueError(f"{dest.relative_to(workspace).as_posix()} would be written through a " + "symbolic link in the workspace") shutil.copytree(reference, workspace, dirs_exist_ok=True) return "" diff --git a/dokimi/dokimi/repos/held_guidance.py b/dokimi/dokimi/repos/held_guidance.py index ffcfedeb57..25953247d6 100644 --- a/dokimi/dokimi/repos/held_guidance.py +++ b/dokimi/dokimi/repos/held_guidance.py @@ -7,6 +7,7 @@ from __future__ import annotations import os +import stat from collections.abc import Iterable from pathlib import Path @@ -38,15 +39,20 @@ def __init__(self, ws: Path, files: Iterable[str]) -> None: def _walk(self) -> tuple[dict[str, str], frozenset[str]]: """Each link of the workspace as it is now (its path, absolute from the real root, and where it points), and - its directories that are no link; the paths are keyed as ``os.path.normcase`` writes them (lower case on Windows).""" + its directories that are no link; the paths are keyed as ``os.path.normcase`` writes them (lower case on Windows). + A directory that cannot be listed raises its OSError (the directory and the reason): its links are not skipped.""" links: dict[str, str] = {} dirs_here = {os.path.normcase(self.root)} - for here, dirs, names in os.walk(self.root): + + def unlistable(error: OSError) -> None: + raise error + + for here, dirs, names in os.walk(self.root, onerror=unlistable): if here == self.root and ".git" in dirs: dirs.remove(".git") for name in (*dirs, *names): path = os.path.join(here, name) - if os.path.islink(path): + if stat.S_ISLNK(os.lstat(path).st_mode): # os.path.islink reads a failed lstat as no link links[os.path.normcase(path)] = str(_link_target(Path(path))) elif name in dirs: dirs_here.add(os.path.normcase(path)) diff --git a/dokimi/tests/test_agent_sandbox.py b/dokimi/tests/test_agent_sandbox.py index d11a0d5923..535dd58404 100644 --- a/dokimi/tests/test_agent_sandbox.py +++ b/dokimi/tests/test_agent_sandbox.py @@ -846,6 +846,57 @@ def test_state_sees_a_file_the_agent_writes_under_a_dot_skill_dir(): ws.cleanup() +_NOT_ROOT = pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") + + +@_NOT_ROOT +@pytest.mark.parametrize("mode", [0o111, 0o644]) +def test_state_of_a_tree_with_a_directory_that_cannot_be_listed_raises_its_error(mode): + """#1361: a state that cannot be listed (no r) or whose files cannot be stat'd (no x) is an error.""" + ws = AgentWorkspace.create() + try: + (ws.work / "sub").mkdir() + (ws.work / "t.txt").write_text("t", encoding="utf-8") + (ws.work / "sub" / "a.txt").write_text("a", encoding="utf-8") + before = ws.state() + assert sorted(path for path, _, _ in before) == ["sub/a.txt", "t.txt"] + assert ws.edited_since(before) == (False, None) + (ws.work / "sub").chmod(mode) + with pytest.raises(PermissionError, match="sub"): + ws.state() + edited, error = ws.edited_since(before) + assert edited is True and isinstance(error, PermissionError) + finally: + (ws.work / "sub").chmod(0o700) + ws.cleanup() + + +@_NOT_ROOT +def test_a_solve_that_leaves_a_directory_unlistable_is_a_run_error_that_keeps_the_cost(tmp_path): + """#1361: the host solve reports a failed listing as the cell's error and keeps the cost.""" + obj = {"type": "result", "subtype": "success", "num_turns": 3, "total_cost_usd": 0.1, + "usage": {"output_tokens": 50}, "modelUsage": {"claude-sonnet-4-5": {"costUSD": 0.1}}} + held: list[Path] = [] + + def claude(call): + (call.cwd / "sub").mkdir() + (call.cwd / "sub" / "a.txt").write_text("written", encoding="utf-8") + (call.cwd / "sub").chmod(0o111) + held.append(call.cwd.parent) + return reply(json.dumps(obj)) + + task = load_task(_content_checkout(tmp_path)) + try: + result = create_harness("docker-claude-host", runner=_docker_cli(solver=claude)).run( + task, output_dir=tmp_path / "out") + finally: + (held[0] / "work" / "sub").chmod(0o700) + shutil.rmtree(held[0]) + assert result.returncode == 1 and result.reward is None and result.passed is False + assert result.metrics["error"].startswith("PermissionError: ") and "sub" in result.metrics["error"] + assert result.metrics["cost_usd"] == 0.1 + + def test_run_probe_timeout_raises_and_runs_with_exactly_the_agent_env(tmp_path, monkeypatch): """A hung probe check showed nothing closed: the caller records every class untested.""" from dokimi import process diff --git a/dokimi/tests/test_repo_run_guidance.py b/dokimi/tests/test_repo_run_guidance.py index 207bd6a7a9..4eb2b63309 100644 --- a/dokimi/tests/test_repo_run_guidance.py +++ b/dokimi/tests/test_repo_run_guidance.py @@ -7,9 +7,12 @@ import json import ntpath +import os import subprocess from types import SimpleNamespace +import pytest + from dokimi.repos import held_guidance as held_module from dokimi.repos import parse_manifest from dokimi.repos.held_guidance import HeldGuidance, held_guidance @@ -140,3 +143,23 @@ def test_guidance_read_leaves_out_a_file_the_arm_removed(setup, monkeypatch): # monkeypatch.setenv("FAKE_TOOL_USES", json.dumps(calls)) _run(setup, "--arm", "guidance:none", "--task", "fix_add") assert _process(setup, "guidance:none")["guidance_read"] == [] + + +@pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") +@pytest.mark.parametrize("mode", [0o111, 0o644]) +def test_a_workspace_directory_that_cannot_be_listed_raises_instead_of_dropping_its_links(tmp_path, mode): + """#1363: a directory HeldGuidance cannot list (no r) or whose entries it cannot stat (no x) raises its OSError.""" + ws = tmp_path / "workspace" + (ws / "sub").mkdir(parents=True) + (ws / "sub" / "AGENTS.md").write_text("s\n") + (ws / "sub" / "l").symlink_to("AGENTS.md") + (ws / "top").symlink_to("sub", target_is_directory=True) + subprocess.run(["git", "init", "-q", str(ws)], check=True) + subprocess.run(["git", "-C", str(ws), "add", "-A"], check=True) + assert sorted(HeldGuidance(ws, []).links) == [os.path.join(os.path.realpath(ws), n) for n in ("sub/l", "top")] + (ws / "sub").chmod(mode) + try: + with pytest.raises(PermissionError, match="sub"): + HeldGuidance(ws, []) + finally: + (ws / "sub").chmod(0o700) diff --git a/dokimi/tests/test_repo_typecheck_grader.py b/dokimi/tests/test_repo_typecheck_grader.py index 30f7b8edca..0ffab0031d 100644 --- a/dokimi/tests/test_repo_typecheck_grader.py +++ b/dokimi/tests/test_repo_typecheck_grader.py @@ -826,3 +826,58 @@ def test_a_dot_directory_with_a_listed_file_is_still_read(tmp_path): os.symlink(tmp_path, run / "workspace" / ".tools" / "out") with pytest.raises(ValueError, match="outside the workspace"): typecheck.grade(task, tmp_path, "", run) + + +_NOT_ROOT = pytest.mark.skipif(not hasattr(os, "geteuid") or os.geteuid() == 0, reason="root lists a mode 111 directory") + + +@_NOT_ROOT +def test_a_workspace_directory_that_cannot_be_listed_is_a_grading_error_not_a_smaller_workspace(tmp_path): + """#1362: _reachable raises for an unlistable workspace directory; main.grade reports a run not graded.""" + run = _run(tmp_path, {"pkg/__init__.py": "", "pkg/api.py": CLEAN, "sub/json.pyi": ""}, _task()) + assert typecheck.grade(_task(), tmp_path, "", run)["n_suppressions"] == 1 + (run / "workspace" / "sub").chmod(0o111) + try: + with pytest.raises(PermissionError, match="sub"): + typecheck.grade(_task(), tmp_path, "", run) + graded = main.grade("typecheck", tmp_path, run) + finally: + (run / "workspace" / "sub").chmod(0o700) + assert graded["pass"] is None and graded["errors"][0].startswith("PermissionError: ") + + +@_NOT_ROOT +def test_a_dot_directory_that_cannot_be_listed_is_not_walked_so_it_does_not_fail_the_grade(tmp_path): + """#1362: the pruned dot directories stay out of the walk, so an unlistable .venv raises nothing.""" + run = _run(tmp_path, {"pkg/__init__.py": "", "pkg/api.py": CLEAN, ".venv/lib/x.pyi": ""}, _task()) + (run / "workspace" / ".venv").chmod(0o111) + try: + result = typecheck.grade(_task(), tmp_path, "", run) + finally: + (run / "workspace" / ".venv").chmod(0o700) + assert result["pass"] is True and result["n_suppressions"] == 0 + + +@_NOT_ROOT +@pytest.mark.skipif(sys.platform == "win32", reason="a symbolic link needs privileges on Windows") +def test_the_oracle_refuses_a_reference_directory_that_cannot_be_listed_as_a_value_error(tmp_path): + """#1362: the oracle's ValueError of the reference/ paragraph of docs/repo-evaluation-contract.md, for a link and for a directory it cannot list.""" + task_dir = tmp_path / "task" + (task_dir / "reference" / "sub").mkdir(parents=True) + (task_dir / "reference" / "sub" / "f.py").write_text(CLEAN, encoding="utf-8") + os.symlink("f.py", task_dir / "reference" / "sub" / "link") + run = _run(tmp_path, {"pkg/api.py": WRONG}, _task()) + with pytest.raises(ValueError, match="reference/sub/link is a symbolic link"): + typecheck.oracle(_task(), task_dir, run) + (task_dir / "reference" / "sub").chmod(0o111) + try: + with pytest.raises(ValueError, match="reference/sub cannot be listed: Permission denied"): + main.oracle("typecheck", task_dir, run) + finally: + (task_dir / "reference" / "sub").chmod(0o700) + (task_dir / "reference").chmod(0o111) + try: + with pytest.raises(ValueError, match=r"^reference cannot be listed: Permission denied"): + typecheck.oracle(_task(), task_dir, run) + finally: + (task_dir / "reference").chmod(0o700)