diff --git a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md new file mode 100644 index 000000000..f41c94f5d --- /dev/null +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -0,0 +1,5 @@ +### Fixed + +- **`memory lint` refuses a memory directory it cannot list.** `read_claude_memory` found the topic files with a glob, which gives nothing for a directory without list permission, so the store linted as an empty one, with no topic files and no findings. It now exits 2 with `: cannot list the memory directory: `. A missing or non-directory path still gives `not a directory` ([#1506](https://github.com/intel/dokimi/issues/1506)). +- **`trace` names a session's `subagents` directory it cannot list.** `subagent_files` listed the transcripts with a glob, so such a directory read as no subagents and their tool calls were missing from the session. It now raises `SessionError` (`cannot read : `); `read_session_tree` keeps the parent session's events and records the error on the session, so `trace prefilter` warns on stderr and reports the status `partial`. A session with no `subagents` directory is unchanged ([#1508](https://github.com/intel/dokimi/issues/1508)). +- **The BenchFlow and Harbor result readers name a jobs or job directory they cannot list.** `rollout_dirs`, `rollout_results` and `read_harbor_job` found the rollouts with globs, which give nothing for such a directory, so the cell read as one that wrote no result (`harbor: no Harbor result.json`). The cell's `metrics.error` is now `benchflow: cannot list : ` or `harbor: cannot list : `, with no reward (after a BenchFlow timeout it follows the timeout error, after `; `); a missing jobs directory still has no rollout. A command cell's output directory is read the same way: a directory under it that cannot be listed gives `solver_error: no verdict: cannot list : `, where a reward file in it was missed and the exit code read as the reward. A directory that disappears while the output directory is walked gives the same `cannot list ` error instead of an output directory with no reward, and a reward file that is listed but cannot be read gives `solver_error: no verdict: cannot read : `. After a BenchFlow timeout, the rollout containers under the job directories that can be listed are still removed when another job directory cannot be listed ([#1509](https://github.com/intel/dokimi/issues/1509)). diff --git a/dokimi/docs/memory.md b/dokimi/docs/memory.md index 0e6661978..83a2a7a40 100644 --- a/dokimi/docs/memory.md +++ b/dokimi/docs/memory.md @@ -9,7 +9,7 @@ SPDX-License-Identifier: Apache-2.0 [#728](https://github.com/intel/dokimi/issues/728)). The first reader is Claude Code auto memory, `~/.claude/projects//memory/`: a `MEMORY.md` index whose first 200 lines or 25KB load at every session start, and one topic file per memory with YAML frontmatter (`name`, `description`, -`type`: user, feedback, project or reference). Files under `archive/` are read and counted, but not checked and never expected in the index. An `archive/` directory that cannot be listed is an input error (exit 2), not a smaller store. +`type`: user, feedback, project or reference). Files under `archive/` are read and counted, but not checked and never expected in the index. A memory directory, or its `archive/` directory, that cannot be listed is an input error (exit 2), not a smaller store. ## memory lint diff --git a/dokimi/docs/session-prefilter.md b/dokimi/docs/session-prefilter.md index 1c1f06bfe..07a3b5f03 100644 --- a/dokimi/docs/session-prefilter.md +++ b/dokimi/docs/session-prefilter.md @@ -105,7 +105,7 @@ This slice reads **Claude Code** session logs: JSON lines under (`/subagents/*.jsonl` next to `.jsonl`) is read as part of that session, its records merged in time order, so its tool calls count as the agent acting and `**/*.jsonl` still gives one session per log; a subagent transcript named without its session log is skipped with a -warning. A resumed or forked session log repeats the records it continues, with the same +warning. A `subagents` directory that cannot be listed is a skipped part of its session in the same way (`cannot read : ` on stderr, the session's own records kept, `status` `partial`, exit code 0). A resumed or forked session log repeats the records it continues, with the same `uuid`: logs that share a record are read as one session, each record once. A file that cannot be read, is a device (`/dev/zero`: "not a file") or holds no prompt and no tool call, is reported and the rest are still read; the exit code is 1 when any of the files named on the command line failed. A failed subagent transcript is not such a file: it is a skipped part of its session, named on stderr as a warning, and the exit code stays 0 (`status` `partial`). When no session can be read at all, the command refuses the input: exit 2, and with `--json` a `failed` document with an `input` error `no session could be read`. A guidance file that is a device exits 2, `guidance : not a file`; one that is missing, a directory or unreadable exits 2 too, `guidance : `. A line that is valid JSON but not an object, or a diff --git a/dokimi/dokimi/commands/context.py b/dokimi/dokimi/commands/context.py index 63a3863b4..78bdf7265 100644 --- a/dokimi/dokimi/commands/context.py +++ b/dokimi/dokimi/commands/context.py @@ -245,7 +245,12 @@ def _read_sessions(names: list[str], dropped: list | None = None) -> tuple[list, from dokimi.context.session_log import SessionError, merge_repeats, read_session_tree, subagent_files paths = _session_paths(names) - folded = {os.path.realpath(sub) for path in paths for sub in subagent_files(Path(path))} + folded: set[str] = set() + for path in paths: + try: + folded.update(os.path.realpath(sub) for sub in subagent_files(Path(path))) + except SessionError: # read_session_tree below reports the directory + pass loaded, failed = [], False for path in paths: if os.path.realpath(path) in folded: # read with its session diff --git a/dokimi/dokimi/context/session_log.py b/dokimi/dokimi/context/session_log.py index ff98ebeb6..a92b79a7c 100644 --- a/dokimi/dokimi/context/session_log.py +++ b/dokimi/dokimi/context/session_log.py @@ -25,6 +25,7 @@ from pathlib import Path from typing import Any +from dokimi.digest_entries import children_matching from dokimi.text_spans import replace_pairs from dokimi.files import InputError, refuse_device @@ -85,14 +86,27 @@ def read_session(path: Path) -> Session: def subagent_files(path: Path) -> list[Path]: - """The subagent transcripts Claude Code wrote for the session log ``path``.""" - return sorted((path.parent / path.stem / "subagents").glob("*.jsonl")) if path.suffix == ".jsonl" else [] + """The subagent transcripts Claude Code wrote for the session log ``path``: none when it has no ``subagents`` + directory; a ``subagents`` directory that cannot be listed raises SessionError.""" + if path.suffix != ".jsonl": + return [] + directory = path.parent / path.stem / "subagents" + try: + return children_matching(directory, "*.jsonl") + except OSError as exc: + raise SessionError(f"cannot read {directory}: {exc}") from exc def read_session_tree(path: Path) -> Session: - """A session log with its subagents' transcripts folded in, in time order: their tool calls are the agent acting.""" + """A session log with its subagents' transcripts folded in, in time order: their tool calls are the agent acting. + A ``subagents`` directory that cannot be listed is an error of the session, as an unreadable transcript is.""" session = read_session(path) - for sub in subagent_files(path): + try: + subagents = subagent_files(path) + except SessionError as exc: + add_error(session, str(exc)) + subagents = [] + for sub in subagents: try: session.events.extend(read_session(sub).events) except SessionError as exc: diff --git a/dokimi/dokimi/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 73a2d96f6..263eeada4 100644 --- a/dokimi/dokimi/harnesses/benchflow.py +++ b/dokimi/dokimi/harnesses/benchflow.py @@ -46,6 +46,7 @@ from .command import clear_run_dir from .harbor_export import harbor_view from .models import HarnessResult, OperationRecord, PreflightError +from .rollouts import look_for_rollouts, rollout_dirs, rollout_results # noqa: F401 - rollout_results: re-exported from .tasks import TaskSpec SKILL_MODE_NO_SKILL = "no-skill" @@ -190,8 +191,7 @@ def run( elapsed = time.time() - start (output_dir / "bench.log").write_text(stdout + stderr, encoding="utf-8") - results = rollout_results(jobs_dir) - n_attempts = len(rollout_dirs(jobs_dir)) + results, n_attempts, list_error = look_for_rollouts(jobs_dir) result_path = results[-1] if results else None result = _load_json(result_path) if result_path else None reward, metrics = parse_result(result) @@ -222,7 +222,7 @@ def run( # means bench wedged: no verdict, whatever an attempt left behind. reward = None metrics["timed_out"] = True - metrics["error"] = f"benchflow: bench killed after {timeout:.0f}s (outer budget)" + metrics["error"] = "; ".join(filter(None, (f"benchflow: bench killed after {timeout:.0f}s (outer budget)", list_error))) elif n_attempts > 1: # --retry-attempts 0 makes one cell one attempt; more means the # flag stopped working, and the row would mix attempts. @@ -236,8 +236,8 @@ def run( else: # bench failed before writing a rollout (a rubric it rejects, a # bad task, its own hard deadline): its stderr says why. - metrics["error"] = (f"no BenchFlow result.json (exit {returncode})" - + (f": {reason}" if reason else "")) + metrics["error"] = list_error or (f"no BenchFlow result.json (exit {returncode})" + + (f": {reason}" if reason else "")) if result: operations.append( OperationRecord( @@ -633,9 +633,11 @@ def remove_rollout_containers(jobs_dir: Path, runner: process.Runner = process.r run of the same task. """ removed: list[str] = [] - if not jobs_dir.is_dir(): - return removed - for rollout in rollout_dirs(jobs_dir): + try: + rollouts = rollout_dirs(jobs_dir) + except OSError: # a job dir that cannot be listed: glob skips it; look_for_rollouts names it in the cell's error + rollouts = sorted(p for p in jobs_dir.glob("*/*__*") if p.is_dir()) + for rollout in rollouts: project = _compose_project_name(rollout.name) # Bounded like BenchFlow's own _force_kill_project: a wedged daemon # must not hang the sweep after we already gave up on bench. @@ -756,21 +758,6 @@ def skill_loads(rollout_dir: Path, reported: Optional[int], *, return out -def rollout_dirs(jobs_dir: Path) -> list[Path]: - """Every rollout dir (``/__``) under a jobs dir, whether or not - it got as far as a ``result.json`` (a kill or a hard deadline leaves none).""" - if not jobs_dir.is_dir(): - return [] - return sorted(p for p in jobs_dir.glob("*/*__*") if p.is_dir()) - - -def rollout_results(jobs_dir: Path) -> list[Path]: - """Every rollout ``result.json`` under a BenchFlow jobs dir, oldest first.""" - if not jobs_dir.is_dir(): - return [] - return sorted(jobs_dir.glob("*/*/result.json"), key=lambda p: p.stat().st_mtime) - - def _subprocess_env(extra: dict[str, str], agent: Optional[str] = None, runner: process.Runner = process.run) -> dict[str, str]: """The env for ``bench``: behind a proxy, both ``no_proxy`` spellings get one diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index abfe8e688..0c352c017 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -7,10 +7,12 @@ import json import math +import os import shlex import shutil import time from dataclasses import dataclass, field +from os.path import normcase from pathlib import Path from typing import Any @@ -20,6 +22,7 @@ from .models import HarnessResult, OperationRecord from .operations import load_operations from .harbor_export import harbor_view +from .rollouts import cannot_list, harbor_results from .tasks import TaskSpec, harbor_task_problem from .verifier_reward import _parse_reward_text, primary_reward, reward_in_file @@ -154,12 +157,7 @@ def run( given_dir / Path(harbor_metrics["result_json"]).relative_to(output_dir)) passed = reward is not None and reward >= 1.0 else: - # A printed reward is no verdict from a command that never ran or was killed. - printed = (stdout, stderr) if not _never_finished(returncode) else ("", "") - reward = _find_reward(output_dir, *printed) - if reward is None: - reward = _exit_code_reward(returncode, output_dir) - harbor_metrics = _no_verdict(reward, returncode, output_dir) + reward, harbor_metrics = _command_verdict(output_dir, returncode, stdout, stderr) passed = reward is not None and reward >= 1.0 metrics: dict[str, Any] = { @@ -255,11 +253,13 @@ def read_harbor_job(jobs_dir: Path | None, returncode: int) -> tuple[float | Non """ if jobs_dir is None: return None, {"error": "harbor: no output dir, so no Harbor result.json to read"} - trials = sorted(jobs_dir.glob("*/*/result.json")) + try: + trials, has_job_result = harbor_results(jobs_dir) + except OSError as exc: # not "no result.json": the jobs could not be looked through + return None, {"n_trials": 0, "error": f"harbor: {cannot_list(exc, jobs_dir)}"} metrics: dict[str, Any] = {"n_trials": len(trials)} if not trials: - found = "a job result.json but no trial result.json" if any(jobs_dir.glob("*/result.json")) \ - else "no Harbor result.json" + found = "a job result.json but no trial result.json" if has_job_result else "no Harbor result.json" metrics["error"] = f"harbor: {found} (exit {returncode})" return None, metrics if len(trials) > 1: @@ -472,22 +472,61 @@ def _no_verdict(reward: float | None, returncode: int, output_dir: Path | None) return {"solver_error": f"no verdict: exit {returncode}{no_reward}"} +class _UnreadableReward(Exception): + """A reward file that is listed but cannot be read, not one that cannot be listed.""" + + +def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stderr: str) -> tuple[float | None, dict[str, Any]]: + """``(reward, metrics)`` of a command cell. A directory of the output dir that cannot be listed is no verdict + that names it: a reward file in it would be missed, and the exit code read as the reward.""" + # A printed reward is no verdict from a command that never ran or was killed. + printed = (stdout, stderr) if not _never_finished(returncode) else ("", "") + try: + reward = _find_reward(output_dir, *printed) + if reward is None: + reward = _exit_code_reward(returncode, output_dir) + return reward, _no_verdict(reward, returncode, output_dir) + except _UnreadableReward as exc: + return None, {"solver_error": f"no verdict: {exc}"} + except OSError as exc: + return None, {"solver_error": f"no verdict: {cannot_list(exc, output_dir)}"} + return reward, {} + + +def _reward_files(output_dir: Path) -> list[Path]: + """The ``reward.txt`` files under ``output_dir``, then its ``reward.json`` files, each sorted: what ``rglob`` finds + (names compared as the platform's file system does, so ``REWARD.TXT`` counts on Windows), except that a + directory that cannot be listed, or sit behind one that cannot be searched, raises its OSError, and so does one + that vanishes mid-walk (an absent ``output_dir``, or one that is no directory, has no reward files).""" + from dokimi.digest_entries import listed_entries + + try: + entries = listed_entries(output_dir) + except (FileNotFoundError, NotADirectoryError) as exc: + if os.fspath(exc.filename) != os.fspath(output_dir): + raise # a directory under it went away mid-walk: the walk is incomplete, not the output dir absent + entries = [] + return [path for name in ("reward.txt", "reward.json") for path in sorted(e for e in entries if normcase(e.name) == name)] + + def _has_reward_file(output_dir: Path | None) -> bool: if not output_dir: return False - return any(next(output_dir.rglob(name), None) for name in ("reward.txt", "reward.json")) + return bool(_reward_files(output_dir)) def _find_reward(output_dir: Path | None, stdout: str, stderr: str) -> float | None: if output_dir: - candidates = sorted(output_dir.rglob("reward.txt")) + sorted( - output_dir.rglob("reward.json") - ) + candidates = _reward_files(output_dir) for path in candidates: if not path.is_file(): # a directory of that name holds no reward, like an empty file continue try: - return reward_in_file(path.name, path.read_bytes()) + data = path.read_bytes() + except OSError as exc: + raise _UnreadableReward(f"cannot read {path}: {exc.strerror or exc}") from exc + try: + return reward_in_file(normcase(path.name), data) except ValueError: # no reward in this one: the next file may have it continue if candidates: diff --git a/dokimi/dokimi/harnesses/rollouts.py b/dokimi/dokimi/harnesses/rollouts.py new file mode 100644 index 000000000..80d04031a --- /dev/null +++ b/dokimi/dokimi/harnesses/rollouts.py @@ -0,0 +1,59 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The rollout files of a BenchFlow or Harbor jobs dir (``///...``). + +A missing jobs dir has no rollout. A jobs dir or a job dir that cannot be listed raises its OSError, which names it, +where a glob gave nothing and the cell read as one that wrote no result (#1509). +""" + +from __future__ import annotations + +from pathlib import Path + +from dokimi.digest_entries import children_matching + + +def result_files(directory: Path) -> list[Path]: + """``directory//result.json`` for each child that holds an entry of that name, as ``directory.glob("*/result.json")`` + finds them, except that a directory that cannot be listed or a child that cannot be searched raises its OSError.""" + found = [] + for child in children_matching(directory, "*"): + try: + (child / "result.json").lstat() + except (FileNotFoundError, NotADirectoryError): + continue + found.append(child / "result.json") + return found + + +def rollout_dirs(jobs_dir: Path) -> list[Path]: + """Every rollout dir (``/__``) under a jobs dir, whether or not it got as far as a ``result.json`` + (a kill or a hard deadline leaves none).""" + return sorted(p for job in children_matching(jobs_dir, "*") for p in children_matching(job, "*__*") if p.is_dir()) + + +def rollout_results(jobs_dir: Path) -> list[Path]: + """Every rollout ``result.json`` under a BenchFlow jobs dir, oldest first.""" + found = [path for job in children_matching(jobs_dir, "*") for path in result_files(job)] + return sorted(found, key=lambda p: p.stat().st_mtime) + + +def harbor_results(jobs_dir: Path) -> tuple[list[Path], bool]: + """``(//result.json files, whether a /result.json exists)`` under a Harbor jobs dir.""" + jobs = children_matching(jobs_dir, "*") + return sorted(path for job in jobs for path in result_files(job)), bool(result_files(jobs_dir)) + + +def look_for_rollouts(jobs_dir: Path) -> tuple[list[Path], int, str | None]: + """``(result.json files, rollout dir count, error)``: a jobs or job dir that cannot be listed is the cell's error + naming it, not a cell with no result.json.""" + try: + return rollout_results(jobs_dir), len(rollout_dirs(jobs_dir)), None + except OSError as exc: + return [], 0, f"benchflow: {cannot_list(exc, jobs_dir)}" + + +def cannot_list(exc: OSError, fallback: Path | None) -> str: + """``cannot list : `` for the OSError of a listing: the directory it names, else ``fallback``.""" + return f"cannot list {exc.filename or fallback}: {exc.strerror or exc}" diff --git a/dokimi/dokimi/memory/store.py b/dokimi/dokimi/memory/store.py index 6abde0af1..fe6a8a829 100644 --- a/dokimi/dokimi/memory/store.py +++ b/dokimi/dokimi/memory/store.py @@ -23,7 +23,7 @@ import yaml from dokimi.code_spans import LINE_BREAK, CodeSpan, CodeSpanScanner -from dokimi.digest_entries import listed_entries +from dokimi.digest_entries import children_matching, listed_entries from dokimi.memory.blocks import ( FENCE as _FENCE, close_ahead, @@ -745,7 +745,11 @@ def read_claude_memory(root: str | Path) -> MemoryStore: raise MemoryStoreError(f"{root}: has {marker} and no {INDEX_NAME}, so it looks like a repository, " "not a memory directory; pass the directory that holds the memory files") index = _entry(root, index_path, False) if index_path.is_file() else None - entries = [_entry(root, p, False) for p in sorted(root.glob("*.md")) if p.name != INDEX_NAME and p.is_file()] + try: + topics = children_matching(root, "*.md") + except OSError as exc: # the store would lint as one with no topic files + raise MemoryStoreError(f"{root}: cannot list the memory directory: {exc}") from exc + entries = [_entry(root, p, False) for p in topics if p.name != INDEX_NAME and p.is_file()] archive = root / ARCHIVE_DIR if archive.is_dir(): try: diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index fd36c5e58..79887eae7 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -1,6 +1,6 @@ { "files": { - "dokimi/harnesses/benchflow.py": {"lines": 873, "rationale": "#1389: the pack check refuses a skills root it cannot list, in 7 lines; the file is split in its own PR"}, + "dokimi/harnesses/benchflow.py": {"lines": 860, "rationale": "#1389: the pack check refuses a skills root it cannot list, in 7 lines; the file is split in its own PR"}, "dokimi/llm.py": {"lines": 977, "rationale": "grew on main in #180 (replay a stored retry) after #93 seeded this baseline; split it in its own PR"}, "dokimi/report/model_compare.py": {"lines": 1102, "rationale": "grew on main in #73 (judge-validity --context stored) before the ratchet landed; split it in its own PR"}, "tests/test_arm_runner.py": {"lines": 1175, "rationale": "pre-existing when the gate was introduced"}, @@ -29,7 +29,7 @@ "dokimi/gate/novelty_gate.py::evaluate_novelty": {"complexity": 27, "rationale": "grew on main in #72 and #101 before the ratchet landed; split it in its own PR"}, "dokimi/harnesses/benchflow.py::BenchflowHarness.run": {"complexity": 19}, "dokimi/harnesses/benchflow.py::skill_loads": {"complexity": 12}, - "dokimi/harnesses/command.py::CommandHarness.run": {"complexity": 15, "rationale": "pre-existing when the gate was introduced"}, + "dokimi/harnesses/command.py::CommandHarness.run": {"complexity": 14, "rationale": "pre-existing when the gate was introduced"}, "dokimi/harnesses/docker_solver.py::DockerSolverHarness.run": {"complexity": 14}, "dokimi/harnesses/registry.py::_create": {"complexity": 17, "rationale": "pre-existing when the gate was introduced"}, "dokimi/harnesses/skill_treatment.py::stream_stats": {"complexity": 16}, diff --git a/dokimi/tests/test_memory_store_unlistable.py b/dokimi/tests/test_memory_store_unlistable.py new file mode 100644 index 000000000..0f00d195c --- /dev/null +++ b/dokimi/tests/test_memory_store_unlistable.py @@ -0,0 +1,58 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1506: a memory directory that cannot be listed is an error naming it, not a store with no topic files.""" + +from __future__ import annotations + +import os +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from dokimi.cli import build_parser +from dokimi.memory import MemoryStoreError, read_claude_memory +from tests.cli_refusal import refusal + + +@contextmanager +def unlistable(path: Path): + """``path`` at mode 111 for the block: a process that is not root cannot list it.""" + path.chmod(0o111) + try: + try: + os.listdir(path) + except PermissionError: + yield + else: + pytest.skip("this process lists a mode 111 directory (root)") + finally: + path.chmod(0o700) + + +@pytest.fixture +def mem(tmp_path: Path) -> Path: + (tmp_path / "MEMORY.md").write_text("# Index\n- [A](a.md) - hook\n", encoding="utf-8") + (tmp_path / "a.md").write_text("---\nname: a\ndescription: about a\ntype: project\n---\n\nfact\n", encoding="utf-8") + return tmp_path + + +def test_a_memory_directory_that_cannot_be_listed_is_refused_naming_it(mem: Path): + assert [e.path for e in read_claude_memory(mem).entries] == ["a.md"] + with unlistable(mem), pytest.raises(MemoryStoreError, match=r"cannot list the memory directory: .*Permission denied") as err: + read_claude_memory(mem) + assert str(err.value).startswith(f"{mem}: ") + + +def test_a_missing_or_non_directory_root_keeps_its_not_a_directory_error(mem: Path): + for root in (mem / "missing", mem / "a.md"): + with pytest.raises(MemoryStoreError, match="not a directory"): + read_claude_memory(root) + + +def test_memory_lint_ends_in_an_input_error_for_a_directory_it_cannot_list(mem: Path): + args = build_parser().parse_args(["memory", "lint", str(mem)]) + with unlistable(mem), refusal() as out: + args.func(args) + assert out.code == 2 and f"Error: {mem}: cannot list the memory directory: " in out.err diff --git a/dokimi/tests/test_rollout_readers_unlistable.py b/dokimi/tests/test_rollout_readers_unlistable.py new file mode 100644 index 000000000..1d1f77637 --- /dev/null +++ b/dokimi/tests/test_rollout_readers_unlistable.py @@ -0,0 +1,258 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1509: a jobs or job directory that cannot be listed is an error naming it, not a run with no rollout. + +The reward files of a command cell's output dir are read the same way: a directory under it that cannot be listed is +the cell's error, not a cell whose exit code is the reward.""" + +from __future__ import annotations + +import ntpath +import os +import posixpath +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from dokimi.harnesses import command, load_task +from dokimi.harnesses.benchflow import remove_rollout_containers, rollout_dirs, rollout_results +from dokimi.harnesses.command import _command_verdict, _reward_files, read_harbor_job +from dokimi.harnesses.registry import create_harness +from dokimi.harnesses.rollouts import cannot_list, look_for_rollouts +from dokimi.process import FakeRunner, reply +from tests.test_benchflow_harness import _Bench, _task + + +@contextmanager +def unlistable(path: Path): + """``path`` at mode 111 for the block: a process that is not root cannot list it.""" + path.chmod(0o111) + try: + try: + os.listdir(path) + except PermissionError: + yield + else: + pytest.skip("this process lists a mode 111 directory (root)") + finally: + path.chmod(0o700) + + +@pytest.fixture +def jobs(tmp_path: Path) -> Path: + (tmp_path / "jobs" / "j1" / "t__abc").mkdir(parents=True) + (tmp_path / "jobs" / "j1" / "t__abc" / "result.json").write_text("{}", encoding="utf-8") + (tmp_path / "jobs" / "j1" / "stray__file").write_text("not a rollout", encoding="utf-8") + return tmp_path / "jobs" + + +def test_rollout_readers_list_the_rollouts_and_refuse_a_directory_they_cannot_list(jobs: Path): + assert [p.name for p in rollout_dirs(jobs)] == ["t__abc"] + assert [p.name for p in rollout_results(jobs)] == ["result.json"] + for directory in (jobs, jobs / "j1"): + with unlistable(directory): + for reader in (rollout_dirs, rollout_results): + with pytest.raises(PermissionError, match=str(directory)): + reader(jobs) + + +def test_rollout_readers_return_nothing_for_a_missing_jobs_directory(jobs: Path): + assert rollout_dirs(jobs / "missing") == [] and rollout_results(jobs / "missing") == [] + + +def test_a_cleanup_after_a_timeout_goes_on_when_the_jobs_directory_cannot_be_listed(jobs: Path): + with unlistable(jobs): + assert remove_rollout_containers(jobs) == [] + + +def test_a_cleanup_after_a_timeout_removes_the_rollouts_of_the_job_directories_it_can_list(jobs: Path): + (jobs / "j2").mkdir() + fake = FakeRunner(lambda call: reply("c1\n" if call.argv[1] == "ps" else "")) + with unlistable(jobs / "j2"): + assert remove_rollout_containers(jobs, runner=fake) == ["t__abc"] + + +def test_a_command_cell_whose_output_subdirectory_vanishes_mid_walk_has_no_verdict(tmp_path: Path, monkeypatch): + out = tmp_path / "out" + (out / "gone").mkdir(parents=True) + (out / "reward.txt").write_text("0", encoding="utf-8") + real_scandir = os.scandir + + def scandir(path): + if os.fspath(path) == str(out / "gone"): + raise FileNotFoundError(2, "No such file or directory", os.fspath(path)) + return real_scandir(path) + + monkeypatch.setattr(os, "scandir", scandir) + reward, metrics = _command_verdict(out, 0, "", "") + assert reward is None + assert metrics == {"solver_error": f"no verdict: cannot list {out / 'gone'}: No such file or directory"} + + +def test_a_command_cell_with_an_unreadable_reward_file_says_it_cannot_read_it(tmp_path: Path): + (tmp_path / "reward.txt").write_text("1", encoding="utf-8") + (tmp_path / "reward.txt").chmod(0o000) + try: + try: + (tmp_path / "reward.txt").read_bytes() + except PermissionError: + reward, metrics = _command_verdict(tmp_path, 0, "", "") + else: + pytest.skip("this process reads a mode 000 file (root)") + finally: + (tmp_path / "reward.txt").chmod(0o600) + assert reward is None + assert metrics == {"solver_error": f"no verdict: cannot read {tmp_path / 'reward.txt'}: Permission denied"} + + +def test_a_read_error_with_no_reason_text_is_worded_by_the_error_itself(tmp_path: Path, monkeypatch): + (tmp_path / "reward.txt").write_text("1", encoding="utf-8") + + def broken(self): + raise OSError("boom") + + monkeypatch.setattr(Path, "read_bytes", broken) + assert _command_verdict(tmp_path, 0, "", "") == (None, {"solver_error": f"no verdict: cannot read {tmp_path / 'reward.txt'}: boom"}) + + +@pytest.mark.parametrize("name", ["jobs", "j1"]) +def test_a_harbor_cell_reports_the_directory_it_could_not_list(jobs: Path, name: str): + directory = jobs if name == "jobs" else jobs / "j1" + with unlistable(directory): + reward, metrics = read_harbor_job(jobs, 0) + assert reward is None and metrics == {"n_trials": 0, "error": f"harbor: cannot list {directory}: Permission denied"} + + +def test_a_harbor_cell_keeps_its_other_results(jobs: Path, tmp_path: Path): + assert read_harbor_job(jobs, 0)[1]["n_trials"] == 1 + assert read_harbor_job(jobs / "missing", 0) == (None, {"n_trials": 0, "error": "harbor: no Harbor result.json (exit 0)"}) + (tmp_path / "job-only" / "j").mkdir(parents=True) + (tmp_path / "job-only" / "j" / "result.json").write_text("{}", encoding="utf-8") + assert read_harbor_job(tmp_path / "job-only", 3)[1]["error"] == "harbor: a job result.json but no trial result.json (exit 3)" + + +def test_a_command_cell_names_a_directory_it_could_not_list_instead_of_reading_its_exit_code_as_the_reward(tmp_path: Path): + out = tmp_path / "out" + (out / "sub" / "deep").mkdir(parents=True) + (out / "sub" / "deep" / "reward.txt").write_text("0", encoding="utf-8") + assert _command_verdict(out, 0, "", "") == (0.0, {}) + with unlistable(out / "sub"): + reward, metrics = _command_verdict(out, 0, "", "") + assert reward is None + assert metrics == {"solver_error": f"no verdict: cannot list {out / 'sub'}: Permission denied"} + + +def test_a_command_cell_whose_output_dir_sits_behind_an_unsearchable_directory_has_no_verdict(tmp_path: Path, monkeypatch): + parent = tmp_path / "parent" + (parent / "out").mkdir(parents=True) + (parent / "out" / "reward.txt").write_text("0", encoding="utf-8") + # Python 3.14 Path.is_dir() answers False for a path it cannot stat because of permissions + monkeypatch.setattr(Path, "is_dir", lambda self, **kw: os.path.isdir(self)) + parent.chmod(0o600) + try: + try: + os.stat(parent / "out") + except PermissionError: + reward, metrics = _command_verdict(parent / "out", 0, "", "") + else: + pytest.skip("this process searches a mode 600 directory (root)") + finally: + parent.chmod(0o700) + assert reward is None + assert metrics == {"solver_error": f"no verdict: cannot list {parent / 'out'}: Permission denied"} + + +def test_a_file_as_the_output_dir_holds_no_reward_file(tmp_path: Path): + (tmp_path / "f").write_text("0", encoding="utf-8") + assert _reward_files(tmp_path / "f") == [] + + +def test_a_command_cell_with_no_reward_file_keeps_its_exit_code_verdict(tmp_path: Path): + (tmp_path / "out").mkdir() + for output_dir in (tmp_path / "out", tmp_path / "missing", None): + assert _command_verdict(output_dir, 0, "", "") == (1.0, {}) + assert _command_verdict(output_dir, 1, "", "") == (0.0, {}) + + +@pytest.mark.parametrize("name", ["jobs", "j1"]) +def test_a_benchflow_cell_reports_the_directory_it_could_not_list(tmp_path: Path, name: str): + def bench(cmd, cwd): + jobs = Path(cmd[cmd.index("--jobs-dir") + 1]) + rollout = jobs / "j1" / "sb-task__0" + rollout.mkdir(parents=True) + (rollout / "result.json").write_text("{}", encoding="utf-8") + (jobs if name == "jobs" else jobs / "j1").chmod(0o111) + return 0, "", "" + + (tmp_path / "probe").mkdir() + with unlistable(tmp_path / "probe"): # skips when this process lists a mode 111 directory (root) + task = load_task(_task(tmp_path)) + harness = create_harness("benchflow:claude-agent-acp", runner=_Bench(bench)) + directory = tmp_path / "o" / "jobs" if name == "jobs" else tmp_path / "o" / "jobs" / "j1" + try: + res = harness.run(task, model="m", output_dir=tmp_path / "o") + finally: + for path in (tmp_path / "o" / "jobs", tmp_path / "o" / "jobs" / "j1"): + path.chmod(0o700) + assert res.reward is None and res.metrics["n_attempts"] == 0 + assert res.metrics["error"] == f"benchflow: cannot list {directory}: Permission denied" + + +def test_a_benchflow_timeout_keeps_the_directory_it_could_not_list_in_its_error(tmp_path: Path): + def bench(cmd, cwd): + jobs = Path(cmd[cmd.index("--jobs-dir") + 1]) + (jobs / "j1" / "sb-task__0").mkdir(parents=True) + jobs.chmod(0o111) + return 124, "", "", True + + (tmp_path / "probe").mkdir() + with unlistable(tmp_path / "probe"): + task = load_task(_task(tmp_path)) + harness = create_harness("benchflow:claude-agent-acp", runner=_Bench(bench)) + try: + res = harness.run(task, model="m", output_dir=tmp_path / "o") + finally: + (tmp_path / "o" / "jobs").chmod(0o700) + assert res.metrics["timed_out"] is True + assert res.metrics["error"] == (f"benchflow: bench killed after {res.metrics['timeout_sec']:.0f}s (outer budget); " + f"benchflow: cannot list {tmp_path / 'o' / 'jobs'}: Permission denied") + + +def test_a_reward_file_is_found_by_the_platforms_name_comparison_and_read_by_its_canonical_name(tmp_path: Path, monkeypatch): + (tmp_path / "REWARD.TXT").write_text("0", encoding="utf-8") + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "REWARD.JSON").write_text('{"reward": 0.5}', encoding="utf-8") + monkeypatch.setattr(command, "normcase", posixpath.normcase) + assert _reward_files(tmp_path) == [] + assert _command_verdict(tmp_path, 0, "", "") == (1.0, {}) + monkeypatch.setattr(command, "normcase", ntpath.normcase) + assert [p.name for p in _reward_files(tmp_path)] == ["REWARD.TXT", "REWARD.JSON"] + assert _command_verdict(tmp_path, 0, "", "") == (0.0, {}) + (tmp_path / "REWARD.TXT").unlink() + assert _command_verdict(tmp_path, 0, "", "") == (0.5, {}) + + +def test_the_rollout_lookup_gives_the_error_with_no_result_and_no_attempt(jobs: Path): + assert look_for_rollouts(jobs) == ([jobs / "j1" / "t__abc" / "result.json"], 1, None) + with unlistable(jobs): + assert look_for_rollouts(jobs) == ([], 0, f"benchflow: cannot list {jobs}: Permission denied") + + +def test_a_listing_error_names_its_directory_else_the_one_asked_for_and_gives_its_reason(): + assert cannot_list(PermissionError(13, "Permission denied", "/x/j1"), Path("/x")) == "cannot list /x/j1: Permission denied" + assert cannot_list(OSError("boom"), Path("/x")) == "cannot list /x: boom" + + +def test_the_reward_files_are_the_reward_txt_files_then_the_reward_json_files_at_any_depth(tmp_path: Path): + for rel in ("a/reward.txt", "reward.txt", "b/c/reward.json", "notes.txt", "reward.md"): + (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / rel).write_text("1", encoding="utf-8") + assert [p.relative_to(tmp_path).as_posix() for p in _reward_files(tmp_path)] == ["a/reward.txt", "reward.txt", "b/c/reward.json"] + assert _reward_files(tmp_path / "missing") == [] + + +def test_a_printed_reward_counts_unless_the_command_never_finished(tmp_path: Path): + assert _command_verdict(tmp_path, 1, "reward: 0.5", "") == (0.5, {}) + assert _command_verdict(tmp_path, 127, "reward: 0.5", "") == (None, {"solver_error": "no verdict: exit 127"}) diff --git a/dokimi/tests/test_session_subagents_unlistable.py b/dokimi/tests/test_session_subagents_unlistable.py new file mode 100644 index 000000000..015cfb411 --- /dev/null +++ b/dokimi/tests/test_session_subagents_unlistable.py @@ -0,0 +1,72 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""#1508: a session's ``subagents`` directory that cannot be listed is an error naming it, not no subagents.""" + +from __future__ import annotations + +import os +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from dokimi.commands.context import _read_sessions +from dokimi.context.session_log import SessionError, read_session_tree, subagent_files +from tests.test_context_prefilter import _prompt, _tool, _write + + +@contextmanager +def unlistable(path: Path): + """``path`` at mode 111 for the block: a process that is not root cannot list it.""" + path.chmod(0o111) + try: + try: + os.listdir(path) + except PermissionError: + yield + else: + pytest.skip("this process lists a mode 111 directory (root)") + finally: + path.chmod(0o700) + + +@pytest.fixture +def log(tmp_path: Path) -> Path: + _write(tmp_path / "s.jsonl", [_prompt("push the branch"), _tool("Bash", command="ls")]) + (tmp_path / "s" / "subagents").mkdir(parents=True) + _write(tmp_path / "s" / "subagents" / "a.jsonl", [_tool("Bash", command="make ci-local")]) + (tmp_path / "s" / "subagents" / "notes.txt").write_text("not a transcript\n", encoding="utf-8") + return tmp_path / "s.jsonl" + + +def test_subagent_files_list_the_transcripts_and_refuse_a_directory_they_cannot_list(log: Path): + directory = log.parent / "s" / "subagents" + assert [p.name for p in subagent_files(log)] == ["a.jsonl"] + with unlistable(directory), pytest.raises(SessionError, match=r"cannot read .*subagents: .*Permission denied") as err: + subagent_files(log) + assert str(err.value).startswith(f"cannot read {directory}: ") + + +def test_a_session_with_no_subagents_directory_has_no_subagents(log: Path): + assert subagent_files(log.parent / "other.jsonl") == [] + assert subagent_files(log.parent / "s.txt") == [] + (log.parent / "s" / "subagents" / "a.jsonl").unlink() + (log.parent / "s" / "subagents" / "notes.txt").unlink() + (log.parent / "s" / "subagents").rmdir() + assert subagent_files(log) == [] + + +def test_the_session_tree_keeps_the_parent_and_records_the_directory_it_could_not_list(log: Path): + assert [e.command for e in read_session_tree(log).events] == ["", "ls", "make ci-local"] + with unlistable(log.parent / "s" / "subagents"): + session = read_session_tree(log) + assert [e.command for e in session.events] == ["", "ls"] + assert len(session.errors) == 1 and session.errors[0].startswith(f"cannot read {log.parent / 's' / 'subagents'}: ") + + +def test_trace_reads_the_session_and_warns_about_a_subagents_directory_it_cannot_list(log: Path, capsys): + with unlistable(log.parent / "s" / "subagents"): + sessions, failed = _read_sessions([str(log)]) + assert failed is False and [e.command for e in sessions[0].events] == ["", "ls"] + assert f"warning: {log}: cannot read {log.parent / 's' / 'subagents'}: " in capsys.readouterr().err