diff --git a/custom_components/pyscript/decorator.py b/custom_components/pyscript/decorator.py index cd5fbc4c..d7efd48f 100644 --- a/custom_components/pyscript/decorator.py +++ b/custom_components/pyscript/decorator.py @@ -248,11 +248,21 @@ def __init__(self, ast_ctx: AstEval, eval_func_var: EvalFuncVar) -> None: self.logger = self.eval_func.logger - def on_func_var_deleted(): + def stop_deleted_func(): if self.status is DecoratorManagerStatus.RUNNING: self.hass.async_create_task(self.safe_await(self.stop())) - weakref.finalize(eval_func_var, on_func_var_deleted) + def on_func_var_deleted(): + # garbage collection can run this in any thread, so hand off to the loop + try: + self.hass.loop.call_soon_threadsafe(stop_deleted_func) + except RuntimeError: + # once HA has closed the loop at shutdown there is nothing left to stop + pass + + # not at interpreter exit either, the loop is closed by then + self.func_var_finalizer = weakref.finalize(eval_func_var, on_func_var_deleted) + self.func_var_finalizer.atexit = False async def _call(self, data: DispatchData) -> None: handlers = self.get_decorators(CallHandlerDecorator) diff --git a/tests/test_decorator_manager.py b/tests/test_decorator_manager.py index fd8e28e6..9b6ffa71 100644 --- a/tests/test_decorator_manager.py +++ b/tests/test_decorator_manager.py @@ -3,10 +3,13 @@ from __future__ import annotations import ast +import asyncio from collections.abc import Awaitable +import gc import logging +from types import SimpleNamespace from typing import Any, ClassVar -from unittest.mock import patch +from unittest.mock import Mock, patch import pytest import voluptuous as vol @@ -844,6 +847,68 @@ async def handle_call_result(self, data: DispatchData, result: object) -> None: assert ast_ctx.logged_exceptions == [handler_bug] +@pytest.mark.asyncio +async def test_function_decorator_manager_stops_when_function_is_deleted(hass): + """Deleting the function of a running manager should stop the manager.""" + DecoratorManager.hass = hass + func_var = DummyEvalFuncVar() + manager = FunctionDecoratorManager(DummyAstCtx(), func_var) + manager.update_status(DecoratorManagerStatus.RUNNING) + + del func_var + gc.collect() + await hass.async_block_till_done() + + assert manager.status is DecoratorManagerStatus.STOPPED + + +def test_function_decorator_manager_finalizer_skips_closed_loop(): + """A running manager whose function goes away after HA closed the loop must not schedule stop().""" + closed_loop = asyncio.new_event_loop() + closed_loop.close() + create_task = Mock() + DecoratorManager.hass = SimpleNamespace(loop=closed_loop, async_create_task=create_task) + func_var = DummyEvalFuncVar() + manager = FunctionDecoratorManager(DummyAstCtx(), func_var) + manager.update_status(DecoratorManagerStatus.RUNNING) + + del func_var + gc.collect() + + create_task.assert_not_called() + assert manager.status is DecoratorManagerStatus.RUNNING + + +@pytest.mark.asyncio +async def test_function_decorator_manager_finalizer_not_run_at_exit(hass): + """The finalizer should not run from atexit, after HA has closed the loop.""" + DecoratorManager.hass = hass + func_var = DummyEvalFuncVar() + manager = FunctionDecoratorManager(DummyAstCtx(), func_var) + + assert manager.func_var_finalizer.alive + assert manager.func_var_finalizer.atexit is False + + +@pytest.mark.asyncio +async def test_function_decorator_manager_finalizer_in_worker_thread(hass, caplog): + """Deleting the function in a worker thread should stop the manager via the loop.""" + DecoratorManager.hass = hass + holder = [DummyEvalFuncVar()] + manager = FunctionDecoratorManager(DummyAstCtx(), holder[0]) + manager.update_status(DecoratorManagerStatus.RUNNING) + + def drop(): + holder.clear() + gc.collect() + + await hass.async_add_executor_job(drop) + await hass.async_block_till_done() + + assert manager.status is DecoratorManagerStatus.STOPPED + assert "thread other than the event loop" not in caplog.text + + @pytest.mark.asyncio async def test_call_result_handler_default_handle_call_exception_forwards_none(): """Default handle_call_exception should forward the call to handle_call_result with None."""