diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index a3f0e0e5e10b..9765ca636059 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -1111,6 +1111,7 @@ class ReloadServiceHelper[_T]: The helper has the following purposes: - Make sure reloads do not happen in parallel - Avoid redundant reloads of the same target + - Keep reloads running if the caller is cancelled """ def __init__( @@ -1126,6 +1127,17 @@ class ReloadServiceHelper[_T]: self._reload_targets_func = reload_targets_func async def execute_service(self, service_call: ServiceCall) -> None: + """Execute the reload independently of caller cancellation.""" + # Reloading may remove and stop the automation that called the service. + await asyncio.shield( + service_call.hass.async_create_task( + self._execute_service(service_call), + f"reload {service_call.domain}.{service_call.service}", + eager_start=True, + ) + ) + + async def _execute_service(self, service_call: ServiceCall) -> None: """Execute the service. If a previous reload task is currently in progress, wait for it to finish first. diff --git a/tests/components/automation/test_init.py b/tests/components/automation/test_init.py index d2308512d65b..c6a5355dded1 100644 --- a/tests/components/automation/test_init.py +++ b/tests/components/automation/test_init.py @@ -36,6 +36,7 @@ from homeassistant.components.automation.const import ( AutomationService, AutomationServiceArgument, ) +from homeassistant.components.automation.entity import BaseAutomationEntity from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, @@ -68,6 +69,7 @@ from homeassistant.helpers import ( issue_registry as ir, trigger as trigger_helper, ) +from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.script import ( SCRIPT_MODE_CHOICES, @@ -747,6 +749,109 @@ async def test_reload_config_service( assert calls[1].data.get("event") == "test_event2" +@pytest.mark.parametrize( + "reload_data", + [pytest.param({}, id="all"), pytest.param({"id": "reload_self"}, id="single")], +) +async def test_reload_from_changed_automation( + hass: HomeAssistant, + calls: list[ServiceCall], + reload_data: dict[str, str], +) -> None: + """A running automation can reload its own changed configuration.""" + config = { + automation.DOMAIN: [ + { + "id": "reload_self", + "alias": "reload_self", + "triggers": [{"trigger": "event", "event_type": "reload_self"}], + "actions": [{"action": "automation.reload", "data": reload_data}], + }, + { + "id": "bystander", + "alias": "bystander", + "triggers": [{"trigger": "event", "event_type": "bystander"}], + "actions": [{"action": "test.automation"}], + }, + ] + } + assert await async_setup_component(hass, automation.DOMAIN, config) + reloaded = async_capture_events(hass, EVENT_AUTOMATION_RELOADED) + new_config = { + automation.DOMAIN: [ + { + **config[automation.DOMAIN][0], + "alias": "reloaded_self", + "actions": [{"action": "test.automation"}], + }, + config[automation.DOMAIN][1], + ] + } + with patch("homeassistant.config.load_yaml_config_file", return_value=new_config): + hass.bus.async_fire("reload_self") + await hass.async_block_till_done() + + assert len(reloaded) == 1 + assert hass.states.get("automation.reload_self").state == STATE_ON + assert hass.states.get("automation.reload_self").name == "reloaded_self" + assert hass.states.get("automation.bystander").state == STATE_ON + hass.bus.async_fire("reload_self") + hass.bus.async_fire("bystander") + await hass.async_block_till_done() + assert len(calls) == 2 + + +async def test_reload_cancellation_preserves_serialization(hass: HomeAssistant) -> None: + """Cancelling a caller must not interrupt a reload or allow overlapping reloads.""" + config = {automation.DOMAIN: []} + assert await async_setup_component(hass, automation.DOMAIN, config) + reloaded = async_capture_events(hass, EVENT_AUTOMATION_RELOADED) + started = asyncio.Event() + finish = asyncio.Event() + + async def async_process_config( + hass: HomeAssistant, + config: ConfigType, + component: EntityComponent[BaseAutomationEntity], + ) -> None: + started.set() + await finish.wait() + + with ( + patch("homeassistant.config.load_yaml_config_file", return_value=config), + patch( + "homeassistant.components.automation.services.async_process_config", + side_effect=async_process_config, + ) as process_config, + ): + first_reload = hass.async_create_task( + hass.services.async_call( + automation.DOMAIN, AutomationService.RELOAD, blocking=True + ) + ) + await started.wait() + first_reload.cancel() + with pytest.raises(asyncio.CancelledError): + await first_reload + + second_reload = hass.async_create_task( + hass.services.async_call( + automation.DOMAIN, AutomationService.RELOAD, blocking=True + ), + eager_start=True, + ) + assert process_config.await_count == 1 + assert not second_reload.done() + assert not reloaded + + finish.set() + await second_reload + await hass.async_block_till_done() + + assert process_config.await_count == 2 + assert len(reloaded) == 2 + + async def test_reload_config_when_invalid_config( hass: HomeAssistant, calls: list[ServiceCall] ) -> None: diff --git a/tests/helpers/test_service.py b/tests/helpers/test_service.py index 463851341057..e848ea92dbba 100644 --- a/tests/helpers/test_service.py +++ b/tests/helpers/test_service.py @@ -2882,6 +2882,49 @@ async def test_async_extract_config_entry_ids(hass: HomeAssistant) -> None: assert await service.async_extract_config_entry_ids(call) == {"abc"} +@pytest.mark.parametrize( + "cancelled_caller", + [pytest.param(0, id="active"), pytest.param(1, id="waiting")], +) +async def test_reload_service_helper_cancellation( + hass: HomeAssistant, cancelled_caller: int +) -> None: + """Cancelling active or waiting callers preserves serialized reloads.""" + finish = asyncio.Event() + reloaded: list[str] = [] + + async def reload_service_handler(service_call: ServiceCall) -> None: + await finish.wait() + reloaded.append(service_call.data["target"]) + + handler = AsyncMock(side_effect=reload_service_handler) + reloader = service.ReloadServiceHelper(handler, lambda call: {call.data["target"]}) + callers = [ + hass.async_create_task( + reloader.execute_service( + ServiceCall(hass, "test", "reload", {"target": target}) + ), + eager_start=True, + ) + for target in ("first", "second") + ] + callers[cancelled_caller].cancel() + with pytest.raises(asyncio.CancelledError): + await callers[cancelled_caller] + + assert handler.await_count == 1 + assert not reloaded + finish.set() + await asyncio.gather(*callers, return_exceptions=True) + await hass.async_block_till_done() + assert reloaded == ["first", "second"] + + await reloader.execute_service( + ServiceCall(hass, "test", "reload", {"target": "third"}) + ) + assert reloaded == ["first", "second", "third"] + + async def test_reload_service_helper(hass: HomeAssistant) -> None: """Test the reload service helper."""