From 5e23184fb56df1dbb42d78d03bd2d8799efe8731 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 10:52:15 +0000 Subject: [PATCH 1/6] fix(memory): memory lint refuses a memory directory it cannot list (#1506) read_claude_memory found the topic files with root.glob("*.md"), which gives nothing for a directory without list permission (mode 111). The store then linted as one with no topic files, while the MEMORY.md index was still read, so memory lint reported its entries as dead links instead of saying the directory cannot be listed. The topic files are now listed with digest_entries.children_matching, and its OSError becomes MemoryStoreError(": cannot list the memory directory: "), worded like the archive's error. memory lint turns it into its usual input error (exit 2). A missing or non-directory root keeps its "not a directory" error. Signed-off-by: Anton Volkov --- ...20261204_120000_unlistable-root-readers.md | 3 + dokimi/docs/memory.md | 2 +- dokimi/dokimi/memory/store.py | 8 ++- dokimi/tests/test_memory_store_unlistable.py | 58 +++++++++++++++++++ 4 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 dokimi/changelog.d/20261204_120000_unlistable-root-readers.md create mode 100644 dokimi/tests/test_memory_store_unlistable.py 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..5cb781970 --- /dev/null +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -0,0 +1,3 @@ +### 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 one with no topic files and reported the `MEMORY.md` entries as dead links. 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)). 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/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/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 From 6229669cafbe7edd00264bc4d4c2bc6b224112e4 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 10:52:20 +0000 Subject: [PATCH 2/6] fix(trace): a subagents directory that cannot be listed is a session error, not no subagents (#1508) subagent_files found the transcripts of a session with (dir / "subagents").glob("*.jsonl"), which gives nothing for a directory without list permission (mode 111). read_session_tree then folded in no subagent, and their tool calls were missing from the session the trace commands read, with no word about it. The directory is now listed with digest_entries.children_matching, and its OSError raises SessionError("cannot read : "), as read_session does for the log itself. A missing subagents directory still means no subagents. read_session_tree keeps the parent's events and records the error on the session, as it does for a subagent transcript it cannot read, so trace prefilter warns and reports the status as partial. The folded-transcript pass of trace prefilter skips such a session and leaves the report to read_session_tree, so no traceback reaches the user. Signed-off-by: Anton Volkov --- ...20261204_120000_unlistable-root-readers.md | 1 + dokimi/docs/session-prefilter.md | 2 +- dokimi/dokimi/commands/context.py | 7 +- dokimi/dokimi/context/session_log.py | 22 ++++-- .../test_session_subagents_unlistable.py | 70 +++++++++++++++++++ 5 files changed, 96 insertions(+), 6 deletions(-) create mode 100644 dokimi/tests/test_session_subagents_unlistable.py diff --git a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md index 5cb781970..1da66bbbb 100644 --- a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -1,3 +1,4 @@ ### 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 one with no topic files and reported the `MEMORY.md` entries as dead links. 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)). 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/tests/test_session_subagents_unlistable.py b/dokimi/tests/test_session_subagents_unlistable.py new file mode 100644 index 000000000..c9681751b --- /dev/null +++ b/dokimi/tests/test_session_subagents_unlistable.py @@ -0,0 +1,70 @@ +# 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")]) + 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").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 From 19fb83fd5b50a2c039d2b731f1fec49dab40d3ae Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 10:52:26 +0000 Subject: [PATCH 3/6] fix(harnesses): a jobs or job directory that cannot be listed is the cell's error, not a run with no rollout (#1509) rollout_dirs, rollout_results and read_harbor_job found the rollouts with jobs_dir.glob("*/*__*"), glob("*/*/result.json") and glob("*/result.json"), which give nothing for a jobs directory or a job directory without list permission (mode 111). The cell was reported without a result, and read_harbor_job blamed a missing result ("harbor: no Harbor result.json (exit 0)"). Each level is now listed with digest_entries.children_matching, in the new harnesses/rollouts.py (rollout_dirs and rollout_results are still importable from benchflow). A missing jobs directory still has no rollout. An unlistable one raises its OSError, which names the directory; the BenchFlow cell reports it as "benchflow: cannot list : " and read_harbor_job as "harbor: cannot list : ", with no reward. The cleanup after a BenchFlow timeout goes on without removing containers, since the cell's error names the directory. The same cause in the command harness: _find_reward and _has_reward_file looked for reward.txt and reward.json with output_dir.rglob, which skips a directory it cannot list. A reward file in one was missed and the exit code was read as the reward (a reward.txt holding 0 under an unlistable directory scored 1.0 for exit 0). The files are now found with listed_entries, and the cell gets "solver_error: no verdict: cannot list : ". Signed-off-by: Anton Volkov --- ...20261204_120000_unlistable-root-readers.md | 1 + dokimi/dokimi/harnesses/benchflow.py | 29 +--- dokimi/dokimi/harnesses/command.py | 46 ++++-- dokimi/dokimi/harnesses/rollouts.py | 59 +++++++ dokimi/scripts/growth_baseline.json | 4 +- .../tests/test_rollout_readers_unlistable.py | 146 ++++++++++++++++++ 6 files changed, 249 insertions(+), 36 deletions(-) create mode 100644 dokimi/dokimi/harnesses/rollouts.py create mode 100644 dokimi/tests/test_rollout_readers_unlistable.py diff --git a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md index 1da66bbbb..95e61dc1e 100644 --- a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -2,3 +2,4 @@ - **`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 one with no topic files and reported the `MEMORY.md` entries as dead links. 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; 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 ([#1509](https://github.com/intel/dokimi/issues/1509)). diff --git a/dokimi/dokimi/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 73a2d96f6..46c27002e 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) @@ -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(): + try: + rollouts = rollout_dirs(jobs_dir) + except OSError: # the cell's error names the directory (look_for_rollouts) return removed - for rollout in rollout_dirs(jobs_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..f7ac7c39d 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -20,6 +20,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 +155,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 +251,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,17 +470,39 @@ def _no_verdict(reward: float | None, returncode: int, output_dir: Path | None) return {"solver_error": f"no verdict: exit {returncode}{no_reward}"} +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 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, + except that a directory that cannot be listed raises its OSError.""" + from dokimi.digest_entries import listed_entries + + entries = listed_entries(output_dir) if output_dir.is_dir() else [] + return [path for name in ("reward.txt", "reward.json") for path in sorted(e for e in entries if 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 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/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_rollout_readers_unlistable.py b/dokimi/tests/test_rollout_readers_unlistable.py new file mode 100644 index 000000000..417444158 --- /dev/null +++ b/dokimi/tests/test_rollout_readers_unlistable.py @@ -0,0 +1,146 @@ +# 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 os +from contextlib import contextmanager +from pathlib import Path + +import pytest + +from dokimi.harnesses import 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 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) == [] + + +@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_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_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"}) From 032345a945a6c2c0c4260457128c05d33ef97511 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Fri, 4 Dec 2026 23:59:15 +0000 Subject: [PATCH 4/6] fix(harnesses): keep the unlistable jobs directory in a timed-out BenchFlow error and match reward files by the platform's name rules A BenchFlow timeout set metrics.error to the outer-budget message and dropped the jobs directory the rollout lookup could not list, so nothing explained why containers may remain; the listing error now follows the timeout error after "; ". The command cell's reward lookup compared file names case-sensitively, so REWARD.TXT on Windows, which rglob found, was missed and the exit code read as the reward. Names are now compared with os.path.normcase and the reward file is parsed by its canonical name, so REWARD.JSON reaches the JSON parser. Signed-off-by: Anton Volkov --- ...20261204_120000_unlistable-root-readers.md | 2 +- dokimi/dokimi/harnesses/benchflow.py | 2 +- dokimi/dokimi/harnesses/command.py | 10 +++--- .../tests/test_rollout_readers_unlistable.py | 36 ++++++++++++++++++- 4 files changed, 43 insertions(+), 7 deletions(-) diff --git a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md index 95e61dc1e..6adb42a98 100644 --- a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -2,4 +2,4 @@ - **`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 one with no topic files and reported the `MEMORY.md` entries as dead links. 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; 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 ([#1509](https://github.com/intel/dokimi/issues/1509)). +- **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 ([#1509](https://github.com/intel/dokimi/issues/1509)). diff --git a/dokimi/dokimi/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 46c27002e..502537f3a 100644 --- a/dokimi/dokimi/harnesses/benchflow.py +++ b/dokimi/dokimi/harnesses/benchflow.py @@ -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. diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index f7ac7c39d..14349eb6c 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -11,6 +11,7 @@ import shutil import time from dataclasses import dataclass, field +from os.path import normcase from pathlib import Path from typing import Any @@ -486,12 +487,13 @@ def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stde 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, - except that a directory that cannot be listed raises its OSError.""" + """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 raises its OSError.""" from dokimi.digest_entries import listed_entries entries = listed_entries(output_dir) if output_dir.is_dir() else [] - return [path for name in ("reward.txt", "reward.json") for path in sorted(e for e in entries if e.name == name)] + 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: @@ -507,7 +509,7 @@ def _find_reward(output_dir: Path | None, stdout: str, stderr: str) -> float | N 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()) + return reward_in_file(normcase(path.name), path.read_bytes()) except ValueError: # no reward in this one: the next file may have it continue if candidates: diff --git a/dokimi/tests/test_rollout_readers_unlistable.py b/dokimi/tests/test_rollout_readers_unlistable.py index 417444158..80abee035 100644 --- a/dokimi/tests/test_rollout_readers_unlistable.py +++ b/dokimi/tests/test_rollout_readers_unlistable.py @@ -8,13 +8,14 @@ from __future__ import annotations +import ntpath import os from contextlib import contextmanager from pathlib import Path import pytest -from dokimi.harnesses import load_task +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 @@ -122,6 +123,39 @@ def bench(cmd, cwd): 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") + 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): From d306e4cc141d9a26830b80482950f416eda2d7dd Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sat, 5 Dec 2026 00:43:04 +0000 Subject: [PATCH 5/6] fix(harnesses): a command cell lists its output dir without an is_dir guard, so an unsearchable ancestor is no verdict Review points 4807801100 and 4807801107. `_reward_files` guarded the listing with `Path.is_dir()`, which answers False for a path it cannot stat because of permissions on Python 3.14; the cell then found no reward file and read exit 0 as reward 1.0. It now lists the directory and treats only a missing or non-directory output dir as having no reward files, so any other OSError reaches `_command_verdict` as the no-verdict diagnostic. The reward-name test now sets the POSIX name comparison before its first assertions, so it also holds where the platform's own comparison is `ntpath.normcase`. Signed-off-by: Anton Volkov --- dokimi/dokimi/harnesses/command.py | 8 ++++-- .../tests/test_rollout_readers_unlistable.py | 27 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index 14349eb6c..0db347c25 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -489,10 +489,14 @@ def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stde 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 raises its OSError.""" + directory that cannot be listed, or sit behind one that cannot be searched, raises its OSError (an absent + ``output_dir``, or one that is no directory, has no reward files).""" from dokimi.digest_entries import listed_entries - entries = listed_entries(output_dir) if output_dir.is_dir() else [] + try: + entries = listed_entries(output_dir) + except (FileNotFoundError, NotADirectoryError): + entries = [] return [path for name in ("reward.txt", "reward.json") for path in sorted(e for e in entries if normcase(e.name) == name)] diff --git a/dokimi/tests/test_rollout_readers_unlistable.py b/dokimi/tests/test_rollout_readers_unlistable.py index 80abee035..e777f3ba5 100644 --- a/dokimi/tests/test_rollout_readers_unlistable.py +++ b/dokimi/tests/test_rollout_readers_unlistable.py @@ -10,6 +10,7 @@ import ntpath import os +import posixpath from contextlib import contextmanager from pathlib import Path @@ -92,6 +93,31 @@ def test_a_command_cell_names_a_directory_it_could_not_list_instead_of_reading_i 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): @@ -147,6 +173,7 @@ def test_a_reward_file_is_found_by_the_platforms_name_comparison_and_read_by_its (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) From e017dec20ce27ce6f4e81893404e3bf3006e88c8 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Sun, 6 Dec 2026 12:20:21 +0000 Subject: [PATCH 6/6] fix(harnesses): a vanished or unreadable reward path is a named error A command cell's output walk treated any missing path as an absent output dir, so a subdirectory that disappeared mid-walk dropped a reward already found and the exit code became the reward. Only the output dir itself being absent is empty now; a vanished child raises and the cell reports `cannot list `. A reward file that is listed but cannot be read now reports `cannot read : `, not `cannot list`. After a BenchFlow timeout, a job directory that cannot be listed no longer ends the whole container cleanup: the rollouts under the other job directories are still removed. The subagents fixture holds a non-transcript file, so a `*` pattern is caught, and the changelog states what the old memory lint did with an unlistable directory (an empty store with no findings). Signed-off-by: Anton Volkov --- ...20261204_120000_unlistable-root-readers.md | 4 +- dokimi/dokimi/harnesses/benchflow.py | 4 +- dokimi/dokimi/harnesses/command.py | 21 ++++++-- .../tests/test_rollout_readers_unlistable.py | 51 +++++++++++++++++++ .../test_session_subagents_unlistable.py | 2 + 5 files changed, 74 insertions(+), 8 deletions(-) diff --git a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md index 6adb42a98..f41c94f5d 100644 --- a/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md +++ b/dokimi/changelog.d/20261204_120000_unlistable-root-readers.md @@ -1,5 +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 one with no topic files and reported the `MEMORY.md` entries as dead links. 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)). +- **`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 ([#1509](https://github.com/intel/dokimi/issues/1509)). +- **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/dokimi/harnesses/benchflow.py b/dokimi/dokimi/harnesses/benchflow.py index 502537f3a..263eeada4 100644 --- a/dokimi/dokimi/harnesses/benchflow.py +++ b/dokimi/dokimi/harnesses/benchflow.py @@ -635,8 +635,8 @@ def remove_rollout_containers(jobs_dir: Path, runner: process.Runner = process.r removed: list[str] = [] try: rollouts = rollout_dirs(jobs_dir) - except OSError: # the cell's error names the directory (look_for_rollouts) - return removed + 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 diff --git a/dokimi/dokimi/harnesses/command.py b/dokimi/dokimi/harnesses/command.py index 0db347c25..0c352c017 100644 --- a/dokimi/dokimi/harnesses/command.py +++ b/dokimi/dokimi/harnesses/command.py @@ -7,6 +7,7 @@ import json import math +import os import shlex import shutil import time @@ -471,6 +472,10 @@ 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.""" @@ -481,6 +486,8 @@ def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stde 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, {} @@ -489,13 +496,15 @@ def _command_verdict(output_dir: Path | None, returncode: int, stdout: str, stde 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 (an absent - ``output_dir``, or one that is no directory, has no reward files).""" + 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): + 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)] @@ -513,7 +522,11 @@ def _find_reward(output_dir: Path | None, stdout: str, stderr: str) -> float | N if not path.is_file(): # a directory of that name holds no reward, like an empty file continue try: - return reward_in_file(normcase(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/tests/test_rollout_readers_unlistable.py b/dokimi/tests/test_rollout_readers_unlistable.py index e777f3ba5..1d1f77637 100644 --- a/dokimi/tests/test_rollout_readers_unlistable.py +++ b/dokimi/tests/test_rollout_readers_unlistable.py @@ -21,6 +21,7 @@ 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 @@ -66,6 +67,56 @@ def test_a_cleanup_after_a_timeout_goes_on_when_the_jobs_directory_cannot_be_lis 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" diff --git a/dokimi/tests/test_session_subagents_unlistable.py b/dokimi/tests/test_session_subagents_unlistable.py index c9681751b..015cfb411 100644 --- a/dokimi/tests/test_session_subagents_unlistable.py +++ b/dokimi/tests/test_session_subagents_unlistable.py @@ -36,6 +36,7 @@ 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" @@ -51,6 +52,7 @@ 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) == []