| 1 |
"""Benchmarks for the auto-scan scheduler hot paths.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import asyncio |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from habluetooth import ( |
| 11 |
BaseHaScanner, |
| 12 |
BluetoothScanningMode, |
| 13 |
get_manager, |
| 14 |
) |
| 15 |
|
| 16 |
from . import generate_advertisement_data, generate_ble_device |
| 17 |
|
| 18 |
if TYPE_CHECKING: |
| 19 |
from collections.abc import Iterable |
| 20 |
|
| 21 |
from bleak.backends.scanner import AdvertisementData, BLEDevice |
| 22 |
from pytest_codspeed import BenchmarkFixture |
| 23 |
|
| 24 |
from habluetooth.const import CALLBACK_TYPE |
| 25 |
|
| 26 |
pytestmark = pytest.mark.timeout(60) |
| 27 |
|
| 28 |
|
| 29 |
class _AutoScanner(BaseHaScanner): |
| 30 |
"""Minimal AUTO-mode scanner that exposes nothing to the discovery cache.""" |
| 31 |
|
| 32 |
# Mirrors the _RecordingAutoScanner used by test_auto_scheduler.py but |
| 33 |
# without window-call tracking; the scheduler hot paths under benchmark |
| 34 |
# never enter the scanner's active-window path. |
| 35 |
|
| 36 |
__slots__ = () |
| 37 |
|
| 38 |
def __init__(self, source: str) -> None: |
| 39 |
super().__init__(source, source, requested_mode=BluetoothScanningMode.AUTO) |
| 40 |
self.connectable = True |
| 41 |
|
| 42 |
async def async_request_active_window(self, duration: float) -> bool: |
| 43 |
return True |
| 44 |
|
| 45 |
@property |
| 46 |
def discovered_devices(self) -> list[BLEDevice]: |
| 47 |
return [] |
| 48 |
|
| 49 |
@property |
| 50 |
def discovered_devices_and_advertisement_data( |
| 51 |
self, |
| 52 |
) -> dict[str, tuple[BLEDevice, AdvertisementData]]: |
| 53 |
return {} |
| 54 |
|
| 55 |
def get_discovered_device_advertisement_data( |
| 56 |
self, address: str |
| 57 |
) -> tuple[BLEDevice, AdvertisementData] | None: |
| 58 |
return None |
| 59 |
|
| 60 |
@property |
| 61 |
def discovered_addresses(self) -> Iterable[str]: |
| 62 |
return () |
| 63 |
|
| 64 |
|
| 65 |
class _DiscoverableAutoScanner(_AutoScanner): |
| 66 |
""" |
| 67 |
AUTO scanner that reports a configurable discovered set. |
| 68 |
|
| 69 |
``_resolve_fallback_for_address`` reads candidate scanners via |
| 70 |
``manager.async_scanner_devices_by_address``, which filters on |
| 71 |
``get_discovered_device_advertisement_data``. The plain |
| 72 |
``_AutoScanner`` exposes nothing, so the fallback resolver would |
| 73 |
iterate an empty candidate list; this subclass lets a device be |
| 74 |
seen by several scanners so the resolver does real scan-and-score |
| 75 |
work. |
| 76 |
""" |
| 77 |
|
| 78 |
__slots__ = ("_discovered",) |
| 79 |
|
| 80 |
def __init__(self, source: str) -> None: |
| 81 |
super().__init__(source) |
| 82 |
self._discovered: dict[str, tuple[BLEDevice, AdvertisementData]] = {} |
| 83 |
|
| 84 |
def add_discovered(self, address: str, rssi: int) -> None: |
| 85 |
device = generate_ble_device(address, "x") |
| 86 |
adv = generate_advertisement_data(local_name="x", rssi=rssi) |
| 87 |
self._discovered[address] = (device, adv) |
| 88 |
|
| 89 |
def get_discovered_device_advertisement_data( |
| 90 |
self, address: str |
| 91 |
) -> tuple[BLEDevice, AdvertisementData] | None: |
| 92 |
return self._discovered.get(address) |
| 93 |
|
| 94 |
|
| 95 |
def _make_address(i: int) -> str: |
| 96 |
return f"AA:BB:CC:{(i >> 16) & 0xFF:02X}:{(i >> 8) & 0xFF:02X}:{i & 0xFF:02X}" |
| 97 |
|
| 98 |
|
| 99 |
def _make_source(i: int) -> str: |
| 100 |
# Distinct source MACs so each scanner registers as its own worker. |
| 101 |
return f"DD:EE:FF:{(i >> 16) & 0xFF:02X}:{(i >> 8) & 0xFF:02X}:{i & 0xFF:02X}" |
| 102 |
|
| 103 |
|
| 104 |
def _inject(scanner: _AutoScanner, address: str, now: float) -> None: |
| 105 |
"""Drive a fake advertisement through the scanner's normal entry point.""" |
| 106 |
adv = generate_advertisement_data(local_name="x") |
| 107 |
device = generate_ble_device(address, "x") |
| 108 |
scanner._async_on_advertisement( |
| 109 |
device.address, |
| 110 |
adv.rssi, |
| 111 |
device.name or "", |
| 112 |
adv.service_uuids, |
| 113 |
adv.service_data, |
| 114 |
adv.manufacturer_data, |
| 115 |
adv.tx_power, |
| 116 |
{}, |
| 117 |
now, |
| 118 |
) |
| 119 |
|
| 120 |
|
| 121 |
def _setup_scheduler( |
| 122 |
num_scanners: int, num_devices: int |
| 123 |
) -> tuple[list[_AutoScanner], list[CALLBACK_TYPE], list[CALLBACK_TYPE]]: |
| 124 |
""" |
| 125 |
Register ``num_scanners`` AUTO scanners and ``num_devices`` scan requests. |
| 126 |
|
| 127 |
Each address is owned by exactly one scanner via a round-robin |
| 128 |
advertisement injection that populates manager history and |
| 129 |
auto_scheduler._due_at (and the per-worker _owned_due_at view on |
| 130 |
branches that have it). |
| 131 |
""" |
| 132 |
manager = get_manager() |
| 133 |
loop = asyncio.get_running_loop() |
| 134 |
now = loop.time() |
| 135 |
scanners: list[_AutoScanner] = [] |
| 136 |
scanner_cancels: list[CALLBACK_TYPE] = [] |
| 137 |
for i in range(num_scanners): |
| 138 |
scanner = _AutoScanner(_make_source(i)) |
| 139 |
scanners.append(scanner) |
| 140 |
scanner_cancels.append(manager.async_register_scanner(scanner)) |
| 141 |
request_cancels: list[CALLBACK_TYPE] = [] |
| 142 |
for i in range(num_devices): |
| 143 |
address = _make_address(i) |
| 144 |
request_cancels.append( |
| 145 |
manager.async_register_active_scan(address, scan_interval=120.0) |
| 146 |
) |
| 147 |
# Inject through the round-robin owner so manager history points |
| 148 |
# back to that scanner's source. The scheduler picks ownership |
| 149 |
# from history.source on both the old and new code paths. |
| 150 |
_inject(scanners[i % num_scanners], address, now) |
| 151 |
return scanners, scanner_cancels, request_cancels |
| 152 |
|
| 153 |
|
| 154 |
def _teardown_scheduler( |
| 155 |
scanner_cancels: list[CALLBACK_TYPE], |
| 156 |
request_cancels: list[CALLBACK_TYPE], |
| 157 |
) -> None: |
| 158 |
"""Release scanner and active-scan registrations from ``_setup_scheduler``.""" |
| 159 |
for cancel in request_cancels: |
| 160 |
cancel() |
| 161 |
for cancel in scanner_cancels: |
| 162 |
cancel() |
| 163 |
|
| 164 |
|
| 165 |
@pytest.mark.asyncio |
| 166 |
async def test_next_event_at_single_worker_8_scanners_200_devices( |
| 167 |
benchmark: BenchmarkFixture, |
| 168 |
) -> None: |
| 169 |
""" |
| 170 |
One worker computing its next wake among 8 scanners and 200 tracked devices. |
| 171 |
|
| 172 |
Prior to the per-worker owned-needs optimization (PR #508 / issue #506), |
| 173 |
every wake iterated the global ``_due_at`` map (200 entries) and called |
| 174 |
``async_last_service_info`` on each to filter by ownership. The |
| 175 |
optimization narrows the iteration to the ~25 entries the worker owns |
| 176 |
and removes the per-entry history lookup. This benchmark exercises the |
| 177 |
single-worker hot path so any regression in ``_next_event_at`` cost |
| 178 |
shows up immediately. |
| 179 |
""" |
| 180 |
_, scanner_cancels, request_cancels = _setup_scheduler( |
| 181 |
num_scanners=8, num_devices=200 |
| 182 |
) |
| 183 |
manager = get_manager() |
| 184 |
scheduler = manager._auto_scheduler |
| 185 |
worker = next(iter(scheduler._workers.values())) |
| 186 |
loop = asyncio.get_running_loop() |
| 187 |
|
| 188 |
@benchmark |
| 189 |
def run() -> None: |
| 190 |
worker._next_event_at(loop.time()) |
| 191 |
|
| 192 |
_teardown_scheduler(scanner_cancels, request_cancels) |
| 193 |
|
| 194 |
|
| 195 |
@pytest.mark.asyncio |
| 196 |
async def test_next_event_at_burst_8_scanners_200_devices( |
| 197 |
benchmark: BenchmarkFixture, |
| 198 |
) -> None: |
| 199 |
""" |
| 200 |
All 8 workers compute their next wake — the burst scenario from issue #506. |
| 201 |
|
| 202 |
When an advertisement burst wakes every worker, the old code did |
| 203 |
O(K·N) work (K=8 workers each scanning N=200 entries). The |
| 204 |
optimization makes the total work O(N) because each worker only |
| 205 |
visits its owned subset. This benchmark captures the headline win. |
| 206 |
""" |
| 207 |
_, scanner_cancels, request_cancels = _setup_scheduler( |
| 208 |
num_scanners=8, num_devices=200 |
| 209 |
) |
| 210 |
manager = get_manager() |
| 211 |
scheduler = manager._auto_scheduler |
| 212 |
workers = list(scheduler._workers.values()) |
| 213 |
loop = asyncio.get_running_loop() |
| 214 |
|
| 215 |
@benchmark |
| 216 |
def run() -> None: |
| 217 |
now = loop.time() |
| 218 |
for worker in workers: |
| 219 |
worker._next_event_at(now) |
| 220 |
|
| 221 |
_teardown_scheduler(scanner_cancels, request_cancels) |
| 222 |
|
| 223 |
|
| 224 |
@pytest.mark.asyncio |
| 225 |
async def test_collect_due_buckets_single_worker_8_scanners_200_devices( |
| 226 |
benchmark: BenchmarkFixture, |
| 227 |
) -> None: |
| 228 |
""" |
| 229 |
One worker collecting due buckets among 8 scanners and 200 devices. |
| 230 |
|
| 231 |
``_collect_due_buckets`` shares the same iteration-scope problem as |
| 232 |
``_next_event_at``: pre-#508 it iterated the global ``_due_at`` and |
| 233 |
called ``async_last_service_info`` on every address to skip foreign |
| 234 |
owners; post-#508 it iterates the per-worker owned view directly. |
| 235 |
With entries scheduled well into the future, this exercises the |
| 236 |
no-dispatch read path that runs on every tick. |
| 237 |
""" |
| 238 |
_, scanner_cancels, request_cancels = _setup_scheduler( |
| 239 |
num_scanners=8, num_devices=200 |
| 240 |
) |
| 241 |
manager = get_manager() |
| 242 |
scheduler = manager._auto_scheduler |
| 243 |
worker = next(iter(scheduler._workers.values())) |
| 244 |
loop = asyncio.get_running_loop() |
| 245 |
|
| 246 |
@benchmark |
| 247 |
def run() -> None: |
| 248 |
worker._collect_due_buckets(loop.time()) |
| 249 |
|
| 250 |
_teardown_scheduler(scanner_cancels, request_cancels) |
| 251 |
|
| 252 |
|
| 253 |
@pytest.mark.asyncio |
| 254 |
async def test_collect_due_buckets_burst_8_scanners_200_devices( |
| 255 |
benchmark: BenchmarkFixture, |
| 256 |
) -> None: |
| 257 |
"""All 8 workers collect due buckets — burst variant of the read path.""" |
| 258 |
_, scanner_cancels, request_cancels = _setup_scheduler( |
| 259 |
num_scanners=8, num_devices=200 |
| 260 |
) |
| 261 |
manager = get_manager() |
| 262 |
scheduler = manager._auto_scheduler |
| 263 |
workers = list(scheduler._workers.values()) |
| 264 |
loop = asyncio.get_running_loop() |
| 265 |
|
| 266 |
@benchmark |
| 267 |
def run() -> None: |
| 268 |
now = loop.time() |
| 269 |
for worker in workers: |
| 270 |
worker._collect_due_buckets(now) |
| 271 |
|
| 272 |
_teardown_scheduler(scanner_cancels, request_cancels) |
| 273 |
|
| 274 |
|
| 275 |
@pytest.mark.asyncio |
| 276 |
async def test_on_advertisement_steady_state_8_scanners_200_devices( |
| 277 |
benchmark: BenchmarkFixture, |
| 278 |
) -> None: |
| 279 |
""" |
| 280 |
Ingestion hot path: re-deliver an advertisement for every tracked address. |
| 281 |
|
| 282 |
``AutoScanScheduler.on_advertisement`` runs once per advertisement |
| 283 |
for any address that has an active-scan request, fed from |
| 284 |
``BluetoothManager._scanner_adv_received``. The existing benchmarks |
| 285 |
cover the timer side (``_next_event_at`` / ``_collect_due_buckets``); |
| 286 |
this one covers the per-advertisement ingestion side that the timer |
| 287 |
benchmarks never touch. |
| 288 |
|
| 289 |
The scenario is steady state — the address is already seeded and |
| 290 |
owned by the delivering scanner — so each call exercises the dominant |
| 291 |
real-world cost: a ``_requests_by_address`` lookup, a no-op |
| 292 |
``_seed_requests`` pass (every request already present, so |
| 293 |
``_DueSchedule.seed`` short-circuits), and a same-source |
| 294 |
``_DueSchedule.assign`` that skips the owner reattach and only fires |
| 295 |
the worker's ``wake``. Delivering the cached ``service_info`` objects |
| 296 |
directly isolates the scheduler cost from the manager's dispatch and |
| 297 |
scoring path. |
| 298 |
""" |
| 299 |
_, scanner_cancels, request_cancels = _setup_scheduler( |
| 300 |
num_scanners=8, num_devices=200 |
| 301 |
) |
| 302 |
manager = get_manager() |
| 303 |
scheduler = manager._auto_scheduler |
| 304 |
# Cached service_info objects carry the round-robin owner as |
| 305 |
# ``.source``, so each delivery hits the same-owner steady-state path. |
| 306 |
service_infos = list(manager._all_history.values()) |
| 307 |
|
| 308 |
@benchmark |
| 309 |
def run() -> None: |
| 310 |
for service_info in service_infos: |
| 311 |
scheduler.on_advertisement(service_info) |
| 312 |
|
| 313 |
_teardown_scheduler(scanner_cancels, request_cancels) |
| 314 |
|
| 315 |
|
| 316 |
def _setup_fallback_mesh( |
| 317 |
num_scanners: int, num_devices: int, seen_by: int |
| 318 |
) -> tuple[list[_DiscoverableAutoScanner], list[CALLBACK_TYPE], list[str]]: |
| 319 |
""" |
| 320 |
Register ``num_scanners`` discoverable AUTO scanners over a dense mesh. |
| 321 |
|
| 322 |
Each of ``num_devices`` addresses is marked discovered by the first |
| 323 |
``seen_by`` scanners with descending RSSI, so the fallback resolver |
| 324 |
iterates ``seen_by`` candidates per address and exercises the |
| 325 |
RSSI-scoring branch (``rssi > best_rssi``) on every step. The first |
| 326 |
scanner is the connecting owner the resolver excludes. |
| 327 |
""" |
| 328 |
manager = get_manager() |
| 329 |
scanners: list[_DiscoverableAutoScanner] = [] |
| 330 |
scanner_cancels: list[CALLBACK_TYPE] = [] |
| 331 |
for i in range(num_scanners): |
| 332 |
scanner = _DiscoverableAutoScanner(_make_source(i)) |
| 333 |
scanners.append(scanner) |
| 334 |
scanner_cancels.append(manager.async_register_scanner(scanner)) |
| 335 |
addresses: list[str] = [] |
| 336 |
for i in range(num_devices): |
| 337 |
address = _make_address(i) |
| 338 |
addresses.append(address) |
| 339 |
for j in range(seen_by): |
| 340 |
# Descending RSSI so the best candidate is the last one |
| 341 |
# visited — the resolver can't early-exit its scan. |
| 342 |
scanners[j].add_discovered(address, rssi=-50 - j) |
| 343 |
return scanners, scanner_cancels, addresses |
| 344 |
|
| 345 |
|
| 346 |
@pytest.mark.asyncio |
| 347 |
async def test_resolve_fallback_8_scanners_25_devices_dense_mesh( |
| 348 |
benchmark: BenchmarkFixture, |
| 349 |
) -> None: |
| 350 |
""" |
| 351 |
Connecting-fallback resolution over a dense 8-scanner mesh. |
| 352 |
|
| 353 |
When a device's owning scanner is mid-connect, every due address is |
| 354 |
routed through ``_resolve_fallback_for_address``, which iterates the |
| 355 |
scanners that currently see the address and picks the highest-RSSI |
| 356 |
non-connecting AUTO fallback. This is the only sync auto-scheduler |
| 357 |
hot path with no benchmark; the timer (``_next_event_at`` / |
| 358 |
``_collect_due_buckets``) and ingestion (``on_advertisement``) |
| 359 |
benchmarks never enter it. |
| 360 |
|
| 361 |
The scenario mirrors a connect storm in a dense proxy mesh: 25 |
| 362 |
devices each visible to all 8 scanners, so each resolution scans 7 |
| 363 |
candidates (owner excluded) and scores every one. Descending RSSI |
| 364 |
means the resolver visits the full candidate list rather than |
| 365 |
short-circuiting, capturing the worst-case scan cost. |
| 366 |
""" |
| 367 |
scanners, scanner_cancels, addresses = _setup_fallback_mesh( |
| 368 |
num_scanners=8, num_devices=25, seen_by=8 |
| 369 |
) |
| 370 |
manager = get_manager() |
| 371 |
scheduler = manager._auto_scheduler |
| 372 |
owner_source = scanners[0].source |
| 373 |
|
| 374 |
@benchmark |
| 375 |
def run() -> None: |
| 376 |
for address in addresses: |
| 377 |
scheduler._resolve_fallback_for_address(address, owner_source) |
| 378 |
|
| 379 |
for cancel in scanner_cancels: |
| 380 |
cancel() |