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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
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.158.1"
__version__ = "0.158.2"
47 changes: 45 additions & 2 deletions src/onlyworlds/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@

import datetime as _dt
import json
import math
import re
import time
import urllib.error
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand All @@ -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

Expand Down
48 changes: 48 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down
Loading