From 5946b0f19c80d6255bafab3830aa62af2a6cf8e8 Mon Sep 17 00:00:00 2001 From: Titus Date: Sat, 28 Nov 2026 00:47:15 +0100 Subject: [PATCH] 0.158.2: a body holding a non-finite number or nested past 200 is refused before sending json.dumps wrote the bare tokens NaN, Infinity and -Infinity, which are not JSON, and the server answered them with a 500. Any request body holding one now raises a ValueError that names the value and its place; nothing is sent, and the body is encoded with allow_nan=False after. A body nested more than 200 deep, counted as the folder readers count it, is refused the same way, by a walk with its own stack. A body with both is refused for its depth. The npm SDK refuses both in the same words (4.219.2). Watched failing on 0.158.1: each body was sent. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 ++++ src/onlyworlds/_version.py | 2 +- src/onlyworlds/http.py | 47 +++++++++++++++++++++++++++++++++++-- tests/test_client.py | 48 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 99 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d88db00..2ff3c97 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.158.2 (2026-11-28) + +- **Fixed: a non-finite number in a request body is refused before sending, by name and with its place.** `json.dumps` wrote the bare tokens `NaN`, `Infinity` and `-Infinity`, which are not JSON, and the server answered them with a 500. Any write now raises `ValueError: a request body holds NaN at x_score, which JSON cannot carry: send a finite number, or None to clear the field. Nothing was sent.`, the place a list index in brackets (`items[1].element.x_weight` in a `bulk`). The body is then encoded with `allow_nan=False`, so no bare token leaves the client. +- **Fixed: a body nested more than 200 deep is refused before sending**, counted as the folder readers count it (an object or list at the top is depth 1), however deep it goes: `ValueError: a request body is nested more than 200 deep (an object or list at the top is depth 1), past what onlyworlds.com reads. Nothing was sent.` A body with both faults is refused for its depth. The npm SDK refuses both in the same words (4.219.2). + ## 0.158.1 (2026-11-27) - **Fixed: a body the client cannot send raises at once, under its own name.** A value JSON cannot hold (`patch_world({"x_tool": object()})`, the same inside a `bulk` item) or a body carrying `world` was built inside the retry loop, so its `TypeError` or `ValueError` was read as no response: retried five times with the policy's waits, then raised as `ConnectionError: gave up after 5 retries`. The request is now built once, before the first try, and only the transport's own exceptions are retried. The `Transport` protocol now says so, and that a transport refusing a request on purpose raises a `BaseException` that is not an `Exception`, which reaches the caller at once. diff --git a/src/onlyworlds/_version.py b/src/onlyworlds/_version.py index 68b6360..efdbfbe 100644 --- a/src/onlyworlds/_version.py +++ b/src/onlyworlds/_version.py @@ -1 +1 @@ -__version__ = "0.158.1" +__version__ = "0.158.2" diff --git a/src/onlyworlds/http.py b/src/onlyworlds/http.py index d36ccd4..834e551 100644 --- a/src/onlyworlds/http.py +++ b/src/onlyworlds/http.py @@ -30,6 +30,7 @@ import datetime as _dt import json +import math import re import time import urllib.error @@ -41,6 +42,7 @@ from typing import Any, Protocol from ._ids import uuid7 +from ._outside_json import MAX_DEPTH from ._schema import FIELD_KINDS from ._version import __version__ from .errors import ApiError, api_error, error_code, parse_retry_after @@ -197,6 +199,46 @@ def _segment(value: str, pattern: re.Pattern[str], what: str) -> str: return value +def _encode_body(payload: Any) -> bytes: + """A request body as the JSON bytes sent, or ``ValueError`` before anything is sent, in the npm SDK's + words (None where it says null), for the two bodies keel cannot read as written: + + - nested more than ``MAX_DEPTH`` (200) deep, counted as the folder readers count it (an object or list + at the top is depth 1), however deep it goes: the walk keeps its own stack. keel reads 256, so a body + this sends is under its line. + - a non-finite float (NaN, either infinity) anywhere in it, named with its place: keel answers the bare + tokens ``json.dumps`` writes with a 500. + + A body with both is refused for its depth. The place is the first in the order the body is written.""" + stack: list[tuple[Any, int, str]] = [(payload, 0, "")] + non_finite: str | None = None + while stack: + value, parent, place = stack.pop() + if isinstance(value, Mapping): + children: list[tuple[Any, str]] = [(v, f"{place}.{k}" if place else str(k)) for k, v in value.items()] + elif isinstance(value, (list, tuple)): + children = [(v, f"{place}[{i}]") for i, v in enumerate(value)] + else: + if non_finite is None and isinstance(value, float) and not math.isfinite(value): + token = "NaN" if math.isnan(value) else ("Infinity" if value > 0 else "-Infinity") + non_finite = f"{token} at {place or 'the top'}" + continue + depth = parent + 1 + if depth > MAX_DEPTH: + raise ValueError( + f"a request body is nested more than {MAX_DEPTH} deep (an object or list at the top is depth 1)," + " past what onlyworlds.com reads. Nothing was sent." + ) + stack.extend((v, depth, p) for v, p in reversed(children)) + if non_finite is not None: + raise ValueError( + f"a request body holds {non_finite}, which JSON cannot carry: send a finite number, or None to" + " clear the field. Nothing was sent." + ) + # allow_nan off as a second layer: no bare token leaves this client. + return json.dumps(payload, ensure_ascii=True, allow_nan=False).encode("ascii") + + def _if_match(change_seq: int | None) -> dict[str, str] | None: """The ``If-Match`` header for a ``change_seq``, or None. A bool is not a number here.""" if change_seq is None: @@ -484,7 +526,8 @@ def _prepare( self, method: str, path: str, payload: Any, headers: Mapping[str, str] | None ) -> tuple[str, dict[str, str], bytes | None]: """The URL, headers and body of one request. Raises at once on a body it cannot send - (one carrying `world`, a value JSON cannot hold): the request was never made.""" + (one carrying `world`, a value JSON cannot hold, a non-finite number, a nesting past 200 levels): + the request was never made.""" sent = dict(self._headers) if path.split("?", 1)[0].strip("/") == "health": # The one route keel answers without a key (no security in its document): no credential rides. @@ -497,7 +540,7 @@ def _prepare( if payload is not None: if isinstance(payload, Mapping) and "world" in payload: raise ValueError("a request body never carries `world`; the key names the world") - body = json.dumps(payload, ensure_ascii=True).encode("ascii") + body = _encode_body(payload) sent["Content-Type"] = "application/json" return self.url(path), sent, body diff --git a/tests/test_client.py b/tests/test_client.py index af9e426..30feecb 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -331,6 +331,54 @@ def test_a_body_the_client_cannot_send_raises_at_once(make_client: MakeClient, s assert t.calls == [] and sleeps == [] +def test_a_non_finite_number_anywhere_in_a_body_is_refused_by_name_with_its_place( + make_client: MakeClient, sleeps: list[float] +) -> None: + """keel answers the bare tokens with a 500; nothing is sent, and the place is named as the npm SDK names it.""" + t = FakeTransport() + c = make_client(t) + pid = "11111111-2222-4333-8444-555555555555" + cases: list[tuple[Callable[[], Any], str]] = [ + (lambda: c.patch("character", pid, {"x_score": float("nan")}), "NaN at x_score"), + (lambda: c.patch_world({"x_tool": {"scale": [1, 2, float("inf")]}}), "Infinity at x_tool.scale[2]"), + ( + lambda: c.bulk( + [ + {"type": "pin", "element": {"id": pid, "x": 1}}, + {"type": "pin", "element": {"id": pid, "x_weight": -float("inf")}}, + ] + ), + "-Infinity at items[1].element.x_weight", + ), + ] + for call, want in cases: + with pytest.raises(ValueError, match=re.escape(f"a request body holds {want}")) as got: + call() + assert str(got.value).endswith("Nothing was sent.") + assert t.calls == [] and sleeps == [] + + +def _nest(levels: int) -> Any: + """``levels - 1`` lists inside the body's own object: the body is ``levels`` deep.""" + v: Any = 1 + for _ in range(levels - 1): + v = [v] + return v + + +def test_a_body_nested_past_200_levels_is_refused_by_name_and_200_is_sent(make_client: MakeClient) -> None: + t = FakeTransport(script=[jresp(200, {})]) + c = make_client(t) + for body in ({"x_tool": _nest(201)}, {"x_tool": _nest(200_000)}, {"x_score": float("nan"), "x_tool": _nest(201)}): + # Deeper than json.dumps can walk is the same refusal; past the line and holding NaN, the depth is named. + with pytest.raises(ValueError, match="a request body is nested more than 200 deep") as got: + c.patch_world(body) + assert str(got.value).endswith("Nothing was sent.") + assert t.calls == [] + c.patch_world({"x_tool": _nest(200)}) + assert len(t.calls) == 1 + + def test_a_transport_refusal_that_is_not_an_exception_is_never_retried(make_client: MakeClient) -> None: """A wrapper that refuses a request on purpose raises a BaseException, as the Transport protocol says."""