| 1 |
"""Benchmarks for the BluetoothManager hot paths.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from typing import TYPE_CHECKING |
| 6 |
|
| 7 |
import pytest |
| 8 |
from bluetooth_data_tools import monotonic_time_coarse |
| 9 |
|
| 10 |
from habluetooth import ( |
| 11 |
BaseHaRemoteScanner, |
| 12 |
BaseHaScanner, |
| 13 |
HaBluetoothConnector, |
| 14 |
get_manager, |
| 15 |
) |
| 16 |
from habluetooth.models import BluetoothServiceInfoBleak |
| 17 |
|
| 18 |
from . import ( |
| 19 |
MockBleakClient, |
| 20 |
generate_advertisement_data, |
| 21 |
generate_ble_device, |
| 22 |
) |
| 23 |
|
| 24 |
if TYPE_CHECKING: |
| 25 |
from collections.abc import Iterable |
| 26 |
|
| 27 |
from bleak.backends.scanner import AdvertisementData, BLEDevice |
| 28 |
from pytest_codspeed import BenchmarkFixture |
| 29 |
|
| 30 |
pytestmark = pytest.mark.timeout(60) |
| 31 |
|
| 32 |
|
| 33 |
class _LocalScannerLike(BaseHaScanner): |
| 34 |
"""Stand-in for HaScanner that rebuilds its discovered-dict each access.""" |
| 35 |
|
| 36 |
# The real HaScanner.discovered_addresses delegates to |
| 37 |
# bleak.BleakScanner.discovered_devices_and_advertisement_data which |
| 38 |
# walks bleak's backend cache and constructs a new dict each call. This |
| 39 |
# fake reproduces that allocation pattern so the benchmarks reflect the |
| 40 |
# redundant-rebuild cost that issue #505 targets — without depending on |
| 41 |
# a live BlueZ stack. |
| 42 |
|
| 43 |
def __init__(self, source: str, adapter: str, addresses: list[str]) -> None: |
| 44 |
super().__init__(source, adapter, connectable=True) |
| 45 |
self._addresses = addresses |
| 46 |
self._device = generate_ble_device( |
| 47 |
addresses[0] if addresses else "00:00:00:00:00:00", "x", {} |
| 48 |
) |
| 49 |
self._adv = generate_advertisement_data(local_name="x") |
| 50 |
|
| 51 |
@property |
| 52 |
def discovered_devices(self) -> list[BLEDevice]: |
| 53 |
return [self._device for _ in self._addresses] |
| 54 |
|
| 55 |
@property |
| 56 |
def discovered_devices_and_advertisement_data( |
| 57 |
self, |
| 58 |
) -> dict[str, tuple[BLEDevice, AdvertisementData]]: |
| 59 |
# Rebuild the dict on every access, matching bleak's behavior. |
| 60 |
return dict.fromkeys(self._addresses, (self._device, self._adv)) |
| 61 |
|
| 62 |
@property |
| 63 |
def discovered_addresses(self) -> Iterable[str]: |
| 64 |
# Match HaScanner: dict iteration yields keys, but the dict is |
| 65 |
# rebuilt on every access. |
| 66 |
return self.discovered_devices_and_advertisement_data |
| 67 |
|
| 68 |
def get_discovered_device_advertisement_data( |
| 69 |
self, address: str |
| 70 |
) -> tuple[BLEDevice, AdvertisementData] | None: |
| 71 |
return self.discovered_devices_and_advertisement_data.get(address) |
| 72 |
|
| 73 |
|
| 74 |
def _make_address(i: int) -> str: |
| 75 |
return f"AA:BB:CC:{(i >> 16) & 0xFF:02X}:{(i >> 8) & 0xFF:02X}:{i & 0xFF:02X}" |
| 76 |
|
| 77 |
|
| 78 |
def _seed_history(num_devices: int, source: str) -> list[str]: |
| 79 |
"""Populate manager history with ``num_devices`` devices from ``source``.""" |
| 80 |
manager = get_manager() |
| 81 |
now = monotonic_time_coarse() |
| 82 |
addresses: list[str] = [] |
| 83 |
for i in range(num_devices): |
| 84 |
address = _make_address(i) |
| 85 |
addresses.append(address) |
| 86 |
device = generate_ble_device(address, f"dev{i}", {}) |
| 87 |
adv = generate_advertisement_data( |
| 88 |
local_name=f"dev{i}", |
| 89 |
manufacturer_data={1: bytes((i & 0xFF,))}, |
| 90 |
service_uuids=[], |
| 91 |
rssi=-60, |
| 92 |
) |
| 93 |
manager.scanner_adv_received( |
| 94 |
BluetoothServiceInfoBleak( |
| 95 |
name=adv.local_name, |
| 96 |
address=address, |
| 97 |
rssi=adv.rssi, |
| 98 |
manufacturer_data=adv.manufacturer_data, |
| 99 |
service_data=adv.service_data, |
| 100 |
service_uuids=adv.service_uuids, |
| 101 |
source=source, |
| 102 |
device=device, |
| 103 |
advertisement=adv, |
| 104 |
connectable=True, |
| 105 |
time=now, |
| 106 |
tx_power=adv.tx_power, |
| 107 |
) |
| 108 |
) |
| 109 |
return addresses |
| 110 |
|
| 111 |
|
| 112 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 113 |
@pytest.mark.asyncio |
| 114 |
async def test_check_unavailable_steady_state_remote( |
| 115 |
benchmark: BenchmarkFixture, |
| 116 |
) -> None: |
| 117 |
"""Steady-state _async_check_unavailable with one remote scanner and 200 devices.""" |
| 118 |
# Nothing has disappeared — every history address is still in the scanner's |
| 119 |
# discovered_addresses. This is the dominant production path: each cycle |
| 120 |
# runs the difference twice (connectable + non-connectable loops). |
| 121 |
manager = get_manager() |
| 122 |
connector = HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: True) |
| 123 |
scanner = BaseHaRemoteScanner("esp32", "esp32", connector, connectable=True) |
| 124 |
unsetup = scanner.async_setup() |
| 125 |
cancel = manager.async_register_scanner(scanner) |
| 126 |
|
| 127 |
addresses = _seed_history(200, "esp32") |
| 128 |
# Inject through the remote scanner's normal entry point so its |
| 129 |
# discovered_addresses (== _previous_service_info) is populated too. |
| 130 |
now = monotonic_time_coarse() |
| 131 |
for i, address in enumerate(addresses): |
| 132 |
scanner._async_on_advertisement( |
| 133 |
address, |
| 134 |
-60, |
| 135 |
f"dev{i}", |
| 136 |
[], |
| 137 |
{}, |
| 138 |
{1: bytes((i & 0xFF,))}, |
| 139 |
None, |
| 140 |
{"scanner_specific_data": "test"}, |
| 141 |
now, |
| 142 |
) |
| 143 |
|
| 144 |
@benchmark |
| 145 |
def run() -> None: |
| 146 |
manager._async_check_unavailable() |
| 147 |
|
| 148 |
cancel() |
| 149 |
unsetup() |
| 150 |
|
| 151 |
|
| 152 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 153 |
@pytest.mark.asyncio |
| 154 |
async def test_check_unavailable_steady_state_local_like( |
| 155 |
benchmark: BenchmarkFixture, |
| 156 |
) -> None: |
| 157 |
"""Steady-state _async_check_unavailable with one rebuilding local-like scanner.""" |
| 158 |
# The local-like scanner rebuilds its discovered_addresses dict on every |
| 159 |
# property access. This isolates the cost issue #505 calls out: |
| 160 |
# _async_check_unavailable invokes discovered_addresses on every |
| 161 |
# connectable scanner twice per cycle, and for local HaScanner each |
| 162 |
# access rebuilds bleak's discovered-devices dict. |
| 163 |
manager = get_manager() |
| 164 |
addresses = _seed_history(200, "hci0") |
| 165 |
scanner = _LocalScannerLike("hci0", "hci0", addresses) |
| 166 |
cancel = manager.async_register_scanner(scanner) |
| 167 |
|
| 168 |
@benchmark |
| 169 |
def run() -> None: |
| 170 |
manager._async_check_unavailable() |
| 171 |
|
| 172 |
cancel() |
| 173 |
|
| 174 |
|
| 175 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 176 |
@pytest.mark.asyncio |
| 177 |
async def test_check_unavailable_many_scanners_local_like( |
| 178 |
benchmark: BenchmarkFixture, |
| 179 |
) -> None: |
| 180 |
"""Steady-state _async_check_unavailable: four local-like + one remote scanner.""" |
| 181 |
# 200 devices total. Multi-scanner deployments amplify the redundant-rebuild |
| 182 |
# cost: every connectable scanner's discovered_addresses is materialized |
| 183 |
# twice per cycle (issue #505). |
| 184 |
manager = get_manager() |
| 185 |
addresses = _seed_history(200, "hci0") |
| 186 |
|
| 187 |
scanners: list[BaseHaScanner] = [] |
| 188 |
cancels = [] |
| 189 |
for idx, adapter in enumerate(("hci0", "hci1", "hci2", "hci3")): |
| 190 |
# Each local-like scanner sees a non-empty overlapping slice so the |
| 191 |
# set difference work mirrors a real multi-adapter install. |
| 192 |
slice_size = max(1, len(addresses) // (idx + 1)) |
| 193 |
local = _LocalScannerLike(adapter, adapter, addresses[:slice_size]) |
| 194 |
scanners.append(local) |
| 195 |
cancels.append(manager.async_register_scanner(local)) |
| 196 |
|
| 197 |
connector = HaBluetoothConnector( |
| 198 |
MockBleakClient, "mock_bleak_client", lambda: False |
| 199 |
) |
| 200 |
remote = BaseHaRemoteScanner("esp32_nc", "esp32_nc", connector, connectable=False) |
| 201 |
remote_unsetup = remote.async_setup() |
| 202 |
cancels.append(manager.async_register_scanner(remote)) |
| 203 |
|
| 204 |
@benchmark |
| 205 |
def run() -> None: |
| 206 |
manager._async_check_unavailable() |
| 207 |
|
| 208 |
for c in cancels: |
| 209 |
c() |
| 210 |
remote_unsetup() |
| 211 |
|
| 212 |
|
| 213 |
@pytest.mark.usefixtures("enable_bluetooth") |
| 214 |
@pytest.mark.asyncio |
| 215 |
async def test_check_unavailable_all_disappeared( |
| 216 |
benchmark: BenchmarkFixture, |
| 217 |
) -> None: |
| 218 |
"""Worst case: every history address has disappeared from every scanner.""" |
| 219 |
# Exercises the disappear-callback and tracker-cleanup branches of the |
| 220 |
# inner loop. Re-seeds history each iteration so the benchmark measures |
| 221 |
# the dispatch work, not a one-shot drain. 50 devices is small on purpose |
| 222 |
# to keep the re-seed overhead from dominating. |
| 223 |
manager = get_manager() |
| 224 |
connector = HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: True) |
| 225 |
scanner = BaseHaRemoteScanner("esp32", "esp32", connector, connectable=True) |
| 226 |
unsetup = scanner.async_setup() |
| 227 |
cancel = manager.async_register_scanner(scanner) |
| 228 |
|
| 229 |
template_addresses = [_make_address(i) for i in range(50)] |
| 230 |
|
| 231 |
def reseed() -> None: |
| 232 |
manager._all_history.clear() |
| 233 |
manager._connectable_history.clear() |
| 234 |
now = monotonic_time_coarse() - 10_000 # ensure beyond stale threshold |
| 235 |
for i, address in enumerate(template_addresses): |
| 236 |
device = generate_ble_device(address, f"dev{i}", {}) |
| 237 |
adv = generate_advertisement_data( |
| 238 |
local_name=f"dev{i}", |
| 239 |
manufacturer_data={1: bytes((i & 0xFF,))}, |
| 240 |
service_uuids=[], |
| 241 |
rssi=-60, |
| 242 |
) |
| 243 |
manager.scanner_adv_received( |
| 244 |
BluetoothServiceInfoBleak( |
| 245 |
name=adv.local_name, |
| 246 |
address=address, |
| 247 |
rssi=adv.rssi, |
| 248 |
manufacturer_data=adv.manufacturer_data, |
| 249 |
service_data=adv.service_data, |
| 250 |
service_uuids=adv.service_uuids, |
| 251 |
source="esp32", |
| 252 |
device=device, |
| 253 |
advertisement=adv, |
| 254 |
connectable=True, |
| 255 |
time=now, |
| 256 |
tx_power=adv.tx_power, |
| 257 |
) |
| 258 |
) |
| 259 |
|
| 260 |
@benchmark |
| 261 |
def run() -> None: |
| 262 |
reseed() |
| 263 |
manager._async_check_unavailable() |
| 264 |
|
| 265 |
cancel() |
| 266 |
unsetup() |