Move state length validation to StateMachine APIs (#143681)

* Move state length validation to StateMachine async_set method

We call validate_state to make sure we do not allow any states
into the state machine that have a length>255 so we do not break
the recorder. Since async_set_internal already requires callers
to pre-validate the state, we can move the check to async_set
instead of at State object creation time to avoid needing to
check it twice in the hot path (entity write state)

* move check in async_set_internal so it only happens on state change

* no need to check if same_state
This commit is contained in:
J. Nick Koston
2025-04-25 15:15:15 -10:00
committed by GitHub
parent 03950f270a
commit 34d17ca458
4 changed files with 51 additions and 22 deletions

View File

@@ -35,6 +35,7 @@ from homeassistant.const import (
EVENT_STATE_CHANGED,
EVENT_STATE_REPORTED,
MATCH_ALL,
STATE_UNKNOWN,
)
from homeassistant.core import (
CoreState,
@@ -1368,9 +1369,6 @@ def test_state_init() -> None:
with pytest.raises(InvalidEntityFormatError):
ha.State("invalid_entity_format", "test_state")
with pytest.raises(InvalidStateError):
ha.State("domain.long_state", "t" * 256)
def test_state_domain() -> None:
"""Test domain."""
@@ -1440,6 +1438,38 @@ def test_state_repr() -> None:
)
async def test_statemachine_async_set_invalid_state(hass: HomeAssistant) -> None:
"""Test setting an invalid state with the async_set method."""
with pytest.raises(
InvalidStateError,
match="Invalid state with length 256. State max length is 255 characters.",
):
hass.states.async_set("light.bowl", "o" * 256, {})
async def test_statemachine_async_set_internal_invalid_state(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test setting an invalid state with the async_set_internal method."""
long_state = "o" * 256
hass.states.async_set_internal(
"light.bowl",
long_state,
{},
force_update=False,
context=None,
state_info=None,
timestamp=time.time(),
)
assert hass.states.get("light.bowl").state == STATE_UNKNOWN
assert (
"homeassistant.core",
logging.ERROR,
f"State {long_state} for light.bowl is longer than 255, "
f"falling back to {STATE_UNKNOWN}",
) in caplog.record_tuples
async def test_statemachine_is_state(hass: HomeAssistant) -> None:
"""Test is_state method."""
hass.states.async_set("light.bowl", "on", {})