Skip to content

Stop task.wait_until's triggers when the waiting task is cancelled - #943

Merged
craigbarratt merged 1 commit into
custom-components:masterfrom
jfriend00:wait-until-cancel
Dec 4, 2026
Merged

craigbarratt merged 1 commit into
custom-components:masterfrom
jfriend00:wait-until-cancel

Conversation

@jfriend00

Copy link
Copy Markdown
Contributor

Stop task.wait_until's triggers when the waiting task is cancelled

What was broken

Cancelling a task while it waits in task.wait_until(), with task.cancel() or a newer task.unique() call, didn't stop the wait's triggers. A leftover state_trigger keeps evaluating its expression on each change of the entities it watches until the expression is next true. After that, its queue stays registered and gets an item for each later change of those entities, until Home Assistant restarts. Nothing else runs (the code after task.wait_until() never resumes), and no warning or error is logged.

So the cost is small: an extra evaluation of the expression per change until it's next true, then a queue item per change. It only adds up when waits are cancelled often, as with task.unique() and task.wait_until() together, on entities that change often. 2.1.1 does this too, so it isn't new in 3.0.0. With allow_all_imports set, calling pyscript.wait_until_demo shows the leftover queue:

from custom_components.pyscript.state import State


def waiter():
    task.wait_until(state_trigger="pyscript.wu == 'go'")


@service
def wait_until_demo():
    state.set("pyscript.wu", "no")
    waiter_task = task.create(waiter)
    task.sleep(0.1)
    task.cancel(waiter_task)
    task.sleep(0.1)
    # "go" runs the leftover trigger once and ends its task; later changes pile up in its queue
    for value in ["go", "a", "b", "c"]:
        state.set("pyscript.wu", value)
        task.sleep(0.1)
    log.warning(f"pyscript.wu queues: {[q.qsize() for q in State.notify.get('pyscript.wu', {})]}")


# 2.1.1 and 3.0.0:  pyscript.wu queues: [3]
# with this change: pyscript.wu queues: []

Why

WaitUntilDecoratorManager stops its decorators in dispatch(), when a trigger or the timeout fires, and in handle_exception(). When the waiting task is cancelled, await self._future raises CancelledError and neither of them runs, so the decorators keep running. For a state_trigger, only its stop() calls State.notify_del(). The next time the expression is true, dispatch() calls self._future.exception() on the cancelled future, which raises CancelledError and ends the trigger's task, but its queue stays in State.notify.

What I changed

WaitUntilDecoratorManager.wait_until() now stops the decorators when the wait is cancelled. It checks that the manager is still running first, since a trigger may have fired just before the cancel, and stop() warns when it isn't running. A cancel that arrives while the triggers are still starting isn't covered: DecoratorManager.start() only rolls back when a decorator raises an Exception, and only mqtt_trigger and sentence_trigger wait while they start.

Testing

A new test in tests/test_decorator_manager.py cancels a task that's waiting in WaitUntilDecoratorManager.wait_until() and checks that the wait's decorator was stopped. It fails without the change. tests/test_decorator_manager.py (38 tests) and tests/test_unique.py (3 tests) pass, and ruff, codespell, pylint and mypy are clean. This ran on Windows with local stand-ins for Home Assistant's Linux-only imports, so CI is its first Linux run.

Assisted by Claude Code

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @jfriend00, good find. Verified end to end that a wait cancelled with task.cancel() or task.unique() leaves its trigger queues and tasks behind on master, and nothing with this change. Approving.

@craigbarratt
craigbarratt merged commit 937e05b into custom-components:master Dec 4, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants