Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,28 @@ Sections
removes a pairing (guarded, since removing the last admin wipes all
pairings). Also `load_accessory_state`/`save_accessory_state`/
`remove_client_pairing` in `pyhap.client` for the programmatic equivalent.
- Test tooling that fails on awaitables that are never awaited: pytest now
promotes `RuntimeWarning` ("coroutine ... was never awaited", surfacing as
`PytestUnraisableExceptionWarning` under the error filter) to test
failures via `filterwarnings` in `pyproject.toml`, a guard fixture in
`tests/conftest.py` fails any test during which asyncio logs "Task was
destroyed but it is pending!", and ruff's `RUF006` flags
`create_task`/`ensure_future` results that are not kept. Together with the
`_noop()` side effect of the `async_zeroconf` mock, this makes the existing
start/stop tests fail if the driver ever stops awaiting the broadcast
awaitables zeroconf returns (the
[#580](https://github.com/ikalchev/HAP-python/pull/580) bug class).
`tests/test_asyncio_guards.py` guards the `filterwarnings` config itself.

### Fixed

- Drop the write response of a coroutine setter that answers only after its
connection closed. The per-connection response was kept under the closed
connection's address forever, where a later connection reusing the address
could read it, e.g. a Setup Endpoints answer with its session's SRTP keys.
- Cancel tasks still pending on the loop before `AccessoryDriver.start`
closes it, so e.g. a `run_at_interval` wrapper is not destroyed pending at
shutdown ("Task was destroyed but it is pending!").

### Changed

Expand Down
10 changes: 9 additions & 1 deletion docs/source/advanced/async.rst
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,15 @@ Caveats
never back to the connection that caused it.
* **Un-awaited tasks are not free.** A bare ``asyncio.create_task`` result
can be garbage-collected before it runs, and its exception is only a
warning; prefer :func:`pyhap.util.async_create_background_task`.
warning; prefer :func:`pyhap.util.async_create_background_task`. The same
applies to awaitables returned *by* awaited calls — e.g. zeroconf's
``async_unregister_service`` returns the goodbye-broadcast task, which must
be awaited too, or it is still pending when the loop closes. The test
suite enforces this: ``RuntimeWarning`` ("coroutine ... was never
awaited") is promoted to a test error via ``filterwarnings``, a guard
fixture in ``tests/conftest.py`` fails any test during which asyncio logs
"Task was destroyed but it is pending!", and ruff's ``RUF006`` flags
``create_task``/``ensure_future`` results that are not kept.
* **Subprocesses on the loop's executor.** If your accessory runs ffmpeg or
other subprocesses (cameras do), be aware the loop reaps them; the driver
sets a child watcher when it owns the loop. Starting subprocesses from a
Expand Down
17 changes: 17 additions & 0 deletions pyhap/accessory_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,9 +492,26 @@ def start(self) -> None:
self.loop.call_soon_threadsafe(self.loop.create_task, self.async_stop())
self.loop.run_forever()
finally:
self._cancel_pending_tasks()
self.loop.close()
logger.info("Closed the event loop")

def _cancel_pending_tasks(self) -> None:
"""Cancel tasks still pending on the loop before it is closed.

Without this, a task that is still running when the loop stops (e.g.
a ``run_at_interval`` wrapper awaiting its ``run`` task) is destroyed
pending at loop close, which asyncio logs as "Task was destroyed but
it is pending!".
"""
pending = [task for task in asyncio.all_tasks(self.loop) if not task.done()]
for task in pending:
task.cancel()
if pending:
self.loop.run_until_complete(
asyncio.gather(*pending, return_exceptions=True)
)

def start_service(self) -> None:
"""Start the service."""
self._validate_start()
Expand Down
15 changes: 15 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ select = [
"UP", # pyupgrade
"ANN", # flake8-annotations
"E721", # type-comparison: use isinstance(x, T) instead of type(x) == T
"RUF006", # asyncio-dangling-task: keep a reference to create_task/ensure_future results
]
ignore = [
"ANN401", # Any is sometimes the honest type; prefer precise types
Expand Down Expand Up @@ -161,3 +162,17 @@ norecursedirs = [
"testing_config",
]
asyncio_mode = "auto"
# Catch awaitables that are never awaited: an un-awaited coroutine raises
# RuntimeWarning("coroutine ... was never awaited") when it is finalized;
# the error filter turns that into an exception inside the coroutine's
# __del__, which surfaces as an unraisable "Exception ignored while
# finalizing coroutine ..." (pytest.PytestUnraisableExceptionWarning) and is
# promoted to a test failure by the second entry.
#
# Pending tasks destroyed at
# loop shutdown ("Task was destroyed but it is pending!") only log on the
# asyncio logger and are caught by the guard fixture in tests/conftest.py.
filterwarnings = [
"error::RuntimeWarning",
"error:Exception ignored.*coroutine:pytest.PytestUnraisableExceptionWarning",
]
43 changes: 43 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import asyncio
from collections.abc import AsyncIterator, Callable, Iterator
import gc
import logging
import pathlib
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
Expand Down Expand Up @@ -59,6 +61,47 @@ def mock_local_address() -> Iterator[None]:
yield


@pytest.fixture(autouse=True)
def fail_on_dangling_asyncio_objects() -> Iterator[None]:
"""Fail a test when asyncio reports an awaitable that was never awaited.

An un-awaited coroutine raises ``RuntimeWarning("coroutine ... was never
awaited")`` when finalized, which ``filterwarnings`` in pyproject.toml
promotes to an error. A pending task that is garbage collected only logs
"Task was destroyed but it is pending!" on the asyncio logger, so capture
those records here and fail the test that was running when it happened.
"""
records: list[logging.LogRecord] = []

class _Handler(logging.Handler):
def emit(self, record: logging.LogRecord) -> None:
records.append(record)

handler = _Handler(level=logging.ERROR)
asyncio_logger = logging.getLogger("asyncio")
asyncio_logger.addHandler(handler)
try:
yield
finally:
gc.collect()
asyncio_logger.removeHandler(handler)
dangling = [
record.getMessage()
for record in records
if record.levelno >= logging.ERROR
and (
"was destroyed but it is pending" in record.getMessage()
or "was never awaited" in record.getMessage()
)
]
if dangling:
pytest.fail(
"asyncio reported un-awaited or dangling awaitables:\n"
+ "\n".join(dangling),
pytrace=False,
)


class MockDriver:
def __init__(self) -> None:
self.loader = Loader()
Expand Down
51 changes: 51 additions & 0 deletions tests/test_asyncio_guards.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Guard tests for the suite's un-awaited-awaitable detection.

pyproject.toml promotes ``RuntimeWarning`` and
``pytest.PytestUnraisableExceptionWarning`` to test failures, and
``tests/conftest.py`` fails a test when asyncio logs "Task was destroyed but
it is pending!" / "... was never awaited". The tests here prove that this
harness actually catches awaitables that are never awaited.
"""

import pathlib
import subprocess
import sys

REPO_ROOT = pathlib.Path(__file__).resolve().parent.parent


def test_suite_fails_on_unawaited_coroutine(tmp_path: pathlib.Path) -> None:
"""A test that drops a coroutine must fail under the suite's config.

Runs a scratch test file through pytest with this repo's pyproject.toml
as the config, so the assertion exercises the real ``filterwarnings``
setup rather than a copy of it.

A separate process fork is necessary as __del__ on a coroutine raises when
it is not awaited and propagates to sys.unraisablehook, not to the caller
(so we cannot assert properly here).
"""
test_file = tmp_path / "test_unawaited_coroutine.py"
test_file.write_text(
"def test_unawaited():\n async def coro():\n pass\n coro()\n"
)
proc = subprocess.run(
[
sys.executable,
"-m",
"pytest",
"-c",
str(REPO_ROOT / "pyproject.toml"),
"-p",
"no:cacheprovider",
"-q",
str(test_file),
],
capture_output=True,
text=True,
cwd=REPO_ROOT,
timeout=120,
check=False,
)
assert proc.returncode != 0
assert "coroutine" in proc.stdout
Loading