Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ The package version runs on its own semver; the schema it is generated from is `

## Unreleased

## 0.149.0 (2026-11-24)

- **Added: `calendar.format_steps(cfg, steps)`, a page of dates in one calendar.** The same words as `format_step` for every step, with the calendar's own work done once: its year shape, its eras in order, which months each day outside the months follows and the week's skipped days once for the call, each year's start and slots once per year. On a calendar of 64 eras, four leap rules and a year of 1,000 slots, 200 dates across the 32-bit range take about a sixth of the time `format_step` takes for them one by one; on two of the profile fixture's real calendars, about a quarter to a third. Held against `format_step` on every valid calendar of the fixture (the fixture's steps, a dense run inside a few years, a step in each of many years, the far edges); a step `format_step` refuses is refused the same way. `format_step` itself is unchanged.

## 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.
Expand Down
2 changes: 1 addition & 1 deletion src/onlyworlds/_version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.148.2"
__version__ = "0.149.0"
115 changes: 110 additions & 5 deletions src/onlyworlds/calendar.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
from __future__ import annotations

import bisect
import contextvars
import json
import math
import re
Expand Down Expand Up @@ -763,13 +764,47 @@ def _leap_rule(cfg: object, ic: object) -> _LeapRule:
)


# ---- One calendar's work, done once for many steps ----

# ``format_steps``' memo: while it runs, what depends only on the calendar (its year shape, its eras in
# order) or on the calendar and one year (that year's start, its slots) is worked out once and read back.
# Outside it the memo is None and every function computes as it always did. A key names an object by
# ``id`` and the memo holds that object for as long as it lives, so no id is reused while it is read.
_MEMO: contextvars.ContextVar[dict[tuple[Any, ...], Any] | None] = contextvars.ContextVar(
"onlyworlds_calendar_memo", default=None
)


def _memo(key: tuple[Any, ...], anchor: object, make: Callable[[], Any]) -> Any:
"""``make()``, read once per ``key`` while ``format_steps`` runs; ``key[1]`` is ``id(anchor)``."""
memo = _MEMO.get()
if memo is None:
return make()
try:
return memo[key]
except KeyError: # NaN never equals itself, so a key holding one is made again each time: the same answer
value = make()
memo[key] = value
memo[("held", id(anchor))] = anchor
return value


def _year_key(y: float) -> tuple[float, float]:
"""A year as a memo key, its sign kept: -0.0 and 0.0 are equal keys, and a year's start keeps the sign."""
return (y, math.copysign(1.0, y))


def _leap_rules(cfg: object, inter: list[Any]) -> list[_LeapRule]:
return [_leap_rule(cfg, i) for i in inter if not _nullish(_get(i, "every_years"))]


def _year_shape(cfg: object) -> tuple[float, list[_LeapRule]]:
"""The base year length (months and the days outside them that are not leap days, or
``bundles.year.steps``, or 1) and the leap entries' rules."""
return cast("tuple[float, list[_LeapRule]]", _memo(("shape", id(cfg)), cfg, lambda: _year_shape_of(cfg)))


def _year_shape_of(cfg: object) -> tuple[float, list[_LeapRule]]:
months = _bundle(cfg, "months")
inter = _list_or_empty(_prop(cfg, "intercalary"))
rules = _leap_rules(cfg, inter)
Expand Down Expand Up @@ -824,6 +859,10 @@ def intercalary_in_year(cfg: Mapping[str, Any], ic: Mapping[str, Any], y: int) -


def _year_start(cfg: object, y: float) -> float:
return cast(float, _memo(("start", id(cfg), *_year_key(y)), cfg, lambda: _year_start_of(cfg, y)))


def _year_start_of(cfg: object, y: float) -> float:
base, rules = _year_shape(cfg)
start = y * base
for r in rules:
Expand Down Expand Up @@ -897,6 +936,10 @@ def _direction(era: object) -> Any:


def _era_domains(eras: list[Any]) -> list[EraDomain]:
return cast("list[EraDomain]", _memo(("eras", id(eras)), eras, lambda: _era_domains_of(eras)))


def _era_domains_of(eras: list[Any]) -> list[EraDomain]:
ordered = _js_sorted(eras, lambda a, b: _to_number(_get(a, "start")) - _to_number(_get(b, "start")))
out: list[EraDomain] = []
for i, era in enumerate(ordered):
Expand All @@ -919,11 +962,32 @@ def resolve_era_domains(eras: list[Mapping[str, Any]]) -> list[EraDomain]:
return _era_domains(_items(eras))


def _era_bounds(eras: list[Any]) -> list[tuple[EraDomain, float | None, float | None]]:
"""Each era's domain with its two bounds as numbers, or None for a bound that is not one."""
return [
(d, _num(d.lo) if _is_num(d.lo) else None, _num(d.hi) if _is_num(d.hi) else None) for d in _era_domains(eras)
]


def _era_for(cfg: object, step: float) -> Any:
eras = _list_or_empty(_prop(cfg, "eras"))
if len(eras) == 0:
return None
holding = [d for d in _era_domains(eras) if _js_le(d.lo, step) and _js_lt(step, d.hi)]
if _MEMO.get() is None:
holding = [d for d in _era_domains(eras) if _js_le(d.lo, step) and _js_lt(step, d.hi)]
else:
# Under format_steps: each bound that is a number read once as one; JavaScript's <= and < on two
# numbers are Python's on two floats (NaN false both ways), and any other bound keeps _js_le.
bounds = cast(
"list[tuple[EraDomain, float | None, float | None]]",
_memo(("bounds", id(eras)), eras, lambda: _era_bounds(eras)),
)
holding = [
d
for d, lo, hi in bounds
if (lo <= step if lo is not None else _js_le(d.lo, step))
and (step < hi if hi is not None else _js_lt(step, d.hi))
]
if not holding:
return None
place = {id(e): i for i, e in enumerate(eras)}
Expand Down Expand Up @@ -1121,9 +1185,19 @@ def _year_runs(cfg: object, y: float) -> list[_Run] | None:
inter = _list_or_empty(_prop(cfg, "intercalary"))
runs: list[_Run] = []
at = 0
# Under format_steps: which entries follow each month, and each one's leap rule, read once per calendar.
groups: list[list[tuple[Any, _LeapRule | None]]] | None = None
if _MEMO.get() is not None:
groups = _memo(("after", id(cfg)), cfg, lambda: _after_groups(cfg, inter, len(names)))

def push(after: int) -> None:
nonlocal at
if groups is not None:
for ic, rule in groups[after]:
if rule is None or _rule_holds(rule, y):
runs.append(_Run(at, 1, 0, _Slot("intercalary", 0, 0, ic)))
at += 1
return
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)))
Expand All @@ -1139,6 +1213,19 @@ def push(after: int) -> None:
return runs


def _after_groups(cfg: object, inter: list[Any], months: int) -> list[list[tuple[Any, _LeapRule | None]]]:
"""For each ``after`` from 0 to ``months``, the intercalary entries ``push(after)`` reads, in order, each
with its leap rule (None for an entry in every year): ``_in_year``'s two halves, read once."""
return [
[
(ic, None if _nullish(_get(ic, "every_years")) else _leap_rule(cfg, ic))
for ic in inter
if _strict_eq(_get(ic, "after_month"), after)
]
for after in range(months + 1)
]


class _Position(NamedTuple):
abs_year: float
offset: float
Expand All @@ -1151,7 +1238,7 @@ 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(cfg, y)
slots = cast(_Year, _memo(("year", id(cfg), *_year_key(y)), cfg, lambda: _Year(cfg, y)))
slot = slots.at(offset)
return _Position(y, offset, None if slot is _UNDEF else slot, slots)

Expand All @@ -1174,16 +1261,22 @@ def _weekday(cfg: object, step: float, pos: _Position) -> Any:
# Free: the counted steps leave out in_week false days outside the months; counted 0 is names[0].
if pos.slot is not None and pos.slot.kind == "intercalary" and _prop(pos.slot.intercalary, "in_week") is False:
return None
skipped = [i for i in _list_or_empty(_prop(cfg, "intercalary")) if _get(i, "in_week") is False]
every, rules = cast("tuple[int, list[_LeapRule]]", _memo(("week", id(cfg)), cfg, lambda: _week_skipped(cfg)))
y = pos.abs_year
skipped_before = y * len([i for i in skipped if _nullish(_get(i, "every_years"))])
for r in _leap_rules(cfg, skipped):
skipped_before = y * every
for r in rules:
skipped_before += _leap_years_before(y, r)
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))))


def _week_skipped(cfg: object) -> tuple[int, list[_LeapRule]]:
"""The days outside the week (``in_week`` false): how many fall in every year, and the leap rules of the rest."""
skipped = [i for i in _list_or_empty(_prop(cfg, "intercalary")) if _get(i, "in_week") is False]
return len([i for i in skipped if _nullish(_get(i, "every_years"))]), _leap_rules(cfg, skipped)


def weekday_for_step(cfg: Mapping[str, Any], step: int) -> str | None:
"""The weekday of a step, or None: no week, a nested week outside the months, a day out of the week,
or fewer names than the week's length."""
Expand Down Expand Up @@ -1331,6 +1424,18 @@ def format_step(cfg: Mapping[str, Any], step: int) -> str:
return _render(template, values)


def format_steps(cfg: Mapping[str, Any], steps: Iterable[int]) -> list[str]:
"""``[format_step(cfg, s) for s in steps]``, the same words for every step, with the calendar's own
work done once: its year shape and its eras in order once for the call, each year's start and slots
once per year. For a page of dates in one calendar; a step that ``format_step`` refuses is refused
here the same way."""
token = _MEMO.set({})
try:
return [format_step(cfg, s) for s in steps]
finally:
_MEMO.reset(token)


def _year_label(cfg: object, step: float) -> str:
era = _era_for(cfg, step)
year = _display_year(cfg, step, era)
Expand Down
78 changes: 78 additions & 0 deletions tests/test_calendar_steps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
"""``format_steps``: a page of steps in one calendar, the same words as ``format_step`` for every step, with the
calendar's own work done once. Held against the loop on every valid calendar of the vendored profile fixture,
over the fixture's own steps, a dense run inside a few years, steps spread over many years, and the far edges."""

from __future__ import annotations

import json
import random
from pathlib import Path
from typing import Any

import pytest

from onlyworlds import calendar as cal

FIXTURE = Path(__file__).resolve().parents[1] / "codegen" / "schema-dist" / "profiles" / "calendar.fixture.json"
CASES: list[dict[str, Any]] = [c for c in json.loads(FIXTURE.read_text(encoding="utf-8"))["cases"] if c["valid"]]
EDGES = [0, 1, -1, 2**31 - 1, -(2**31), 2**53 - 1, -(2**53 - 1)]


def steps_for(c: dict[str, Any], cfg: Any) -> list[int]:
rng = random.Random(c["name"])
length = cal.approx_year_length(cfg) or 365
out = [s["step"] for s in c.get("steps", [])] + EDGES
for start in (0, -3 * length, 40 * length): # a dense run: every step of a stretch inside a few years
out += list(range(start, start + 2 * length + 3))
out += [rng.randint(-(2**40), 2**40) for _ in range(200)] # one step in each of many years
out += out[:50] # a step asked twice in one call
return out


def test_every_fixture_calendar_says_the_same_words_as_format_step() -> None:
assert len(CASES) == 35 # counted, so a fixture that stops loading fails here rather than passing on nothing
compared = 0
for c in CASES:
cfg = cal.read_calendar_value(c["value"])
assert cfg is not None, c["name"]
steps = steps_for(c, cfg)
loop = [cal.format_step(cfg, s) for s in steps]
assert cal.format_steps(cfg, steps) == loop, c["name"]
compared += len(steps)
assert compared > 35 * 400


def test_steps_may_be_any_iterable_and_no_steps_give_an_empty_list() -> None:
cfg = cal.read_calendar_value(CASES[0]["value"])
assert cfg is not None
assert cal.format_steps(cfg, (s for s in [0, 1, 2])) == [cal.format_step(cfg, s) for s in [0, 1, 2]]
assert cal.format_steps(cfg, []) == []


def test_the_memo_lives_only_for_the_call() -> None:
cfg = cal.read_calendar_value(CASES[0]["value"])
assert cfg is not None
assert cal._MEMO.get() is None
cal.format_steps(cfg, [0, 5, 10])
assert cal._MEMO.get() is None
with pytest.raises(TypeError):
cal.format_steps(cfg, [0, "not a step"]) # type: ignore[list-item]
assert cal._MEMO.get() is None


def test_a_step_format_step_refuses_is_refused_the_same_way() -> None:
cfg = cal.read_calendar_value(CASES[0]["value"])
assert cfg is not None
with pytest.raises(TypeError) as one:
cal.format_step(cfg, "not a step") # type: ignore[arg-type]
with pytest.raises(TypeError) as many:
cal.format_steps(cfg, [0, "not a step"]) # type: ignore[list-item]
assert (type(many.value), str(many.value)) == (type(one.value), str(one.value))


def test_two_calendars_in_one_process_keep_their_own_answers() -> None:
a, b = (cal.read_calendar_value(c["value"]) for c in CASES[:2])
assert a is not None and b is not None
steps = list(range(-400, 400, 7))
assert cal.format_steps(a, steps) == [cal.format_step(a, s) for s in steps]
assert cal.format_steps(b, steps) == [cal.format_step(b, s) for s in steps]
Loading