From dd8144b1752e05b6ea3218cb13991eb27a6e5262 Mon Sep 17 00:00:00 2001 From: Titus Date: Mon, 23 Nov 2026 18:07:50 +0100 Subject: [PATCH 1/2] 0.142.0: the doctor names what it could not read; a file nested too deep is skipped The doctor said nothing about a file the folder reader skipped. With one element file cut off mid-write it reported the other elements as the whole world and listed every link to the unread one as a link to an element that is not there. Report.unread (and unread in --json, after written) now lists each such file with why, the prose report prints the list before any finding, and any entry makes the exit code 1. A second file of one id and a directory that is no type's are listed too; a dot-prefixed file is not. A value nested thousands deep made json.loads raise RecursionError, which no reader caught: on an element file or a world.json the doctor and pack stopped with a traceback. _outside_json.loads turns that into a ValueError in plain words, and gives an integer of more than 4,300 digits a reason of its own in place of Python's advice about an interpreter setting. The folder reader, the archive reader, the Kanka and LegendKeeper doors and lint's world.json read parse through it. A test reads the package's syntax trees and fails on a json.loads that is neither that reader nor named. Not changed: python -m onlyworlds.lint reads element files through the schema distribution's own checker, which still stops on such a file. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 5 ++ README.md | 2 + src/onlyworlds/_outside_json.py | 29 ++++++++++ src/onlyworlds/_version.py | 2 +- src/onlyworlds/doctor.py | 43 +++++++++++++-- src/onlyworlds/folder.py | 4 +- src/onlyworlds/kanka.py | 3 +- src/onlyworlds/legendkeeper.py | 5 +- src/onlyworlds/lint.py | 4 +- src/onlyworlds/worldfile.py | 10 ++-- tests/test_doctor.py | 70 ++++++++++++++++++++++++- tests/test_outside_json.py | 93 +++++++++++++++++++++++++++++++++ 12 files changed, 254 insertions(+), 16 deletions(-) create mode 100644 src/onlyworlds/_outside_json.py create mode 100644 tests/test_outside_json.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d3a244..d033cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.142.0 (2026-11-23) + +- **The doctor names what it could not read.** On a folder, `Report.unread` (and `unread` in `--json`, after `written`) lists each file the folder reader did not read as an element, with why: a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. The prose report puts the list first, and any entry makes the exit code 1. Until now the doctor said nothing: with one element file cut off mid-write it reported the other elements as the whole world and listed every link to the unread one under "a link to an element that is not there". A dot-prefixed file is not listed. The API door's list is always empty. +- **A file nested too deep is skipped, not a traceback.** An element file or a `world.json` holding a value nested thousands deep made `read_folder` raise `RecursionError`, which nothing caught: the doctor and `pack` stopped with a traceback. Such a file is now read as one that cannot be read ("nested too deep to read"), the way a file that is not JSON is. The archive reader and the Kanka and LegendKeeper doors parse their files through the same reader. A number of more than 4,300 digits was already skipped; its reason now says so in plain words in place of Python's advice about an interpreter setting. +- Not changed: `python -m onlyworlds.lint` reads element files through the schema distribution's own checker, which still stops on a file nested that deep. - `KindLayout` and `AroundLayout` say in their docstrings that the `version` key is deprecated: it is always 1, the layout profile's mark carries no such key, and it leaves when the npm SDK's does, at its 5.0. Until now only a source comment said so, so `help()` and an editor's hover showed nothing. No behaviour changes. - A test holds the address parser's length check on a moment: a run of more than 4,300 digits after `@` is refused as `bad_moment` before `int()` can raise on it, and the readers of prose pass over it. diff --git a/README.md b/README.md index 9be0c31..e21e42c 100644 --- a/README.md +++ b/README.md @@ -253,6 +253,8 @@ for finding in report.findings: It looks for links to elements that are not there, Events that end before they start, elements with no links in or out, two elements of one type whose names collide once case, character width, spacing and punctuation are folded (a name shared across types, such as a Location and its Pin, is not one), stubs never filled (a known-of element older than `--days`, or an element with no text in any of its type's text fields, on every type but map, marker, pin and relation), and a charter Law untouched after `--changes` changes in the feed. On a folder it also checks `world.json`: a `format_version` older than this package's (flag 9), and an `api_key` in a `world.json` that git tracks (flag 10). On both doors it reads the world's own house rules (flag 11, the checks profile: `x_checks_rules` on the world's Charter, the newest Law with supertype Charter that carries the mark `x_charter_of`, applied by `onlyworlds.apply_checks`) and names every element a rule finds short, with each rule's scoped and short counts, and every rule it cannot apply, with why; an older marked Charter is a finding, its rules not applied; a Law with supertype Charter and no mark is lore, not a Charter and not a finding, and its rules are never applied. Flag 14 names a marked Guide or Domain whose links name an element that is not in the world or a hidden one (every other reader is served the Guide or Domain without it; not through a guest key, and the hidden half only through a key that is served hidden elements). On a spine world (one where an element carries an `x_spine_` key), flag 13 reads each element with `read_spine_element` and names an off-list supertype on a listed type, every value the reader drops and a probe not in the probe form; then, on a source world, it checks that each row (an Object, Construct, Location or Law of a listed kind, the Charter too) is kept by exactly one Seat (a Title with supertype `Seat`, through its field for the row's type; any other Title neither owns nor counts), that every `x_spine_depends_on` id is in the world (not through a guest key), that a `legacy` or `provenance` row has an Event with supertype `Retirement` that names it in `x_spine_retires` and links it through its typed field where the type has one (`objects`, `constructs`, `locations`; an Event has no `laws` field, so a Law's retirement is attributed by the key alone; only through a key that sees every element, hidden ones too), that no row is still at `gone` (its retirement is unfinished), and that no two rows of one row type share a name once trimmed and folded for case (a Seat or any other element is outside that rule). Whether a probe passes and `x_spine_probed` are not checked, and the report says so. A projection (a public world built from a spine, each row naming its keeping Seat in `x_spine_owner`) is marked on its World with `x_spine_projection`, `{source, at}`: `source` the projected-from world's id as a string, a UUID that is no element's id in this world, and `at` the ISO 8601 time of the last rebuild, which must parse; each is a finding on the world otherwise. On a projection only the projection's own checks run: every row must carry `x_spine_owner` (the keeping Seat's name in the source, which need match nothing in the projection) and no element may be hidden; the source's checks do not run there, and the report names each. On an unmarked world `x_spine_owner` is a finding (the projection's third check), and a malformed mark is a finding on the world, which is then read as unmarked. Each check says how much it could compare, and one it cannot run (a folder has no change feed; nothing records whether a message was read) is listed with the reason, never counted as clean. A finding on a message or a room thing (supertype Message, Board, Work item, Spec, Heart, Vote or Sitting) is marked `"kind": "message"` and listed last, outside the count of things to look at. `--json` prints the same report for a tool, and `--packet` prints the findings as work packets (the `packet` extension profile: a Relation with supertype `Work item`, its elements with a reason each under `x_packet_elements`, a JSON array, empty when clean) for a tool that lands them in a world or a parlor. The exit code is 0 when there is nothing to look at, 1 when there is (a message finding too), 2 when nothing could be read. +On a folder, the report names first what it could not read as an element (`report.unread`, each a `file` and a `why`): a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. Every check ran on the rest, so an element in such a file counts as not there and a link to it reads as a link to a missing element; any unread file makes the exit code 1. A dot-prefixed file is a tool's litter and is not listed. + The API door reads the key from `OW_API_KEY` and the PIN from `OW_API_PIN`, or from the toolkit's `ONLYWORLDS_API_KEY` and `ONLYWORLDS_API_PIN` when those are not set. ## The lint diff --git a/src/onlyworlds/_outside_json.py b/src/onlyworlds/_outside_json.py new file mode 100644 index 0000000..d819af3 --- /dev/null +++ b/src/onlyworlds/_outside_json.py @@ -0,0 +1,29 @@ +"""``json.loads`` for text this package did not write: a world folder's file, an archive, another tool's export. + +Two inputs that are JSON by the grammar make ``json.loads`` raise something its callers do not expect. +A value nested thousands deep raises ``RecursionError``, which is no ``ValueError``, so every reader +that catches "not JSON" let it through as a traceback. An integer of more than 4,300 digits raises a +plain ``ValueError`` whose message advises a Python setting. Here both are a ``ValueError`` in plain +words, so a caller's ``except ValueError`` reads either as a file it cannot read, and says why.""" + +from __future__ import annotations + +import json +import sys +from typing import Any + + +def _int(text: str) -> int: + limit = sys.get_int_max_str_digits() + if limit and len(text.lstrip("-")) > limit: + raise ValueError(f"a number of more than {limit} digits") + return int(text) + + +def loads(text: str, **kwargs: Any) -> Any: + """``json.loads(text, **kwargs)``, with the two cases above raised as ``ValueError``.""" + kwargs.setdefault("parse_int", _int) + try: + return json.loads(text, **kwargs) + except RecursionError: + raise ValueError("nested too deep to read") from None diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 8734918..193f98e 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.141.0" +__version__ = "0.142.0" diff --git a/src/onlyworlds/doctor.py b/src/onlyworlds/doctor.py index eedf6cf..762a3fc 100644 --- a/src/onlyworlds/doctor.py +++ b/src/onlyworlds/doctor.py @@ -28,6 +28,12 @@ 7. a message unread by its addressee after N days; 8. a charter (a Law with supertype Charter) untouched after N changes; +On the folder door the report also says what it did not read as an element (``Report.unread``, each a +``file`` and a ``why``, printed before any finding): a file the folder reader skipped (not JSON, not an +object, no ``id``), a second file of one id, a directory that is no type's. Every flag runs on the rest, +so an element in such a file counts as not there; any entry makes the exit code 1. It is no flag and has +no number. A dot-prefixed file is a tool's litter and is not listed. + and two from the file side, on the folder door only: (9) a ``format_version`` older than this package's ``FORMAT_VERSION``; (10) an ``api_key`` in ``world.json``'s ``api`` block when ``world.json`` is tracked by git. @@ -313,6 +319,10 @@ class Report: compared: dict[str, dict[str, Any]] = field(default_factory=dict) #: always 0: the doctor never writes written: int = 0 + #: the folder door: what the folder reader did not read as an element, each ``{file, why}`` + #: (a file that is not JSON, not an object or has no id; a second file of one id; a directory + #: that is no type's). Every flag ran on the rest. Always empty on the API door. + unread: list[dict[str, str]] = field(default_factory=list) def as_dict(self) -> dict[str, Any]: return { @@ -322,12 +332,13 @@ def as_dict(self) -> dict[str, Any]: "findings": self.findings, "compared": self.compared, "written": self.written, + "unread": self.unread, } @property def exit_code(self) -> int: - """1 for any finding, a message-shaped one too; 0 for none.""" - return 1 if self.findings else 0 + """1 for any finding, a message-shaped one too, or any unread file; 0 for none.""" + return 1 if self.findings or self.unread else 0 @property def to_look_at(self) -> list[dict[str, Any]]: @@ -1240,7 +1251,26 @@ def doctor_folder(folder: Folder, *, days: int = 14, changes: int = 50, now: _dt run.skip("8", "no feed in a folder") run.skip(PROPOSALS_FLAG, "proposals are kept on the server, not in a folder") _file_side(run, folder) - return run.done() + report = run.done() + report.unread = _unread(folder) + return report + + +def _unread(folder: Folder) -> list[dict[str, str]]: + """What ``read_folder`` did not read as an element, by path: every flag ran without it, so an + element in such a file counts as not there and a link to it reads as a link to a missing element. + A dot-prefixed file is a tool's litter, never an element, and is not listed.""" + + def rel(path: Path) -> str: + return path.relative_to(folder.root).as_posix() + + out = [{"file": rel(s.path), "why": s.reason} for s in folder.skipped if not s.path.name.startswith(".")] + out += [ + {"file": rel(d.ignored), "why": f"its id {d.id} is also in {rel(d.kept)}, which was read"} + for d in folder.duplicates + ] + out += [{"file": rel(d) + "/", "why": "not a type directory"} for d in folder.ignored_dirs] + return sorted(out, key=lambda x: x["file"]) # --------------------------------------------------------------------------- @@ -1493,6 +1523,13 @@ def _lines(report: Report) -> Iterable[str]: f"{len(report.not_run)} could not run, {report.written} things written" + (f" ({len(messages)} on messages and room things, listed last)" if messages else "") ) + if report.unread: + n = len(report.unread) + yield "" + yield f"Not read ({n}): everything below is about the rest of the folder" + yield " An element in one of these counts as not there, and a link to it reads as a link to a missing element." + for item in report.unread: + yield f" - {item['file']}: {item['why']}" yield from _by_flag(report.to_look_at) yield "" yield "What was checked" diff --git a/src/onlyworlds/folder.py b/src/onlyworlds/folder.py index f31567f..bfc3b32 100644 --- a/src/onlyworlds/folder.py +++ b/src/onlyworlds/folder.py @@ -15,7 +15,6 @@ from __future__ import annotations -import json import os import re import shutil @@ -26,6 +25,7 @@ from pathlib import Path from typing import Any, Literal +from . import _outside_json from ._jsonfmt import encode from ._schema import ELEMENT_TYPES @@ -445,7 +445,7 @@ def _reject_constant(token: str) -> Any: def _load_json(path: Path) -> Any: text = path.read_bytes().decode("utf-8-sig") - return json.loads(text, parse_constant=_reject_constant) + return _outside_json.loads(text, parse_constant=_reject_constant) def read_folder(root: str | os.PathLike[str], *, legacy: bool = True) -> Folder: diff --git a/src/onlyworlds/kanka.py b/src/onlyworlds/kanka.py index 1fdb045..f55fa5e 100644 --- a/src/onlyworlds/kanka.py +++ b/src/onlyworlds/kanka.py @@ -188,6 +188,7 @@ from pathlib import Path from typing import Any +from . import _outside_json from ._made import MadeName, _counts, _lines from ._schema import FIELD_KINDS, LINK_TARGETS from ._version import __version__ @@ -829,7 +830,7 @@ def __init__(self, files: Mapping[str, Callable[[], bytes]], source: Path, notes def _json(self, rel: str) -> Any: try: - return json.loads(self.files[rel]().decode("utf-8-sig")) + return _outside_json.loads(self.files[rel]().decode("utf-8-sig")) except (ValueError, UnicodeDecodeError) as exc: self.report.notes.append(_NOTE["not_json"].format(rel=rel, error=type(exc).__name__)) return None diff --git a/src/onlyworlds/legendkeeper.py b/src/onlyworlds/legendkeeper.py index 2520202..94817c6 100644 --- a/src/onlyworlds/legendkeeper.py +++ b/src/onlyworlds/legendkeeper.py @@ -382,6 +382,7 @@ from pathlib import Path from typing import Any, Protocol +from . import _outside_json from ._jsonfmt import encode from ._made import ANY_TYPE, MadeName, _counts, _lines from ._schema import ELEMENT_TYPES, FIELD_KINDS, LINK_TARGETS @@ -629,7 +630,7 @@ def _json_or_text(text: str) -> Any: or an object cannot ride a key-value row otherwise), else the text itself.""" if text[:1] in "[{": try: - return json.loads(text) + return _outside_json.loads(text) except ValueError: pass return text @@ -935,7 +936,7 @@ def __init__(self, path: str | os.PathLike[str], project_id: str | None = None) raise FileNotFoundError(f"{self.path}: no such export file") raw = _export_bytes(self.path) try: - data = json.loads(raw.decode("utf-8-sig")) + data = _outside_json.loads(raw.decode("utf-8-sig")) except ValueError: # UnicodeDecodeError and JSONDecodeError both raise ValueError(f"{self.path}: not a LegendKeeper export (not UTF-8 JSON)") from None if not isinstance(data, dict) or not isinstance(data.get("resources"), list): diff --git a/src/onlyworlds/lint.py b/src/onlyworlds/lint.py index a3f9109..98225c0 100644 --- a/src/onlyworlds/lint.py +++ b/src/onlyworlds/lint.py @@ -34,6 +34,8 @@ from types import ModuleType from typing import Any +from . import _outside_json + _WALK = Path(__file__).resolve().parent / "_walk" @@ -71,7 +73,7 @@ def lint(folder: str | Path) -> Any: def _linked(src: Path) -> bool: try: - world = json.loads((src / "world.json").read_text(encoding="utf-8")) + world = _outside_json.loads((src / "world.json").read_text(encoding="utf-8")) except (OSError, ValueError): return False return isinstance(world, dict) and bool(world.get("api")) diff --git a/src/onlyworlds/worldfile.py b/src/onlyworlds/worldfile.py index 2cb76a7..59bd632 100644 --- a/src/onlyworlds/worldfile.py +++ b/src/onlyworlds/worldfile.py @@ -59,7 +59,6 @@ from __future__ import annotations import io -import json import os import re import shutil @@ -73,6 +72,7 @@ from pathlib import Path from typing import IO, Any, Literal, NoReturn +from . import _outside_json from ._casefold import FOLD_RUNS from ._jsonfmt import encode from ._nfc import CLASS_RUNS, DECOMPOSITIONS, EXCLUSIONS @@ -556,7 +556,7 @@ def _reject_constant(token: str) -> Any: def _parse_world(data: bytes) -> dict[str, Any]: text = data.decode("utf-8", errors="replace").removeprefix(_BOM) try: - meta = json.loads(text, parse_constant=_reject_constant) + meta = _outside_json.loads(text, parse_constant=_reject_constant) except ValueError: _refuse("not_a_world") if not isinstance(meta, dict): @@ -812,7 +812,7 @@ def unreadable(why: str) -> NoReturn: ) try: - doc = json.loads(raw.decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant) + doc = _outside_json.loads(raw.decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant) except ValueError: # not UTF-8, or not JSON unreadable("is not JSON") if not isinstance(doc, list) or not all(isinstance(e, dict) for e in doc): @@ -843,7 +843,7 @@ def _hidden_element_file(rel: str, src: Path) -> bool: if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): return False try: - body = json.loads(src.read_bytes().decode("utf-8-sig")) + body = _outside_json.loads(src.read_bytes().decode("utf-8-sig")) except (UnicodeDecodeError, ValueError): return False return isinstance(body, dict) and is_hidden(body) @@ -864,7 +864,7 @@ def _without_author_fields(rel: str, src: Path) -> bytes | None: if len(segs) != 3 or segs[0] not in (ELEMENTS_DIR, LEGACY_SPATIAL_DIR) or not rel.lower().endswith(".json"): return None try: - body = json.loads(src.read_bytes().decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant) + body = _outside_json.loads(src.read_bytes().decode("utf-8").removeprefix(_BOM), parse_constant=_reject_constant) except ValueError: # not UTF-8, or not JSON return None if not isinstance(body, dict) or not any(k in body for k in _AUTHOR_FIELDS): diff --git a/tests/test_doctor.py b/tests/test_doctor.py index 86333e3..bad0196 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -141,7 +141,7 @@ def test_the_clean_world_has_nothing_to_look_at(tmp_path: Path) -> None: def test_the_json_report_keeps_its_key_order(tmp_path: Path) -> None: r = folder_report(tmp_path, clean()) - assert list(r.as_dict()) == ["world", "ran", "not_run", "findings", "compared", "written"] + assert list(r.as_dict()) == ["world", "ran", "not_run", "findings", "compared", "written", "unread"] assert set(r.compared) <= set(FLAGS) @@ -2263,3 +2263,71 @@ def test_14_through_the_api_by_role() -> None: assert contributor.compared[AIDS]["not_checked"] == ["hidden"] guest = api_report(FakeReader(planted, role="guest")) assert AIDS not in guest.ran and AIDS in {x["flag"] for x in guest.not_run} + + +# --- what the folder reader did not read as an element --------------------------- + + +def _file_of(root: Path, element_id: str) -> Path: + (path,) = [ + p for p in (root / "elements").rglob("*.json") if json.loads(p.read_text(encoding="utf-8"))["id"] == element_id + ] + return path + + +def _body(element_id: str, extra: str) -> str: + return '{"id": "' + element_id + '", "name": "Harbor", ' + extra + "}" + + +@pytest.mark.parametrize( + ("text", "why"), + [ + ('{"id": ', "unparseable JSON"), # a file cut off mid-write + (_body(L1, '"x_count": ' + "7" * 4301), "a number of more than 4300 digits"), + (_body(L1, '"x_deep": ' + "[" * 100_000 + "]" * 100_000), "nested too deep to read"), + ("[]", "not a JSON object"), + ('{"name": "Harbor"}', "no id: not an element"), + ], +) +def test_a_file_the_reader_could_not_read_is_named_before_any_finding(tmp_path: Path, text: str, why: str) -> None: + root = tmp_path / "w" + write_folder(root, WORLD, clean()) + whole = doctor_folder(read_folder(root), now=NOW) + assert whole.unread == [] and whole.exit_code == 0 and "Not read" not in render_prose(whole) + + path = _file_of(root, L1) + path.write_text(text, encoding="utf-8") + rel = path.relative_to(root).as_posix() + r = doctor_folder(read_folder(root), now=NOW) + assert [u["file"] for u in r.unread] == [rel] + assert why in r.unread[0]["why"] + assert r.exit_code == 1 + prose = render_prose(r) + assert "Not read (1): everything below is about the rest of the folder" in prose + assert f" - {rel}: " in prose + # It stands before the first finding: the links to the unread element read as links to nothing. + assert found(r, "1") and prose.index("Not read (1)") < prose.index("1. A link to an element that is not there") + code, out, err = run_main([str(root), "--json"]) + assert code == 1 and err == "" + assert json.loads(out)["unread"] == r.unread + + +def test_unread_lists_a_second_file_of_one_id_and_a_stray_directory_but_not_a_tools_litter(tmp_path: Path) -> None: + root = tmp_path / "w" + write_folder(root, WORLD, clean()) + first = _file_of(root, L1) + twin = first.with_name("zz-copy.json") + twin.write_bytes(first.read_bytes()) + (first.parent / ".sync-temp.json").write_text("{", encoding="utf-8") + (root / "elements" / "notes").mkdir() + r = doctor_folder(read_folder(root), now=NOW) + files = {u["file"]: u["why"] for u in r.unread} + assert [u["file"] for u in r.unread] == [twin.relative_to(root).as_posix(), "elements/notes/"] + assert files["elements/notes/"] == "not a type directory" + kept = first.relative_to(root).as_posix() + assert files[twin.relative_to(root).as_posix()] == f"its id {L1} is also in {kept}, which was read" + assert r.exit_code == 1 + + +def test_the_api_door_has_nothing_unread() -> None: + assert Report(world={}).unread == [] and Report(world={}).exit_code == 0 diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py new file mode 100644 index 0000000..89993fd --- /dev/null +++ b/tests/test_outside_json.py @@ -0,0 +1,93 @@ +"""Text this package did not write (a folder's file, an archive, another tool's export) is parsed through +``_outside_json.loads``: two inputs that are JSON by the grammar must come back as a ``ValueError`` a reader +catches, never a traceback. And every ``json.loads`` in the package is either that one or named here.""" + +from __future__ import annotations + +import ast +import json +from pathlib import Path + +import pytest + +from onlyworlds import _outside_json, read_folder, write_folder +from onlyworlds.folder import FORMAT_VERSION + +SRC = Path(__file__).resolve().parent.parent / "src" / "onlyworlds" +DEEP = "[" * 100_000 + "]" * 100_000 +LONG = "7" * 4301 + + +def test_what_json_reads_it_reads_the_same() -> None: + for text in ('{"a": [1, 2.5, -3, 1e400, "x", null, true]}', "12345678901234567890", "-" + "7" * 4300, "[[[[1]]]]"): + assert _outside_json.loads(text) == json.loads(text) + assert _outside_json.loads("1", parse_int=float) == 1.0 + + +@pytest.mark.parametrize( + ("text", "why"), + [ + (DEEP, "nested too deep to read"), + ('{"a": ' + DEEP + "}", "nested too deep to read"), + (LONG, "a number of more than 4300 digits"), + ("-" + LONG, "a number of more than 4300 digits"), + ('{"a": [' + LONG + "]}", "a number of more than 4300 digits"), + ], +) +def test_too_deep_and_too_long_are_value_errors_in_plain_words(text: str, why: str) -> None: + with pytest.raises(ValueError, match=why) as err: + _outside_json.loads(text) + assert not isinstance(err.value, json.JSONDecodeError) + assert "set_int_max_str_digits" not in str(err.value) + + +def test_text_that_is_not_json_is_still_a_decode_error() -> None: + with pytest.raises(json.JSONDecodeError): + _outside_json.loads('{"id": ') + + +@pytest.mark.parametrize( + ("value", "why"), [(DEEP, "nested too deep to read"), (LONG, "a number of more than 4300 digits")] +) +def test_the_folder_reader_skips_such_a_file_with_the_reason(tmp_path: Path, value: str, why: str) -> None: + eid = "l0000000-0000-7000-8000-000000000001" + world = {"id": "w0000000-0000-7000-8000-000000000000", "name": "W", "format_version": FORMAT_VERSION} + write_folder(tmp_path / "w", world, {"location": [{"id": eid, "name": "Harbor"}]}) + (path,) = (tmp_path / "w" / "elements").rglob("*.json") + path.write_text('{"id": "' + eid + '", "name": "Harbor", "x": ' + value + "}", encoding="utf-8") + folder = read_folder(tmp_path / "w") + assert folder.all_elements() == {} + assert [(s.path, s.reason) for s in folder.skipped] == [(path, f"unparseable JSON: {why}")] + + +#: Every other ``json.loads`` in the package, by file, with what it reads. A new one fails this test until it +#: goes through ``_outside_json`` or gets a line here. +NAMED = { + "_outside_json.py": 1, # the reader itself + "calendar.py": 3, # a calendar's own text, with its own integer rule and a parser past json's depth + "errors.py": 2, # a response body from the server + "http.py": 1, # a response body from the server + "kanka.py": 1, # the package's own tables + "legendkeeper.py": 1, # the import map a person keeps beside their export + "lint.py": 1, # the package's own schema + "push.py": 1, # a line of the log this package writes +} + + +def test_every_json_loads_is_the_outside_reader_or_named() -> None: + def calls(path: Path, module: str) -> int: + """Calls of ``.loads`` or ``.load`` in the file's code: its syntax tree, never its text.""" + return sum( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in ("loads", "load") + and isinstance(node.func.value, ast.Name) + and node.func.value.id == module + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))) + ) + + files = sorted(SRC.glob("*.py")) + assert len(files) > 40 # the search saw the package + assert {p.name: calls(p, "json") for p in files if calls(p, "json")} == NAMED + used = {p.name: calls(p, "_outside_json") for p in files if calls(p, "_outside_json")} + assert used == {"folder.py": 1, "kanka.py": 1, "legendkeeper.py": 2, "lint.py": 1, "worldfile.py": 4} From 3d356f63b3a3caa8bf6bc1eced2bd82eb09a8f34 Mon Sep 17 00:00:00 2001 From: Titus Date: Mon, 23 Nov 2026 18:15:55 +0100 Subject: [PATCH 2/2] The depth refused is one number on every platform The first version of this change relied on json.loads raising RecursionError for a value nested 100,000 deep. Python 3.14 on Linux reads that value whole, so the same file was skipped on Windows and read on Linux, and the depth was left to whatever walked the value next. _outside_json.loads now refuses nesting past MAX_DEPTH (200) itself, after the parse, with a loop that keeps its own stack; a RecursionError from the parser reads as the same refusal. A test holds the line at 200 and 201 for arrays and for objects, so each interpreter in CI shows it parses that deep and refuses one more. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 2 +- src/onlyworlds/_outside_json.py | 47 ++++++++++++++++++++++++++++----- tests/test_doctor.py | 2 +- tests/test_outside_json.py | 22 ++++++++++++--- 4 files changed, 61 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d033cdc..bd85bfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ The package version runs on its own semver; the schema it is generated from is ` ## 0.142.0 (2026-11-23) - **The doctor names what it could not read.** On a folder, `Report.unread` (and `unread` in `--json`, after `written`) lists each file the folder reader did not read as an element, with why: a file that is not JSON, is not an object or has no `id`, a second file of one id, a directory that is no type's. The prose report puts the list first, and any entry makes the exit code 1. Until now the doctor said nothing: with one element file cut off mid-write it reported the other elements as the whole world and listed every link to the unread one under "a link to an element that is not there". A dot-prefixed file is not listed. The API door's list is always empty. -- **A file nested too deep is skipped, not a traceback.** An element file or a `world.json` holding a value nested thousands deep made `read_folder` raise `RecursionError`, which nothing caught: the doctor and `pack` stopped with a traceback. Such a file is now read as one that cannot be read ("nested too deep to read"), the way a file that is not JSON is. The archive reader and the Kanka and LegendKeeper doors parse their files through the same reader. A number of more than 4,300 digits was already skipped; its reason now says so in plain words in place of Python's advice about an interpreter setting. +- **A file nested too deep is skipped, not a traceback.** An element file or a `world.json` holding a value nested 100,000 deep made `read_folder` raise `RecursionError` on Windows and on Python 3.12 and 3.13, which nothing caught: the doctor and `pack` stopped with a traceback. Python 3.14 on Linux read the same file whole, and left the depth to whatever walked the value next. A value nested more than 200 deep is now refused on every platform, as a file that cannot be read ("nested more than 200 deep"), the way a file that is not JSON is. The archive reader and the Kanka and LegendKeeper doors parse their files through the same reader. A number of more than 4,300 digits was already skipped; its reason now says so in plain words in place of Python's advice about an interpreter setting. - Not changed: `python -m onlyworlds.lint` reads element files through the schema distribution's own checker, which still stops on a file nested that deep. - `KindLayout` and `AroundLayout` say in their docstrings that the `version` key is deprecated: it is always 1, the layout profile's mark carries no such key, and it leaves when the npm SDK's does, at its 5.0. Until now only a source comment said so, so `help()` and an editor's hover showed nothing. No behaviour changes. - A test holds the address parser's length check on a moment: a run of more than 4,300 digits after `@` is refused as `bad_moment` before `int()` can raise on it, and the readers of prose pass over it. diff --git a/src/onlyworlds/_outside_json.py b/src/onlyworlds/_outside_json.py index d819af3..86d4ec4 100644 --- a/src/onlyworlds/_outside_json.py +++ b/src/onlyworlds/_outside_json.py @@ -1,10 +1,17 @@ """``json.loads`` for text this package did not write: a world folder's file, an archive, another tool's export. -Two inputs that are JSON by the grammar make ``json.loads`` raise something its callers do not expect. -A value nested thousands deep raises ``RecursionError``, which is no ``ValueError``, so every reader -that catches "not JSON" let it through as a traceback. An integer of more than 4,300 digits raises a -plain ``ValueError`` whose message advises a Python setting. Here both are a ``ValueError`` in plain -words, so a caller's ``except ValueError`` reads either as a file it cannot read, and says why.""" +Two inputs that are JSON by the grammar make ``json.loads`` do something its callers do not expect. + +A value nested very deep: where the interpreter's own limit is met first, ``json.loads`` raises +``RecursionError``, which is no ``ValueError``, so every reader that catches "not JSON" let it through as +a traceback. Where the limit is higher (Python 3.14 on Linux reads 100,000 levels), the value comes back +whole and the next recursive walk over it fails instead. So the depth is refused here by one number, +``MAX_DEPTH``, the same on every platform. + +An integer of more than 4,300 digits: a plain ``ValueError`` whose message advises a Python setting. + +Here both are a ``ValueError`` in plain words, so a caller's ``except ValueError`` reads either as a file +it cannot read, and says why.""" from __future__ import annotations @@ -12,6 +19,12 @@ import sys from typing import Any +#: The deepest nesting read: a value at the top is depth 0, an object or array there depth 1, what it holds +#: depth 2. No world data comes near it; every supported interpreter parses this deep. +MAX_DEPTH = 200 + +_TOO_DEEP = f"nested more than {MAX_DEPTH} deep" + def _int(text: str) -> int: limit = sys.get_int_max_str_digits() @@ -20,10 +33,30 @@ def _int(text: str) -> int: return int(text) +def _too_deep(value: Any) -> bool: + """Whether any object or array sits deeper than ``MAX_DEPTH``. A loop with its own stack, never recursion.""" + stack: list[tuple[Any, int]] = [(value, 1)] + while stack: + item, depth = stack.pop() + if isinstance(item, dict): + children: Any = item.values() + elif isinstance(item, list): + children = item + else: + continue + if depth > MAX_DEPTH: + return True + stack.extend((child, depth + 1) for child in children if isinstance(child, (dict, list))) + return False + + def loads(text: str, **kwargs: Any) -> Any: """``json.loads(text, **kwargs)``, with the two cases above raised as ``ValueError``.""" kwargs.setdefault("parse_int", _int) try: - return json.loads(text, **kwargs) + value = json.loads(text, **kwargs) except RecursionError: - raise ValueError("nested too deep to read") from None + raise ValueError(_TOO_DEEP) from None + if _too_deep(value): + raise ValueError(_TOO_DEEP) + return value diff --git a/tests/test_doctor.py b/tests/test_doctor.py index bad0196..661d005 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -2284,7 +2284,7 @@ def _body(element_id: str, extra: str) -> str: [ ('{"id": ', "unparseable JSON"), # a file cut off mid-write (_body(L1, '"x_count": ' + "7" * 4301), "a number of more than 4300 digits"), - (_body(L1, '"x_deep": ' + "[" * 100_000 + "]" * 100_000), "nested too deep to read"), + (_body(L1, '"x_deep": ' + "[" * 100_000 + "]" * 100_000), "nested more than 200 deep"), ("[]", "not a JSON object"), ('{"name": "Harbor"}', "no id: not an element"), ], diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py index 89993fd..30abd64 100644 --- a/tests/test_outside_json.py +++ b/tests/test_outside_json.py @@ -27,8 +27,8 @@ def test_what_json_reads_it_reads_the_same() -> None: @pytest.mark.parametrize( ("text", "why"), [ - (DEEP, "nested too deep to read"), - ('{"a": ' + DEEP + "}", "nested too deep to read"), + (DEEP, "nested more than 200 deep"), + ('{"a": ' + DEEP + "}", "nested more than 200 deep"), (LONG, "a number of more than 4300 digits"), ("-" + LONG, "a number of more than 4300 digits"), ('{"a": [' + LONG + "]}", "a number of more than 4300 digits"), @@ -41,13 +41,29 @@ def test_too_deep_and_too_long_are_value_errors_in_plain_words(text: str, why: s assert "set_int_max_str_digits" not in str(err.value) +def test_the_depth_refused_is_one_number_on_every_platform() -> None: + def nest(depth: int, open_: str, close: str) -> str: + return open_ * depth + close * depth + + assert _outside_json.MAX_DEPTH == 200 + for open_, close in (("[", "]"), ('{"a": ', "}")): + inner = "1" if open_ != "[" else "" + text = open_ * 200 + inner + close * 200 + assert _outside_json.loads(text) == json.loads(text) + with pytest.raises(ValueError, match="nested more than 200 deep"): + _outside_json.loads(open_ * 201 + inner + close * 201) + assert _outside_json.loads('{"a": ' + nest(199, "[", "]") + "}") is not None + with pytest.raises(ValueError, match="nested more than 200 deep"): + _outside_json.loads('{"a": ' + nest(200, "[", "]") + "}") + + def test_text_that_is_not_json_is_still_a_decode_error() -> None: with pytest.raises(json.JSONDecodeError): _outside_json.loads('{"id": ') @pytest.mark.parametrize( - ("value", "why"), [(DEEP, "nested too deep to read"), (LONG, "a number of more than 4300 digits")] + ("value", "why"), [(DEEP, "nested more than 200 deep"), (LONG, "a number of more than 4300 digits")] ) def test_the_folder_reader_skips_such_a_file_with_the_reason(tmp_path: Path, value: str, why: str) -> None: eid = "l0000000-0000-7000-8000-000000000001"