diff --git a/CHANGELOG.md b/CHANGELOG.md index 9efc261..4eded70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ The package version runs on its own semver; the schema it is generated from is ` ## Unreleased +## 0.156.1 (2026-11-27) + +- **Fixed: the depth check before a parse took time growing with the square of a text's length.** Since 0.155.0 every reader of a file this package did not write (`read_folder`, `read_world_file`, the import doors) first counts the text's nesting, and that scan cut the strings out with a pattern that, on a string left open, retried from every quote to the end of the text: a 16 KB file of escaped quotes took about a second, and a 1 MB one would take about an hour. Valid JSON heavy with quotes read several times slower than before the check. The scan is now one pass over the brackets, quotes and backslashes, linear in the length, with the same answers: held to the old reading on 20,000 random texts, and a 40 KB text of that shape is timed (the old scan took 6.7 s on it). + ## 0.156.0 (2026-11-27) - **A world file refused for a `world.json` it cannot read says what is wrong with it**: `WorldFileError.world_fault` is `too_deep` (nested past 200 levels), `not_json` or `number_out_of_range` (a number too large to read), beside the reason `not_a_world` the folder format gives it, so a tool reads the field, never the message. It is None on every other refusal, a missing `world.json` or one with no id included. diff --git a/src/onlyworlds/_outside_json.py b/src/onlyworlds/_outside_json.py index 64e28a7..15e1e59 100644 --- a/src/onlyworlds/_outside_json.py +++ b/src/onlyworlds/_outside_json.py @@ -24,7 +24,6 @@ import math import re import sys -from itertools import accumulate 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 @@ -52,26 +51,41 @@ def _int(text: str) -> int: return int(text) -#: A whole JSON string: a backslash escapes the character after it. -_STRING = re.compile(r'"[^"\\]*(?:\\.[^"\\]*)*"', re.DOTALL) -_BRACKET = re.compile(r"[\[\]{}]") -_STEP = {"[": 1, "{": 1, "]": -1, "}": -1} +#: The characters the depth scan reads: the four brackets, the quote and the backslash. +_SPECIAL = re.compile(r'[\[\]{}"\\]') def _text_too_deep(text: str) -> bool: """Whether the text opens an object or array deeper than ``MAX_DEPTH``, counted in the text itself as each one opens, before any parse (the folder format's rule since serial 148): so each value of a repeated key counts, and a text past the line is too deep whatever else is wrong with it. Brackets inside a string are - not counted; a string left open runs to the end of the text, as the npm SDK's scan reads it.""" - outside = _STRING.sub("", text) - open_quote = outside.find('"') - if open_quote >= 0: - outside = outside[:open_quote] - brackets = "".join(_BRACKET.findall(outside)) + not counted, and a backslash in a string escapes the character after it; a string left open runs to the + end of the text, as the npm SDK's scan reads it. One pass, in time linear in the text's length.""" # No text can open more levels than it has opening brackets. - if brackets.count("[") + brackets.count("{") <= MAX_DEPTH: + if text.count("[") + text.count("{") <= MAX_DEPTH: return False - return max(accumulate(_STEP[b] for b in brackets)) > MAX_DEPTH + depth = 0 + in_string = False + escaped_at = -1 + for m in _SPECIAL.finditer(text): + i = m.start() + if i == escaped_at: + continue + c = m.group() + if in_string: + if c == "\\": + escaped_at = i + 1 + elif c == '"': + in_string = False + elif c == '"': + in_string = True + elif c == "[" or c == "{": + depth += 1 + if depth > MAX_DEPTH: + return True + elif c == "]" or c == "}": + depth -= 1 + return False def loads(text: str, **kwargs: Any) -> Any: diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 34c0061..e994588 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.156.0" +__version__ = "0.156.1" diff --git a/tests/test_outside_json.py b/tests/test_outside_json.py index eddb68d..9ab6aa7 100644 --- a/tests/test_outside_json.py +++ b/tests/test_outside_json.py @@ -315,3 +315,48 @@ def test_the_kanka_door_writes_no_file_holding_a_number_the_export_does_not(tmp_ written = sorted(out.rglob("*.json")) assert len(written) > 10 assert not any("Infinity" in p.read_text(encoding="utf-8") for p in written) + + +def _too_deep_by_strings_removed(text: str, limit: int) -> bool: + """The scan as 0.156.0 wrote it (closed strings cut out by a pattern, an open one to the end): its + answers, kept as the reading the one-pass scan must give. Its time grew with the square of the length.""" + import re + from itertools import accumulate + + outside = re.sub(r'"[^"\\]*(?:\\.[^"\\]*)*"', "", text, flags=re.DOTALL) + if '"' in outside: + outside = outside[: outside.find('"')] + steps = [1 if c in "[{" else -1 for c in outside if c in "[]{}"] + return bool(steps) and max(accumulate(steps)) > limit + + +def test_the_depth_scan_answers_as_the_strings_removed_reading(monkeypatch: pytest.MonkeyPatch) -> None: + import random + + monkeypatch.setattr(_outside_json, "MAX_DEPTH", 3) + rng = random.Random(149) + alphabet = '[]{}"\\a,' + for _ in range(20_000): + text = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 40))) + assert _outside_json._text_too_deep(text) == _too_deep_by_strings_removed(text, 3), repr(text) + + +def test_the_depth_scan_is_linear_on_a_string_left_open_full_of_escaped_quotes() -> None: + import time + + # The shape that took the square of its length in 0.156.0: about a second at 16 KB, here 40 KB. + text = "[" * 300 + '"' + '\\"' * 20_000 + start = time.perf_counter() + assert _outside_json._text_too_deep(text) is True + ms = (time.perf_counter() - start) * 1000 + assert ms < 2000, f"{round(ms)} ms" + + +def test_valid_json_heavy_with_quotes_reads_in_linear_time() -> None: + import time + + text = json.dumps({"x": '"' * 500_000, "y": ["[" * 300]}) + start = time.perf_counter() + assert _outside_json.loads(text)["y"] == ["[" * 300] + ms = (time.perf_counter() - start) * 1000 + assert ms < 2000, f"{round(ms)} ms"