From e7c2b1d746d779e03054238ef0ee4bc935f2b605 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 20:52:39 -0800 Subject: [PATCH 1/4] fix: refuse a deeply nested user file instead of a RecursionError traceback json.loads and yaml.safe_load raise RecursionError, not ValueError, past the interpreter's nesting limit. The user-file readers that caught only ValueError (repo compare --ledger, the batch stamp, eval and answers files, repair receipts, --resume and --jsonl rows, task source lines, skill, eval-coverage and upstream manifests, the runtime config) let it escape as a traceback. The ledger now goes through the shared reader in dokimi.files, which already refuses deep nesting; the others catch RecursionError with the handler they already have. Tests: tests/test_deep_user_inputs.py (16 cases, red on the base, green here). Signed-off-by: Nikolay Petrov --- ...100000_napetrov_deep-user-input-refusal.md | 8 + dokimi/dokimi/commands/catalog_scan.py | 2 +- dokimi/dokimi/commands/opportunities.py | 2 +- dokimi/dokimi/commands/repair_receipt.py | 2 +- dokimi/dokimi/eval_coverage.py | 18 +- dokimi/dokimi/external/upstream.py | 2 +- dokimi/dokimi/mcp/factory.py | 2 +- dokimi/dokimi/novelty/sweep.py | 2 +- dokimi/dokimi/report/eval_io.py | 4 +- dokimi/dokimi/repos/compare.py | 2 +- dokimi/dokimi/repos/conformance.py | 2 +- dokimi/dokimi/repos/ledger.py | 8 +- dokimi/dokimi/skill_coverage.py | 9 +- dokimi/dokimi/skills/formats.py | 4 +- dokimi/dokimi/task_formats/source.py | 2 +- dokimi/scripts/duplicates_baseline.json | 1 - dokimi/tests/test_deep_user_inputs.py | 167 ++++++++++++++++++ 17 files changed, 207 insertions(+), 30 deletions(-) create mode 100644 dokimi/changelog.d/20261204_100000_napetrov_deep-user-input-refusal.md create mode 100644 dokimi/tests/test_deep_user_inputs.py diff --git a/dokimi/changelog.d/20261204_100000_napetrov_deep-user-input-refusal.md b/dokimi/changelog.d/20261204_100000_napetrov_deep-user-input-refusal.md new file mode 100644 index 0000000000..8e2b09626f --- /dev/null +++ b/dokimi/changelog.d/20261204_100000_napetrov_deep-user-input-refusal.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A deeply nested user file is refused, not a traceback** — a JSON or YAML file nested past the parser's recursion limit printed a `RecursionError` traceback from `repo compare --ledger`, `report eval` and `report generate` (eval and answers files), conformance expectations (`repos/conformance.py`), `catalog scan --resume` and `catalog novelty --resume` (`--jsonl` rows), `catalog repair-receipt`, `report opportunities`, `catalog eval` and `eval skill-coverage` (`evals.json`), task source lines, skill and upstream manifests, and the runtime config. `repo compare --ledger` now exits 2 with `cannot read the ledger: is not valid JSON: ...`, and refuses a device path such as `/dev/null` as `not a file`. The other readers treat such a file as they treat a malformed one: an input error naming the file, or a missing stamp or answers file. Native task logs (Inspect, promptfoo) and the subject descriptor still raise a traceback on deep nesting; a follow-up will route them the same way. diff --git a/dokimi/dokimi/commands/catalog_scan.py b/dokimi/dokimi/commands/catalog_scan.py index 8eeb16f6d1..dd98eba3b8 100644 --- a/dokimi/dokimi/commands/catalog_scan.py +++ b/dokimi/dokimi/commands/catalog_scan.py @@ -395,7 +395,7 @@ def _parse_row(raw: bytes, path: Path, lineno: int) -> Optional[dict]: return None try: row = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, ValueError): + except (UnicodeDecodeError, ValueError, RecursionError): # RecursionError: nested too deeply, not a scan row row = None if _is_row(row): return row diff --git a/dokimi/dokimi/commands/opportunities.py b/dokimi/dokimi/commands/opportunities.py index 890797ee5f..9af5b42e6c 100644 --- a/dokimi/dokimi/commands/opportunities.py +++ b/dokimi/dokimi/commands/opportunities.py @@ -52,7 +52,7 @@ def _read(path: str, repository: str | None) -> tuple[str, list[opportunities.Op raise InputError(f"{path}: {e}") from e try: data = json.loads(text) - except ValueError as e: + except (ValueError, RecursionError) as e: # RecursionError: nested too deeply to parse if _looks_like_json(path, text): raise InputError(f"{path}: not valid JSON ({e})") from e return "llms_txt", opportunities.from_llms_txt(llms_txt.check(text), target=path) diff --git a/dokimi/dokimi/commands/repair_receipt.py b/dokimi/dokimi/commands/repair_receipt.py index fe5b42f92e..5a5dc4248d 100644 --- a/dokimi/dokimi/commands/repair_receipt.py +++ b/dokimi/dokimi/commands/repair_receipt.py @@ -27,7 +27,7 @@ def add_repair_receipt(catalog_sub) -> None: def _load(path: str) -> dict: try: data = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: # UnicodeDecodeError and JSONDecodeError are ValueErrors + except (OSError, ValueError, RecursionError) as exc: # UnicodeDecodeError and JSONDecodeError are ValueErrors raise InputError(f"cannot read {path} as a `catalog check --format json` report (#960, docs/external-content.md, Repair receipt): {exc}") from exc if not isinstance(data, dict): raise InputError(f"{path} is not a `catalog check --format json` report (#960, docs/external-content.md, Repair receipt)") diff --git a/dokimi/dokimi/eval_coverage.py b/dokimi/dokimi/eval_coverage.py index 54689bd2d4..998fc10ab2 100644 --- a/dokimi/dokimi/eval_coverage.py +++ b/dokimi/dokimi/eval_coverage.py @@ -83,6 +83,17 @@ def _labelled(eid: str, source: str, value: Any) -> LabelledEval: return LabelledEval(eid, source, None, malformed=True) +def read_evals_rows(path: Path) -> list[Any]: + """The ``evals`` list of one skill-creator ``evals.json``. Raises ``ValueError`` on an unreadable or malformed file.""" + try: + rows = json.loads(path.read_text(encoding="utf-8")).get("evals", []) + except (OSError, ValueError, AttributeError, RecursionError) as exc: # RecursionError: nested too deeply + raise ValueError(f"{path}: not a skill-creator evals.json ({exc})") from exc + if not isinstance(rows, list): + raise ValueError(f"{path}: \"evals\" is not a list") + return rows + + def _evals_files(root: Path) -> list[Path]: if root.is_file(): return [root] @@ -141,12 +152,7 @@ def read_labels(root: Path) -> list[LabelledEval]: """ out: list[LabelledEval] = [] for path in _evals_files(root): - try: - rows = json.loads(path.read_text(encoding="utf-8")).get("evals", []) - except (OSError, ValueError, AttributeError) as exc: - raise ValueError(f"{path}: not a skill-creator evals.json ({exc})") from exc - if not isinstance(rows, list): - raise ValueError(f"{path}: \"evals\" is not a list") + rows = read_evals_rows(path) for index, row in enumerate(rows): if isinstance(row, dict): out.append(_labelled(str(row.get("id", index)), path.name, row.get("needs", _ABSENT))) diff --git a/dokimi/dokimi/external/upstream.py b/dokimi/dokimi/external/upstream.py index 5ef7818017..a21559b9b1 100644 --- a/dokimi/dokimi/external/upstream.py +++ b/dokimi/dokimi/external/upstream.py @@ -359,7 +359,7 @@ def load_manifest(path: Path, order: int) -> tuple[Upstream, list[Version]]: """The upstream and versions a manifest lists. Each entry is ``{"path", "content", "head"?, "commit"?, "date"?}``.""" try: data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: + except (OSError, UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc: raise InputError(f"{path}: not a readable JSON manifest: {exc}") from exc if not isinstance(data, dict) or data.get("schema") != MANIFEST_SCHEMA: raise InputError(f"{path}: a manifest is a JSON object with \"schema\": \"{MANIFEST_SCHEMA}\"") diff --git a/dokimi/dokimi/mcp/factory.py b/dokimi/dokimi/mcp/factory.py index b1fbf6072f..55e3f3b31e 100644 --- a/dokimi/dokimi/mcp/factory.py +++ b/dokimi/dokimi/mcp/factory.py @@ -70,7 +70,7 @@ def _context7_settings() -> dict: raise ValueError(f"products config root must be a mapping: {path}") block = load_products_config(path).context7 block = {} if block is None else block - except (yaml.YAMLError, ValueError, OSError) as exc: + except (yaml.YAMLError, ValueError, OSError, RecursionError) as exc: # RecursionError: deep nesting raise InputError(f"{path}: cannot read the runtime config: {exc} (#1291)") from exc if not isinstance(block, dict): raise InputError(f"{path}: 'context7' must be a mapping (#1291)") diff --git a/dokimi/dokimi/novelty/sweep.py b/dokimi/dokimi/novelty/sweep.py index 6c768ea021..09e5384ef9 100644 --- a/dokimi/dokimi/novelty/sweep.py +++ b/dokimi/dokimi/novelty/sweep.py @@ -170,7 +170,7 @@ def read_rows(path: Path) -> list[dict]: continue try: row = json.loads(raw.decode("utf-8")) - except (UnicodeDecodeError, ValueError) as exc: + except (UnicodeDecodeError, ValueError, RecursionError) as exc: if lineno == len(lines) and not raw.endswith(b"\n"): break raise InputError(f"--jsonl {path} line {lineno} is not a sweep row: {exc}") from exc diff --git a/dokimi/dokimi/report/eval_io.py b/dokimi/dokimi/report/eval_io.py index 8802d162cb..74b8f14eb2 100644 --- a/dokimi/dokimi/report/eval_io.py +++ b/dokimi/dokimi/report/eval_io.py @@ -31,7 +31,7 @@ def answers_by_id(answers_path: str) -> dict[str, Record]: try: data = json.loads(Path(answers_path).read_text(encoding="utf-8")) - except (OSError, UnicodeDecodeError, json.JSONDecodeError): + except (OSError, UnicodeDecodeError, json.JSONDecodeError, RecursionError): return {} items = data.get("answers") if isinstance(data, dict) else data return answers_from_items(items, source=answers_path) @@ -61,6 +61,8 @@ def load_eval(eval_path: str) -> dict: data = json.load(f) except OSError as exc: raise RecordError(f"cannot read {eval_path}: {exc}") from exc + except RecursionError as exc: # nested too deeply to parse + raise RecordError(f"{eval_path} is nested too deeply to read as JSON") from exc except ValueError as exc: # not JSON, or not UTF-8 raise RecordError(f"{eval_path} is not valid UTF-8 JSON: {exc}") from exc if not isinstance(data, dict) or not isinstance(data.get("evaluations"), list): diff --git a/dokimi/dokimi/repos/compare.py b/dokimi/dokimi/repos/compare.py index 677231214f..3d3adc938f 100644 --- a/dokimi/dokimi/repos/compare.py +++ b/dokimi/dokimi/repos/compare.py @@ -188,7 +188,7 @@ def batch_stamp(batch_dir: Path) -> dict[str, str]: """What ``repo run`` pinned the batch to (``_eval/batch.json``); empty for a batch that has none.""" try: stamp = json.loads((batch_dir / "_eval" / "batch.json").read_text(encoding="utf-8")) - except (OSError, ValueError): + except (OSError, ValueError, RecursionError): # RecursionError: nested too deeply to parse, read as no stamp return {} return {k: str(v) for k, v in stamp.items() if k in ("tree", *STAMP_KEYS)} if isinstance(stamp, dict) else {} diff --git a/dokimi/dokimi/repos/conformance.py b/dokimi/dokimi/repos/conformance.py index 334ad9b11a..2c50312c14 100644 --- a/dokimi/dokimi/repos/conformance.py +++ b/dokimi/dokimi/repos/conformance.py @@ -96,7 +96,7 @@ def cases(fixtures: Path) -> list[str]: def load_expectations(path: Path) -> dict[str, Any]: try: data = yaml.safe_load(path.read_text(encoding="utf-8")) - except (OSError, ValueError, yaml.YAMLError) as exc: + except (OSError, ValueError, yaml.YAMLError, RecursionError) as exc: # RecursionError: deep nesting raise ConformanceError(f"{path}: {exc}") from exc errors = schema_errors(SCHEMA_EXPECTATIONS, data) if errors: diff --git a/dokimi/dokimi/repos/ledger.py b/dokimi/dokimi/repos/ledger.py index 9fb5911b7e..d2bb4e43bc 100644 --- a/dokimi/dokimi/repos/ledger.py +++ b/dokimi/dokimi/repos/ledger.py @@ -17,7 +17,6 @@ from __future__ import annotations -import json import math import re from collections import Counter @@ -28,6 +27,7 @@ from dokimi.artifacts import schema_errors from dokimi.eval.comparison_verdict import ComparisonVerdict, decide +from dokimi.files import InputError, read_json_input from dokimi.eval.sign_flip import ALPHA, EPS, min_sign_flip_p from dokimi.eval.stats import adjust_pvalues @@ -66,9 +66,9 @@ class Ledger: def load_ledger(path: Path) -> Ledger: """The ledger in ``path``, validated against ``repo_ledger.v1`` and checked for duplicate ids.""" try: - raw = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: - raise LedgerError(f"{path}: cannot read the ledger: {exc}") from exc + raw = read_json_input(path) # the shared reader: deep nesting is refused there too (RecursionError) + except InputError as exc: + raise LedgerError(f"cannot read the ledger: {exc}") from exc errors = schema_errors("repo_ledger.v1", raw) if errors: raise LedgerError(f"{path}: " + "; ".join(errors)) diff --git a/dokimi/dokimi/skill_coverage.py b/dokimi/dokimi/skill_coverage.py index 02d18bbb55..94a7674f2c 100644 --- a/dokimi/dokimi/skill_coverage.py +++ b/dokimi/dokimi/skill_coverage.py @@ -37,7 +37,7 @@ from typing import Any from dokimi.digest_entries import listed_entries -from dokimi.eval_coverage import _evals_files, _is_task +from dokimi.eval_coverage import _evals_files, _is_task, read_evals_rows from dokimi.novelty.client import LLMClient SCHEMA_VERSION = "skill_coverage.v1" @@ -109,12 +109,7 @@ def _evals_checks(root: Path) -> list[tuple[str, str, str]]: """(unit, name, source) for each evals.json row: the row's id, its body without ``needs``.""" out: list[tuple[str, str, str]] = [] for path in _evals_files(root): - try: - rows = json.loads(path.read_text(encoding="utf-8")).get("evals", []) - except (OSError, ValueError, AttributeError) as exc: - raise ValueError(f"{path}: not a skill-creator evals.json ({exc})") from exc - if not isinstance(rows, list): - raise ValueError(f"{path}: \"evals\" is not a list") + rows = read_evals_rows(path) for index, row in enumerate(rows): if not isinstance(row, dict): continue diff --git a/dokimi/dokimi/skills/formats.py b/dokimi/dokimi/skills/formats.py index ea0b54f39f..d2873b09c1 100644 --- a/dokimi/dokimi/skills/formats.py +++ b/dokimi/dokimi/skills/formats.py @@ -167,7 +167,7 @@ def _manifest(path: Path, fmt: str) -> SkillPackage: pkg = SkillPackage(path, fmt, selected_by="install") try: data = json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: + except (OSError, ValueError, RecursionError) as exc: # RecursionError: nested too deeply to parse pkg.problems.append(f"unreadable JSON: {exc}") return pkg if not isinstance(data, dict): @@ -222,7 +222,7 @@ def _marketplace_skills(bundle: Path, marketplace: Path, problems: list[str]) -> if marketplace.is_file(): try: market = json.loads(marketplace.read_text(encoding="utf-8")) - except (OSError, ValueError) as exc: + except (OSError, ValueError, RecursionError) as exc: # RecursionError: nested too deeply to parse problems.append(f"marketplace.json: unreadable JSON: {exc}") return found if not isinstance(market, dict): diff --git a/dokimi/dokimi/task_formats/source.py b/dokimi/dokimi/task_formats/source.py index 675fd46ecc..16916e6457 100644 --- a/dokimi/dokimi/task_formats/source.py +++ b/dokimi/dokimi/task_formats/source.py @@ -144,7 +144,7 @@ def _parse_jsonl(text: str, problems: list[str]) -> list[Any]: continue try: rows.append(json.loads(line)) - except ValueError as exc: + except (ValueError, RecursionError) as exc: # RecursionError: nested too deeply, a bad line bad += 1 if bad <= 3: problems.append(f"line {number}: not valid JSON: {_one_line(exc)}") diff --git a/dokimi/scripts/duplicates_baseline.json b/dokimi/scripts/duplicates_baseline.json index 2fd59958b6..25aa3a590b 100644 --- a/dokimi/scripts/duplicates_baseline.json +++ b/dokimi/scripts/duplicates_baseline.json @@ -7,7 +7,6 @@ "a2801d27c7b0": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/eval/ragas_eval.py"]}, "b120773b627e": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/commands/repo_run.py"]}, "e00d5aa50148": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/repos/reach.py", "dokimi/repos/skill_reach.py"]}, - "e1ae802e7aec": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/eval_coverage.py", "dokimi/skill_coverage.py"]}, "fcc318c1e962": {"count": 2, "rationale": "pre-existing when the gate was introduced", "where": ["dokimi/commands/redteam.py", "dokimi/commands/skill_coverage.py"]} } } diff --git a/dokimi/tests/test_deep_user_inputs.py b/dokimi/tests/test_deep_user_inputs.py new file mode 100644 index 0000000000..3e7c4338fd --- /dev/null +++ b/dokimi/tests/test_deep_user_inputs.py @@ -0,0 +1,167 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""A deeply nested user file is refused (or read as bad, as the loader reads bad input), never a RecursionError. + +Each case is a user-supplied file read by a loader that catches bad input: the loader's own refusal is what the +user sees. ``json.loads`` and ``yaml.safe_load`` raise RecursionError, not ValueError, past the interpreter's limit. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +DEEP = "[" * 200000 + "]" * 200000 # balanced: the parsers recurse on the nesting before they reach the end + + +def _deep(tmp_path: Path, name: str = "input.json", text: str = DEEP) -> Path: + path = tmp_path / name + path.write_text(text, encoding="utf-8") + return path + + +def test_load_ledger_refuses_a_deeply_nested_ledger_naming_it(tmp_path): + from dokimi.repos.ledger import LedgerError, load_ledger + + path = _deep(tmp_path, "ledger.json") + with pytest.raises(LedgerError) as exc: + load_ledger(path) + assert "cannot read the ledger" in str(exc.value) and str(path) in str(exc.value) + + +def test_repo_compare_ledger_deeply_nested_exits_2_naming_it(tmp_path, monkeypatch, capsys): + from dokimi.cli import build_parser + from tests.cli_refusal import refusal + + path = _deep(tmp_path, "ledger.json") + monkeypatch.setattr("dokimi.repos.compare.compare", lambda *a, **k: {}) # the ledger is the input under test + args = build_parser().parse_args(["repo", "compare", str(tmp_path), "--baseline", "a", "--ledger", str(path)]) + with refusal() as outcome: + args.func(args) + assert outcome.code == 2 + assert f"cannot read the ledger: {path} is not valid JSON" in outcome.err and "Traceback" not in outcome.err + + +def test_batch_stamp_reads_a_deeply_nested_stamp_as_no_stamp(tmp_path): + from dokimi.repos.compare import batch_stamp + + (tmp_path / "_eval").mkdir() + (tmp_path / "_eval" / "batch.json").write_text(DEEP, encoding="utf-8") + assert batch_stamp(tmp_path) == {} + + +def test_load_expectations_refuses_a_deeply_nested_yaml_naming_it(tmp_path): + from dokimi.repos.conformance import ConformanceError, load_expectations + + path = _deep(tmp_path, "expectations.yaml") + with pytest.raises(ConformanceError, match="expectations.yaml"): + load_expectations(path) + + +def test_load_eval_refuses_a_deeply_nested_eval_naming_it(tmp_path): + from dokimi.report.eval_io import load_eval + from dokimi.records import RecordError + + path = _deep(tmp_path, "eval.json") + with pytest.raises(RecordError) as exc: + load_eval(str(path)) + assert str(exc.value) == f"{path} is nested too deeply to read as JSON" + + +def test_answers_by_id_reads_a_deeply_nested_answers_file_as_no_answers(tmp_path): + from dokimi.report.eval_io import answers_by_id + + assert answers_by_id(str(_deep(tmp_path, "answers.json"))) == {} + + +def test_repair_receipt_refuses_a_deeply_nested_report_naming_it(tmp_path): + from dokimi.commands.repair_receipt import _load + from dokimi.files import InputError + + path = _deep(tmp_path, "report.json") + with pytest.raises(InputError, match="report.json"): + _load(str(path)) + + +def test_opportunities_refuses_a_deeply_nested_input_naming_it(tmp_path): + from dokimi.commands.opportunities import _read + from dokimi.files import InputError + + path = _deep(tmp_path, "input.json") + with pytest.raises(InputError) as exc: + _read(str(path), None) + assert str(exc.value).startswith(f"{path}: not valid JSON") + + +def test_catalog_scan_resume_refuses_a_deeply_nested_complete_row_naming_it(tmp_path): + from dokimi.commands.catalog_scan import _parse_row + from dokimi.files import InputError + + path = _deep(tmp_path, "scan.jsonl") + with pytest.raises(InputError, match="is not a scan row"): + _parse_row((DEEP + "\n").encode(), path, 1) + + +def test_sweep_resume_refuses_a_deeply_nested_row_naming_it(tmp_path): + from dokimi.files import InputError + from dokimi.novelty.sweep import read_rows + + path = _deep(tmp_path, "sweep.jsonl", DEEP + "\n") + with pytest.raises(InputError, match=f"--jsonl {path} line 1 is not a sweep row"): + read_rows(path) + + +def test_task_source_jsonl_counts_a_deeply_nested_line_as_bad(tmp_path): + from dokimi.task_formats.source import _parse_jsonl + + problems: list[str] = [] + assert _parse_jsonl(DEEP + "\n", problems) == [] + assert problems and problems[0].startswith("line 1: not valid JSON") + + +def test_upstream_manifest_refuses_a_deeply_nested_manifest_naming_it(tmp_path): + from dokimi.external.upstream import load_manifest + from dokimi.files import InputError + + path = _deep(tmp_path, "manifest.json") + with pytest.raises(InputError, match="not a readable JSON manifest"): + load_manifest(path, 0) + + +def test_skill_manifest_reports_a_deeply_nested_manifest_as_unreadable(tmp_path): + from dokimi.skills.formats import _manifest + + path = _deep(tmp_path, "plugin.json") + pkg = _manifest(path, "plugin") + assert pkg.problems and pkg.problems[0].startswith("unreadable JSON") + + +def test_context7_settings_refuses_a_deeply_nested_runtime_config_naming_it(tmp_path, monkeypatch): + import dokimi.config + from dokimi.files import InputError + from dokimi.mcp.factory import _context7_settings + + path = _deep(tmp_path, "config.yaml") + monkeypatch.setattr(dokimi.config, "runtime_config_path", lambda: path) + with pytest.raises(InputError, match="cannot read the runtime config"): + _context7_settings() + + +def test_eval_coverage_refuses_a_deeply_nested_evals_json_naming_it(tmp_path): + from dokimi.eval_coverage import read_labels + + path = _deep(tmp_path, "evals.json") # a file root: _evals_files reads it as the one evals.json + with pytest.raises(ValueError, match="not a skill-creator evals.json") as exc: + read_labels(path) + assert str(path) in str(exc.value) + + +def test_skill_coverage_refuses_a_deeply_nested_evals_json_naming_it(tmp_path): + from dokimi.skill_coverage import _evals_checks + + path = _deep(tmp_path, "evals.json") + with pytest.raises(ValueError, match="not a skill-creator evals.json") as exc: + _evals_checks(path) + assert str(path) in str(exc.value) From 1ba09fc698fe8edbe1bee1ccd5cddff6ef8ca776 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Fri, 4 Dec 2026 23:43:12 -0800 Subject: [PATCH 2/4] fix: refuse a deeply nested native log, subject descriptor, dataset cell or ideal The readers that #1645 did not reach still let a RecursionError escape on deeply nested input: the native log (eval native-import), the subject descriptor (catalog show --kind subject), a SWE-bench FAIL_TO_PASS cell, and a json_match ideal. The log and the descriptor now go through the shared reader in dokimi.files, which refuses deep nesting as InputError. The cell and the ideal are not files: a cell nested too deeply is not a list, and an ideal nested too deeply is dropped with the note an ideal that is not JSON already gets. batch_stamp and answers_by_id stay as they are: both already read any unparseable file, deep or not, as a missing stamp or answers file, and tests/test_deep_user_inputs.py pins that. Tests: tests/test_deep_user_inputs.py (4 new cases, red on the base). Signed-off-by: Nikolay Petrov --- ...1204_110000_napetrov_deep-input-readers.md | 8 +++++ dokimi/dokimi/subjects/loader.py | 4 +-- dokimi/dokimi/task_formats/datasets.py | 2 +- .../task_formats/imports/native_logs.py | 4 ++- .../task_formats/imports/openai_evals.py | 2 +- dokimi/tests/test_deep_user_inputs.py | 36 +++++++++++++++++++ 6 files changed, 51 insertions(+), 5 deletions(-) create mode 100644 dokimi/changelog.d/20261204_110000_napetrov_deep-input-readers.md diff --git a/dokimi/changelog.d/20261204_110000_napetrov_deep-input-readers.md b/dokimi/changelog.d/20261204_110000_napetrov_deep-input-readers.md new file mode 100644 index 0000000000..04abfe75c8 --- /dev/null +++ b/dokimi/changelog.d/20261204_110000_napetrov_deep-input-readers.md @@ -0,0 +1,8 @@ + + +### Fixed + +- **A deeply nested native log or subject descriptor is refused, not a traceback** — a JSON file nested past the parser's recursion limit printed a `RecursionError` traceback from `eval native-import` (the Inspect and promptfoo log) and from `catalog show --kind subject` (the subject descriptor). It now exits 2 with ` is not valid JSON: ...`, as a malformed file does. A log or descriptor that cannot be read at all (missing, a device, not UTF-8) is an input error naming the file too, not an OS or decode traceback. A dataset cell whose JSON string (SWE-bench `FAIL_TO_PASS` / `PASS_TO_PASS`) is nested too deeply is read as not a list, and a `json_match` ideal nested too deeply is dropped with the same note as one that is not JSON. diff --git a/dokimi/dokimi/subjects/loader.py b/dokimi/dokimi/subjects/loader.py index 0922371b19..d45958e09e 100644 --- a/dokimi/dokimi/subjects/loader.py +++ b/dokimi/dokimi/subjects/loader.py @@ -6,12 +6,12 @@ from __future__ import annotations import errno -import json import tomllib from pathlib import Path from typing import Any from dokimi.defaults import DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER +from dokimi.files import read_json_input from dokimi.treatments.specs import combine_specs from .models import NON_ARM_KINDS, SUBJECT_KINDS, SubjectArtifact, SubjectDescriptor, SubjectMember, SubjectSuite @@ -95,7 +95,7 @@ def _load_mapping(path: Path) -> dict[str, Any]: raise FileNotFoundError(path) suffix = path.suffix.lower() if suffix == ".json": - raw = json.loads(path.read_text(encoding="utf-8")) + raw = read_json_input(path) # the shared reader: a deeply nested descriptor is an InputError, not a RecursionError elif suffix == ".toml": raw = tomllib.loads(path.read_text(encoding="utf-8")) else: diff --git a/dokimi/dokimi/task_formats/datasets.py b/dokimi/dokimi/task_formats/datasets.py index 1c01c00704..0a88459407 100644 --- a/dokimi/dokimi/task_formats/datasets.py +++ b/dokimi/dokimi/task_formats/datasets.py @@ -75,7 +75,7 @@ def _test_list(value: Any) -> list[Any] | None: if isinstance(value, str): try: parsed = json.loads(value) - except ValueError: + except (ValueError, RecursionError): # RecursionError: a cell nested too deeply to parse is not a list return None return parsed if isinstance(parsed, list) else None return None diff --git a/dokimi/dokimi/task_formats/imports/native_logs.py b/dokimi/dokimi/task_formats/imports/native_logs.py index 5ff0181fd8..25ac579bcd 100644 --- a/dokimi/dokimi/task_formats/imports/native_logs.py +++ b/dokimi/dokimi/task_formats/imports/native_logs.py @@ -22,6 +22,8 @@ from pathlib import Path from typing import Any, Mapping, Optional +from dokimi.files import read_json_input + NATIVE_CONDITION = "without_docs" #: Inspect's score letters (CORRECT, PARTIAL, INCORRECT, NOANSWER) as numbers. @@ -117,7 +119,7 @@ def read_promptfoo(data: Mapping[str, Any]) -> NativeRun: def read_log(path: Path) -> NativeRun: """A native log, by shape: Inspect (``eval`` + ``samples``) or promptfoo (``results.results``).""" - data = json.loads(Path(path).read_text(encoding="utf-8")) + data = read_json_input(path) # the shared reader: a deeply nested log is an InputError, not a RecursionError if isinstance(data, Mapping) and "samples" in data and "eval" in data: return read_inspect(data) if isinstance(data, Mapping) and isinstance((data.get("results") or {}).get("results"), list): diff --git a/dokimi/dokimi/task_formats/imports/openai_evals.py b/dokimi/dokimi/task_formats/imports/openai_evals.py index a67af45e17..0ffe6ec955 100644 --- a/dokimi/dokimi/task_formats/imports/openai_evals.py +++ b/dokimi/dokimi/task_formats/imports/openai_evals.py @@ -119,7 +119,7 @@ def _checks(template: str, args: Mapping[str, Any], ideals: list[Any], imp: Impo for t in texts: try: values.append(json.loads(t)) - except ValueError: + except (ValueError, RecursionError): # RecursionError: an ideal nested too deeply is not JSON we can use imp.note("ideal that is not JSON dropped") # An empty `values` means "any JSON" to the grader; with no ideal left nothing is compared. return [{"type": "json", "values": values}] if values else [unsupported("json_match")] diff --git a/dokimi/tests/test_deep_user_inputs.py b/dokimi/tests/test_deep_user_inputs.py index 3e7c4338fd..223eb7626a 100644 --- a/dokimi/tests/test_deep_user_inputs.py +++ b/dokimi/tests/test_deep_user_inputs.py @@ -165,3 +165,39 @@ def test_skill_coverage_refuses_a_deeply_nested_evals_json_naming_it(tmp_path): with pytest.raises(ValueError, match="not a skill-creator evals.json") as exc: _evals_checks(path) assert str(path) in str(exc.value) + + +def test_read_log_refuses_a_deeply_nested_log_naming_it(tmp_path): + from dokimi.task_formats.imports.native_logs import read_log + + path = _deep(tmp_path, "log.json") + with pytest.raises(ValueError, match="is not valid JSON") as exc: + read_log(path) + assert str(path) in str(exc.value) + + +def test_load_subject_refuses_a_deeply_nested_descriptor_naming_it(tmp_path): + from dokimi.subjects.loader import load_subject + + path = _deep(tmp_path, "subject.json") + with pytest.raises(ValueError, match="is not valid JSON") as exc: + load_subject(path) + assert str(path) in str(exc.value) + + +def test_swe_bench_test_list_reads_a_deeply_nested_cell_as_no_list(): + from dokimi.task_formats.datasets import _test_list + + assert _test_list(DEEP) is None # a cell that is not a JSON list, as a malformed one is + + +def test_openai_evals_json_match_deep_ideal_is_dropped_with_a_note(tmp_path): + import json + + from dokimi.task_formats.imports.openai_evals import import_file + + path = tmp_path / "samples.json" + path.write_text(json.dumps([{"input": "q", "ideal": DEEP}]), encoding="utf-8") # the ideal is a deep JSON string + imp = import_file(path, grader="json_match") + assert imp.lossy["ideal that is not JSON dropped"] == 1 + assert imp.questions and imp.questions[0]["grading"]["checks"][0]["type"] == "unsupported" From a06b406ad2eb22e45e7a0bdab9a0aaa91063182a Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 00:16:20 -0800 Subject: [PATCH 3/4] test(cli): drop the native-import rows this fix makes refuse The four eval native-import log rows (missing, directory, unreadable, dangling-link) exit 2 with an input error now, so the allowlist names them as known failures that pass. Rows and digest follow the list. Signed-off-by: Nikolay Petrov --- dokimi/tests/cli_faults.py | 4 ++-- dokimi/tests/data/cli_fault_allowlist.txt | 4 ---- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/dokimi/tests/cli_faults.py b/dokimi/tests/cli_faults.py index 15fe083222..2a0d9d36ef 100644 --- a/dokimi/tests/cli_faults.py +++ b/dokimi/tests/cli_faults.py @@ -87,8 +87,8 @@ } # The allowlist only shrinks: any row added, deleted or swapped changes this count or digest (#1294), so review sees it. -ALLOWLIST_ROWS = 48 -ALLOWLIST_DIGEST = "98d781d77eb6" +ALLOWLIST_ROWS = 44 +ALLOWLIST_DIGEST = "af0204faa0f7" # Commands whose input refusals are not all exit 2 (docs/quickstart.md, "Exit codes"): they may also exit 1. OWN_CODES: dict[str, frozenset[int]] = { diff --git a/dokimi/tests/data/cli_fault_allowlist.txt b/dokimi/tests/data/cli_fault_allowlist.txt index 6a64e77257..c5e1357edc 100644 --- a/dokimi/tests/data/cli_fault_allowlist.txt +++ b/dokimi/tests/data/cli_fault_allowlist.txt @@ -22,10 +22,6 @@ catalog list | --registry | empty | exit 0 eval inspect | path | not-a-directory | exit 0, nothing on stderr eval inspect | path | unreadable | exit 0, nothing on stderr eval judge wording | --answers | json-list | exit 5 with a traceback (NoUsablePairs) -eval native-import | log | missing | exit 5 with a traceback (FileNotFoundError) -eval native-import | log | directory | exit 5 with a traceback (IsADirectoryError) -eval native-import | log | unreadable | exit 5 with a traceback (PermissionError) -eval native-import | log | dangling-link | exit 5 with a traceback (FileNotFoundError) eval tasks list | --tasks-root | unreadable | exit 5 with a traceback (PermissionError) explore run | --out-md | directory | exit 2 but leaves a results directory behind in the working directory explore run | --out-md | unwritable-parent | exit 2 but leaves a results directory behind in the working directory From cc9893d9f066fdfd50a72e886fb3ff387e77376d Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 22:15:32 -0800 Subject: [PATCH 4/4] fix: refuse a deeply nested, non-UTF-8 or unreadable subject, promptfoo or arms file A TOML subject descriptor nested past the parser's limit, or one that cannot be read, and an awareness arms.v1 file nested past the limit, not UTF-8 or unreadable, still let a RecursionError or a decode or OS error escape as a traceback. Each is now an InputError naming the file: the descriptor is read by a helper, the arms file is read with its JSON error still reported as before. A promptfoo code config whose node output nests past the parser's limit is refused the same way, naming the config; its other output failures keep their ValueError and exit code. A malformed TOML or arms file keeps its current error. Tests: tests/test_deep_user_inputs.py (8 new cases, 5 red on the base). Signed-off-by: Nikolay Petrov --- ...205_120000_napetrov_deep-input-subjects.md | 9 ++ dokimi/dokimi/subjects/loader.py | 19 ++- dokimi/dokimi/subjects/run_plan.py | 11 +- .../dokimi/task_formats/imports/promptfoo.py | 3 + dokimi/tests/test_deep_user_inputs.py | 117 ++++++++++++++++++ 5 files changed, 156 insertions(+), 3 deletions(-) create mode 100644 dokimi/changelog.d/20261205_120000_napetrov_deep-input-subjects.md diff --git a/dokimi/changelog.d/20261205_120000_napetrov_deep-input-subjects.md b/dokimi/changelog.d/20261205_120000_napetrov_deep-input-subjects.md new file mode 100644 index 0000000000..55be80f124 --- /dev/null +++ b/dokimi/changelog.d/20261205_120000_napetrov_deep-input-subjects.md @@ -0,0 +1,9 @@ + + +### Fixed + +- **A deeply nested, non-UTF-8 or unreadable subject descriptor or awareness arms file is refused, not a traceback** — a TOML subject descriptor nested past the parser's limit, or one that cannot be read, printed a traceback and exited 5; it now exits 2 with ` is not valid TOML: ...` or `cannot read : ...`. A TOML descriptor that is not UTF-8 already exited 2, without naming the file; it now names it, ` is not UTF-8 text: ...`. The same message is the `ERROR` line of `subjects list`, whose exit code is unchanged. An awareness `arms.v1` file that `subjects run` reads back, nested past the parser's limit, not UTF-8 or unreadable, printed a traceback and exited 5; it now exits 2 naming the file (`cannot read : ...` for an unreadable one). A file that is not valid JSON at all, such as one an interrupted cell left, keeps its current error. +- **A promptfoo code config whose node output is nested too deeply is refused, not a traceback** — a config (`.js`, `.mjs`, `.cjs`, `.ts`) whose output nests past the parser's limit now exits 2 with `: node wrote a config nested too deeply to read`, instead of a traceback. diff --git a/dokimi/dokimi/subjects/loader.py b/dokimi/dokimi/subjects/loader.py index d45958e09e..4e0903bedb 100644 --- a/dokimi/dokimi/subjects/loader.py +++ b/dokimi/dokimi/subjects/loader.py @@ -11,7 +11,7 @@ from typing import Any from dokimi.defaults import DEFAULT_ANSWER_MODEL, DEFAULT_ANSWER_PROVIDER -from dokimi.files import read_json_input +from dokimi.files import InputError, read_json_input from dokimi.treatments.specs import combine_specs from .models import NON_ARM_KINDS, SUBJECT_KINDS, SubjectArtifact, SubjectDescriptor, SubjectMember, SubjectSuite @@ -97,12 +97,27 @@ def _load_mapping(path: Path) -> dict[str, Any]: if suffix == ".json": raw = read_json_input(path) # the shared reader: a deeply nested descriptor is an InputError, not a RecursionError elif suffix == ".toml": - raw = tomllib.loads(path.read_text(encoding="utf-8")) + raw = _read_toml(path) else: raise ValueError(f"subject descriptor must be .json or .toml, got {path}") return _mapping(raw, "descriptor") +def _read_toml(path: Path) -> Any: + """The TOML at ``path``. A file that is not UTF-8, or nested past the parser's limit, is an InputError naming it.""" + try: + text = path.read_text(encoding="utf-8") + except UnicodeDecodeError as exc: + raise InputError(f"{path} is not UTF-8 text: {exc}") from exc + except OSError as exc: # unreadable, as read_json_input names it + reason = getattr(exc, "strerror", None) or exc + raise InputError(f"cannot read {path}: {reason}") from exc + try: + return tomllib.loads(text) + except RecursionError as exc: # a value nested too deeply for tomllib, as a deep JSON file is for json + raise InputError(f"{path} is not valid TOML: {exc}") from exc + + def _mapping(raw: Any, name: str) -> dict[str, Any]: if not isinstance(raw, dict): raise ValueError(f"{name} must be an object") diff --git a/dokimi/dokimi/subjects/run_plan.py b/dokimi/dokimi/subjects/run_plan.py index 98e60b3eaa..0d96d56688 100644 --- a/dokimi/dokimi/subjects/run_plan.py +++ b/dokimi/dokimi/subjects/run_plan.py @@ -16,6 +16,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any +from dokimi.files import InputError from dokimi.runner.plan import cell_id from .models import SubjectArtifact, SubjectDescriptor @@ -118,7 +119,15 @@ def record_awareness(run: RunDir, product: str, cells: list[MatrixCellDescriptor path = saved.get(cell.name) if path is None: continue - data = json.loads(path.read_text(encoding="utf-8")) + try: + data = json.loads(path.read_text(encoding="utf-8")) + except UnicodeDecodeError as exc: + raise InputError(f"{path} is not UTF-8 text: {exc}") from exc + except OSError as exc: # unreadable, as the TOML descriptor is named + reason = getattr(exc, "strerror", None) or exc + raise InputError(f"cannot read {path}: {reason}") from exc + except RecursionError as exc: # nested past the parser's limit: named; a malformed file keeps its error + raise InputError(f"{path} is not valid JSON: {exc}") from exc answers = list(read(data, source=str(path), section="answers")) stopped = data.get("terminated") for arm in arms: diff --git a/dokimi/dokimi/task_formats/imports/promptfoo.py b/dokimi/dokimi/task_formats/imports/promptfoo.py index 800860d2a6..1eb3101c37 100644 --- a/dokimi/dokimi/task_formats/imports/promptfoo.py +++ b/dokimi/dokimi/task_formats/imports/promptfoo.py @@ -31,6 +31,7 @@ from pathlib import Path from typing import Any, Mapping, Optional +from dokimi.files import InputError from dokimi.task_formats.configs import PROMPTFOO_CODE_SUFFIXES from dokimi.task_formats.imports.common import ( Imported, as_list, judge, match, question, render_chat, render_template, unsupported, @@ -73,6 +74,8 @@ def _code_config(path: Path) -> Any: raise ValueError(f"{path}: node could not read the config: {named.group(0) if named else 'no error text'}") try: return json.loads(out.read_text(encoding="utf-8")) + except RecursionError as exc: # a config nested past the parser's limit: named, not a traceback + raise InputError(f"{path}: node wrote a config nested too deeply to read") from exc except (OSError, ValueError) as exc: raise ValueError(f"{path}: node wrote no JSON for the config ({exc})") from exc diff --git a/dokimi/tests/test_deep_user_inputs.py b/dokimi/tests/test_deep_user_inputs.py index 223eb7626a..e1da01f56b 100644 --- a/dokimi/tests/test_deep_user_inputs.py +++ b/dokimi/tests/test_deep_user_inputs.py @@ -201,3 +201,120 @@ def test_openai_evals_json_match_deep_ideal_is_dropped_with_a_note(tmp_path): imp = import_file(path, grader="json_match") assert imp.lossy["ideal that is not JSON dropped"] == 1 assert imp.questions and imp.questions[0]["grading"]["checks"][0]["type"] == "unsupported" + + +def test_awareness_record_refuses_a_deeply_nested_arms_file_naming_it(tmp_path): + from types import SimpleNamespace + + from dokimi.files import InputError + from dokimi.subjects.run_plan import record_awareness + + path = _deep(tmp_path, "arms.v1.json") + with pytest.raises(InputError, match="is not valid JSON") as exc: + record_awareness(None, "product", [SimpleNamespace(name="cell")], ["arm"], {"cell": path}) + assert str(path) in str(exc.value) + + +def test_awareness_record_refuses_a_non_utf8_arms_file_naming_it(tmp_path): + from types import SimpleNamespace + + from dokimi.files import InputError + from dokimi.subjects.run_plan import record_awareness + + path = tmp_path / "arms.v1.json" + path.write_bytes(b'{"terminated": "\xff\xfe"}') + with pytest.raises(InputError, match="is not UTF-8 text") as exc: + record_awareness(None, "product", [SimpleNamespace(name="cell")], ["arm"], {"cell": path}) + assert str(path) in str(exc.value) + + +def test_awareness_record_refuses_an_unreadable_arms_file_naming_it(tmp_path, monkeypatch): + from types import SimpleNamespace + + from dokimi.files import InputError + from dokimi.subjects.run_plan import record_awareness + + path = tmp_path / "arms.v1.json" + path.write_text("{}", encoding="utf-8") + + def denied(self, *args, **kwargs): # root reads a chmod-000 file, so the denial is simulated + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(Path, "read_text", denied) + with pytest.raises(InputError, match="cannot read") as exc: + record_awareness(None, "product", [SimpleNamespace(name="cell")], ["arm"], {"cell": path}) + assert str(path) in str(exc.value) + + +def _fake_node(monkeypatch, write): + """Stand in for node: ``write(out)`` leaves whatever the config reader would have written at ``out``.""" + from types import SimpleNamespace + + import dokimi.process + + def fake_run(argv, **_kwargs): + write(Path(argv[-1])) + return SimpleNamespace(ok=True, stderr="") + + monkeypatch.setattr("shutil.which", lambda _name: "/usr/bin/node") + monkeypatch.setattr(dokimi.process, "run", fake_run) + + +def test_promptfoo_code_config_refuses_a_deeply_nested_output_naming_the_config(tmp_path, monkeypatch): + from dokimi.files import InputError + from dokimi.task_formats.imports.promptfoo import import_file + + path = tmp_path / "promptfooconfig.mjs" + path.write_text("export default {}\n", encoding="utf-8") + _fake_node(monkeypatch, lambda out: out.write_text(DEEP, encoding="utf-8")) + with pytest.raises(InputError) as exc: + import_file(path) + assert str(path) in str(exc.value) and "Traceback" not in str(exc.value) + + +def test_promptfoo_code_config_refuses_a_non_utf8_output_naming_the_config(tmp_path, monkeypatch): + from dokimi.task_formats.imports.promptfoo import import_file + + path = tmp_path / "promptfooconfig.mjs" + path.write_text("export default {}\n", encoding="utf-8") + _fake_node(monkeypatch, lambda out: out.write_bytes(b'{"x": "\xff"}')) + with pytest.raises(ValueError, match="node wrote no JSON") as exc: + import_file(path) + assert str(path) in str(exc.value) + + +def test_subject_toml_refuses_a_deeply_nested_descriptor_naming_it(tmp_path): + from dokimi.files import InputError + from dokimi.subjects.loader import load_subject + + path = _deep(tmp_path, "subject.toml", text="a = " + DEEP) + with pytest.raises(InputError, match="is not valid TOML") as exc: + load_subject(path) + assert str(path) in str(exc.value) and "Traceback" not in str(exc.value) + + +def test_subject_toml_refuses_an_unreadable_descriptor_naming_it(tmp_path, monkeypatch): + from dokimi.files import InputError + from dokimi.subjects.loader import load_subject + + path = tmp_path / "subject.toml" + path.write_text('id = "x"\n', encoding="utf-8") + + def denied(self, *args, **kwargs): # root reads a chmod-000 file, so the denial is simulated + raise PermissionError(13, "Permission denied") + + monkeypatch.setattr(Path, "read_text", denied) + with pytest.raises(InputError, match="cannot read") as exc: + load_subject(path) + assert str(path) in str(exc.value) + + +def test_subject_toml_refuses_a_non_utf8_descriptor_naming_it(tmp_path): + from dokimi.files import InputError + from dokimi.subjects.loader import load_subject + + path = tmp_path / "subject.toml" + path.write_bytes(b'id = "\xff"\n') + with pytest.raises(InputError, match="is not UTF-8 text") as exc: + load_subject(path) + assert str(path) in str(exc.value)