Skip to content
Draft
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` 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: <file> 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.
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 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 `<file> 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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!--
Copyright (C) 2026 Intel Corporation
SPDX-License-Identifier: Apache-2.0
-->

### 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 `<file> is not valid TOML: ...` or `cannot read <file>: ...`. A TOML descriptor that is not UTF-8 already exited 2, without naming the file; it now names it, `<file> 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 <file>: ...` 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 `<config>: node wrote a config nested too deeply to read`, instead of a traceback.
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
21 changes: 18 additions & 3 deletions dokimi/dokimi/subjects/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 InputError, read_json_input
from dokimi.treatments.specs import combine_specs

from .models import NON_ARM_KINDS, SUBJECT_KINDS, SubjectArtifact, SubjectDescriptor, SubjectMember, SubjectSuite
Expand Down Expand Up @@ -95,14 +95,29 @@
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"))
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

Check warning on line 113 in dokimi/dokimi/subjects/loader.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-boolop `getattr(exc, "strerror", None) or exc` -> `getattr(exc, 'strerror', None) and exc`

Check warning on line 113 in dokimi/dokimi/subjects/loader.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `getattr(exc, "strerror", None) or exc` -> `(getattr(exc, "strerror", None))`

Check warning on line 113 in dokimi/dokimi/subjects/loader.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `getattr(exc, "strerror", None) or exc` -> `(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")
Expand Down
11 changes: 10 additions & 1 deletion dokimi/dokimi/subjects/run_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -118,7 +119,15 @@
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

Check warning on line 127 in dokimi/dokimi/subjects/run_plan.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-boolop `getattr(exc, "strerror", None) or exc` -> `getattr(exc, 'strerror', None) and exc`

Check warning on line 127 in dokimi/dokimi/subjects/run_plan.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `getattr(exc, "strerror", None) or exc` -> `(getattr(exc, "strerror", None))`

Check warning on line 127 in dokimi/dokimi/subjects/run_plan.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: drop-clause `getattr(exc, "strerror", None) or exc` -> `(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:
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/task_formats/datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion dokimi/dokimi/task_formats/imports/native_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion dokimi/dokimi/task_formats/imports/openai_evals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
3 changes: 3 additions & 0 deletions dokimi/dokimi/task_formats/imports/promptfoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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

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
Loading
Loading