diff --git a/CHANGELOG.md b/CHANGELOG.md index 86df296..f0bb377 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.148.2 (2026-11-24) + +- **Fixed: a stored calendar no longer sets what one date label costs.** `format_step` collapsed the separators around an empty token with a regular expression that took cubic time on a long run of white space (a template with 1,000 spaces: about half a second for one label; 4,000 spaces: about a minute), and trimmed a label's edges with one that took quadratic time on a long run of commas; both are one pass now. A year was built as a list of every day on each call, so a month of 5,000,000 days cost seconds a label in `format_step`, `weekday_for_step`, `breakdown_step` and `parse_date`; a month is one run now, and each answer is arithmetic. Every answer is the same as before: the profile's fixture, the old and new builds compared on 7,071 steps of the fixture's calendars and of made ones (formats, weekdays, breakdowns and parses), and eight timed cases in `tests/fixtures/calendar-cost.cases.json`, the same bytes as the npm SDK's, each inside its bound. Not changed: a calendar with 1,500 eras still costs about 20 milliseconds a label, and one with 800 leap rules about a tenth of a second. + ## 0.148.1 (2026-11-24) - **Fixed: `read_world_file` no longer refuses a world file whose world holds a tool's own `world.json` under a dot-folder** (`abbey/.atlas/world.json`, or deeper, `abbey/elements/character/.trash/world.json`). A dot-folder is never a world, wherever it sits, as the folder reader already had it: `read_folder` never reads a dot-folder. So the same world now opens as a file and as a folder. Only the check for a second `world.json` inside the world skips those paths; every other check still runs on their entries (paths, names, duplicates, collisions, size and count), and they are still returned in `entries`. A nested `world.json` outside a dot-folder and outside `records/` (`abbey/inner/world.json`) is still refused. This follows a ruling on the world-file conformance checks OW-4 and OW-5; the conformance case comes with the next schema distribution serial. diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index dab408e..b4e2c30 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.148.1" +__version__ = "0.148.2" diff --git a/src/onlyworlds/calendar.py b/src/onlyworlds/calendar.py index 81de25e..5785cb7 100644 --- a/src/onlyworlds/calendar.py +++ b/src/onlyworlds/calendar.py @@ -77,6 +77,7 @@ from __future__ import annotations +import bisect import json import math import re @@ -245,7 +246,6 @@ def __repr__(self) -> str: ) + "".join(map(chr, (0x202F, 0x205F, 0x3000, 0xFEFF))) _S: Final = "[" + re.escape(_JS_SPACE) + "]" _MIDDOT: Final = chr(0xB7) -_SEP: Final = "[" + re.escape(_JS_SPACE) + ",;" + _MIDDOT + "]" def _js_trim(s: str) -> str: @@ -1021,11 +1021,129 @@ def push(after: int) -> None: return slots +class _Run(NamedTuple): + start: int + length: int + month: int # 0 for an intercalary day + slot: _Slot | None # the intercalary day's slot; None for a month's run of days + + +class _Year: + """One year's slots, in ``_year_slots``' order, asked four questions. Where every month length is a + whole ``int`` a month is one run and each answer is arithmetic, so a long month costs nothing; any + other config keeps ``_year_slots``' list and the questions are asked of it as before, so an odd input + answers as it did.""" + + __slots__ = ("_list", "_runs", "_starts", "total") + + def __init__(self, cfg: object, y: float) -> None: + runs = _year_runs(cfg, y) + self._list: list[_Slot] | None = _year_slots(cfg, y) if runs is None else None + self._runs: list[_Run] = runs or [] + self._starts = [r.start for r in self._runs] + if self._list is not None: + self.total = len(self._list) + else: + self.total = self._runs[-1].start + self._runs[-1].length if self._runs else 0 + + def at(self, i: float) -> Any: + """``slots[i]``: undefined unless ``i`` is a whole index inside the year.""" + if self._list is not None: + return _at(self._list, i) + if not (i.is_integer() and 0 <= i < self.total): + return _UNDEF + k = int(i) + r = self._runs[bisect.bisect_right(self._starts, k) - 1] + return r.slot if r.slot is not None else _Slot("month", r.month, k - r.start + 1, None) + + def skipped_before(self, offset: float) -> float: + """The intercalary days out of the week at the indexes 0, 1, ... below ``offset``; reading past the + year's last slot throws, as the reference's loop does.""" + n = 0.0 + if self._list is not None: + i = 0 + while i < offset: + s = _at(self._list, i) + if s is _UNDEF: + raise TypeError("Cannot read properties of undefined (reading 'kind')") + if s.kind == "intercalary" and _prop(s.intercalary, "in_week") is False: + n += 1 + i += 1 + return n + if not offset > 0: # the loop never runs: zero, a negative or NaN + return n + if offset > self.total: + raise TypeError("Cannot read properties of undefined (reading 'kind')") + for r in self._runs: + if r.start >= offset: + break + if r.slot is not None and _prop(r.slot.intercalary, "in_week") is False: + n += 1 + return n + + def index_of_intercalary(self, intercalary: object) -> int: + if self._list is not None: + return next( + (i for i, s in enumerate(self._list) if s.kind == "intercalary" and s.intercalary is intercalary), -1 + ) + return next((r.start for r in self._runs if r.slot is not None and r.slot.intercalary is intercalary), -1) + + def index_of_day(self, month: object, day: object) -> int: + if self._list is not None: + return next( + (i for i, s in enumerate(self._list) if s.kind == "month" and s.month == month and s.day == day), -1 + ) + if not _is_finite_number(day): + return -1 + d = cast(float, day) + for r in self._runs: + if r.slot is None and r.month == month: + k = int(d) + return r.start + k - 1 if k == d and 1 <= k <= r.length else -1 + return -1 + + +def _is_finite_number(v: object) -> bool: + return isinstance(v, (int, float)) and math.isfinite(v) + + +def _year_runs(cfg: object, y: float) -> list[_Run] | None: + """``_year_slots`` as runs, or None where a month's length is not a whole ``int`` (or the names and + lengths are not lists, or fewer lengths than names): the list is built for those.""" + months = _bundle(cfg, "months") + if not _truthy(months): + return [] + names, lengths = _get(months, "names"), _get(months, "lengths") + if not isinstance(names, list) or not isinstance(lengths, list) or len(lengths) < len(names): + return None + if any(type(v) is not int for v in lengths[: len(names)]): + return None + inter = _list_or_empty(_prop(cfg, "intercalary")) + runs: list[_Run] = [] + at = 0 + + def push(after: int) -> None: + nonlocal at + for ic in inter: + if _strict_eq(_get(ic, "after_month"), after) and _in_year(cfg, ic, y): + runs.append(_Run(at, 1, 0, _Slot("intercalary", 0, 0, ic))) + at += 1 + + push(0) + for m in range(1, len(names) + 1): + days = lengths[m - 1] + if days > 0: + runs.append(_Run(at, days, m, None)) + at += days + push(m) + return runs + + class _Position(NamedTuple): abs_year: float offset: float slot: _Slot | None - slots: list[_Slot] | None + slots: _Year | None def _position(cfg: object, step: float) -> _Position: @@ -1033,8 +1151,8 @@ def _position(cfg: object, step: float) -> _Position: offset = step - _year_start(cfg, y) if not _truthy(_bundle(cfg, "months")): return _Position(y, offset, None, None) - slots = _year_slots(cfg, y) - slot = _at(slots, offset) + slots = _Year(cfg, y) + slot = slots.at(offset) return _Position(y, offset, None if slot is _UNDEF else slot, slots) @@ -1061,16 +1179,7 @@ def _weekday(cfg: object, step: float, pos: _Position) -> Any: skipped_before = y * len([i for i in skipped if _nullish(_get(i, "every_years"))]) for r in _leap_rules(cfg, skipped): skipped_before += _leap_years_before(y, r) - skipped_in_year = 0.0 - if pos.slots is not None: - i = 0 - while i < pos.offset: - s = _at(pos.slots, i) - if s is _UNDEF: - raise TypeError("Cannot read properties of undefined (reading 'kind')") - if s.kind == "intercalary" and _prop(s.intercalary, "in_week") is False: - skipped_in_year += 1 - i += 1 + skipped_in_year = pos.slots.skipped_before(pos.offset) if pos.slots is not None else 0.0 counted = step - skipped_before - skipped_in_year return _none(_at(names, _floor_mod(counted, _to_number(length)))) @@ -1134,9 +1243,41 @@ def breakdown_step(cfg: Mapping[str, Any], step: int) -> StepBreakdown: #: U+E000, a private-use code point, as the reference's (never NUL). _EMPTY_KNOWN: Final = chr(0xE000) _TOKEN = re.compile(r"\{([a-z_]+)\}") -_COLLAPSE = re.compile(_S + "*[,;" + _MIDDOT + "]?" + _S + "*" + _EMPTY_KNOWN + _S + "*[,;" + _MIDDOT + "]?" + _S + "*") _SPACES = re.compile(_S + "{2,}") -_EDGES = re.compile(r"\A" + _SEP + "+|" + _SEP + r"+\Z") +_MARKS: Final = ",;" + _MIDDOT +_EDGE_CHARS: Final = _JS_SPACE + _MARKS + + +def _collapse(text: str) -> str: + """The reference's ``/\\s*[,;·]?\\s*\\uE000\\s*[,;·]?\\s*/g`` replaced by one space, in one pass: each + marker takes the white space, at most one mark and white space before it (back to where the last + replacement ended) and the same after it. A regular expression took cubic time on a long run of white + space that held no marker.""" + i = text.find(_EMPTY_KNOWN) + if i == -1: + return text + n, done, parts = len(text), 0, [] + while i != -1: + j = i + while j > done and text[j - 1] in _JS_SPACE: + j -= 1 + if j > done and text[j - 1] in _MARKS: + j -= 1 + while j > done and text[j - 1] in _JS_SPACE: + j -= 1 + k = i + 1 + while k < n and text[k] in _JS_SPACE: + k += 1 + if k < n and text[k] in _MARKS: + k += 1 + while k < n and text[k] in _JS_SPACE: + k += 1 + parts.append(text[done:j]) + parts.append(" ") + done = k + i = text.find(_EMPTY_KNOWN, done) + parts.append(text[done:]) + return "".join(parts) def _render(template: object, values: dict[str, Any]) -> str: @@ -1152,8 +1293,9 @@ def token(m: re.Match[str]) -> str: return _EMPTY_KNOWN if _nullish(v) or v == "" else _js_string(v) out = _TOKEN.sub(token, template) - out = _js_trim(_SPACES.sub(" ", _COLLAPSE.sub(" ", out))) - return _EDGES.sub("", out) + out = _js_trim(_SPACES.sub(" ", _collapse(out))) + # The reference's /^[\s,;·]+|[\s,;·]+$/g: its second half took quadratic time on a long run of marks. + return out.strip(_EDGE_CHARS) def _era_label(era: object) -> Any: @@ -1428,16 +1570,14 @@ def resolve_in_year(abs_year: float) -> ParseResult | ParseError: start = _year_start(cfg, abs_year) if month_index is None and intercalary is None: return {"step": _out(start)} - slots = _year_slots(cfg, abs_year) + slots = _Year(cfg, abs_year) if intercalary is not None: - idx = next((i for i, s in enumerate(slots) if s.kind == "intercalary" and s.intercalary is intercalary), -1) + idx = slots.index_of_intercalary(intercalary) if idx == -1: return {"error": f"{_js_string(_get(intercalary, 'name'))} does not occur in that year"} return {"step": _out(start + idx)} want = 1.0 if day is None else day - idx = next( - (i for i, s in enumerate(slots) if s.kind == "month" and s.month == month_index and s.day == want), -1 - ) + idx = slots.index_of_day(month_index, want) if idx == -1: return {"error": "that day does not exist in that month"} return {"step": _out(start + idx)} diff --git a/tests/fixtures/calendar-cost.cases.json b/tests/fixtures/calendar-cost.cases.json new file mode 100644 index 0000000..637c91d --- /dev/null +++ b/tests/fixtures/calendar-cost.cases.json @@ -0,0 +1,62 @@ +{ + "about": "Timed cases for the calendar renderer: a stored calendar must not set what one label costs. Each case is a calendar readCalendarConfig accepts, a step, a call (format: formatStep; weekday: weekdayForStep; roundtrip: formatStep, then parseDate of its label) and its words. A string written as {\"$repeat\": [[piece, times], ...]} is the pieces joined, each repeated. Before 4.201.2 and onlyworlds 0.148.2 the template collapse was cubic on a run of white space, the edge trim quadratic on a run of marks, and a year was built one entry a day: every case here ran past its bound on one of the two packages. Held byte for byte in the Python package's tests/fixtures.", + "underMs": 50, + "cases": [ + { + "name": "a template with 4000 spaces before its last word", + "call": "format", + "step": 370, + "cfg": { "version": 1, "grain": "year", "format": { "$repeat": [["Year {year} {era}", 1], [" ", 4000], ["x", 1]] }, "eras": [{ "name": "Before Time", "abbrev": "BT", "start": 250, "direction": "down" }, { "name": "Years Since Landing", "abbrev": "YSL", "start": 250, "year_base": 0 }] }, + "want": "Year 120 YSL x" + }, + { + "name": "a template of one word and 3000 spaces", + "call": "format", + "step": 370, + "cfg": { "version": 1, "grain": "year", "format": { "$repeat": [["x", 1], [" ", 3000]] }, "eras": [{ "name": "Years Since Landing", "abbrev": "YSL", "start": 250, "year_base": 0 }] }, + "want": "x" + }, + { + "name": "a template with 20000 commas before its year", + "call": "format", + "step": 370, + "cfg": { "version": 1, "grain": "year", "format": { "$repeat": [["x", 1], [",", 20000], ["{year}", 1]] } }, + "want": { "$repeat": [["x", 1], [",", 20000], ["370", 1]] } + }, + { + "name": "a template with 20000 commas after its year", + "call": "format", + "step": 370, + "cfg": { "version": 1, "grain": "year", "format": { "$repeat": [["{year}", 1], [",", 20000], ["x", 1]] } }, + "want": { "$repeat": [["370", 1], [",", 20000], ["x", 1]] } + }, + { + "name": "a month name with 3000 spaces inside", + "call": "format", + "step": 3, + "cfg": { "version": 1, "grain": "day", "bundles": { "months": { "names": [{ "$repeat": [["A", 1], [" ", 3000], ["B", 1]] }, "C"], "lengths": [10, 10] } } }, + "want": "4 A B, 0" + }, + { + "name": "the last day of one month of 5000000 days", + "call": "format", + "step": 4999999, + "cfg": { "version": 1, "grain": "day", "bundles": { "months": { "names": ["Long"], "lengths": [5000000] } } }, + "want": "5000000 Long, 0" + }, + { + "name": "the weekday of the last day of one month of 5000000 days", + "call": "weekday", + "step": 4999999, + "cfg": { "version": 1, "grain": "day", "bundles": { "months": { "names": ["Long"], "lengths": [5000000] }, "week": { "length": 7, "names": ["a", "b", "c", "d", "e", "f", "g"] } }, "intercalary": [{ "name": "Pause", "after_month": 0, "in_week": false }] }, + "want": "d" + }, + { + "name": "the last day of one month of 5000000 days read back", + "call": "roundtrip", + "step": 4999999, + "cfg": { "version": 1, "grain": "day", "bundles": { "months": { "names": ["Long"], "lengths": [5000000] } } }, + "want": ["5000000 Long, 0", { "step": 4999999 }] + } + ] +} diff --git a/tests/test_calendar_cost.py b/tests/test_calendar_cost.py new file mode 100644 index 0000000..c3b7ff3 --- /dev/null +++ b/tests/test_calendar_cost.py @@ -0,0 +1,62 @@ +"""A stored calendar does not set what one label costs. The shared cases (``tests/fixtures/calendar-cost.cases.json``, +the same bytes as the npm SDK's ``test/fixtures/calendar-cost.cases.json``; both suites hold its sha256): a long run +of white space in a template or a name, a long run of marks at a label's edge, and a month of millions of days, each +answered with its words inside the bound. Before 0.148.2 every case ran past it.""" + +from __future__ import annotations + +import hashlib +import json +import time +from pathlib import Path +from typing import Any + +import pytest + +from onlyworlds import calendar as cal + +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "calendar-cost.cases.json" +FIXTURE_SHA256 = "1e326d378cbdc6db91deba2219ed07cf67ad72211653bd25219f963fc81ebc0f" +DATA: dict[str, Any] = json.loads(FIXTURE.read_bytes()) +PYTHON_FACTOR = 5 + + +def _expand(v: Any) -> Any: + if isinstance(v, list): + return [_expand(x) for x in v] + if isinstance(v, dict): + if "$repeat" in v: + return "".join(piece * times for piece, times in v["$repeat"]) + return {k: _expand(x) for k, x in v.items()} + return v + + +def test_the_cases_are_the_sdks_bytes() -> None: + assert hashlib.sha256(FIXTURE.read_bytes()).hexdigest() == FIXTURE_SHA256 + + +@pytest.mark.parametrize("case", DATA["cases"], ids=[c["name"] for c in DATA["cases"]]) +def test_each_case_answers_its_words_inside_the_bound(case: dict[str, Any]) -> None: + cfg = cal.read_calendar_config(_expand(case["cfg"])) + assert cfg is not None, "the case's calendar is one the reader accepts" + start = time.perf_counter() + if case["call"] == "format": + got: Any = cal.format_step(cfg, case["step"]) + elif case["call"] == "weekday": + got = cal.weekday_for_step(cfg, case["step"]) + else: + label = cal.format_step(cfg, case["step"]) + got = [label, cal.parse_date(cfg, label)] + ms = (time.perf_counter() - start) * 1000 + assert got == _expand(case["want"]) + assert ms < DATA["underMs"] * PYTHON_FACTOR, f"{round(ms)} ms" + + +def test_a_length_that_is_not_a_whole_int_keeps_the_list_and_its_answer() -> None: + # The runs are built only where every month length is an int; a float length is read as before. + as_int = {"version": 1, "grain": "day", "bundles": {"months": {"names": ["A", "B"], "lengths": [3, 2]}}} + as_float = {"version": 1, "grain": "day", "bundles": {"months": {"names": ["A", "B"], "lengths": [3.0, 2.0]}}} + assert cal._year_runs(as_float, 0) is None + assert cal._year_runs(as_int, 0) is not None + for step in range(-6, 7): + assert cal.format_step(as_float, step) == cal.format_step(as_int, step)