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

Filter by extension

Filter by extension

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

### Fixed

- **A 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` (eval and optional answers files), conformance expectations (`repos/conformance.py`), `catalog scan --resume` and `catalog novelty --resume` (`--jsonl` rows), `catalog repair-receipt`, `report opportunities`, `eval coverage` 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: <file> is not valid JSON: ...`, and refuses a device path such as `/dev/null` as `not a file`. The other readers handle deep nesting the same way as malformed input. `report eval` continues without answers from an unreadable answers file, and repository comparisons treat an unreadable batch stamp as missing. 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.
2 changes: 1 addition & 1 deletion dokimi/dokimi/commands/catalog_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/commands/opportunities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/commands/repair_receipt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down
18 changes: 12 additions & 6 deletions dokimi/dokimi/eval_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)))
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/external/upstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}\"")
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/mcp/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/novelty/sweep.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion dokimi/dokimi/report/eval_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/repos/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}

Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/repos/conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions dokimi/dokimi/repos/ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from __future__ import annotations

import json
import math
import re
from collections import Counter
Expand All @@ -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

Expand Down Expand Up @@ -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))
Expand Down
9 changes: 2 additions & 7 deletions dokimi/dokimi/skill_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions dokimi/dokimi/skills/formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/task_formats/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}")
Expand Down
1 change: 0 additions & 1 deletion dokimi/scripts/duplicates_baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]}
}
}
167 changes: 167 additions & 0 deletions dokimi/tests/test_deep_user_inputs.py
Original file line number Diff line number Diff line change
@@ -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)
Loading