From 15bb7956969acdcf39f44567911d628c7ebacedc Mon Sep 17 00:00:00 2001 From: Donald Clark Jackson Date: Wed, 11 Nov 2026 15:27:08 -0800 Subject: [PATCH] Follow Homie 5 on effective state and five payload rules (#110) A child's effective state is its own $state unless its root is lost (convention.md:262-267). /set and publish validation reject what the convention rules out: int64 or float overflow after step rounding, hour 24 with minutes, day 366 outside leap years, week 53 in years without one, non-finite JSON numbers and lone surrogates, and numeric payloads past Python's 4,300-digit limit. A huge exponent no longer costs a huge exact power, and deep JSON nesting is jsonInvalid. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VUQ6apRySRNW8y3ppJMdJC --- CHANGELOG.md | 8 ++ README.md | 6 +- doc/consuming-a-homie-tree.md | 2 +- examples/simple-controller | 2 +- src/ebus_sdk/homie.py | 168 +++++++++++++++++++++++++++------ tests/test_controller.py | 23 ++--- tests/test_homie_compliance.py | 63 ++++++++++++- 7 files changed, 225 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 571ffaa..f12b0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to `ebus-sdk` are recorded here. Format follows [Keep a Chan ## [Unreleased] +### Changed + +- `Controller.get_effective_state()` and `HOMIE_EFFECTIVE_STATE_TABLE` follow the convention's rule (convention.md:262-267): a child's effective state is its own `$state` unless its root is `lost`. A root in `init`, `disconnected` or `sleeping` no longer overrides its descendants, so a child of a `disconnected` root that reports `ready` now reads `ready`. ([#110](https://github.com/electrification-bus/python-sdk/issues/110)) + +### Fixed + +- Payload validation applies Homie 5 rules it missed. On `/set`, an integer that step rounding carries past the int64 range is rejected as `integerOutOf64Bit` (`9223372036854775807` with `$format` `0::2` was accepted as `9223372036854775808`), and a float carried past the float range as `floatOutOfRange`. On `/set` and on publish, a datetime accepts hour 24 only as `24:00[:00[.0]]`, ordinal day 366 only in a leap year and ISO week 53 only in a year that has one (`2024-01-01T24:30`, `2023-366` and `2021-W53` were accepted), and a json payload holding a number outside the float range (`[1e400]` decoded to `inf`), a string or key with a lone surrogate (`["\ud800"]`) or nesting too deep to parse is rejected as `jsonInvalid`. A number over Python's 4,300-digit int conversion limit no longer raises `ValueError`: an integer or float `/set` is a grammar rejection (`propertySetRejected`, where it was logged as `propertySetCallbackException`), an integer published with `set_value()` is refused as out of int64, and a numeric `$format` bound is ignored, like any other bound that does not parse. A float `/set` or `$format` bound with a huge exponent (`1e-100000000`) no longer computes the power exactly, which took seconds. ([#110](https://github.com/electrification-bus/python-sdk/issues/110)) + ## [0.27.0] — 2026-10-21 A device built without nodes announces once, in its caller's first transition, instead of publishing `ready` before any value. Breaking for code that relied on a bare `Device(...)` being `ready`. diff --git a/README.md b/README.md index 58ee3ce..34e4dfc 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,7 @@ Device(id='mid-1', type='...metering', parent=bess) panel.children()[0].delete() ``` -Children may have children of their own. A single Last Will registered on the root marks the entire tree `lost` if the publisher process dies, and `root.declare_lost()` publishes the same thing deliberately when the publisher knows it is dying — controllers compute effective state per the Homie 5 precedence table (see [`HOMIE_EFFECTIVE_STATE_TABLE`](src/ebus_sdk/homie.py)). +Children may have children of their own. A single Last Will registered on the root marks the entire tree `lost` if the publisher process dies, and `root.declare_lost()` publishes the same thing deliberately when the publisher knows it is dying — controllers compute effective state per the Homie 5 rule that a lost root makes every descendant lost (see [`HOMIE_EFFECTIVE_STATE_TABLE`](src/ebus_sdk/homie.py)). `$description` republishes are minimized: structural changes made inside one `state_transition()` collapse to a single consolidated publish at exit (not one per `add_node`), and `publish_description()` is a no-op when the description content is unchanged — so a `state_transition()` that changes nothing structural does not re-emit the (potentially multi-KB) `$description`. A reconnect always republishes regardless, to restore retained state. Note this suppresses the redundant `$description` payload, not the `$state` `init`→`ready` edge of an empty transition. Property *values* are minimized the same way and with the same reconnect carve-out (see [Unchanged values are not republished](#unchanged-values-are-not-republished)). The document's `version` is derived from its content (the top 52 bits of a SHA-256 of the document without `version`), so an unchanged document keeps its version across reconnects and restarts, and any change gets a new one. Homie 5 lets `$description` change only while the device is `init`, `disconnected` or `lost`: a structural change made outside a `state_transition()` on a `ready` or `sleeping` device is published as `init`, the changed values, the new `$description`, then the state the device was in. A change that leaves the document as last published (a property added to a node not yet attached to its device, or an identical re-declaration) publishes only its values. @@ -274,8 +274,8 @@ Controllers can also navigate device hierarchies and compute effective state: roots = controller.get_root_devices() for root in roots: for descendant in controller.get_descendants(root.device_id): - # When the root is lost/disconnected/sleeping/init, every descendant - # is effectively the same regardless of its own reported $state. + # When the root is lost, every descendant is effectively lost + # regardless of its own reported $state. print(f'{descendant.device_id}: {controller.get_effective_state(descendant.device_id)}') ``` diff --git a/doc/consuming-a-homie-tree.md b/doc/consuming-a-homie-tree.md index 1b07a84..c9bc256 100644 --- a/doc/consuming-a-homie-tree.md +++ b/doc/consuming-a-homie-tree.md @@ -40,7 +40,7 @@ It is specifically **not**: The rollup reading is the common one and it cannot be made true by any producer. Children are commissioned and decommissioned out of band, so at any instant a new child may be mid-publish. **There is no moment at which a producer knows it has published "all" its children.** The strongest guarantee any producer can offer is per-transaction: *within this cascade, my announcement follows the content it announces.* That is a statement about a transaction, not about the world. -The one thing a root's state **is** authoritative for is **effective state**. Homie 5 propagates a non-ready root down the tree: when the root is `init`, `disconnected`, `sleeping`, or `lost`, its descendants are effectively that too, because the root is the gateway. Only when the root is `ready` do a child's own reported states stand. `Controller.get_effective_state(device_id)` implements this. Note it keys on the **root**, not on the immediate parent, so a mid-tree device entering a `state_transition()` does not mask its own children. +The one thing a root's state **is** authoritative for is **effective state**, and only when it is `lost` (convention.md:262-267). The root's Last Will sets the root `lost` but cannot update its descendants, so a lost root makes every descendant effectively `lost`. In every other root state (`init`, `ready`, `disconnected`, `sleeping`) a child's own reported `$state` stands. `Controller.get_effective_state(device_id)` implements this. Note it keys on the **root**, not on the immediate parent, so a mid-tree device entering a `state_transition()` does not mask its own children. ## What a consumer MUST do diff --git a/examples/simple-controller b/examples/simple-controller index a5f8462..1b80b5c 100755 --- a/examples/simple-controller +++ b/examples/simple-controller @@ -62,7 +62,7 @@ def _print_device(controller: Controller, device: DiscoveredDevice, depth: int) pad = " " * depth effective = controller.get_effective_state(device.device_id) own = device.state - # Show the effective state; call out when a non-ready root has suppressed a + # Show the effective state; call out when a lost root has overridden a # descendant's own state (the whole point of a tree-aware view). state = str(effective) if effective == own else f"{effective} (own: {own})" dtype = (device.description or {}).get("type", "?") diff --git a/src/ebus_sdk/homie.py b/src/ebus_sdk/homie.py index f7966c9..e7495dc 100644 --- a/src/ebus_sdk/homie.py +++ b/src/ebus_sdk/homie.py @@ -38,6 +38,7 @@ """ import asyncio +import calendar import contextlib import datetime import decimal @@ -410,7 +411,7 @@ class PropertyDatatype(StrEnum): | -?W(?P\d{2})(?:-?(?P\d))? )? (?: - T(?P\d{2})(?::?(?P\d{2})(?::?(?P\d{2}))?)?(?:[.,]\d+)? + T(?P\d{2})(?::?(?P\d{2})(?::?(?P\d{2}))?)?(?:[.,](?P\d+))? (?:Z|[+-](?P\d{2})(?::?(?P\d{2}))?)? )? """, @@ -424,6 +425,36 @@ def _reject_json_constant(name: str) -> Any: raise ValueError(f"{name} is not JSON") +def _finite_json_float(text: str) -> float: + # A number outside the float range (`1e400`) would otherwise decode to inf. + number = float(text) + if not math.isfinite(number): + raise ValueError(f"{text} is not a finite number") + return number + + +def _json_has_lone_surrogate(value: Any) -> bool: + """Whether any string or key in a decoded JSON value holds a lone surrogate. + + A `\\ud800` escape decodes to a code point that is not a Unicode scalar value + and cannot be encoded as UTF-8. Iterative, so nesting depth costs no stack. + """ + pending = [value] + while pending: + item = pending.pop() + if isinstance(item, dict): + pending.extend(item.keys()) + pending.extend(item.values()) + elif isinstance(item, list): + pending.extend(item) + elif isinstance(item, str): + try: + item.encode("utf-8") + except UnicodeEncodeError: + return True + return False + + def _format_float(number: float) -> Optional[str]: """A finite float in the convention's grammar: no `+` in the exponent (:97).""" if not math.isfinite(number): @@ -437,7 +468,10 @@ def _encode_integer(value: Any) -> tuple: if isinstance(value, str): if not _INTEGER_PAYLOAD.fullmatch(value): return None, "integerGrammar" - number = int(value) + try: + number = int(value) + except ValueError: # over Python's 4,300-digit int conversion limit + return None, "integerOutOf64Bit" elif isinstance(value, numbers.Integral): number = int(value) elif isinstance(value, numbers.Real): @@ -551,7 +585,8 @@ def _check_datetime_payload(text: str) -> Optional[str]: match = _DATETIME_PAYLOAD.fullmatch(text) if not match: return "datetimeGrammar" - fields = {k: int(v) for k, v in match.groupdict().items() if v is not None} + fraction = match.group("fraction") + fields = {k: int(v) for k, v in match.groupdict().items() if v is not None and k != "fraction"} if "hour" in fields and not fields.keys() & {"day", "bday", "ordinal", "weekday"}: return "datetimeGrammar" # a time of day needs a complete date try: @@ -566,9 +601,29 @@ def _check_datetime_payload(text: str) -> Optional[str]: for name, (low, high) in limits.items(): if name in fields and not low <= fields[name] <= high: return "datetimeRange" + # 24 is only the end-of-day instant 24:00[:00[.0]]. + if fields.get("hour") == 24 and (fields.get("minute") or fields.get("second") or (fraction or "").strip("0")): + return "datetimeRange" + if fields.get("ordinal") == 366 and not calendar.isleap(fields["year"]): + return "datetimeRange" + if fields.get("week") == 53 and not _has_iso_week_53(fields["year"]): + return "datetimeRange" return None +def _has_iso_week_53(year: int) -> bool: + """Whether ISO ``year`` has a week 53 (it ends on a Thursday, or its predecessor on a Wednesday). + + Arithmetic rather than ``date(year, 12, 28).isocalendar()``, which cannot + represent year 0000. + """ + + def dec31_weekday(y: int) -> int: # 0 = Sunday ... 4 = Thursday + return (y + y // 4 - y // 100 + y // 400) % 7 + + return dec31_weekday(year) == 4 or dec31_weekday(year - 1) == 3 + + def _encode_datetime(value: Any) -> tuple: if isinstance(value, (datetime.datetime, datetime.date)): # ISO 8601 extended form, `T` separator (convention.md:132). @@ -605,13 +660,19 @@ def _encode_duration(value: Any) -> tuple: def _decode_json_container(text: str) -> tuple: - """Parse a json payload: an array or object, never NaN/Infinity (convention.md:150).""" + """Parse a json payload: an array or object (convention.md:150). + + Rejected as ``jsonInvalid``: NaN/Infinity, a number outside the float range, + and a string or key holding a lone surrogate. + """ try: - decoded = json.loads(text, parse_constant=_reject_json_constant) - except (ValueError, TypeError): + decoded = json.loads(text, parse_constant=_reject_json_constant, parse_float=_finite_json_float) + except (ValueError, TypeError, RecursionError): return None, "jsonInvalid" if not isinstance(decoded, (list, dict)): return None, "jsonNotArrayOrObject" + if _json_has_lone_surrogate(decoded): + return None, "jsonInvalid" return decoded, None @@ -623,9 +684,12 @@ def _encode_json(value: Any) -> tuple: if not isinstance(value, (list, tuple, dict)): return None, "jsonNotArrayOrObject" try: - return json.dumps(value, allow_nan=False), None - except (TypeError, ValueError): + payload = json.dumps(value, allow_nan=False) + except (TypeError, ValueError, RecursionError): return None, "jsonInvalid" + # The same grammar the /set path applies: no lone surrogates. + _, problem = _decode_json_container(payload) + return (None, problem) if problem else (payload, None) def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tuple: @@ -656,6 +720,41 @@ def _encode_property_value(value: Any, datatype: Any, format_: Any = None) -> tu return (str(value.value) if isinstance(value, Enum) else str(value)), None +# Past float's range both ways (about 1.8e308 down to 4.9e-324). +_EXACT_MAGNITUDE_LIMIT = 1000 + + +def _exact_number(text: str) -> Optional[Fraction]: + """The exact value of a ``_FLOAT_PAYLOAD`` text, or None over 4,300 digits. + + A nonzero magnitude past ``10**±_EXACT_MAGNITUDE_LIMIT`` is clamped to it, + sign kept, so ``1e-100000000`` costs no ``10**100000000``. Clamping keeps + its order against every float-range number. + """ + mantissa, _, exponent = text.lower().partition("e") + negative = mantissa.startswith("-") + whole, _, fraction = mantissa.lstrip("-").partition(".") + try: + significand = int(whole + fraction) + except ValueError: # over Python's 4,300-digit int conversion limit + return None + if significand == 0: + return Fraction(0) + exponent_digits = exponent.lstrip("-").lstrip("0") + if len(exponent_digits) > 6: + scale = (-1 if exponent.startswith("-") else 1) * (10 * _EXACT_MAGNITUDE_LIMIT) + else: + scale = int(exponent or "0") - len(fraction) + magnitude = scale + len(str(significand)) + if magnitude > _EXACT_MAGNITUDE_LIMIT: + number = Fraction(10**_EXACT_MAGNITUDE_LIMIT) + elif magnitude < -_EXACT_MAGNITUDE_LIMIT: + number = Fraction(1, 10**_EXACT_MAGNITUDE_LIMIT) + else: + number = significand * Fraction(10) ** scale + return -number if negative else number + + def _numeric_format(format_: Any) -> tuple: """``(min, max, step)`` as Fractions (each may be None) from ``[min]:[max][:step]``. @@ -669,9 +768,7 @@ def _numeric_format(format_: Any) -> tuple: return None, None, None def bound(text: str) -> Optional[Fraction]: - if not _FLOAT_PAYLOAD.fullmatch(text): - return None - return Fraction(text) + return _exact_number(text) if _FLOAT_PAYLOAD.fullmatch(text) else None low, high = bound(parts[0]), bound(parts[1]) step = bound(parts[2]) if len(parts) == 3 else None @@ -715,22 +812,38 @@ def _parse_set_payload(text: str, datatype: Any, format_: Any, current: Any) -> if datatype == PropertyDatatype.JSON: return _decode_json_container(text) if datatype == PropertyDatatype.INTEGER: - if not _INTEGER_PAYLOAD.fullmatch(text) or not _INT64_MIN <= int(text) <= _INT64_MAX: + if not _INTEGER_PAYLOAD.fullmatch(text): + return None, "integerGrammar" + try: + number = int(text) + except ValueError: # over Python's 4,300-digit int conversion limit + return None, "integerGrammar" + if not _INT64_MIN <= number <= _INT64_MAX: return None, "integerGrammar" - rounded, problem = _round_and_range_check(Fraction(int(text)), format_, current) + rounded, problem = _round_and_range_check(Fraction(number), format_, current) if problem: return None, problem if rounded.denominator != 1: return None, "integerStepNotWhole" - return (text if rounded == int(text) else str(int(rounded))), None + # Step rounding can carry an in-range payload past int64 (convention.md:87-88). + if not _INT64_MIN <= rounded <= _INT64_MAX: + return None, "integerOutOf64Bit" + return (text if rounded == number else str(int(rounded))), None if datatype == PropertyDatatype.FLOAT: if not _FLOAT_PAYLOAD.fullmatch(text) or not math.isfinite(float(text)): return None, "floatGrammar" - number = Fraction(text) + number = _exact_number(text) + if number is None: + return None, "floatGrammar" rounded, problem = _round_and_range_check(number, format_, current) if problem: return None, problem - return (text if rounded == number else _format_float(float(rounded))), None + if rounded == number: + return text, None + try: + return _format_float(float(rounded)), None + except OverflowError: # step rounding carried it past the float range + return None, "floatOutOfRange" if datatype == PropertyDatatype.BOOLEAN: return (text, None) if text in ("true", "false") else (None, "booleanGrammar") if datatype == PropertyDatatype.ENUM: @@ -845,20 +958,18 @@ class DeviceState(StrEnum): LOST = "lost" -# Homie 5 effective-state precedence table (SDK-zt2). +# Homie 5 effective-state precedence table (convention.md:262-267). # -# A non-root device's effective state is determined by its root's reported state: -# whenever the root is in a non-ready state, that state propagates down the tree -# (the root is the gateway to the children, so if it's lost/disconnected/sleeping/ -# init the children are effectively the same). Only when the root is `ready` do -# the children's own reported states stand. +# A non-root device's effective state is its own reported `$state`, unless its +# root is `lost`: the root's Last Will does not update the children, so a lost +# root makes every descendant lost. A root in any other state overrides nothing. # # Mapping: root_state -> override_for_children. A None value means "no override, # use the child's own state". HOMIE_EFFECTIVE_STATE_TABLE: dict = { - DeviceState.INIT: DeviceState.INIT, - DeviceState.DISCONNECTED: DeviceState.DISCONNECTED, - DeviceState.SLEEPING: DeviceState.SLEEPING, + DeviceState.INIT: None, + DeviceState.DISCONNECTED: None, + DeviceState.SLEEPING: None, DeviceState.LOST: DeviceState.LOST, DeviceState.READY: None, } @@ -5085,13 +5196,12 @@ def _reevaluate_tree_completeness(self) -> None: def get_effective_state(self, device_id: str) -> Optional[str]: """ - Return the device's effective state per the Homie 5 spec (SDK-zt2). + Return the device's effective state per the Homie 5 spec (convention.md:262-267). For a root device: returns its own reported state. - For a child: applies HOMIE_EFFECTIVE_STATE_TABLE — when the root is in a - non-ready state (init/disconnected/sleeping/lost), that state propagates - down the tree. Only when the root is ready do children's own states stand. + For a child: applies HOMIE_EFFECTIVE_STATE_TABLE: a child is ``lost`` when + its root is ``lost``, and otherwise its own reported state stands. Returns None when the device isn't discovered. Returns the device's own state (best-effort) when the device's named root isn't yet discovered — diff --git a/tests/test_controller.py b/tests/test_controller.py index 6977e85..f46c277 100644 --- a/tests/test_controller.py +++ b/tests/test_controller.py @@ -218,23 +218,23 @@ def test_get_children_unknown_device(self, mock_paho): class TestEffectiveStateTable: - """SDK-zt2: HOMIE_EFFECTIVE_STATE_TABLE shape.""" + """HOMIE_EFFECTIVE_STATE_TABLE shape.""" def test_table_covers_all_states(self): for state in DeviceState: assert state in HOMIE_EFFECTIVE_STATE_TABLE, f"DeviceState.{state.name} missing from precedence table" - def test_only_ready_maps_to_none(self): - """Per spec: only when root is READY do children's own states stand.""" + def test_only_lost_overrides(self): + """convention.md:262-267: only a lost root overrides a child's own state.""" for state, override in HOMIE_EFFECTIVE_STATE_TABLE.items(): - if state == DeviceState.READY: - assert override is None + if state == DeviceState.LOST: + assert override == DeviceState.LOST else: - assert override == state, f"non-ready root {state} should propagate as itself" + assert override is None, f"root {state} should not override a child's own state" class TestControllerEffectiveState: - """SDK-zt2: Controller.get_effective_state().""" + """Controller.get_effective_state().""" @staticmethod def _discover(ctrl, device_id, state, description=None): @@ -267,10 +267,11 @@ def test_unknown_device_returns_none(self, mock_paho): ("ready", "init", "init"), ("ready", "sleeping", "sleeping"), ("ready", "lost", "lost"), - ("init", "ready", "init"), - ("disconnected", "ready", "disconnected"), - ("disconnected", "lost", "disconnected"), - ("sleeping", "ready", "sleeping"), + ("init", "ready", "ready"), + ("init", "sleeping", "sleeping"), + ("disconnected", "ready", "ready"), + ("disconnected", "lost", "lost"), + ("sleeping", "ready", "ready"), ("lost", "ready", "lost"), ("lost", "init", "lost"), ], diff --git a/tests/test_homie_compliance.py b/tests/test_homie_compliance.py index 9ae1ec7..03c55e5 100644 --- a/tests/test_homie_compliance.py +++ b/tests/test_homie_compliance.py @@ -6,10 +6,12 @@ import datetime import decimal import enum +from fractions import Fraction import inspect import json import logging import socket +import time from unittest.mock import MagicMock, patch import pytest @@ -23,6 +25,10 @@ Node, Property, PropertyDatatype, + _has_iso_week_53, + _exact_number, + _numeric_format, + _parse_set_payload, ) BASE = f"{EBUS_HOMIE_DOMAIN}/{EBUS_HOMIE_VERSION_MAJOR}" @@ -782,6 +788,17 @@ def test_datetime_strings_are_checked(self): for bad in ("garbage", "2026-10-08 12:00", "2026-13-01", "2026-02-30", "2026-10-08T25:00", "\u0662026-10-08"): assert _published(PropertyDatatype.DATETIME, bad) is None, bad + def test_datetime_hour_24_ordinal_366_and_week_53_limits(self): + """:132 (ISO 8601): 24 only as 24:00[:00], day 366 in leap years, week 53 in 53-week years.""" + for good in ("2024-01-01T24:00", "2024-01-01T24:00:00", "2024-01-01T24:00:00.000", "2024-366", "2020-W53"): + assert _published(PropertyDatatype.DATETIME, good) == good, good + for bad in ("2024-01-01T24:30", "2024-01-01T24:00:01", "2024-01-01T24:00:00.5", "2023-366", "2021-W53"): + assert _published(PropertyDatatype.DATETIME, bad) is None, bad + + def test_week_53_years_match_the_calendar(self): + for year in range(1, 3000): + assert _has_iso_week_53(year) == (datetime.date(year, 12, 28).isocalendar()[1] == 53), year + def test_duration_is_ptxhxmxs(self): """:137-144.""" timedelta = datetime.timedelta @@ -819,6 +836,14 @@ def test_json_must_be_an_array_or_object_without_nan(self): assert _published(PropertyDatatype.JSON, {"a": float("nan")}) is None assert _published(PropertyDatatype.JSON, '{"a": NaN}') is None + def test_json_rejects_overflowing_numbers_and_lone_surrogates(self): + """:150: no inf from an out-of-range number, no string that is not Unicode scalar values.""" + assert _published(PropertyDatatype.JSON, "[1e400]") is None + assert _published(PropertyDatatype.JSON, '["\\ud800"]') is None + assert _published(PropertyDatatype.JSON, ["\ud800"]) is None + assert _published(PropertyDatatype.JSON, {"\udfff": 1}) is None + assert _published(PropertyDatatype.JSON, '["\\ud83d\\ude00"]') == '["\\ud83d\\ude00"]' + class TestEventProperties: """:50 and :695: non-retained properties publish at QoS 0 and are never replayed.""" @@ -952,6 +977,40 @@ def test_numbers_round_to_the_step_then_check_min_max(self): def test_the_current_value_is_the_step_base_without_min_or_max(self): assert _accepts(PropertyDatatype.INTEGER, "6", format="::4", value=1) == "5" + def test_an_integer_rounded_past_int64_is_rejected(self): + """:87-88: the 64-bit range applies after step rounding too.""" + integer = PropertyDatatype.INTEGER + assert _parse_set_payload(str(2**63 - 1), integer, "0::2", None) == (None, "integerOutOf64Bit") + assert _parse_set_payload(str(-(2**63)), integer, ":0:3", None) == (None, "integerOutOf64Bit") + assert _parse_set_payload(str(2**63 - 2), integer, "0::2", None) == (str(2**63 - 2), None) + + def test_a_float_rounded_past_the_float_range_is_rejected(self): + assert _parse_set_payload("1.7e308", PropertyDatatype.FLOAT, "0::1e308", None) == (None, "floatOutOfRange") + + def test_over_4300_digits_is_a_rejection_not_an_exception(self): + """Python's int string conversion limit must not escape as ValueError.""" + digits = "1" * 5000 + assert _parse_set_payload(digits, PropertyDatatype.INTEGER, None, None) == (None, "integerGrammar") + assert _parse_set_payload("0." + digits, PropertyDatatype.FLOAT, "0:1", None) == (None, "floatGrammar") + assert _numeric_format(f"0:{digits}") == (0, None, None) + assert _parse_set_payload("1.5", PropertyDatatype.FLOAT, f"0:{digits}:0.5", None) == ("1.5", None) + assert _published(PropertyDatatype.INTEGER, digits) is None + + def test_a_huge_exponent_costs_no_huge_power(self): + """`1e-100000000` must not compute 10**100000000 on the /set path or in `$format`.""" + float_ = PropertyDatatype.FLOAT + start = time.monotonic() + assert _parse_set_payload("1e-100000000", float_, None, None) == ("1e-100000000", None) + assert _parse_set_payload("-1e-100000000", float_, "0:", None) == (None, "belowMin") + assert _parse_set_payload("0e999999999999", float_, "0:1", None) == ("0e999999999999", None) + assert _parse_set_payload("5", float_, "1e-99999999999:1e99999999999", None) == ("5", None) + assert _parse_set_payload("5", float_, "1e99999999999:", None) == (None, "belowMin") + assert time.monotonic() - start < 1.0 + + def test_exact_number_matches_fraction_in_range(self): + for text in ("0", "-0", "1.5", "-.25", "5.", "1e308", "-4.9e-324", "0.000123e-5", "12.5E3", "1e-1000"): + assert _exact_number(text) == Fraction(text), text + def test_non_ascii_digits_are_rejected(self): assert _accepts(PropertyDatatype.INTEGER, "\u0661") == "REJECTED" assert _accepts(PropertyDatatype.FLOAT, "\u0663.5") == "REJECTED" @@ -959,7 +1018,7 @@ def test_non_ascii_digits_are_rejected(self): def test_datetime_must_be_iso_8601(self): assert _accepts(PropertyDatatype.DATETIME, "2026-10-08T12:00:00Z") == "2026-10-08T12:00:00Z" - for bad in ("banana", "2026-10-08 12:00", ""): + for bad in ("banana", "2026-10-08 12:00", "", "2024-01-01T24:30", "2023-366", "2021-W53"): assert _accepts(PropertyDatatype.DATETIME, bad) == "REJECTED", bad def test_boolean_is_case_sensitive(self): @@ -973,7 +1032,7 @@ def test_enum_membership(self): def test_json_must_be_an_array_or_object(self): assert _accepts(PropertyDatatype.JSON, "[1, 2]") == [1, 2] - for bad in ("5", '"s"', "null", "{", '{"a": NaN}'): + for bad in ("5", '"s"', "null", "{", '{"a": NaN}', "[Infinity]", "[1e400]", '["\\ud800"]', "[" * 100000): assert _accepts(PropertyDatatype.JSON, bad) == "REJECTED", bad def test_empty_string_decoding_is_for_string_only(self):