Debian Codegraph @

tests/test_auto_scheduler.py

raw
1 """Tests for the auto-mode active-window scheduler."""
2
3 from __future__ import annotations
4
5 import asyncio
6 import contextlib
7 import logging
8 import math
9 from typing import TYPE_CHECKING, Any
10 from unittest.mock import patch
11
12 import pytest
13 from bluetooth_data_tools import monotonic_time_coarse
14 from freezegun import freeze_time
15
16 from habluetooth import (
17 BaseHaScanner,
18 BluetoothScanningMode,
19 get_manager,
20 )
21 from habluetooth.auto_scheduler import ActiveScanRequest, _ScanSchedule
22 from habluetooth.const import (
23 AUTO_INITIAL_SWEEP_DELAY,
24 AUTO_REDISCOVERY_INTERVAL,
25 AUTO_REDISCOVERY_SWEEP_DURATION,
26 AUTO_WINDOW_MAX_DURATION,
27 AUTO_WINDOW_MIN_DURATION,
28 DEFAULT_ACTIVE_SCAN_DURATION,
29 DEFAULT_ACTIVE_SCAN_INTERVAL,
30 DEFAULT_ON_DEMAND_SWEEP_DURATION,
31 RESCUE_SCAN_ACCEPT_SECONDS,
32 )
33
34 from . import generate_advertisement_data, generate_ble_device
35
36 if TYPE_CHECKING:
37 from collections.abc import Iterable
38
39 from bleak.backends.device import BLEDevice
40 from bleak.backends.scanner import AdvertisementData
41
42
43 class _RecordingAutoScanner(BaseHaScanner):
44 """BaseHaScanner subclass that records active-window calls."""
45
46 __slots__ = ("_block_event", "_return_value", "active_window_calls")
47
48 def __init__(
49 self,
50 source: str,
51 mode: BluetoothScanningMode | None,
52 connectable: bool = True,
53 ) -> None:
54 super().__init__(source, source, requested_mode=mode)
55 self.connectable = connectable
56 self.active_window_calls: list[float] = []
57 self._block_event: asyncio.Event | None = None
58 self._return_value = True
59
60 async def async_request_active_window(self, duration: float) -> bool:
61 self.active_window_calls.append(duration)
62 if self._block_event is not None:
63 await self._block_event.wait()
64 return self._return_value
65
66 @property
67 def discovered_devices(self) -> list[BLEDevice]:
68 return []
69
70 @property
71 def discovered_devices_and_advertisement_data(
72 self,
73 ) -> dict[str, tuple[BLEDevice, AdvertisementData]]:
74 return {}
75
76 def get_discovered_device_advertisement_data(
77 self, address: str
78 ) -> tuple[BLEDevice, AdvertisementData] | None:
79 return None
80
81 @property
82 def discovered_addresses(self) -> Iterable[str]:
83 return ()
84
85
86 def _inject(scanner: _RecordingAutoScanner, address: str) -> None:
87 """Drive a fake advertisement through the scanner's normal path."""
88 adv = generate_advertisement_data(local_name="x")
89 device = generate_ble_device(address, "x")
90 scanner._async_on_advertisement(
91 device.address,
92 adv.rssi,
93 device.name or "",
94 adv.service_uuids,
95 adv.service_data,
96 adv.manufacturer_data,
97 adv.tx_power,
98 {},
99 asyncio.get_running_loop().time(),
100 )
101
102
103 async def _run_worker_tick(scheduler: object, source: str) -> None:
104 """Drive one worker through a single tick for deterministic testing."""
105 worker = scheduler._workers[source] # type: ignore[attr-defined]
106 await worker._tick()
107
108
109 def _assert_schedule_invariant(sched: object) -> None:
110 """
111 Assert the schedule's three indices are in lock step.
112
113 1. ``_due_at`` and ``_owner_by_address`` have the same keyset.
114 2. Every ``_due_at`` value is a non-empty dict.
115 3. For each AUTO worker, its ``_owned_due_at`` exactly equals the
116 addresses the schedule says it owns, and each entry's dict object
117 is the *same* dict aliased from ``_due_at`` (not a copy).
118 4. Addresses owned by a non-AUTO source do not appear in any
119 worker's ``_owned_due_at``.
120 5. Each worker's hot-path ``_next_event_at`` returns without
121 raising. An empty bucket in ``_owned_due_at`` would crash with
122 ``ValueError`` from ``min(())``, so calling it here is the
123 active runtime check for the no-empty-buckets invariant the
124 production code relies on.
125 """
126 schedule = sched._schedule # type: ignore[attr-defined]
127 workers = sched._workers # type: ignore[attr-defined]
128 assert set(schedule._due_at) == set(schedule._owner_by_address), (
129 f"_due_at keys {set(schedule._due_at)} != "
130 f"_owner_by_address keys {set(schedule._owner_by_address)}"
131 )
132 for address, entries in schedule._due_at.items():
133 assert entries, f"_due_at[{address}] is empty"
134 for source, worker in workers.items():
135 index_owned = {
136 addr
137 for addr, owner in schedule._owner_by_address.items()
138 if owner == source
139 }
140 worker_owned = set(worker._owned_due_at)
141 assert worker_owned == index_owned, (
142 f"worker {source}: _owned_due_at={worker_owned} "
143 f"!= index-owned={index_owned}"
144 )
145 for addr in worker_owned:
146 assert worker._owned_due_at[addr] is schedule._due_at[addr], (
147 f"worker {source}: _owned_due_at[{addr}] is not the "
148 f"same dict object as _due_at[{addr}]"
149 )
150 for address, source in schedule._owner_by_address.items():
151 if source not in workers:
152 for worker in workers.values():
153 assert address not in worker._owned_due_at, (
154 f"non-AUTO owner {source} leaked into worker "
155 f"{worker._scanner.source}'s _owned_due_at"
156 )
157 # Hot-path sanity: would raise ``ValueError`` from ``min(())`` if
158 # any owned bucket were empty. This keeps the guard the source
159 # code removed alive at the test layer.
160 now = asyncio.get_running_loop().time()
161 for worker in workers.values():
162 worker._next_event_at(now)
163
164
165 @pytest.mark.asyncio
166 async def test_advertisement_starts_tracking() -> None:
167 """A matching address advertisement creates a per-(address, request) entry."""
168 manager = get_manager()
169 sched = manager._auto_scheduler
170 cancel = manager.async_register_active_scan(
171 "11:22:33:44:55:66", scan_interval=120.0, scan_duration=6.0
172 )
173 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
174 register_cancel = manager.async_register_scanner(scanner)
175 try:
176 _inject(scanner, "11:22:33:44:55:66")
177 assert "11:22:33:44:55:66" in sched._schedule._due_at
178 finally:
179 cancel()
180 register_cancel()
181 assert sched._schedule._due_at == {}
182
183
184 @pytest.mark.asyncio
185 async def test_advertisement_for_unrelated_address_is_ignored() -> None:
186 """An advertisement for an unregistered address creates no tracking."""
187 manager = get_manager()
188 sched = manager._auto_scheduler
189 cancel = manager.async_register_active_scan(
190 "11:22:33:44:55:66", scan_interval=120.0
191 )
192 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
193 register_cancel = manager.async_register_scanner(scanner)
194 try:
195 # The registered address has tracking from add_request; the
196 # unrelated advertisement must not create its own entry.
197 _inject(scanner, "AA:AA:AA:AA:AA:AA")
198 assert "AA:AA:AA:AA:AA:AA" not in sched._schedule._due_at
199 finally:
200 cancel()
201 register_cancel()
202
203
204 @pytest.mark.asyncio
205 async def test_worker_tick_fires_active_window() -> None:
206 """A due tracker entry causes the owning scanner's worker to fire a window."""
207 manager = get_manager()
208 sched = manager._auto_scheduler
209 loop = asyncio.get_running_loop()
210 cancel = manager.async_register_active_scan(
211 "11:22:33:44:55:66", scan_interval=120.0, scan_duration=5.0
212 )
213 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
214 register_cancel = manager.async_register_scanner(scanner)
215 try:
216 _inject(scanner, "11:22:33:44:55:66")
217 entries = sched._schedule._due_at["11:22:33:44:55:66"]
218 request = next(iter(entries))
219 entries[request] = loop.time() - 1.0
220 await _run_worker_tick(sched, scanner.source)
221 assert scanner.active_window_calls == [5.0]
222 assert entries[request] > loop.time()
223 finally:
224 cancel()
225 register_cancel()
226
227
228 @pytest.mark.asyncio
229 async def test_worker_tick_advances_by_scan_interval_from_window_start() -> None:
230 """
231 Next-due is window_start + scan_interval, not window_end + scan_interval.
232
233 scan_interval is documented as the cadence between window *starts*.
234 The scheduler advances entries from the tick's ``now`` (when the
235 window starts) so the effective period is exactly ``scan_interval``;
236 advancing from ``window_end`` instead would make the effective
237 period ``scan_interval + scan_duration``.
238 """
239 manager = get_manager()
240 sched = manager._auto_scheduler
241 loop = asyncio.get_running_loop()
242 address = "11:22:33:44:55:77"
243 cancel = manager.async_register_active_scan(
244 address, scan_interval=120.0, scan_duration=15.0
245 )
246 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
247 register_cancel = manager.async_register_scanner(scanner)
248 try:
249 _inject(scanner, address)
250 entries = sched._schedule._due_at[address]
251 request = next(iter(entries))
252 entries[request] = loop.time() - 1.0
253 before_tick = loop.time()
254 await _run_worker_tick(sched, scanner.source)
255 # entries[request] should be the tick's now + scan_interval ==
256 # roughly before_tick + 120. Definitely NOT before_tick + 135
257 # (which is what "scan_interval after window ends" would give).
258 assert entries[request] == pytest.approx(before_tick + 120.0, abs=0.1)
259 assert entries[request] < before_tick + 130.0
260 finally:
261 cancel()
262 register_cancel()
263
264
265 @pytest.mark.asyncio
266 async def test_worker_tick_coalesces_near_future_due_entries() -> None:
267 """Staggered registrations sync to one window instead of back-to-back flips."""
268 manager = get_manager()
269 sched = manager._auto_scheduler
270 loop = asyncio.get_running_loop()
271 addr_a = "11:22:33:44:55:01"
272 addr_b = "11:22:33:44:55:02"
273 cancel_a = manager.async_register_active_scan(
274 addr_a, scan_interval=300.0, scan_duration=10.0
275 )
276 cancel_b = manager.async_register_active_scan(
277 addr_b, scan_interval=300.0, scan_duration=10.0
278 )
279 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
280 register_cancel = manager.async_register_scanner(scanner)
281 try:
282 _inject(scanner, addr_a)
283 _inject(scanner, addr_b)
284 # A is due now; B is due 10s from now (within the lookahead).
285 # One tick should serve both.
286 now = loop.time()
287 entries_a = sched._schedule._due_at[addr_a]
288 entries_b = sched._schedule._due_at[addr_b]
289 for req in entries_a:
290 entries_a[req] = now - 1.0
291 for req in entries_b:
292 entries_b[req] = now + 10.0
293 await _run_worker_tick(sched, scanner.source)
294 # One window covers both — not two back-to-back.
295 assert scanner.active_window_calls == [10.0]
296 # Both advanced from now (~now + 300), so they coalesce again
297 # next tick rather than staying 10s apart forever.
298 post_tick_now = loop.time()
299 a_next = next(iter(entries_a.values()))
300 b_next = next(iter(entries_b.values()))
301 assert a_next == pytest.approx(post_tick_now + 300.0, abs=1.0)
302 assert b_next == pytest.approx(post_tick_now + 300.0, abs=1.0)
303 assert abs(a_next - b_next) < 0.5
304 finally:
305 cancel_a()
306 cancel_b()
307 register_cancel()
308
309
310 @pytest.mark.asyncio
311 async def test_worker_tick_does_not_fire_when_only_soon_due_no_immediate() -> None:
312 """Soon-due entries alone do not trigger an early tick."""
313 manager = get_manager()
314 sched = manager._auto_scheduler
315 loop = asyncio.get_running_loop()
316 address = "11:22:33:44:55:66"
317 cancel = manager.async_register_active_scan(
318 address, scan_interval=300.0, scan_duration=10.0
319 )
320 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
321 register_cancel = manager.async_register_scanner(scanner)
322 try:
323 _inject(scanner, address)
324 entries = sched._schedule._due_at[address]
325 # Set next_due 5s in the future — within the lookahead but
326 # not immediately due.
327 for req in entries:
328 entries[req] = loop.time() + 5.0
329 await _run_worker_tick(sched, scanner.source)
330 assert scanner.active_window_calls == []
331 finally:
332 cancel()
333 register_cancel()
334
335
336 @pytest.mark.asyncio
337 async def test_worker_tick_coalesces_near_max_window_boundary() -> None:
338 """A 30s window pulls in a device due at now+25; lookahead > max window."""
339 manager = get_manager()
340 sched = manager._auto_scheduler
341 loop = asyncio.get_running_loop()
342 addr_a = "11:22:33:44:55:01"
343 addr_b = "11:22:33:44:55:02"
344 cancel_a = manager.async_register_active_scan(
345 addr_a, scan_interval=300.0, scan_duration=30.0
346 )
347 cancel_b = manager.async_register_active_scan(
348 addr_b, scan_interval=300.0, scan_duration=30.0
349 )
350 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
351 register_cancel = manager.async_register_scanner(scanner)
352 try:
353 _inject(scanner, addr_a)
354 _inject(scanner, addr_b)
355 now = loop.time()
356 entries_a = sched._schedule._due_at[addr_a]
357 entries_b = sched._schedule._due_at[addr_b]
358 for req in entries_a:
359 entries_a[req] = now - 1.0
360 for req in entries_b:
361 entries_b[req] = now + 25.0
362 await _run_worker_tick(sched, scanner.source)
363 # One 30s window covers both.
364 assert scanner.active_window_calls == [30.0]
365 finally:
366 cancel_a()
367 cancel_b()
368 register_cancel()
369
370
371 @pytest.mark.asyncio
372 async def test_worker_tick_fallback_dispatch_rides_soon_due_entries() -> None:
373 """Soon-due entries coalesce into the connecting-fallback dispatch."""
374 manager = get_manager()
375 sched = manager._auto_scheduler
376 loop = asyncio.get_running_loop()
377 addr_a = "11:22:33:44:55:01"
378 addr_b = "11:22:33:44:55:02"
379 cancel_a = manager.async_register_active_scan(
380 addr_a, scan_interval=300.0, scan_duration=10.0
381 )
382 cancel_b = manager.async_register_active_scan(
383 addr_b, scan_interval=300.0, scan_duration=10.0
384 )
385 owner = _DiscoverableAutoScanner("AA:00:00:00:01:01", BluetoothScanningMode.AUTO)
386 fallback = _DiscoverableAutoScanner("AA:00:00:00:01:02", BluetoothScanningMode.AUTO)
387 c_owner = manager.async_register_scanner(owner)
388 c_fallback = manager.async_register_scanner(fallback)
389 try:
390 _inject_with_rssi(owner, addr_a, rssi=-50)
391 _inject_with_rssi(owner, addr_b, rssi=-50)
392 fallback.add_discovered(addr_a, rssi=-70)
393 fallback.add_discovered(addr_b, rssi=-70)
394 owner._add_connecting(addr_a)
395 now = loop.time()
396 entries_a = sched._schedule._due_at[addr_a]
397 entries_b = sched._schedule._due_at[addr_b]
398 for req in entries_a:
399 entries_a[req] = now - 1.0
400 for req in entries_b:
401 entries_b[req] = now + 10.0
402 await _run_worker_tick(sched, owner.source)
403 # Owner is mid-connect; fallback gets exactly one coalesced
404 # call covering both addresses (both scan_duration=10).
405 assert owner.active_window_calls == []
406 assert fallback.active_window_calls == [10.0]
407 # Both addresses advanced by their scan_interval — soon-due
408 # rode the fallback dispatch instead of firing separately.
409 post_tick_now = loop.time()
410 a_new_due = next(iter(entries_a.values()))
411 b_new_due = next(iter(entries_b.values()))
412 assert a_new_due == pytest.approx(post_tick_now + 300.0, abs=1.0)
413 assert b_new_due == pytest.approx(post_tick_now + 300.0, abs=1.0)
414 finally:
415 owner._finished_connecting(addr_a, connected=False)
416 cancel_a()
417 cancel_b()
418 c_owner()
419 c_fallback()
420
421
422 @pytest.mark.asyncio
423 async def test_worker_tick_sweep_alone_pulls_in_soon_due_entries() -> None:
424 """A sweep-only tick pulls in soon-due entries so they don't fire after."""
425 manager = get_manager()
426 sched = manager._auto_scheduler
427 loop = asyncio.get_running_loop()
428 address = "11:22:33:44:55:66"
429 cancel = manager.async_register_active_scan(
430 address, scan_interval=300.0, scan_duration=10.0
431 )
432 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
433 register_cancel = manager.async_register_scanner(scanner)
434 try:
435 _inject(scanner, address)
436 worker = sched._workers[scanner.source]
437 # Make the sweep due; per-device entry is soon-due but not
438 # immediate.
439 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
440 entries = sched._schedule._due_at[address]
441 soon_due_at = loop.time() + 5.0
442 for req in entries:
443 entries[req] = soon_due_at
444 await _run_worker_tick(sched, scanner.source)
445 # Sweep fired; the soon-due entry was advanced so it does
446 # not trigger a back-to-back flip after the sweep ends.
447 assert len(scanner.active_window_calls) == 1
448 post_tick_now = loop.time()
449 new_due = next(iter(entries.values()))
450 assert new_due > soon_due_at
451 assert new_due == pytest.approx(post_tick_now + 300.0, abs=1.0)
452 finally:
453 cancel()
454 register_cancel()
455
456
457 @pytest.mark.asyncio
458 async def test_worker_tick_coalesces_overlapping_requests() -> None:
459 """Multiple requests for the same address coalesce on max scan_duration."""
460 manager = get_manager()
461 sched = manager._auto_scheduler
462 loop = asyncio.get_running_loop()
463 address = "11:22:33:44:55:66"
464 cancel1 = manager.async_register_active_scan(
465 address, scan_interval=120.0, scan_duration=6.0
466 )
467 cancel2 = manager.async_register_active_scan(
468 address, scan_interval=120.0, scan_duration=10.0
469 )
470 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
471 register_cancel = manager.async_register_scanner(scanner)
472 try:
473 _inject(scanner, address)
474 entries = sched._schedule._due_at[address]
475 for req in list(entries):
476 entries[req] = loop.time() - 1.0
477 await _run_worker_tick(sched, scanner.source)
478 assert scanner.active_window_calls == [10.0]
479 finally:
480 cancel1()
481 cancel2()
482 register_cancel()
483
484
485 @pytest.mark.asyncio
486 async def test_multiple_requests_same_address_track_independent_intervals() -> None:
487 """Two registrations for the same address fire on their own cadences."""
488 manager = get_manager()
489 sched = manager._auto_scheduler
490 loop = asyncio.get_running_loop()
491 address = "11:22:33:44:55:66"
492 cancel_fast = manager.async_register_active_scan(
493 address, scan_interval=60.0, scan_duration=5.0
494 )
495 cancel_slow = manager.async_register_active_scan(
496 address, scan_interval=300.0, scan_duration=7.0
497 )
498 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
499 register_cancel = manager.async_register_scanner(scanner)
500 try:
501 _inject(scanner, address)
502 entries = sched._schedule._due_at[address]
503 assert len(entries) == 2
504 fast, slow = sorted(entries, key=lambda r: r.scan_interval)
505 entries[fast] = loop.time() - 1.0
506 entries[slow] = loop.time() + 200.0
507 await _run_worker_tick(sched, scanner.source)
508 assert scanner.active_window_calls == [5.0]
509 assert entries[fast] > loop.time()
510 assert entries[slow] > loop.time() + 100
511 entries[fast] = loop.time() - 1.0
512 entries[slow] = loop.time() - 1.0
513 await _run_worker_tick(sched, scanner.source)
514 assert scanner.active_window_calls == [5.0, 7.0]
515 finally:
516 cancel_fast()
517 cancel_slow()
518 register_cancel()
519
520
521 @pytest.mark.asyncio
522 async def test_no_worker_for_non_auto_scanner() -> None:
523 """ACTIVE / PASSIVE scanners don't get a worker; their windows are never fired."""
524 manager = get_manager()
525 sched = manager._auto_scheduler
526 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.ACTIVE)
527 register_cancel = manager.async_register_scanner(scanner)
528 try:
529 assert scanner.source not in sched._workers
530 finally:
531 register_cancel()
532
533
534 @pytest.mark.asyncio
535 async def test_global_sweep_runs_on_auto_scanner() -> None:
536 """The sweep fires async_request_active_window with SWEEP_DURATION."""
537 manager = get_manager()
538 sched = manager._auto_scheduler
539 loop = asyncio.get_running_loop()
540 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
541 register_cancel = manager.async_register_scanner(scanner)
542 try:
543 worker = sched._workers[scanner.source]
544 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
545 await _run_worker_tick(sched, scanner.source)
546 assert scanner.active_window_calls == [AUTO_REDISCOVERY_SWEEP_DURATION]
547 assert worker._sweep_last_completed > loop.time() - 1.0
548 finally:
549 register_cancel()
550
551
552 @pytest.mark.asyncio
553 async def test_first_sweeps_stagger_across_scanners() -> None:
554 """Concurrently-registered scanners get offset first-sweep times."""
555 manager = get_manager()
556 sched = manager._auto_scheduler
557 loop = asyncio.get_running_loop()
558 s1 = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
559 s2 = _RecordingAutoScanner("AA:BB:CC:DD:EE:11", BluetoothScanningMode.AUTO)
560 s3 = _RecordingAutoScanner("AA:BB:CC:DD:EE:22", BluetoothScanningMode.AUTO)
561 c1 = manager.async_register_scanner(s1)
562 c2 = manager.async_register_scanner(s2)
563 c3 = manager.async_register_scanner(s3)
564 try:
565 now = loop.time()
566 sweep_1 = (
567 sched._workers[s1.source]._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
568 )
569 sweep_2 = (
570 sched._workers[s2.source]._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
571 )
572 sweep_3 = (
573 sched._workers[s3.source]._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
574 )
575 # Each subsequent worker's first sweep is at least one
576 # sweep-duration later than the previous one's. The delta is
577 # `SWEEP_DURATION + (loop.time() drift between spawn calls)`,
578 # so assert the floor rather than equality with a tight
579 # tolerance — CI registrations can take >10ms between
580 # _spawn_worker calls and would otherwise flake.
581 assert sweep_2 - sweep_1 >= AUTO_REDISCOVERY_SWEEP_DURATION
582 assert sweep_3 - sweep_2 >= AUTO_REDISCOVERY_SWEEP_DURATION
583 # And the drift component stays small — well under a second.
584 assert sweep_2 - sweep_1 < AUTO_REDISCOVERY_SWEEP_DURATION + 1.0
585 assert sweep_3 - sweep_2 < AUTO_REDISCOVERY_SWEEP_DURATION + 1.0
586 # Roughly the configured initial delay from now.
587 assert sweep_1 - now == pytest.approx(AUTO_INITIAL_SWEEP_DELAY, abs=1.0)
588 finally:
589 c1()
590 c2()
591 c3()
592
593
594 @pytest.mark.asyncio
595 async def test_first_sweep_stagger_wraps_past_window_size() -> None:
596 """
597 Past AUTO_INITIAL_SWEEP_DELAY/SWEEP_DURATION scanners, offsets wrap.
598
599 With the modulo cap on the spawn offset, the Nth scanner where
600 N == AUTO_INITIAL_SWEEP_DELAY/AUTO_REDISCOVERY_SWEEP_DURATION
601 wraps back to offset 0. This locks in the contract that the
602 stagger does not grow unboundedly with worker count.
603 """
604 manager = get_manager()
605 sched = manager._auto_scheduler
606 wrap_at = int(AUTO_INITIAL_SWEEP_DELAY // AUTO_REDISCOVERY_SWEEP_DURATION)
607 n = wrap_at + 1 # one past the wrap
608 cancels = []
609 try:
610 for i in range(n):
611 s = _RecordingAutoScanner(
612 f"AA:BB:CC:00:00:{i:02x}", BluetoothScanningMode.AUTO
613 )
614 cancels.append(manager.async_register_scanner(s))
615 # The Nth scanner's first sweep is wrap_at scanners' worth of
616 # offset modulo AUTO_INITIAL_SWEEP_DELAY -> back to 0; the
617 # first scanner was also at offset 0, so their next-sweep times
618 # match within a small slack for loop.time() advancing.
619 workers = list(sched._workers.values())
620 first_sweep_a = workers[0]._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
621 first_sweep_wrap = (
622 workers[wrap_at]._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
623 )
624 assert abs(first_sweep_wrap - first_sweep_a) < 1.0
625 finally:
626 for c in cancels:
627 c()
628
629
630 @pytest.mark.asyncio
631 async def test_active_scan_registered_before_auto_scanner_wakes_on_register() -> None:
632 """
633 A request registered before any AUTO scanner exists wakes the right one.
634
635 Sequence: async_register_active_scan (request enters
636 _requests_by_address; no worker exists yet for the device).
637 Later, an AUTO scanner is registered and starts seeing the device.
638 The first advertisement on that scanner must wake its worker so
639 the entry in _due_at is acted upon.
640 """
641 manager = get_manager()
642 sched = manager._auto_scheduler
643 address = "11:22:33:44:55:88"
644 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
645 # Sanity: request is recorded; no worker yet for any source.
646 assert address in sched._requests_by_address
647 try:
648 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:99", BluetoothScanningMode.AUTO)
649 register_cancel = manager.async_register_scanner(scanner)
650 try:
651 worker = sched._workers[scanner.source]
652 worker._wake.clear()
653 _inject(scanner, address)
654 assert worker._wake.is_set()
655 # The address now has a tracked entry on this scanner.
656 assert address in sched._schedule._due_at
657 finally:
658 register_cancel()
659 finally:
660 cancel()
661
662
663 @pytest.mark.asyncio
664 async def test_remove_request_clears_tracking() -> None:
665 """Cancelling a registration removes its per-(address, request) entries."""
666 manager = get_manager()
667 sched = manager._auto_scheduler
668 address = "11:22:33:44:55:66"
669 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
670 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
671 register_cancel = manager.async_register_scanner(scanner)
672 try:
673 _inject(scanner, address)
674 assert address in sched._schedule._due_at
675 cancel()
676 assert address not in sched._schedule._due_at
677 assert sched._requests_by_address == {}
678 finally:
679 register_cancel()
680
681
682 @pytest.mark.asyncio
683 async def test_failed_sweep_advances_sweep_last_completed() -> None:
684 """A False return on a sweep advances the worker's sweep clock."""
685 manager = get_manager()
686 sched = manager._auto_scheduler
687 loop = asyncio.get_running_loop()
688 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
689 scanner._return_value = False
690 register_cancel = manager.async_register_scanner(scanner)
691 try:
692 worker = sched._workers[scanner.source]
693 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
694 before = worker._sweep_last_completed
695 await _run_worker_tick(sched, scanner.source)
696 assert scanner.active_window_calls == [AUTO_REDISCOVERY_SWEEP_DURATION]
697 # Even on False, the worker's sweep clock advanced so the next
698 # sweep is one full interval out instead of immediate.
699 assert worker._sweep_last_completed > before
700 finally:
701 register_cancel()
702
703
704 @pytest.mark.asyncio
705 async def test_stop_cancels_worker_tasks() -> None:
706 """Scheduler.stop cancels every worker task."""
707 manager = get_manager()
708 sched = manager._auto_scheduler
709 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
710 register_cancel = manager.async_register_scanner(scanner)
711 try:
712 worker = sched._workers[scanner.source]
713 task = worker._task
714 assert task is not None
715 sched.stop()
716 await asyncio.sleep(0)
717 assert task.cancelled() or task.done()
718 assert sched._workers == {}
719 finally:
720 register_cancel()
721
722
723 @pytest.mark.asyncio
724 async def test_dispatch_drops_tracking_for_unseen_address() -> None:
725 """An address whose history aged out is pruned on the next worker tick."""
726 manager = get_manager()
727 sched = manager._auto_scheduler
728 loop = asyncio.get_running_loop()
729 address = "AA:BB:CC:DD:EE:FF"
730 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
731 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
732 register_cancel = manager.async_register_scanner(scanner)
733 try:
734 _inject(scanner, address)
735 request = next(iter(sched._schedule._due_at[address]))
736 sched._schedule._due_at[address][request] = loop.time() - 1.0
737 # Simulate the manager's history aging out under the worker's
738 # feet — the orphan-prune branch should clean both _due_at and
739 # _owner_by_address.
740 manager._all_history.pop(address, None)
741 manager._connectable_history.pop(address, None)
742 await _run_worker_tick(sched, scanner.source)
743 assert address not in sched._schedule._due_at
744 assert address not in sched._schedule._owner_by_address
745 assert address not in sched._workers[scanner.source]._owned_due_at
746 finally:
747 cancel()
748 register_cancel()
749
750
751 @pytest.mark.asyncio
752 async def test_first_sweep_is_delayed_after_scanner_registers() -> None:
753 """A newly registered AUTO scanner's first sweep is AUTO_INITIAL_SWEEP_DELAY out."""
754 manager = get_manager()
755 sched = manager._auto_scheduler
756 loop = asyncio.get_running_loop()
757 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
758 register_cancel = manager.async_register_scanner(scanner)
759 try:
760 worker = sched._workers[scanner.source]
761 first_sweep_at = worker._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
762 now = loop.time()
763 assert (
764 AUTO_INITIAL_SWEEP_DELAY - 1.0
765 <= first_sweep_at - now
766 <= AUTO_INITIAL_SWEEP_DELAY + 1.0
767 )
768 finally:
769 register_cancel()
770
771
772 @pytest.mark.asyncio
773 async def test_initial_sweep_fires_4_minutes_after_scanner_registers() -> None:
774 """
775 The initial sweep is suppressed for ~4 minutes after registration.
776
777 Literal seconds are used so this test pins the contract that
778 AUTO_INITIAL_SWEEP_DELAY stays at 4 minutes; the symbolic
779 relationship between the worker's scheduled time and the
780 constant is covered by
781 ``test_first_sweep_is_delayed_after_scanner_registers``.
782
783 Freezegun patches ``time.monotonic`` which backs
784 ``loop.time()``, so the worker's ``_tick`` sees the advanced
785 clock. The background ``_run`` task is cancelled up-front so its
786 own ``wait_for`` timeout (also driven by frozen monotonic) does
787 not race the explicit ticks below.
788 """
789 manager = get_manager()
790 sched = manager._auto_scheduler
791 four_minutes = 4 * 60.0
792 with freeze_time() as frozen:
793 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
794 register_cancel = manager.async_register_scanner(scanner)
795 worker = sched._workers[scanner.source]
796 worker.stop()
797 await asyncio.sleep(0)
798 try:
799 # 1s before the 4-minute mark; no window should fire.
800 frozen.tick(four_minutes - 1.0)
801 await worker._tick()
802 assert scanner.active_window_calls == []
803 # Crossing the 4-minute mark; the sweep fires with SWEEP_DURATION.
804 frozen.tick(2.0)
805 await worker._tick()
806 assert scanner.active_window_calls == [AUTO_REDISCOVERY_SWEEP_DURATION]
807 finally:
808 register_cancel()
809
810
811 @pytest.mark.asyncio
812 async def test_remove_scanner_stops_its_worker() -> None:
813 """Unregistering a scanner cancels and drops its worker."""
814 manager = get_manager()
815 sched = manager._auto_scheduler
816 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
817 cancel = manager.async_register_scanner(scanner)
818 assert scanner.source in sched._workers
819 worker = sched._workers[scanner.source]
820 task = worker._task
821 cancel()
822 await asyncio.sleep(0)
823 assert scanner.source not in sched._workers
824 assert task is not None
825 assert task.cancelled() or task.done()
826
827
828 @pytest.mark.asyncio
829 async def test_remove_scanner_prunes_owned_due_at_entries() -> None:
830 """
831 _due_at entries owned by the leaving scanner are pruned at remove.
832
833 Without the prune, those entries would sit pinned until the
834 device either turns up on another scanner (history flips) or
835 expires from _all_history.
836 """
837 manager = get_manager()
838 sched = manager._auto_scheduler
839 address_owned = "AA:00:00:00:00:10"
840 address_foreign = "AA:00:00:00:00:11"
841 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
842 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
843 c_a = manager.async_register_scanner(s_a)
844 c_b = manager.async_register_scanner(s_b)
845 cancel_owned = manager.async_register_active_scan(
846 address_owned, scan_interval=60.0, scan_duration=5.0
847 )
848 cancel_foreign = manager.async_register_active_scan(
849 address_foreign, scan_interval=60.0, scan_duration=5.0
850 )
851 try:
852 _inject(s_a, address_owned)
853 _inject(s_b, address_foreign)
854 assert address_owned in sched._schedule._due_at
855 assert address_foreign in sched._schedule._due_at
856 # Remove s_a. The owned entry must be pruned; the foreign one
857 # (owned by s_b) must remain.
858 c_a()
859 await asyncio.sleep(0)
860 assert address_owned not in sched._schedule._due_at
861 assert address_foreign in sched._schedule._due_at
862 finally:
863 cancel_owned()
864 cancel_foreign()
865 c_b()
866
867
868 @pytest.mark.asyncio
869 async def test_add_scanner_before_start_defers_worker() -> None:
870 """A scanner registered before start() gets its worker on start()."""
871 manager = get_manager()
872 sched = manager._auto_scheduler
873 loop = sched._loop
874 assert loop is not None
875 sched._loop = None
876 sched._running = False
877 try:
878 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
879 sched.add_scanner(scanner)
880 assert scanner.source not in sched._workers
881 manager._sources[scanner.source] = scanner
882 sched.start(loop)
883 assert scanner.source in sched._workers
884 sched._workers[scanner.source].stop()
885 finally:
886 manager._sources.pop("AA:BB:CC:DD:EE:00", None)
887
888
889 @pytest.mark.asyncio
890 async def test_stop_is_safe_when_already_idle() -> None:
891 """Calling stop() twice in a row is fully idempotent."""
892 manager = get_manager()
893 sched = manager._auto_scheduler
894 sched.stop()
895 sched.stop()
896 assert sched._workers == {}
897
898
899 @pytest.mark.asyncio
900 async def test_stop_clears_loop_so_post_stop_add_request_is_record_only() -> None:
901 """
902 After stop(), add_request and on_advertisement skip _due_at.
903
904 Without nulling _loop, post-stop add_request would seed _due_at
905 with timestamps from the cancelled loop and try to wake a worker
906 that no longer exists. on_advertisement is similar. Both must
907 fall back to the record-only / no-op path once stop() runs.
908 """
909 manager = get_manager()
910 sched = manager._auto_scheduler
911 address = "AA:BB:CC:DD:EE:90"
912 scanner = _RecordingAutoScanner("AA:00:00:00:00:33", BluetoothScanningMode.AUTO)
913 register_cancel = manager.async_register_scanner(scanner)
914 try:
915 _inject(scanner, address) # seed history
916 sched.stop()
917 assert sched._loop is None
918 # add_request after stop: still tracked in _requests_by_address
919 # but no _due_at seed (loop is None).
920 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
921 try:
922 assert address in sched._requests_by_address
923 assert address not in sched._schedule._due_at
924 # on_advertisement after stop is a no-op on _due_at too.
925 _inject(scanner, address)
926 assert address not in sched._schedule._due_at
927 finally:
928 cancel()
929 finally:
930 register_cancel()
931 # Restore the scheduler so the conftest teardown isn't surprised
932 # by a None loop.
933 sched.start(asyncio.get_running_loop())
934
935
936 @pytest.mark.asyncio
937 async def test_duration_clamped_to_bounds() -> None:
938 """_coalesce_duration clamps the requested duration to the configured range."""
939 sched = get_manager()._auto_scheduler
940
941 def _req(duration: float) -> ActiveScanRequest:
942 return ActiveScanRequest("AA", 60.0, duration)
943
944 assert sched._coalesce_duration([_req(0.01)]) == AUTO_WINDOW_MIN_DURATION
945 assert sched._coalesce_duration([_req(1000.0)]) == AUTO_WINDOW_MAX_DURATION
946 assert sched._coalesce_duration([_req(7.5)]) == 7.5
947 assert sched._coalesce_duration([_req(0.01), _req(7.5)]) == 7.5
948 assert (
949 sched._coalesce_duration([_req(7.5), _req(1000.0)]) == AUTO_WINDOW_MAX_DURATION
950 )
951 # Empty list falls back to the configured minimum.
952 assert sched._coalesce_duration([]) == AUTO_WINDOW_MIN_DURATION
953
954
955 @pytest.mark.asyncio
956 async def test_on_advertisement_early_returns_with_no_requests() -> None:
957 """Hot path is a no-op when no active-scan request is registered."""
958 manager = get_manager()
959 sched = manager._auto_scheduler
960 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
961 register_cancel = manager.async_register_scanner(scanner)
962 try:
963 _inject(scanner, "11:22:33:44:55:66")
964 assert sched._schedule._due_at == {}
965 assert sched._requests_by_address == {}
966 finally:
967 register_cancel()
968
969
970 @pytest.mark.asyncio
971 async def test_on_advertisement_re_bootstraps_pruned_tracking() -> None:
972 """If a tracking entry was pruned, the next ad re-creates it and wakes."""
973 manager = get_manager()
974 sched = manager._auto_scheduler
975 address = "11:22:33:44:55:66"
976 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
977 register_cancel = manager.async_register_scanner(scanner)
978 cancel = manager.async_register_active_scan(address, scan_interval=120.0)
979 try:
980 worker = sched._workers[scanner.source]
981 # No advertisement has been seen yet, so add_request skipped
982 # the _due_at seed (the prune-on-no-history path). Simulate the
983 # "pruned" state by ensuring it's not there.
984 sched._schedule._due_at.pop(address, None)
985 worker._wake.clear()
986 _inject(scanner, address)
987 assert address in sched._schedule._due_at
988 assert worker._wake.is_set()
989 finally:
990 cancel()
991 register_cancel()
992
993
994 @pytest.mark.asyncio
995 async def test_register_active_scan_validates_inputs() -> None:
996 """scan_interval / scan_duration below the configured minimums raise."""
997 manager = get_manager()
998 # scan_interval below 60s.
999 with pytest.raises(ValueError, match="scan_interval must"):
1000 manager.async_register_active_scan("AA:BB:CC:DD:EE:00", scan_interval=0)
1001 with pytest.raises(ValueError, match="scan_interval must"):
1002 manager.async_register_active_scan("AA:BB:CC:DD:EE:00", scan_interval=30.0)
1003 # scan_duration below 5s.
1004 with pytest.raises(ValueError, match="scan_duration must"):
1005 manager.async_register_active_scan(
1006 "AA:BB:CC:DD:EE:00", scan_interval=60.0, scan_duration=-0.5
1007 )
1008 with pytest.raises(ValueError, match="scan_duration must"):
1009 manager.async_register_active_scan(
1010 "AA:BB:CC:DD:EE:00", scan_interval=60.0, scan_duration=4.5
1011 )
1012 # Empty address.
1013 with pytest.raises(ValueError, match="address must be a non-empty string"):
1014 manager.async_register_active_scan("", scan_interval=60.0)
1015 # Non-finite values must be rejected: NaN compared to anything
1016 # returns False, so without the explicit isfinite() check a NaN
1017 # would slip past the lower-bound validators.
1018 for bad in (math.nan, math.inf, -math.inf):
1019 with pytest.raises(ValueError, match="scan_interval must be a finite number"):
1020 manager.async_register_active_scan("AA:BB:CC:DD:EE:00", scan_interval=bad)
1021 with pytest.raises(ValueError, match="scan_duration must be a finite number"):
1022 manager.async_register_active_scan(
1023 "AA:BB:CC:DD:EE:00", scan_interval=60.0, scan_duration=bad
1024 )
1025
1026
1027 @pytest.mark.asyncio
1028 async def test_register_active_scan_applies_defaults() -> None:
1029 """Omitting scan_interval/scan_duration uses the configured defaults."""
1030 manager = get_manager()
1031 sched = manager._auto_scheduler
1032 address = "AA:BB:CC:DD:EE:42"
1033 cancel = manager.async_register_active_scan(address)
1034 try:
1035 request = next(iter(sched._requests_by_address[address]))
1036 assert request.scan_interval == DEFAULT_ACTIVE_SCAN_INTERVAL
1037 assert request.scan_duration == DEFAULT_ACTIVE_SCAN_DURATION
1038 finally:
1039 cancel()
1040
1041
1042 @pytest.mark.asyncio
1043 async def test_register_active_scan_uuid_passes_through_unchanged() -> None:
1044 """
1045 MacOS CoreBluetooth UUIDs are not uppercased.
1046
1047 BlueZ / proxy addresses are colon-form MACs and get normalized
1048 to upper-case; UUIDs (no colons) must pass through unchanged
1049 because CoreBluetooth preserves case on its source addresses.
1050 """
1051 manager = get_manager()
1052 sched = manager._auto_scheduler
1053 uuid = "abcd1234-5678-90ab-cdef-1234567890ab"
1054 cancel = manager.async_register_active_scan(uuid, scan_interval=60.0)
1055 try:
1056 assert uuid in sched._requests_by_address
1057 assert uuid.upper() not in sched._requests_by_address
1058 request = next(iter(sched._requests_by_address[uuid]))
1059 assert request.address == uuid
1060 finally:
1061 cancel()
1062
1063
1064 @pytest.mark.asyncio
1065 async def test_register_active_scan_normalizes_address_case() -> None:
1066 """
1067 Lowercase addresses get normalized to the upper-case form.
1068
1069 Matches the upper-case form BlueZ / bleak use for advertisement
1070 source addresses so on_advertisement's dict lookup finds the
1071 request regardless of caller case.
1072 """
1073 manager = get_manager()
1074 sched = manager._auto_scheduler
1075 upper = "AA:BB:CC:DD:EE:55"
1076 cancel = manager.async_register_active_scan(upper.lower(), scan_interval=60.0)
1077 try:
1078 # Stored under the upper-case form, regardless of caller's case.
1079 assert upper in sched._requests_by_address
1080 assert upper.lower() not in sched._requests_by_address
1081 request = next(iter(sched._requests_by_address[upper]))
1082 assert request.address == upper
1083 finally:
1084 cancel()
1085
1086
1087 @pytest.mark.asyncio
1088 async def test_add_request_without_history_skips_seed() -> None:
1089 """
1090 add_request skips _due_at when no last_service_info exists yet.
1091
1092 on_advertisement bootstraps tracking instead. The previous
1093 behavior seeded unconditionally and let the next worker tick
1094 prune the orphan entry; skipping the seed avoids that churn.
1095 """
1096 manager = get_manager()
1097 sched = manager._auto_scheduler
1098 address = "AA:BB:CC:DD:EE:56"
1099 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1100 register_cancel = manager.async_register_scanner(scanner)
1101 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
1102 try:
1103 # Sanity: history doesn't exist for this address yet.
1104 assert manager.async_last_service_info(address, False) is None
1105 # _due_at was not seeded -> no entry to prune later.
1106 assert address not in sched._schedule._due_at
1107 # But the request IS recorded for on_advertisement to pick up.
1108 assert address in sched._requests_by_address
1109 # First advertisement bootstraps tracking and wakes the
1110 # owner's worker.
1111 worker = sched._workers[scanner.source]
1112 worker._wake.clear()
1113 _inject(scanner, address)
1114 assert address in sched._schedule._due_at
1115 assert worker._wake.is_set()
1116 finally:
1117 cancel()
1118 register_cancel()
1119
1120
1121 @pytest.mark.asyncio
1122 async def test_run_window_swallows_scanner_exception() -> None:
1123 """An exception from async_request_active_window is logged, not re-raised."""
1124 manager = get_manager()
1125 sched = manager._auto_scheduler
1126 loop = asyncio.get_running_loop()
1127
1128 class _FailingScanner(_RecordingAutoScanner):
1129 async def async_request_active_window(self, duration: float) -> bool:
1130 msg = "boom"
1131 raise RuntimeError(msg)
1132
1133 scanner = _FailingScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1134 register_cancel = manager.async_register_scanner(scanner)
1135 try:
1136 worker = sched._workers[scanner.source]
1137 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
1138 await worker._tick()
1139 # The exception was swallowed; sweep state still advanced.
1140 assert worker._sweep_last_completed > loop.time() - 1.0
1141 finally:
1142 register_cancel()
1143
1144
1145 @pytest.mark.asyncio
1146 async def test_repeated_window_failures_log_only_first_traceback(
1147 caplog: pytest.LogCaptureFixture,
1148 ) -> None:
1149 """
1150 Persistently failing scanner gets one exception log then warnings.
1151
1152 Without rate-limiting, a permanently broken scanner would emit a
1153 full traceback every scan_interval (>= 60s). The first failure
1154 still logs the full stack so the root cause is captured; subsequent
1155 failures collapse to a one-line warning to avoid flooding the log.
1156 """
1157 manager = get_manager()
1158 sched = manager._auto_scheduler
1159 loop = asyncio.get_running_loop()
1160
1161 class _FailingScanner(_RecordingAutoScanner):
1162 async def async_request_active_window(self, duration: float) -> bool:
1163 msg = "boom"
1164 raise RuntimeError(msg)
1165
1166 scanner = _FailingScanner("AA:BB:CC:DD:EE:11", BluetoothScanningMode.AUTO)
1167 register_cancel = manager.async_register_scanner(scanner)
1168 try:
1169 worker = sched._workers[scanner.source]
1170 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
1171 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
1172 await worker._tick()
1173 # Trigger a second failure.
1174 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
1175 await worker._tick()
1176 records = [
1177 r for r in caplog.records if "error running active window" in r.message
1178 ]
1179 assert len(records) == 2
1180 # First has exception info (full traceback), second does not.
1181 assert records[0].exc_info is not None
1182 assert records[1].exc_info is None
1183 finally:
1184 register_cancel()
1185
1186
1187 @pytest.mark.asyncio
1188 async def test_tick_sync_phase_exception_is_logged_and_worker_survives(
1189 caplog: pytest.LogCaptureFixture,
1190 ) -> None:
1191 """
1192 Sync-phase failures in _tick are logged; worker survives.
1193
1194 Stubs async_last_service_info to raise so _collect_due_buckets
1195 blows up; the outer except in _tick catches it and logs.
1196 """
1197 manager = get_manager()
1198 sched = manager._auto_scheduler
1199 address = "11:22:33:44:55:91"
1200 cancel = manager.async_register_active_scan(
1201 address, scan_interval=60.0, scan_duration=5.0
1202 )
1203 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:31", BluetoothScanningMode.AUTO)
1204 register_cancel = manager.async_register_scanner(scanner)
1205 try:
1206 _inject(scanner, address)
1207 worker = sched._workers[scanner.source]
1208 original = manager.async_last_service_info
1209
1210 def _boom(_addr: str, _conn: bool) -> None:
1211 msg = "boom in last_service_info"
1212 raise RuntimeError(msg)
1213
1214 manager.async_last_service_info = _boom # type: ignore[assignment,method-assign]
1215 try:
1216 with caplog.at_level(logging.ERROR):
1217 await worker._tick()
1218 assert any(
1219 "unexpected error in auto-window tick" in record.message
1220 for record in caplog.records
1221 )
1222 # Worker is still alive; _window_end was reset.
1223 assert worker._window_end == 0.0
1224 finally:
1225 manager.async_last_service_info = original # type: ignore[method-assign]
1226 finally:
1227 cancel()
1228 register_cancel()
1229
1230
1231 @pytest.mark.asyncio
1232 async def test_mode_switch_unregister_then_register_picks_up_existing_request() -> None:
1233 """
1234 Scheduler survives a HA-style scanner mode switch on the same source.
1235
1236 HA's UI mode-switch path reloads the config entry: the old
1237 scanner is unregistered, a new one with the same source is
1238 registered with the new mode. The scheduler must (1) prune
1239 _due_at entries the leaving scanner owned via remove_scanner,
1240 (2) keep user-registered ActiveScanRequests in
1241 _requests_by_address, (3) spawn a fresh worker for a new AUTO
1242 scanner via add_scanner, and (4) bootstrap _due_at on the first
1243 advertisement from the new scanner.
1244 """
1245 manager = get_manager()
1246 sched = manager._auto_scheduler
1247 address = "11:22:33:44:55:92"
1248 # Register the active-scan need first.
1249 cancel = manager.async_register_active_scan(
1250 address, scan_interval=60.0, scan_duration=5.0
1251 )
1252 # Start in AUTO, see the device, then "switch to ACTIVE".
1253 auto_scanner = _RecordingAutoScanner(
1254 "AA:BB:CC:DD:EE:32", BluetoothScanningMode.AUTO
1255 )
1256 auto_cancel = manager.async_register_scanner(auto_scanner)
1257 try:
1258 _inject(auto_scanner, address)
1259 assert address in sched._schedule._due_at
1260 assert auto_scanner.source in sched._workers
1261 # Mode switch in UI -> unregister AUTO scanner.
1262 auto_cancel()
1263 assert auto_scanner.source not in sched._workers
1264 assert address not in sched._schedule._due_at
1265 # User's registration is preserved across the switch.
1266 assert address in sched._requests_by_address
1267 # Re-register with the SAME source but PASSIVE mode.
1268 passive_scanner = _RecordingAutoScanner(
1269 "AA:BB:CC:DD:EE:32", BluetoothScanningMode.PASSIVE
1270 )
1271 passive_cancel = manager.async_register_scanner(passive_scanner)
1272 try:
1273 # PASSIVE doesn't get a worker.
1274 assert passive_scanner.source not in sched._workers
1275 # Still no _due_at entry (no AUTO scanner owns it).
1276 assert address not in sched._schedule._due_at
1277 passive_cancel()
1278 # Now switch BACK to AUTO with the same source.
1279 new_auto = _RecordingAutoScanner(
1280 "AA:BB:CC:DD:EE:32", BluetoothScanningMode.AUTO
1281 )
1282 new_auto_cancel = manager.async_register_scanner(new_auto)
1283 try:
1284 assert new_auto.source in sched._workers
1285 # First advertisement on the new AUTO scanner bootstraps
1286 # tracking again from the still-registered request.
1287 _inject(new_auto, address)
1288 assert address in sched._schedule._due_at
1289 finally:
1290 new_auto_cancel()
1291 except BaseException:
1292 passive_cancel()
1293 raise
1294 finally:
1295 cancel()
1296
1297
1298 @pytest.mark.asyncio
1299 async def test_start_replays_pre_start_requests_into_due_at() -> None:
1300 """
1301 add_request before start() seeds _due_at at start() if history exists.
1302
1303 Also covers the no-history skip path and the
1304 already-in-existing-entries no-op so the replay loop's branches
1305 are all exercised.
1306 """
1307 manager = get_manager()
1308 sched = manager._auto_scheduler
1309 address_with_history = "11:22:33:44:55:80"
1310 address_no_history = "11:22:33:44:55:81"
1311 # Get history in place for one address only.
1312 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:21", BluetoothScanningMode.AUTO)
1313 register_cancel = manager.async_register_scanner(scanner)
1314 _inject(scanner, address_with_history)
1315 try:
1316 saved_loop = sched._loop
1317 assert saved_loop is not None
1318 sched._loop = None
1319 sched._running = False
1320 try:
1321 # Register TWO requests on the with-history address so
1322 # we can pre-populate _due_at with one of them and prove
1323 # start() (a) leaves the pre-existing entry alone and
1324 # (b) inserts a fresh entry for the other.
1325 cancel_with_a = manager.async_register_active_scan(
1326 address_with_history, scan_interval=60.0, scan_duration=5.0
1327 )
1328 cancel_with_b = manager.async_register_active_scan(
1329 address_with_history, scan_interval=120.0, scan_duration=5.0
1330 )
1331 cancel_without = manager.async_register_active_scan(
1332 address_no_history, scan_interval=60.0, scan_duration=5.0
1333 )
1334 try:
1335 assert address_with_history not in sched._schedule._due_at
1336 requests = list(sched._requests_by_address[address_with_history])
1337 pre_existing, to_be_inserted = requests
1338 # Pre-populate _due_at with one request only. The
1339 # sentinel is well above loop.time() + scan_interval
1340 # so the test is robust against the loop being
1341 # freshly-started (CI) or long-lived; we don't care
1342 # about the absolute value, only that start() leaves
1343 # it alone.
1344 sentinel = saved_loop.time() + 1.0e9
1345 sched._schedule._due_at[address_with_history] = {pre_existing: sentinel}
1346 before_start = saved_loop.time()
1347 sched.start(saved_loop)
1348 seeded = sched._schedule._due_at[address_with_history]
1349 # The pre-existing entry was left alone (covers the
1350 # `request not in existing` False branch).
1351 assert seeded[pre_existing] == sentinel
1352 # The other request got freshly inserted (covers the
1353 # insert line in the replay loop).
1354 assert to_be_inserted in seeded
1355 assert seeded[to_be_inserted] == pytest.approx(
1356 before_start + to_be_inserted.scan_interval, abs=0.1
1357 )
1358 # No-history address: skipped by the
1359 # `last_service_info(...) is None` branch.
1360 assert address_no_history not in sched._schedule._due_at
1361 finally:
1362 cancel_with_a()
1363 cancel_with_b()
1364 cancel_without()
1365 finally:
1366 sched._loop = saved_loop
1367 sched._running = True
1368 finally:
1369 register_cancel()
1370
1371
1372 @pytest.mark.asyncio
1373 async def test_start_is_idempotent_when_already_running() -> None:
1374 """
1375 A second start() call without an intervening stop() is a no-op.
1376
1377 Guards against an accidental double-call binding a different loop
1378 to the same scheduler or re-running the pre-start replay block.
1379 """
1380 manager = get_manager()
1381 sched = manager._auto_scheduler
1382 # The conftest's async_setup already called start(), so _running
1383 # is True. A second start with a different loop must NOT replace
1384 # _loop or re-run anything.
1385 original_loop = sched._loop
1386 bogus_loop = object()
1387 sched.start(bogus_loop) # type: ignore[arg-type]
1388 assert sched._loop is original_loop
1389
1390
1391 @pytest.mark.asyncio
1392 async def test_dispatch_does_not_resurrect_cancelled_request() -> None:
1393 """A request cancelled while the window awaits is not re-added to entries."""
1394 manager = get_manager()
1395 sched = manager._auto_scheduler
1396 loop = asyncio.get_running_loop()
1397 address = "11:22:33:44:55:66"
1398 cancel = manager.async_register_active_scan(
1399 address, scan_interval=60.0, scan_duration=6.0
1400 )
1401
1402 gate = asyncio.Event()
1403
1404 class _CancelDuringWindow(_RecordingAutoScanner):
1405 async def async_request_active_window(self, duration: float) -> bool:
1406 # Mid-window: caller cancels the registration.
1407 cancel()
1408 gate.set()
1409 return True
1410
1411 scanner = _CancelDuringWindow("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1412 register_cancel = manager.async_register_scanner(scanner)
1413 try:
1414 _inject(scanner, address)
1415 entries = sched._schedule._due_at[address]
1416 request = next(iter(entries))
1417 entries[request] = loop.time() - 1.0
1418 await sched._workers[scanner.source]._tick()
1419 await gate.wait()
1420 # remove_request emptied the bucket; the tick must not have
1421 # re-added the cancelled request.
1422 assert address not in sched._schedule._due_at
1423 finally:
1424 register_cancel()
1425
1426
1427 @pytest.mark.asyncio
1428 async def test_dispatch_skips_address_owned_by_other_scanner() -> None:
1429 """An address whose owner is a different scanner is left alone."""
1430 manager = get_manager()
1431 sched = manager._auto_scheduler
1432 loop = asyncio.get_running_loop()
1433 address = "11:22:33:44:55:66"
1434 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
1435 owner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1436 other = _RecordingAutoScanner("AA:BB:CC:DD:EE:11", BluetoothScanningMode.AUTO)
1437 c1 = manager.async_register_scanner(owner)
1438 c2 = manager.async_register_scanner(other)
1439 try:
1440 _inject(owner, address)
1441 entries = sched._schedule._due_at[address]
1442 for req in list(entries):
1443 entries[req] = loop.time() - 1.0
1444 # The "other" scanner runs its tick. The address is owned by
1445 # owner, so other should not fire its window.
1446 await sched._workers[other.source]._tick()
1447 assert other.active_window_calls == []
1448 finally:
1449 cancel()
1450 c1()
1451 c2()
1452
1453
1454 @pytest.mark.asyncio
1455 async def test_next_event_at_returns_current_window_end() -> None:
1456 """While a window is in flight, next event is its end time."""
1457 manager = get_manager()
1458 sched = manager._auto_scheduler
1459 loop = asyncio.get_running_loop()
1460 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1461 register_cancel = manager.async_register_scanner(scanner)
1462 try:
1463 worker = sched._workers[scanner.source]
1464 worker._window_end = loop.time() + 42.0
1465 assert worker._next_event_at(loop.time()) == worker._window_end
1466 finally:
1467 register_cancel()
1468
1469
1470 @pytest.mark.asyncio
1471 async def test_next_event_at_returns_earliest_per_device_need() -> None:
1472 """Per-device entries owned by this scanner influence the next-event time."""
1473 manager = get_manager()
1474 sched = manager._auto_scheduler
1475 loop = asyncio.get_running_loop()
1476 address = "11:22:33:44:55:66"
1477 cancel = manager.async_register_active_scan(address, scan_interval=120.0)
1478 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1479 register_cancel = manager.async_register_scanner(scanner)
1480 try:
1481 _inject(scanner, address)
1482 worker = sched._workers[scanner.source]
1483 # Sweep is far in the future (initial delay window). The earliest
1484 # event for the worker is the per-device next-due.
1485 entries = sched._schedule._due_at[address]
1486 request = next(iter(entries))
1487 per_device_at = loop.time() + 5.0
1488 entries[request] = per_device_at
1489 assert worker._next_event_at(loop.time()) == per_device_at
1490 finally:
1491 cancel()
1492 register_cancel()
1493
1494
1495 @pytest.mark.asyncio
1496 async def test_dispatch_per_device_skips_not_yet_due() -> None:
1497 """Entries with future due times don't fire."""
1498 manager = get_manager()
1499 sched = manager._auto_scheduler
1500 loop = asyncio.get_running_loop()
1501 address = "11:22:33:44:55:66"
1502 cancel = manager.async_register_active_scan(address, scan_interval=120.0)
1503 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1504 register_cancel = manager.async_register_scanner(scanner)
1505 try:
1506 _inject(scanner, address)
1507 # Push the due time far in the future.
1508 entries = sched._schedule._due_at[address]
1509 for request in list(entries):
1510 entries[request] = loop.time() + 1000.0
1511 await sched._workers[scanner.source]._tick()
1512 assert scanner.active_window_calls == []
1513 finally:
1514 cancel()
1515 register_cancel()
1516
1517
1518 @pytest.mark.asyncio
1519 async def test_tick_skips_when_sweep_not_due_and_no_per_device() -> None:
1520 """No-op tick: no per-device work due, sweep not due either."""
1521 manager = get_manager()
1522 sched = manager._auto_scheduler
1523 loop = asyncio.get_running_loop()
1524 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1525 register_cancel = manager.async_register_scanner(scanner)
1526 try:
1527 worker = sched._workers[scanner.source]
1528 worker._sweep_last_completed = loop.time()
1529 await worker._tick()
1530 assert scanner.active_window_calls == []
1531 finally:
1532 register_cancel()
1533
1534
1535 @pytest.mark.asyncio
1536 async def test_worker_tick_no_op_when_loop_detached() -> None:
1537 """Worker tick exits cleanly if the scheduler's loop is None."""
1538 manager = get_manager()
1539 sched = manager._auto_scheduler
1540 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1541 register_cancel = manager.async_register_scanner(scanner)
1542 try:
1543 worker = sched._workers[scanner.source]
1544 original_loop = sched._loop
1545 sched._loop = None
1546 try:
1547 await worker._tick()
1548 finally:
1549 sched._loop = original_loop
1550 assert scanner.active_window_calls == []
1551 finally:
1552 register_cancel()
1553
1554
1555 @pytest.mark.asyncio
1556 async def test_tick_no_op_when_already_inside_window() -> None:
1557 """A tick that arrives while a window is in flight returns early."""
1558 manager = get_manager()
1559 sched = manager._auto_scheduler
1560 loop = asyncio.get_running_loop()
1561 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1562 register_cancel = manager.async_register_scanner(scanner)
1563 try:
1564 worker = sched._workers[scanner.source]
1565 # Pretend a window is mid-flight; _tick must defer to that
1566 # window and not start a new one.
1567 worker._window_end = loop.time() + 60.0
1568 await worker._tick()
1569 assert scanner.active_window_calls == []
1570 finally:
1571 register_cancel()
1572
1573
1574 async def _replace_worker_task(worker: object) -> None:
1575 """Cancel the worker's existing task so a fresh _run() can be tested."""
1576 task = worker._task # type: ignore[attr-defined]
1577 if task is not None and not task.done():
1578 task.cancel()
1579 with contextlib.suppress(asyncio.CancelledError):
1580 await task
1581
1582
1583 @pytest.mark.asyncio
1584 async def test_run_exits_when_scheduler_not_running() -> None:
1585 """The worker's _run loop exits cleanly when _running is False after a wake."""
1586 manager = get_manager()
1587 sched = manager._auto_scheduler
1588 loop = asyncio.get_running_loop()
1589 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1590 register_cancel = manager.async_register_scanner(scanner)
1591 try:
1592 worker = sched._workers[scanner.source]
1593 await _replace_worker_task(worker)
1594 # Put the sweep clock far in the past so _next_event_at returns
1595 # a time <= now and the wait_for branch is skipped; the loop
1596 # falls straight through to the "not running" check.
1597 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
1598 sched._running = False
1599 new_task = loop.create_task(worker._run())
1600 await asyncio.wait_for(new_task, timeout=1.0)
1601 assert new_task.done()
1602 assert not new_task.cancelled()
1603 finally:
1604 sched._running = True
1605 register_cancel()
1606
1607
1608 @pytest.mark.asyncio
1609 async def test_run_exits_when_loop_detached() -> None:
1610 """The worker's _run loop exits when scheduler._loop becomes None."""
1611 manager = get_manager()
1612 sched = manager._auto_scheduler
1613 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1614 register_cancel = manager.async_register_scanner(scanner)
1615 try:
1616 worker = sched._workers[scanner.source]
1617 await _replace_worker_task(worker)
1618 original_loop = sched._loop
1619 sched._loop = None
1620 new_task = asyncio.get_running_loop().create_task(worker._run())
1621 await asyncio.wait_for(new_task, timeout=1.0)
1622 assert new_task.done()
1623 assert not new_task.cancelled()
1624 sched._loop = original_loop
1625 finally:
1626 register_cancel()
1627
1628
1629 @pytest.mark.asyncio
1630 async def test_add_request_without_history_does_not_wake() -> None:
1631 """When the address has never been seen, add_request is a pure registry op."""
1632 manager = get_manager()
1633 sched = manager._auto_scheduler
1634 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1635 register_cancel = manager.async_register_scanner(scanner)
1636 try:
1637 worker = sched._workers[scanner.source]
1638 worker._wake.clear()
1639 cancel = manager.async_register_active_scan(
1640 "AA:AA:AA:AA:AA:AA", scan_interval=60.0
1641 )
1642 # No prior advertisement: history is None, so no wake is sent.
1643 assert not worker._wake.is_set()
1644 cancel()
1645 finally:
1646 register_cancel()
1647
1648
1649 @pytest.mark.asyncio
1650 async def test_remove_request_handles_missing_bucket() -> None:
1651 """remove_request tolerates a request whose bucket is already gone."""
1652 manager = get_manager()
1653 sched = manager._auto_scheduler
1654 request = ActiveScanRequest("AA:BB:CC:DD:EE:99", 60.0, 10.0)
1655 # Bucket was never added; remove_request must be a no-op.
1656 sched.remove_request(request)
1657 assert "AA:BB:CC:DD:EE:99" not in sched._requests_by_address
1658 assert "AA:BB:CC:DD:EE:99" not in sched._schedule._due_at
1659
1660
1661 @pytest.mark.asyncio
1662 async def test_on_advertisement_no_match_no_wake() -> None:
1663 """An ad whose address has no registered request doesn't add anything."""
1664 manager = get_manager()
1665 sched = manager._auto_scheduler
1666 cancel = manager.async_register_active_scan("11:22:33:44:55:66", scan_interval=60.0)
1667 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1668 register_cancel = manager.async_register_scanner(scanner)
1669 try:
1670 worker = sched._workers[scanner.source]
1671 worker._wake.clear()
1672 _inject(scanner, "AA:AA:AA:AA:AA:AA")
1673 assert "AA:AA:AA:AA:AA:AA" not in sched._schedule._due_at
1674 assert not worker._wake.is_set()
1675 finally:
1676 cancel()
1677 register_cancel()
1678
1679
1680 @pytest.mark.asyncio
1681 async def test_on_advertisement_wakes_on_every_ad_for_tracked_address() -> None:
1682 """
1683 Every ad on a tracked address wakes the source's worker.
1684
1685 The wake is what makes ownership-flip detection work: when this
1686 scanner becomes the new owner mid-sleep, the wake forces the
1687 worker to re-evaluate _next_event_at and pick up the entry that
1688 is now owned by it.
1689 """
1690 manager = get_manager()
1691 sched = manager._auto_scheduler
1692 address = "11:22:33:44:55:66"
1693 cancel1 = manager.async_register_active_scan(address, scan_interval=60.0)
1694 cancel2 = manager.async_register_active_scan(address, scan_interval=120.0)
1695 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1696 register_cancel = manager.async_register_scanner(scanner)
1697 try:
1698 worker = sched._workers[scanner.source]
1699 _inject(scanner, address)
1700 worker._wake.clear()
1701 _inject(scanner, address)
1702 # Second inject still wakes; the wake is unconditional now so
1703 # ownership flips on an existing entry are seen by the new
1704 # owner.
1705 assert worker._wake.is_set()
1706 finally:
1707 cancel1()
1708 cancel2()
1709 register_cancel()
1710
1711
1712 @pytest.mark.asyncio
1713 async def test_on_advertisement_with_all_requests_already_tracked() -> None:
1714 """on_advertisement still wakes when every request is already in _due_at."""
1715 manager = get_manager()
1716 sched = manager._auto_scheduler
1717 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1718 register_cancel = manager.async_register_scanner(scanner)
1719 address = "11:22:33:44:55:66"
1720 cancel_a = manager.async_register_active_scan(address, scan_interval=60.0)
1721 cancel_b = manager.async_register_active_scan(address, scan_interval=120.0)
1722 try:
1723 # First advertisement seeds + assigns + wakes.
1724 _inject(scanner, address)
1725 worker = sched._workers[scanner.source]
1726 entries_before = dict(sched._schedule._due_at[address])
1727 worker._wake.clear()
1728 # Second advertisement: all requests already tracked; assign
1729 # still wakes for ownership-flip detection.
1730 _inject(scanner, address)
1731 assert worker._wake.is_set()
1732 # Sanity: the entries we put in are untouched.
1733 assert sched._schedule._due_at[address] == entries_before
1734 finally:
1735 cancel_a()
1736 cancel_b()
1737 register_cancel()
1738
1739
1740 @pytest.mark.asyncio
1741 async def test_add_request_with_history_wakes_owning_worker() -> None:
1742 """add_request wakes the worker whose scanner currently sees the address."""
1743 manager = get_manager()
1744 sched = manager._auto_scheduler
1745 address = "11:22:33:44:55:66"
1746 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1747 register_cancel = manager.async_register_scanner(scanner)
1748 try:
1749 # Populate manager._all_history WITHOUT first registering an
1750 # active scan, so the inject doesn't go through on_advertisement's
1751 # wake-on-added path. add_request then sees the history entry
1752 # and assign fires the worker wake itself.
1753 _inject(scanner, address)
1754 worker = sched._workers[scanner.source]
1755 worker._wake.clear()
1756 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
1757 assert worker._wake.is_set()
1758 cancel()
1759 finally:
1760 register_cancel()
1761
1762
1763 @pytest.mark.asyncio
1764 async def test_next_event_at_skips_per_device_later_than_sweep() -> None:
1765 """A per-device next-due later than the sweep cadence does not lower next_at."""
1766 manager = get_manager()
1767 sched = manager._auto_scheduler
1768 loop = asyncio.get_running_loop()
1769 address = "11:22:33:44:55:66"
1770 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
1771 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1772 register_cancel = manager.async_register_scanner(scanner)
1773 try:
1774 _inject(scanner, address)
1775 worker = sched._workers[scanner.source]
1776 sweep_at = worker._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
1777 # Push per-device need past the sweep cadence so the earliest <
1778 # next_at branch is False inside _next_event_at.
1779 for req in list(sched._schedule._due_at[address]):
1780 sched._schedule._due_at[address][req] = sweep_at + 100.0
1781 assert worker._next_event_at(loop.time()) == sweep_at
1782 finally:
1783 cancel()
1784 register_cancel()
1785
1786
1787 @pytest.mark.asyncio
1788 async def test_start_ignores_non_auto_scanner() -> None:
1789 """A non-AUTO scanner already on the manager doesn't get a worker on start."""
1790 manager = get_manager()
1791 sched = manager._auto_scheduler
1792 loop = asyncio.get_running_loop()
1793 auto = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1794 active = _RecordingAutoScanner("AA:BB:CC:DD:EE:11", BluetoothScanningMode.ACTIVE)
1795 c_auto = manager.async_register_scanner(auto)
1796 c_active = manager.async_register_scanner(active)
1797 try:
1798 assert active.source not in sched._workers
1799 # Re-run start() so the False branch (non-AUTO scanner) of the
1800 # `if scanner.requested_mode is AUTO` check inside start() is hit.
1801 # First shut down the worker tasks the existing start() already
1802 # spawned so we don't leak. Also flip _running back to False so
1803 # start()'s idempotency guard lets the re-run through.
1804 for worker in list(sched._workers.values()):
1805 await _replace_worker_task(worker)
1806 sched._workers.clear()
1807 sched._running = False
1808 sched.start(loop)
1809 assert auto.source in sched._workers
1810 assert active.source not in sched._workers
1811 finally:
1812 c_auto()
1813 c_active()
1814
1815
1816 @pytest.mark.asyncio
1817 async def test_coalesce_three_due_uses_max_clamped() -> None:
1818 """Three due requests on one address fire one window using max duration."""
1819 manager = get_manager()
1820 sched = manager._auto_scheduler
1821 loop = asyncio.get_running_loop()
1822 address = "11:22:33:44:55:66"
1823 c1 = manager.async_register_active_scan(
1824 address, scan_interval=60.0, scan_duration=5.0
1825 )
1826 c2 = manager.async_register_active_scan(
1827 address, scan_interval=60.0, scan_duration=7.0
1828 )
1829 c3 = manager.async_register_active_scan(
1830 address, scan_interval=60.0, scan_duration=9.0
1831 )
1832 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1833 register_cancel = manager.async_register_scanner(scanner)
1834 try:
1835 _inject(scanner, address)
1836 entries = sched._schedule._due_at[address]
1837 for req in list(entries):
1838 entries[req] = loop.time() - 1.0
1839 await sched._workers[scanner.source]._tick()
1840 assert scanner.active_window_calls == [9.0]
1841 finally:
1842 c1()
1843 c2()
1844 c3()
1845 register_cancel()
1846
1847
1848 @pytest.mark.asyncio
1849 async def test_coalesce_clamps_oversize_request() -> None:
1850 """A scan_duration above the max is clamped on dispatch."""
1851 manager = get_manager()
1852 sched = manager._auto_scheduler
1853 loop = asyncio.get_running_loop()
1854 address = "11:22:33:44:55:66"
1855 cancel = manager.async_register_active_scan(
1856 address, scan_interval=60.0, scan_duration=AUTO_WINDOW_MAX_DURATION + 50.0
1857 )
1858 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1859 register_cancel = manager.async_register_scanner(scanner)
1860 try:
1861 _inject(scanner, address)
1862 entries = sched._schedule._due_at[address]
1863 for req in list(entries):
1864 entries[req] = loop.time() - 1.0
1865 await sched._workers[scanner.source]._tick()
1866 assert scanner.active_window_calls == [AUTO_WINDOW_MAX_DURATION]
1867 finally:
1868 cancel()
1869 register_cancel()
1870
1871
1872 @pytest.mark.asyncio
1873 async def test_window_honors_35s_request() -> None:
1874 """A 35s scan_duration is dispatched as-is, not clamped down."""
1875 manager = get_manager()
1876 sched = manager._auto_scheduler
1877 loop = asyncio.get_running_loop()
1878 address = "11:22:33:44:55:66"
1879 cancel = manager.async_register_active_scan(
1880 address, scan_interval=60.0, scan_duration=35.0
1881 )
1882 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1883 register_cancel = manager.async_register_scanner(scanner)
1884 try:
1885 _inject(scanner, address)
1886 entries = sched._schedule._due_at[address]
1887 for req in list(entries):
1888 entries[req] = loop.time() - 1.0
1889 await sched._workers[scanner.source]._tick()
1890 assert scanner.active_window_calls == [35.0]
1891 finally:
1892 cancel()
1893 register_cancel()
1894
1895
1896 @pytest.mark.asyncio
1897 async def test_coalesce_only_due_requests_count() -> None:
1898 """Only the requests that are actually due contribute to coalesced duration."""
1899 manager = get_manager()
1900 sched = manager._auto_scheduler
1901 loop = asyncio.get_running_loop()
1902 address = "11:22:33:44:55:66"
1903 c_short = manager.async_register_active_scan(
1904 address, scan_interval=60.0, scan_duration=5.0
1905 )
1906 c_long = manager.async_register_active_scan(
1907 address, scan_interval=300.0, scan_duration=20.0
1908 )
1909 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1910 register_cancel = manager.async_register_scanner(scanner)
1911 try:
1912 _inject(scanner, address)
1913 entries = sched._schedule._due_at[address]
1914 short_req = next(r for r in entries if r.scan_duration == 5.0)
1915 long_req = next(r for r in entries if r.scan_duration == 20.0)
1916 # Only the short request is due; the long one is well in the
1917 # future and must not pull its bigger duration into the window.
1918 entries[short_req] = loop.time() - 1.0
1919 entries[long_req] = loop.time() + 200.0
1920 await sched._workers[scanner.source]._tick()
1921 assert scanner.active_window_calls == [5.0]
1922 finally:
1923 c_short()
1924 c_long()
1925 register_cancel()
1926
1927
1928 @pytest.mark.asyncio
1929 async def test_coalesce_distinct_addresses_share_one_window() -> None:
1930 """Two due addresses on the same scanner share one max-duration window."""
1931 manager = get_manager()
1932 sched = manager._auto_scheduler
1933 loop = asyncio.get_running_loop()
1934 addr_a = "11:22:33:44:55:01"
1935 addr_b = "11:22:33:44:55:02"
1936 c1 = manager.async_register_active_scan(
1937 addr_a, scan_interval=60.0, scan_duration=6.0
1938 )
1939 c2 = manager.async_register_active_scan(
1940 addr_b, scan_interval=60.0, scan_duration=7.0
1941 )
1942 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1943 register_cancel = manager.async_register_scanner(scanner)
1944 try:
1945 _inject(scanner, addr_a)
1946 _inject(scanner, addr_b)
1947 for address in (addr_a, addr_b):
1948 entries = sched._schedule._due_at[address]
1949 for req in list(entries):
1950 entries[req] = loop.time() - 1.0
1951 await sched._workers[scanner.source]._tick()
1952 # A single ACTIVE flip covers both devices; the window length is
1953 # the max of every due request's duration.
1954 assert scanner.active_window_calls == [7.0]
1955 finally:
1956 c1()
1957 c2()
1958 register_cancel()
1959
1960
1961 @pytest.mark.asyncio
1962 async def test_tick_combines_due_sweep_and_per_device_into_one_window() -> None:
1963 """A due sweep + due per-device fold into a single window at max duration."""
1964 manager = get_manager()
1965 sched = manager._auto_scheduler
1966 loop = asyncio.get_running_loop()
1967 address = "11:22:33:44:55:66"
1968 cancel = manager.async_register_active_scan(
1969 address, scan_interval=60.0, scan_duration=6.0
1970 )
1971 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
1972 register_cancel = manager.async_register_scanner(scanner)
1973 try:
1974 _inject(scanner, address)
1975 entries = sched._schedule._due_at[address]
1976 for req in list(entries):
1977 entries[req] = loop.time() - 1.0
1978 worker = sched._workers[scanner.source]
1979 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
1980 await worker._tick()
1981 # The sweep duration (15s) beats the per-device duration (3s)
1982 # so the merged window is sized to the sweep.
1983 assert scanner.active_window_calls == [AUTO_REDISCOVERY_SWEEP_DURATION]
1984 # Sweep clock advanced.
1985 assert worker._sweep_last_completed > loop.time() - 1.0
1986 finally:
1987 cancel()
1988 register_cancel()
1989
1990
1991 @pytest.mark.asyncio
1992 async def test_three_inkbirds_share_one_scan() -> None:
1993 """
1994 Three Inkbirds at the same 5min / 15s cadence share a single window.
1995
1996 Each Inkbird has its own address but all three are owned by the same
1997 scanner and become due at the same time. The worker coalesces every
1998 due request across all addresses into a single 15s active window, so
1999 the radio only stops and restarts once per tick.
2000 """
2001 manager = get_manager()
2002 sched = manager._auto_scheduler
2003 loop = asyncio.get_running_loop()
2004 addresses = ["C0:01:01:11:11:11", "C0:01:01:22:22:22", "C0:01:01:33:33:33"]
2005 cancels = [
2006 manager.async_register_active_scan(
2007 addr, scan_interval=300.0, scan_duration=15.0
2008 )
2009 for addr in addresses
2010 ]
2011 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
2012 register_cancel = manager.async_register_scanner(scanner)
2013 try:
2014 for addr in addresses:
2015 _inject(scanner, addr)
2016 entries = sched._schedule._due_at[addr]
2017 for req in list(entries):
2018 entries[req] = loop.time() - 1.0
2019 await sched._workers[scanner.source]._tick()
2020 # All three addresses fold into one coalesced 15s window.
2021 assert scanner.active_window_calls == [15.0]
2022 # Next-due moved forward by scan_interval for every request.
2023 for addr in addresses:
2024 for due in sched._schedule._due_at[addr].values():
2025 assert due > loop.time() + 250.0
2026 finally:
2027 for cancel in cancels:
2028 cancel()
2029 register_cancel()
2030
2031
2032 @pytest.mark.asyncio
2033 async def test_dispatch_coalesces_different_durations_to_max() -> None:
2034 """Two addresses with different durations fire one window at the max."""
2035 manager = get_manager()
2036 sched = manager._auto_scheduler
2037 loop = asyncio.get_running_loop()
2038 addr_short = "11:22:33:44:55:01"
2039 addr_long = "11:22:33:44:55:02"
2040 c_short = manager.async_register_active_scan(
2041 addr_short, scan_interval=60.0, scan_duration=6.0
2042 )
2043 c_long = manager.async_register_active_scan(
2044 addr_long, scan_interval=60.0, scan_duration=12.0
2045 )
2046 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
2047 register_cancel = manager.async_register_scanner(scanner)
2048 try:
2049 for addr in (addr_short, addr_long):
2050 _inject(scanner, addr)
2051 entries = sched._schedule._due_at[addr]
2052 for req in list(entries):
2053 entries[req] = loop.time() - 1.0
2054 await sched._workers[scanner.source]._tick()
2055 # Single window sized to the larger of the two durations.
2056 assert scanner.active_window_calls == [12.0]
2057 finally:
2058 c_short()
2059 c_long()
2060 register_cancel()
2061
2062
2063 @pytest.mark.asyncio
2064 async def test_three_inkbirds_same_address_coalesce_to_one_scan() -> None:
2065 """
2066 Three Inkbird-style registrations on the same address share one window.
2067
2068 Realistic case: three integrations each register their own callback
2069 for the same Inkbird; the scheduler must NOT fire 3 separate 15s
2070 windows back-to-back. Instead all three requests coalesce into one
2071 single 15s window via _coalesce_duration's max-of-durations.
2072 """
2073 manager = get_manager()
2074 sched = manager._auto_scheduler
2075 loop = asyncio.get_running_loop()
2076 address = "C0:01:01:11:11:11"
2077 cancels = [
2078 manager.async_register_active_scan(
2079 address, scan_interval=300.0, scan_duration=15.0
2080 )
2081 for _ in range(3)
2082 ]
2083 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
2084 register_cancel = manager.async_register_scanner(scanner)
2085 try:
2086 _inject(scanner, address)
2087 entries = sched._schedule._due_at[address]
2088 assert len(entries) == 3
2089 for req in list(entries):
2090 entries[req] = loop.time() - 1.0
2091 await sched._workers[scanner.source]._tick()
2092 # All three coalesced into a single 15s window.
2093 assert scanner.active_window_calls == [15.0]
2094 # Each request's next-due advanced by its own scan_interval.
2095 for due in entries.values():
2096 assert due > loop.time() + 250.0
2097 finally:
2098 for cancel in cancels:
2099 cancel()
2100 register_cancel()
2101
2102
2103 @pytest.mark.asyncio
2104 async def test_three_inkbirds_window_unchanged_after_removal() -> None:
2105 """
2106 Removing one of three same-address registrations preserves the window.
2107
2108 All three asked for the same 15s duration so the coalesced window is
2109 15s. Cancelling one of them leaves two requests still asking for
2110 15s; the resulting window must still be 15s, not regress to the
2111 MIN_DURATION floor.
2112 """
2113 manager = get_manager()
2114 sched = manager._auto_scheduler
2115 loop = asyncio.get_running_loop()
2116 address = "C0:01:01:11:11:11"
2117 cancels = [
2118 manager.async_register_active_scan(
2119 address, scan_interval=300.0, scan_duration=15.0
2120 )
2121 for _ in range(3)
2122 ]
2123 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
2124 register_cancel = manager.async_register_scanner(scanner)
2125 try:
2126 _inject(scanner, address)
2127 entries = sched._schedule._due_at[address]
2128 assert len(entries) == 3
2129 # Cancel one of the three; two should remain in both the registry
2130 # and the _due_at tracker.
2131 cancels.pop()()
2132 assert len(sched._requests_by_address[address]) == 2
2133 entries = sched._schedule._due_at[address]
2134 assert len(entries) == 2
2135 for req in list(entries):
2136 entries[req] = loop.time() - 1.0
2137 await sched._workers[scanner.source]._tick()
2138 # Window duration is unchanged because the remaining two still
2139 # ask for 15s; coalesce takes the max.
2140 assert scanner.active_window_calls == [15.0]
2141 finally:
2142 for cancel in cancels:
2143 cancel()
2144 register_cancel()
2145
2146
2147 @pytest.mark.asyncio
2148 async def test_only_owning_scanner_fires_among_four() -> None:
2149 """
2150 Of four AUTO scanners, only the one owning the device's history fires.
2151
2152 The device is injected from one specific scanner so the manager's
2153 _all_history points at that source. Every worker's _tick runs;
2154 only the owner produces an active window. The other three scanners
2155 stay PASSIVE.
2156 """
2157 manager = get_manager()
2158 sched = manager._auto_scheduler
2159 loop = asyncio.get_running_loop()
2160 address = "11:22:33:44:55:66"
2161 cancel = manager.async_register_active_scan(
2162 address, scan_interval=60.0, scan_duration=5.0
2163 )
2164 scanners = [
2165 _RecordingAutoScanner(f"AA:00:00:00:00:0{n}", BluetoothScanningMode.AUTO)
2166 for n in range(4)
2167 ]
2168 register_cancels = [manager.async_register_scanner(s) for s in scanners]
2169 try:
2170 owner = scanners[2]
2171 _inject(owner, address)
2172 entries = sched._schedule._due_at[address]
2173 for req in list(entries):
2174 entries[req] = loop.time() - 1.0
2175 for scanner in scanners:
2176 await sched._workers[scanner.source]._tick()
2177 # Only the owning scanner flipped to ACTIVE for the requested 5s.
2178 assert [s.active_window_calls for s in scanners] == [[], [], [5.0], []]
2179 finally:
2180 for c in register_cancels:
2181 c()
2182 cancel()
2183
2184
2185 @pytest.mark.asyncio
2186 async def test_add_request_before_start_does_not_seed_due_at() -> None:
2187 """If add_request runs before start() the entry is deferred to advertisement."""
2188 manager = get_manager()
2189 sched = manager._auto_scheduler
2190 address = "BB:00:00:00:00:00"
2191 original_loop = sched._loop
2192 sched._loop = None
2193 try:
2194 sched.add_request(ActiveScanRequest(address, 60.0, 10.0))
2195 assert address in sched._requests_by_address
2196 assert address not in sched._schedule._due_at
2197 finally:
2198 sched._loop = original_loop
2199 sched._requests_by_address.pop(address, None)
2200
2201
2202 @pytest.mark.asyncio
2203 async def test_add_request_idempotent_keeps_existing_due() -> None:
2204 """
2205 Re-adding the same request preserves its existing next-due time.
2206
2207 Also verifies the wake is gated on "actually inserted a new entry":
2208 a re-register (e.g. an HA config-entry reload) is a no-op on the
2209 schedule, so the worker should not be woken.
2210 """
2211 manager = get_manager()
2212 sched = manager._auto_scheduler
2213 address = "BC:00:00:00:00:00"
2214 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:42", BluetoothScanningMode.AUTO)
2215 register_cancel = manager.async_register_scanner(scanner)
2216 try:
2217 request = ActiveScanRequest(address, 60.0, 10.0)
2218 sched.add_request(request)
2219 # Inject so add_request can see history on the second call.
2220 _inject(scanner, address)
2221 sched._schedule._due_at[address][request] = 1234.5
2222 worker = sched._workers[scanner.source]
2223 worker._wake.clear()
2224 sched.add_request(request)
2225 assert sched._schedule._due_at[address][request] == 1234.5
2226 # No new entry → no wake.
2227 assert not worker._wake.is_set()
2228 sched.remove_request(request)
2229 finally:
2230 register_cancel()
2231
2232
2233 @pytest.mark.asyncio
2234 async def test_run_loop_waits_then_ticks() -> None:
2235 """The _run loop's wait_for + _tick path is exercised end-to-end."""
2236 manager = get_manager()
2237 sched = manager._auto_scheduler
2238 loop = asyncio.get_running_loop()
2239 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
2240 register_cancel = manager.async_register_scanner(scanner)
2241 try:
2242 worker = sched._workers[scanner.source]
2243 await _replace_worker_task(worker)
2244 # Sweep ~1ms in the future so _run's wait_for times out quickly
2245 # and _tick runs once before we shut it down.
2246 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL + 0.001
2247 task = loop.create_task(worker._run())
2248 await asyncio.sleep(0.05)
2249 assert scanner.active_window_calls == [AUTO_REDISCOVERY_SWEEP_DURATION]
2250 sched._running = False
2251 worker._wake.set()
2252 await asyncio.wait_for(task, timeout=1.0)
2253 finally:
2254 sched._running = True
2255 register_cancel()
2256
2257
2258 @pytest.mark.asyncio
2259 async def test_owner_flip_during_window_does_not_double_fire() -> None:
2260 """
2261 If ownership flips to a second scanner mid-window, no duplicate fire.
2262
2263 Worker A starts its window for address X. While A awaits the radio,
2264 a new advertisement makes B the owner (B's _all_history.source).
2265 B's worker wakes and ticks. Because A advanced X's next-due BEFORE
2266 starting the await, B's _collect_due_buckets sees the entry as not
2267 yet due and skips it. A finishes alone with one window; B fires
2268 none.
2269 """
2270 manager = get_manager()
2271 sched = manager._auto_scheduler
2272 loop = asyncio.get_running_loop()
2273 address = "11:22:33:44:55:66"
2274 cancel = manager.async_register_active_scan(
2275 address, scan_interval=60.0, scan_duration=5.0
2276 )
2277 gate = asyncio.Event()
2278 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
2279 s_a._block_event = gate
2280 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
2281 c_a = manager.async_register_scanner(s_a)
2282 c_b = manager.async_register_scanner(s_b)
2283 try:
2284 _inject(s_a, address)
2285 entries = sched._schedule._due_at[address]
2286 for req in list(entries):
2287 entries[req] = loop.time() - 1.0
2288
2289 # Worker A starts its tick and blocks inside the scanner call.
2290 t_a = asyncio.create_task(sched._workers[s_a.source]._tick())
2291 for _ in range(4):
2292 await asyncio.sleep(0)
2293 assert s_a.active_window_calls == [5.0]
2294 # A advanced entries BEFORE the await; verify that.
2295 for due in entries.values():
2296 assert due > loop.time() + 50.0
2297
2298 # Ownership flips to B (a fresh advertisement on B).
2299 _inject(s_b, address)
2300
2301 # B's worker ticks. Because the entry is already in the future
2302 # it must NOT fire a second window.
2303 await sched._workers[s_b.source]._tick()
2304 assert s_b.active_window_calls == []
2305
2306 gate.set()
2307 await t_a
2308 finally:
2309 gate.set()
2310 c_a()
2311 c_b()
2312 cancel()
2313
2314
2315 def _inject_with_rssi(scanner: _RecordingAutoScanner, address: str, rssi: int) -> None:
2316 """Drive an advertisement through the scanner with a specific RSSI."""
2317 adv = generate_advertisement_data(local_name="x", rssi=rssi)
2318 device = generate_ble_device(address, "x")
2319 scanner._async_on_advertisement(
2320 device.address,
2321 adv.rssi,
2322 device.name or "",
2323 adv.service_uuids,
2324 adv.service_data,
2325 adv.manufacturer_data,
2326 adv.tx_power,
2327 {},
2328 asyncio.get_running_loop().time(),
2329 )
2330
2331
2332 @pytest.mark.asyncio
2333 async def test_device_migration_between_scanners_fires_on_new_owner() -> None:
2334 """
2335 Migrating from scanner A to B fires the next window on B, not on A.
2336
2337 Sequence: register active_scan. A sees the device first and becomes
2338 owner. A's worker fires the first window. The device then comes
2339 through B with a much stronger RSSI so the manager's
2340 ADV_RSSI_SWITCH_THRESHOLD flips ownership. Make the entry due
2341 again and tick both workers: B fires the new window, A skips.
2342 """
2343 manager = get_manager()
2344 sched = manager._auto_scheduler
2345 loop = asyncio.get_running_loop()
2346 address = "11:22:33:44:55:99"
2347 cancel = manager.async_register_active_scan(
2348 address, scan_interval=60.0, scan_duration=5.0
2349 )
2350 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
2351 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
2352 c_a = manager.async_register_scanner(s_a)
2353 c_b = manager.async_register_scanner(s_b)
2354 try:
2355 # A sees the device first; A becomes owner.
2356 _inject_with_rssi(s_a, address, rssi=-80)
2357 info_a = manager.async_last_service_info(address, False)
2358 assert info_a is not None
2359 assert info_a.source == s_a.source
2360
2361 # Make the existing tracking entry due and fire the first
2362 # window on A.
2363 entries = sched._schedule._due_at[address]
2364 for req in list(entries):
2365 entries[req] = loop.time() - 1.0
2366 await sched._workers[s_a.source]._tick()
2367 assert s_a.active_window_calls == [5.0]
2368 assert s_b.active_window_calls == []
2369
2370 # Device migrates to B with much stronger signal (delta beats
2371 # ADV_RSSI_SWITCH_THRESHOLD). The manager flips
2372 # _all_history.source to B.
2373 _inject_with_rssi(s_b, address, rssi=-30)
2374 info_b = manager.async_last_service_info(address, False)
2375 assert info_b is not None
2376 assert info_b.source == s_b.source
2377
2378 # Force the entry due again and run both workers. B (the new
2379 # owner) fires; A skips because history.source is no longer
2380 # A's source.
2381 for req in list(entries):
2382 entries[req] = loop.time() - 1.0
2383 await sched._workers[s_a.source]._tick()
2384 await sched._workers[s_b.source]._tick()
2385 assert s_a.active_window_calls == [5.0]
2386 assert s_b.active_window_calls == [5.0]
2387 finally:
2388 c_a()
2389 c_b()
2390 cancel()
2391
2392
2393 @pytest.mark.asyncio
2394 async def test_device_migration_wakes_new_owner_worker() -> None:
2395 """
2396 A fresh advertisement on the new owner wakes its worker.
2397
2398 Without this wake, a worker that became the owner mid-sleep would
2399 sit until its previously-computed _next_event_at (sweep cadence)
2400 even though there's a tracked address whose due time is much
2401 sooner. The wake is on_advertisement's job and must fire even when
2402 the _due_at entry already exists (i.e. the ad doesn't add a new
2403 request, it just notifies us this scanner now sees the device).
2404 """
2405 manager = get_manager()
2406 sched = manager._auto_scheduler
2407 address = "11:22:33:44:55:AA"
2408 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
2409 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
2410 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
2411 c_a = manager.async_register_scanner(s_a)
2412 c_b = manager.async_register_scanner(s_b)
2413 try:
2414 # A sees the device first.
2415 _inject_with_rssi(s_a, address, rssi=-80)
2416 worker_b = sched._workers[s_b.source]
2417 worker_b._wake.clear()
2418 # B sees the device with stronger RSSI and becomes the new
2419 # owner. B's worker must be woken so it re-evaluates
2420 # _next_event_at and picks up the existing entry.
2421 _inject_with_rssi(s_b, address, rssi=-30)
2422 assert worker_b._wake.is_set()
2423 finally:
2424 c_a()
2425 c_b()
2426 cancel()
2427
2428
2429 @pytest.mark.asyncio
2430 async def test_stop_clears_due_at_so_restart_does_not_reuse_stale_due_times() -> None:
2431 """
2432 stop() drops _due_at so a later start(new_loop) seeds fresh due-times.
2433
2434 Without this, a restart against a different event loop (whose
2435 ``time()`` origin differs) would reuse timestamps from the
2436 cancelled loop and either fire windows immediately or never.
2437 """
2438 manager = get_manager()
2439 sched = manager._auto_scheduler
2440 address = "11:22:33:44:55:CC"
2441 cancel = manager.async_register_active_scan(
2442 address, scan_interval=60.0, scan_duration=5.0
2443 )
2444 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:CC", BluetoothScanningMode.AUTO)
2445 register_cancel = manager.async_register_scanner(scanner)
2446 try:
2447 _inject(scanner, address)
2448 assert address in sched._schedule._due_at
2449 original_loop = sched._loop
2450 sched.stop()
2451 # _due_at cleared so stale timestamps from the now-defunct loop
2452 # can't survive into a re-start.
2453 assert sched._schedule._due_at == {}
2454 assert sched._loop is None
2455 assert sched._workers == {}
2456 # _requests_by_address is loop-independent and must persist so
2457 # start() can replay registrations on the new loop.
2458 assert address in sched._requests_by_address
2459 # Restart against the same loop; the request gets re-seeded with
2460 # a fresh due time from the new loop.time() base.
2461 assert original_loop is not None
2462 sched.start(original_loop)
2463 assert address in sched._schedule._due_at
2464 entries = sched._schedule._due_at[address]
2465 expected_due = original_loop.time() + 60.0
2466 assert all(abs(due - expected_due) < 0.5 for due in entries.values())
2467 finally:
2468 cancel()
2469 register_cancel()
2470
2471
2472 class _DiscoverableAutoScanner(_RecordingAutoScanner):
2473 """Recording scanner that reports a configurable discovered set."""
2474
2475 __slots__ = ("_discovered",)
2476
2477 def __init__(
2478 self,
2479 source: str,
2480 mode: BluetoothScanningMode | None,
2481 connectable: bool = True,
2482 ) -> None:
2483 super().__init__(source, mode, connectable)
2484 self._discovered: dict[str, tuple[BLEDevice, AdvertisementData]] = {}
2485
2486 def add_discovered(self, address: str, rssi: int | None = -60) -> None:
2487 """Mark ``address`` as currently discovered by this scanner."""
2488 device = generate_ble_device(address, "x")
2489 adv = generate_advertisement_data(local_name="x", rssi=rssi)
2490 self._discovered[address] = (device, adv)
2491
2492 def get_discovered_device_advertisement_data(
2493 self, address: str
2494 ) -> tuple[BLEDevice, AdvertisementData] | None:
2495 return self._discovered.get(address)
2496
2497
2498 def _make_due(sched: object, address: str) -> None:
2499 """Make every tracked request for ``address`` due immediately."""
2500 entries = sched._schedule._due_at[address] # type: ignore[attr-defined]
2501 loop = asyncio.get_running_loop()
2502 for req in list(entries):
2503 entries[req] = loop.time() - 1.0
2504
2505
2506 @pytest.mark.asyncio
2507 async def test_worker_tick_delegates_to_fallback_when_owner_is_connecting() -> None:
2508 """
2509 Owner mid-connect dispatches the active-window scan to fallback.
2510
2511 Owner scanner is in the connect-attempt phase
2512 (``_connections_in_progress() > 0``) so its radio can't service
2513 the active-window flip. A second AUTO scanner also sees the
2514 device. The worker for the owner must call
2515 ``async_request_active_window`` on the fallback, not on the owner.
2516 """
2517 manager = get_manager()
2518 sched = manager._auto_scheduler
2519 address = "11:22:33:44:55:01"
2520 cancel = manager.async_register_active_scan(
2521 address, scan_interval=120.0, scan_duration=7.0
2522 )
2523 owner = _DiscoverableAutoScanner("AA:00:00:00:01:01", BluetoothScanningMode.AUTO)
2524 fallback = _DiscoverableAutoScanner("AA:00:00:00:01:02", BluetoothScanningMode.AUTO)
2525 c_owner = manager.async_register_scanner(owner)
2526 c_fallback = manager.async_register_scanner(fallback)
2527 try:
2528 _inject_with_rssi(owner, address, rssi=-50)
2529 info = manager.async_last_service_info(address, False)
2530 assert info is not None
2531 assert info.source == owner.source
2532 fallback.add_discovered(address, rssi=-70)
2533 owner._add_connecting(address)
2534 _make_due(sched, address)
2535 await _run_worker_tick(sched, owner.source)
2536 # Owner can't service the flip; fallback gets the call.
2537 assert owner.active_window_calls == []
2538 assert fallback.active_window_calls == [7.0]
2539 # The delegated window is recorded against the fallback that ran
2540 # it, not the connecting owner.
2541 entry = sched.async_diagnostics()["requests"][address][0]
2542 assert entry["last_active_window_source"] == fallback.source
2543 assert entry["last_active_window"] is not None
2544 finally:
2545 owner._finished_connecting(address, connected=False)
2546 cancel()
2547 c_owner()
2548 c_fallback()
2549
2550
2551 @pytest.mark.asyncio
2552 async def test_worker_tick_warns_when_no_fallback_available(
2553 caplog: pytest.LogCaptureFixture,
2554 ) -> None:
2555 """No fallback emits a single WARNING; owner is not flipped."""
2556 manager = get_manager()
2557 sched = manager._auto_scheduler
2558 address = "11:22:33:44:55:02"
2559 cancel = manager.async_register_active_scan(
2560 address, scan_interval=120.0, scan_duration=6.0
2561 )
2562 owner = _DiscoverableAutoScanner("AA:00:00:00:02:01", BluetoothScanningMode.AUTO)
2563 c_owner = manager.async_register_scanner(owner)
2564 try:
2565 _inject_with_rssi(owner, address, rssi=-50)
2566 owner._add_connecting(address)
2567 _make_due(sched, address)
2568 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2569 await _run_worker_tick(sched, owner.source)
2570 assert owner.active_window_calls == []
2571 assert any(
2572 "no fallback scanner" in record.message and address in record.message
2573 for record in caplog.records
2574 )
2575 finally:
2576 owner._finished_connecting(address, connected=False)
2577 cancel()
2578 c_owner()
2579
2580
2581 @pytest.mark.asyncio
2582 async def test_worker_tick_no_fallback_warning_is_rate_limited(
2583 caplog: pytest.LogCaptureFixture,
2584 ) -> None:
2585 """A second connecting tick with no fallback does not re-warn."""
2586 manager = get_manager()
2587 sched = manager._auto_scheduler
2588 address = "11:22:33:44:55:03"
2589 cancel = manager.async_register_active_scan(
2590 address, scan_interval=120.0, scan_duration=6.0
2591 )
2592 owner = _DiscoverableAutoScanner("AA:00:00:00:03:01", BluetoothScanningMode.AUTO)
2593 c_owner = manager.async_register_scanner(owner)
2594 try:
2595 _inject_with_rssi(owner, address, rssi=-50)
2596 owner._add_connecting(address)
2597 _make_due(sched, address)
2598 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2599 await _run_worker_tick(sched, owner.source)
2600 count_after_first = sum(
2601 1
2602 for record in caplog.records
2603 if "no fallback scanner" in record.message
2604 )
2605 assert count_after_first == 1
2606 _make_due(sched, address)
2607 await _run_worker_tick(sched, owner.source)
2608 count_after_second = sum(
2609 1
2610 for record in caplog.records
2611 if "no fallback scanner" in record.message
2612 )
2613 assert count_after_second == 1
2614 finally:
2615 owner._finished_connecting(address, connected=False)
2616 cancel()
2617 c_owner()
2618
2619
2620 @pytest.mark.asyncio
2621 async def test_worker_tick_no_fallback_flag_resets_after_recovery(
2622 caplog: pytest.LogCaptureFixture,
2623 ) -> None:
2624 """Successful fallback dispatch re-arms the no-fallback warning."""
2625 manager = get_manager()
2626 sched = manager._auto_scheduler
2627 address = "11:22:33:44:55:04"
2628 cancel = manager.async_register_active_scan(
2629 address, scan_interval=120.0, scan_duration=6.0
2630 )
2631 owner = _DiscoverableAutoScanner("AA:00:00:00:04:01", BluetoothScanningMode.AUTO)
2632 fallback = _DiscoverableAutoScanner("AA:00:00:00:04:02", BluetoothScanningMode.AUTO)
2633 c_owner = manager.async_register_scanner(owner)
2634 c_fallback = manager.async_register_scanner(fallback)
2635 try:
2636 _inject_with_rssi(owner, address, rssi=-50)
2637 owner._add_connecting(address)
2638 _make_due(sched, address)
2639 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2640 # No fallback -> warning.
2641 await _run_worker_tick(sched, owner.source)
2642 assert sched._workers[owner.source]._warned_no_fallback is True
2643 # Fallback appears, dispatch succeeds -> flag clears.
2644 fallback.add_discovered(address, rssi=-70)
2645 _make_due(sched, address)
2646 await _run_worker_tick(sched, owner.source)
2647 assert fallback.active_window_calls == [6.0]
2648 assert sched._workers[owner.source]._warned_no_fallback is False
2649 # Fallback disappears again -> warning fires once more.
2650 fallback._discovered.clear()
2651 _make_due(sched, address)
2652 caplog.clear()
2653 await _run_worker_tick(sched, owner.source)
2654 assert any(
2655 "no fallback scanner" in record.message for record in caplog.records
2656 )
2657 finally:
2658 owner._finished_connecting(address, connected=False)
2659 cancel()
2660 c_owner()
2661 c_fallback()
2662
2663
2664 @pytest.mark.asyncio
2665 async def test_worker_tick_active_scanner_covers_address_no_warning(
2666 caplog: pytest.LogCaptureFixture,
2667 ) -> None:
2668 """
2669 ACTIVE-mode scanner seeing the address counts as scan done.
2670
2671 The owner is mid-connect, so it can't service the active-window
2672 flip. Another scanner has ``requested_mode is ACTIVE`` and sees
2673 the address — by definition that scanner is already actively
2674 scanning. The dispatch must drop the request silently: no
2675 warning, no ``async_request_active_window`` call on the ACTIVE
2676 scanner (which would no-op anyway via the ``requested_mode``
2677 guard in ``HaScanner.async_request_active_window``).
2678 """
2679 manager = get_manager()
2680 sched = manager._auto_scheduler
2681 address = "11:22:33:44:55:05"
2682 cancel = manager.async_register_active_scan(
2683 address, scan_interval=120.0, scan_duration=6.0
2684 )
2685 owner = _DiscoverableAutoScanner("AA:00:00:00:05:01", BluetoothScanningMode.AUTO)
2686 active = _DiscoverableAutoScanner("AA:00:00:00:05:03", BluetoothScanningMode.ACTIVE)
2687 c_owner = manager.async_register_scanner(owner)
2688 c_active = manager.async_register_scanner(active)
2689 try:
2690 _inject_with_rssi(owner, address, rssi=-50)
2691 active.add_discovered(address, rssi=-60)
2692 owner._add_connecting(address)
2693 _make_due(sched, address)
2694 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2695 await _run_worker_tick(sched, owner.source)
2696 assert owner.active_window_calls == []
2697 assert active.active_window_calls == []
2698 assert not any(
2699 "no fallback scanner" in record.message for record in caplog.records
2700 )
2701 assert sched._workers[owner.source]._warned_no_fallback is False
2702 finally:
2703 owner._finished_connecting(address, connected=False)
2704 cancel()
2705 c_owner()
2706 c_active()
2707
2708
2709 @pytest.mark.asyncio
2710 async def test_worker_tick_active_coverage_preferred_over_auto_fallback() -> None:
2711 """When ACTIVE covers, no AUTO-fallback flip is needed either."""
2712 manager = get_manager()
2713 sched = manager._auto_scheduler
2714 address = "11:22:33:44:55:0C"
2715 cancel = manager.async_register_active_scan(
2716 address, scan_interval=120.0, scan_duration=6.0
2717 )
2718 owner = _DiscoverableAutoScanner("AA:00:00:00:0C:01", BluetoothScanningMode.AUTO)
2719 auto_fb = _DiscoverableAutoScanner("AA:00:00:00:0C:02", BluetoothScanningMode.AUTO)
2720 active = _DiscoverableAutoScanner("AA:00:00:00:0C:03", BluetoothScanningMode.ACTIVE)
2721 c_owner = manager.async_register_scanner(owner)
2722 c_auto = manager.async_register_scanner(auto_fb)
2723 c_active = manager.async_register_scanner(active)
2724 try:
2725 _inject_with_rssi(owner, address, rssi=-50)
2726 auto_fb.add_discovered(address, rssi=-55)
2727 active.add_discovered(address, rssi=-70)
2728 owner._add_connecting(address)
2729 _make_due(sched, address)
2730 await _run_worker_tick(sched, owner.source)
2731 # Covered by ACTIVE: no flip needed on AUTO fallback either.
2732 assert owner.active_window_calls == []
2733 assert auto_fb.active_window_calls == []
2734 assert active.active_window_calls == []
2735 finally:
2736 owner._finished_connecting(address, connected=False)
2737 cancel()
2738 c_owner()
2739 c_auto()
2740 c_active()
2741
2742
2743 @pytest.mark.asyncio
2744 async def test_worker_tick_passive_only_fallback_warns(
2745 caplog: pytest.LogCaptureFixture,
2746 ) -> None:
2747 """
2748 Only PASSIVE scanners around: no flip possible, must warn.
2749
2750 A PASSIVE scanner refuses
2751 ``async_request_active_window`` and isn't actively scanning, so
2752 the active scan is truly deferred until the owner's connect
2753 completes — the warning must fire.
2754 """
2755 manager = get_manager()
2756 sched = manager._auto_scheduler
2757 address = "11:22:33:44:55:0D"
2758 cancel = manager.async_register_active_scan(
2759 address, scan_interval=120.0, scan_duration=6.0
2760 )
2761 owner = _DiscoverableAutoScanner("AA:00:00:00:0D:01", BluetoothScanningMode.AUTO)
2762 passive = _DiscoverableAutoScanner(
2763 "AA:00:00:00:0D:02", BluetoothScanningMode.PASSIVE
2764 )
2765 c_owner = manager.async_register_scanner(owner)
2766 c_passive = manager.async_register_scanner(passive)
2767 try:
2768 _inject_with_rssi(owner, address, rssi=-50)
2769 passive.add_discovered(address, rssi=-60)
2770 owner._add_connecting(address)
2771 _make_due(sched, address)
2772 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2773 await _run_worker_tick(sched, owner.source)
2774 assert owner.active_window_calls == []
2775 assert passive.active_window_calls == []
2776 assert any(
2777 "no fallback scanner" in record.message and address in record.message
2778 for record in caplog.records
2779 )
2780 finally:
2781 owner._finished_connecting(address, connected=False)
2782 cancel()
2783 c_owner()
2784 c_passive()
2785
2786
2787 @pytest.mark.asyncio
2788 async def test_worker_tick_dispatch_never_calls_same_fallback_twice() -> None:
2789 """
2790 Per-tick dispatch never calls the same fallback more than once.
2791
2792 Same-tick coalescing guarantees we don't simultaneously trigger
2793 ``async_request_active_window`` twice on one scanner from a
2794 single owner's tick. (Cross-tick concurrency between distinct
2795 owner workers delegating to the same fallback is handled inside
2796 the scanner: ``HaScanner.async_request_active_window`` extends an
2797 open active-window timer instead of stopping and restarting the
2798 radio, and the actual stop/start is serialized by
2799 ``_start_stop_lock``.)
2800 """
2801 manager = get_manager()
2802 sched = manager._auto_scheduler
2803 addresses = ("11:22:33:44:55:0E", "11:22:33:44:55:0F", "11:22:33:44:55:10")
2804 cancels = [
2805 manager.async_register_active_scan(addr, scan_interval=120.0, scan_duration=6.0)
2806 for addr in addresses
2807 ]
2808 owner = _DiscoverableAutoScanner("AA:00:00:00:0E:01", BluetoothScanningMode.AUTO)
2809 fb = _DiscoverableAutoScanner("AA:00:00:00:0E:02", BluetoothScanningMode.AUTO)
2810 c_owner = manager.async_register_scanner(owner)
2811 c_fb = manager.async_register_scanner(fb)
2812 try:
2813 for addr in addresses:
2814 _inject_with_rssi(owner, addr, rssi=-50)
2815 fb.add_discovered(addr, rssi=-60)
2816 owner._add_connecting(addresses[0])
2817 for addr in addresses:
2818 _make_due(sched, addr)
2819 await _run_worker_tick(sched, owner.source)
2820 # One coalesced call regardless of how many addresses route to fb.
2821 assert len(fb.active_window_calls) == 1
2822 assert owner.active_window_calls == []
2823 finally:
2824 owner._finished_connecting(addresses[0], connected=False)
2825 for cancel in cancels:
2826 cancel()
2827 c_owner()
2828 c_fb()
2829
2830
2831 @pytest.mark.asyncio
2832 async def test_worker_tick_active_covers_one_address_warns_for_other(
2833 caplog: pytest.LogCaptureFixture,
2834 ) -> None:
2835 """
2836 Per-address classification: covered for one, warn for another.
2837
2838 Owner is mid-connect with two due addresses. Address A is covered
2839 by an ACTIVE scanner; address B has no fallback. We expect:
2840 silent skip for A, warning for B that names only B.
2841 """
2842 manager = get_manager()
2843 sched = manager._auto_scheduler
2844 addr_covered = "11:22:33:44:55:11"
2845 addr_orphan = "11:22:33:44:55:12"
2846 c1 = manager.async_register_active_scan(
2847 addr_covered, scan_interval=120.0, scan_duration=6.0
2848 )
2849 c2 = manager.async_register_active_scan(
2850 addr_orphan, scan_interval=120.0, scan_duration=6.0
2851 )
2852 owner = _DiscoverableAutoScanner("AA:00:00:00:11:01", BluetoothScanningMode.AUTO)
2853 active = _DiscoverableAutoScanner("AA:00:00:00:11:02", BluetoothScanningMode.ACTIVE)
2854 c_owner = manager.async_register_scanner(owner)
2855 c_active = manager.async_register_scanner(active)
2856 try:
2857 _inject_with_rssi(owner, addr_covered, rssi=-50)
2858 _inject_with_rssi(owner, addr_orphan, rssi=-50)
2859 active.add_discovered(addr_covered, rssi=-60)
2860 # Note: ACTIVE scanner does NOT see addr_orphan.
2861 owner._add_connecting(addr_covered)
2862 _make_due(sched, addr_covered)
2863 _make_due(sched, addr_orphan)
2864 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
2865 await _run_worker_tick(sched, owner.source)
2866 warnings_for_orphan = [
2867 record
2868 for record in caplog.records
2869 if "no fallback scanner" in record.message and addr_orphan in record.message
2870 ]
2871 assert len(warnings_for_orphan) == 1
2872 # The covered address must not appear in any no-fallback
2873 # warning text.
2874 assert not any(
2875 "no fallback scanner" in record.message and addr_covered in record.message
2876 for record in caplog.records
2877 )
2878 assert active.active_window_calls == []
2879 assert owner.active_window_calls == []
2880 finally:
2881 owner._finished_connecting(addr_covered, connected=False)
2882 c1()
2883 c2()
2884 c_owner()
2885 c_active()
2886
2887
2888 @pytest.mark.asyncio
2889 async def test_worker_tick_skips_fallback_that_is_also_connecting() -> None:
2890 """A candidate fallback that's mid-connect is also excluded."""
2891 manager = get_manager()
2892 sched = manager._auto_scheduler
2893 address = "11:22:33:44:55:06"
2894 cancel = manager.async_register_active_scan(
2895 address, scan_interval=120.0, scan_duration=6.0
2896 )
2897 owner = _DiscoverableAutoScanner("AA:00:00:00:06:01", BluetoothScanningMode.AUTO)
2898 busy_fb = _DiscoverableAutoScanner("AA:00:00:00:06:02", BluetoothScanningMode.AUTO)
2899 c_owner = manager.async_register_scanner(owner)
2900 c_busy = manager.async_register_scanner(busy_fb)
2901 try:
2902 _inject_with_rssi(owner, address, rssi=-50)
2903 busy_fb.add_discovered(address, rssi=-55)
2904 owner._add_connecting(address)
2905 busy_fb._add_connecting("AA:BB:CC:DD:EE:FF")
2906 _make_due(sched, address)
2907 await _run_worker_tick(sched, owner.source)
2908 assert owner.active_window_calls == []
2909 assert busy_fb.active_window_calls == []
2910 finally:
2911 owner._finished_connecting(address, connected=False)
2912 busy_fb._finished_connecting("AA:BB:CC:DD:EE:FF", connected=False)
2913 cancel()
2914 c_owner()
2915 c_busy()
2916
2917
2918 @pytest.mark.asyncio
2919 async def test_worker_tick_fallback_picks_highest_rssi() -> None:
2920 """When multiple AUTO fallbacks see the device, highest RSSI wins."""
2921 manager = get_manager()
2922 sched = manager._auto_scheduler
2923 address = "11:22:33:44:55:07"
2924 cancel = manager.async_register_active_scan(
2925 address, scan_interval=120.0, scan_duration=6.0
2926 )
2927 owner = _DiscoverableAutoScanner("AA:00:00:00:07:01", BluetoothScanningMode.AUTO)
2928 weak = _DiscoverableAutoScanner("AA:00:00:00:07:02", BluetoothScanningMode.AUTO)
2929 strong = _DiscoverableAutoScanner("AA:00:00:00:07:03", BluetoothScanningMode.AUTO)
2930 c_owner = manager.async_register_scanner(owner)
2931 c_weak = manager.async_register_scanner(weak)
2932 c_strong = manager.async_register_scanner(strong)
2933 try:
2934 _inject_with_rssi(owner, address, rssi=-50)
2935 weak.add_discovered(address, rssi=-90)
2936 strong.add_discovered(address, rssi=-40)
2937 owner._add_connecting(address)
2938 _make_due(sched, address)
2939 await _run_worker_tick(sched, owner.source)
2940 assert strong.active_window_calls == [6.0]
2941 assert weak.active_window_calls == []
2942 finally:
2943 owner._finished_connecting(address, connected=False)
2944 cancel()
2945 c_owner()
2946 c_weak()
2947 c_strong()
2948
2949
2950 @pytest.mark.asyncio
2951 async def test_worker_tick_groups_addresses_by_fallback() -> None:
2952 """Two due addresses sharing one fallback coalesce to one call."""
2953 manager = get_manager()
2954 sched = manager._auto_scheduler
2955 addr_a = "11:22:33:44:55:08"
2956 addr_b = "11:22:33:44:55:09"
2957 cancel_a = manager.async_register_active_scan(
2958 addr_a, scan_interval=120.0, scan_duration=6.0
2959 )
2960 cancel_b = manager.async_register_active_scan(
2961 addr_b, scan_interval=120.0, scan_duration=11.0
2962 )
2963 owner = _DiscoverableAutoScanner("AA:00:00:00:08:01", BluetoothScanningMode.AUTO)
2964 fb = _DiscoverableAutoScanner("AA:00:00:00:08:02", BluetoothScanningMode.AUTO)
2965 c_owner = manager.async_register_scanner(owner)
2966 c_fb = manager.async_register_scanner(fb)
2967 try:
2968 _inject_with_rssi(owner, addr_a, rssi=-50)
2969 _inject_with_rssi(owner, addr_b, rssi=-50)
2970 fb.add_discovered(addr_a, rssi=-60)
2971 fb.add_discovered(addr_b, rssi=-60)
2972 owner._add_connecting(addr_a)
2973 _make_due(sched, addr_a)
2974 _make_due(sched, addr_b)
2975 await _run_worker_tick(sched, owner.source)
2976 # One coalesced call to the shared fallback with the max duration.
2977 assert fb.active_window_calls == [11.0]
2978 assert owner.active_window_calls == []
2979 finally:
2980 owner._finished_connecting(addr_a, connected=False)
2981 cancel_a()
2982 cancel_b()
2983 c_owner()
2984 c_fb()
2985
2986
2987 @pytest.mark.asyncio
2988 async def test_worker_tick_defers_sweep_when_owner_is_connecting() -> None:
2989 """
2990 Sweep is per-scanner; defer when connecting rather than spinning.
2991
2992 With no per-device buckets but sweep_due True, the connecting
2993 branch must not call ``async_request_active_window`` on the owner.
2994 It must also advance ``_sweep_last_completed`` so the next worker
2995 tick re-evaluates in roughly ``_AUTO_CONNECTING_DEFER`` seconds
2996 rather than firing immediately.
2997 """
2998 manager = get_manager()
2999 sched = manager._auto_scheduler
3000 loop = asyncio.get_running_loop()
3001 owner = _DiscoverableAutoScanner("AA:00:00:00:09:01", BluetoothScanningMode.AUTO)
3002 c_owner = manager.async_register_scanner(owner)
3003 try:
3004 worker = sched._workers[owner.source]
3005 # Force sweep due: place _sweep_last_completed safely in the
3006 # past so now > _sweep_last_completed + AUTO_REDISCOVERY_INTERVAL.
3007 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
3008 owner._add_connecting("11:22:33:44:55:0A")
3009 before = loop.time()
3010 await worker._tick()
3011 assert owner.active_window_calls == []
3012 # Next-due time should be roughly now + _AUTO_CONNECTING_DEFER,
3013 # i.e. _sweep_last_completed + AUTO_REDISCOVERY_INTERVAL >=
3014 # before + (_AUTO_CONNECTING_DEFER - epsilon).
3015 next_sweep_due = worker._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
3016 assert next_sweep_due >= before + 25.0
3017 assert next_sweep_due <= loop.time() + 60.0
3018 finally:
3019 owner._finished_connecting("11:22:33:44:55:0A", connected=False)
3020 c_owner()
3021
3022
3023 @pytest.mark.asyncio
3024 async def test_worker_tick_skips_fallback_when_owner_is_connected_not_connecting() -> (
3025 None
3026 ):
3027 """A fully-connected (not connecting) owner still fires its own window."""
3028 manager = get_manager()
3029 sched = manager._auto_scheduler
3030 address = "11:22:33:44:55:0B"
3031 cancel = manager.async_register_active_scan(
3032 address, scan_interval=120.0, scan_duration=6.0
3033 )
3034 owner = _DiscoverableAutoScanner("AA:00:00:00:0B:01", BluetoothScanningMode.AUTO)
3035 fb = _DiscoverableAutoScanner("AA:00:00:00:0B:02", BluetoothScanningMode.AUTO)
3036 c_owner = manager.async_register_scanner(owner)
3037 c_fb = manager.async_register_scanner(fb)
3038 try:
3039 _inject_with_rssi(owner, address, rssi=-50)
3040 fb.add_discovered(address, rssi=-60)
3041 # No _add_connecting on the owner: connect has either not
3042 # started or has already completed. The owner is responsible
3043 # for the window; fallback stays silent.
3044 _make_due(sched, address)
3045 await _run_worker_tick(sched, owner.source)
3046 assert owner.active_window_calls == [6.0]
3047 assert fb.active_window_calls == []
3048 finally:
3049 cancel()
3050 c_owner()
3051 c_fb()
3052
3053
3054 @pytest.mark.asyncio
3055 async def test_worker_tick_fallback_exception_does_not_block_others(
3056 caplog: pytest.LogCaptureFixture,
3057 ) -> None:
3058 """
3059 A raising fallback gets logged; remaining fallbacks still run.
3060
3061 Two due addresses route to two different fallbacks. The first
3062 fallback's ``async_request_active_window`` raises. The dispatch
3063 must still call the second fallback and the worker must remain
3064 alive.
3065 """
3066
3067 class _RaisingScanner(_DiscoverableAutoScanner):
3068 async def async_request_active_window(self, duration: float) -> bool:
3069 self.active_window_calls.append(duration)
3070 msg = "boom"
3071 raise RuntimeError(msg)
3072
3073 manager = get_manager()
3074 sched = manager._auto_scheduler
3075 addr_a = "11:22:33:44:55:13"
3076 addr_b = "11:22:33:44:55:14"
3077 c1 = manager.async_register_active_scan(
3078 addr_a, scan_interval=120.0, scan_duration=6.0
3079 )
3080 c2 = manager.async_register_active_scan(
3081 addr_b, scan_interval=120.0, scan_duration=6.0
3082 )
3083 owner = _DiscoverableAutoScanner("AA:00:00:00:13:01", BluetoothScanningMode.AUTO)
3084 fb_bad = _RaisingScanner("AA:00:00:00:13:02", BluetoothScanningMode.AUTO)
3085 fb_good = _DiscoverableAutoScanner("AA:00:00:00:13:03", BluetoothScanningMode.AUTO)
3086 c_owner = manager.async_register_scanner(owner)
3087 c_bad = manager.async_register_scanner(fb_bad)
3088 c_good = manager.async_register_scanner(fb_good)
3089 try:
3090 _inject_with_rssi(owner, addr_a, rssi=-50)
3091 _inject_with_rssi(owner, addr_b, rssi=-50)
3092 # Only fb_bad sees addr_a; only fb_good sees addr_b. So each
3093 # address routes to a different fallback.
3094 fb_bad.add_discovered(addr_a, rssi=-60)
3095 fb_good.add_discovered(addr_b, rssi=-60)
3096 owner._add_connecting(addr_a)
3097 _make_due(sched, addr_a)
3098 _make_due(sched, addr_b)
3099 with caplog.at_level(logging.ERROR, logger="habluetooth.auto_scheduler"):
3100 await _run_worker_tick(sched, owner.source)
3101 assert fb_bad.active_window_calls == [6.0]
3102 assert fb_good.active_window_calls == [6.0]
3103 assert any(
3104 "error dispatching fallback active window" in record.message
3105 and fb_bad.name in record.message
3106 for record in caplog.records
3107 )
3108 finally:
3109 owner._finished_connecting(addr_a, connected=False)
3110 c1()
3111 c2()
3112 c_owner()
3113 c_bad()
3114 c_good()
3115
3116
3117 @pytest.mark.asyncio
3118 async def test_worker_tick_sweep_and_per_device_both_handled_when_connecting() -> None:
3119 """
3120 Mixed tick: per-device dispatched to fallback AND sweep deferred.
3121
3122 Sweep is due AND a per-device window is due AND the owner is
3123 mid-connect. The per-device flip lands on the fallback; the sweep
3124 is deferred (no flip on the owner) — both behaviors coexist.
3125 """
3126 manager = get_manager()
3127 sched = manager._auto_scheduler
3128 loop = asyncio.get_running_loop()
3129 address = "11:22:33:44:55:15"
3130 cancel = manager.async_register_active_scan(
3131 address, scan_interval=120.0, scan_duration=6.0
3132 )
3133 owner = _DiscoverableAutoScanner("AA:00:00:00:15:01", BluetoothScanningMode.AUTO)
3134 fb = _DiscoverableAutoScanner("AA:00:00:00:15:02", BluetoothScanningMode.AUTO)
3135 c_owner = manager.async_register_scanner(owner)
3136 c_fb = manager.async_register_scanner(fb)
3137 try:
3138 _inject_with_rssi(owner, address, rssi=-50)
3139 fb.add_discovered(address, rssi=-60)
3140 owner._add_connecting(address)
3141 worker = sched._workers[owner.source]
3142 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
3143 _make_due(sched, address)
3144 before = loop.time()
3145 await worker._tick()
3146 # Per-device went to fallback.
3147 assert fb.active_window_calls == [6.0]
3148 assert owner.active_window_calls == []
3149 # Sweep was deferred (next due roughly now + _AUTO_CONNECTING_DEFER).
3150 next_sweep_due = worker._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
3151 assert next_sweep_due >= before + 25.0
3152 finally:
3153 owner._finished_connecting(address, connected=False)
3154 cancel()
3155 c_owner()
3156 c_fb()
3157
3158
3159 @pytest.mark.asyncio
3160 async def test_worker_tick_two_different_fallbacks_both_dispatched() -> None:
3161 """
3162 Two due addresses with distinct fallbacks → both get called.
3163
3164 Confirms that the per-fallback grouping does *not* collapse
3165 different fallbacks into one — each fallback receives its own
3166 coalesced ``async_request_active_window`` call.
3167 """
3168 manager = get_manager()
3169 sched = manager._auto_scheduler
3170 addr_a = "11:22:33:44:55:16"
3171 addr_b = "11:22:33:44:55:17"
3172 c1 = manager.async_register_active_scan(
3173 addr_a, scan_interval=120.0, scan_duration=6.0
3174 )
3175 c2 = manager.async_register_active_scan(
3176 addr_b, scan_interval=120.0, scan_duration=8.0
3177 )
3178 owner = _DiscoverableAutoScanner("AA:00:00:00:16:01", BluetoothScanningMode.AUTO)
3179 fb_a = _DiscoverableAutoScanner("AA:00:00:00:16:02", BluetoothScanningMode.AUTO)
3180 fb_b = _DiscoverableAutoScanner("AA:00:00:00:16:03", BluetoothScanningMode.AUTO)
3181 c_owner = manager.async_register_scanner(owner)
3182 c_a = manager.async_register_scanner(fb_a)
3183 c_b = manager.async_register_scanner(fb_b)
3184 try:
3185 _inject_with_rssi(owner, addr_a, rssi=-50)
3186 _inject_with_rssi(owner, addr_b, rssi=-50)
3187 fb_a.add_discovered(addr_a, rssi=-60)
3188 fb_b.add_discovered(addr_b, rssi=-60)
3189 owner._add_connecting(addr_a)
3190 _make_due(sched, addr_a)
3191 _make_due(sched, addr_b)
3192 await _run_worker_tick(sched, owner.source)
3193 assert fb_a.active_window_calls == [6.0]
3194 assert fb_b.active_window_calls == [8.0]
3195 assert owner.active_window_calls == []
3196 finally:
3197 owner._finished_connecting(addr_a, connected=False)
3198 c1()
3199 c2()
3200 c_owner()
3201 c_a()
3202 c_b()
3203
3204
3205 @pytest.mark.asyncio
3206 async def test_worker_tick_advance_pre_dispatch_blocks_double_fire() -> None:
3207 """
3208 Per-address ``_due_at`` entries are advanced before the dispatch.
3209
3210 The pre-dispatch advance protects against an in-flight ownership
3211 flip causing a duplicate window on a different worker (same
3212 reasoning as the non-connecting path's pre-await advance).
3213 """
3214 manager = get_manager()
3215 sched = manager._auto_scheduler
3216 loop = asyncio.get_running_loop()
3217 address = "11:22:33:44:55:18"
3218 cancel = manager.async_register_active_scan(
3219 address, scan_interval=90.0, scan_duration=6.0
3220 )
3221 owner = _DiscoverableAutoScanner("AA:00:00:00:18:01", BluetoothScanningMode.AUTO)
3222 fb = _DiscoverableAutoScanner("AA:00:00:00:18:02", BluetoothScanningMode.AUTO)
3223 c_owner = manager.async_register_scanner(owner)
3224 c_fb = manager.async_register_scanner(fb)
3225 try:
3226 _inject_with_rssi(owner, address, rssi=-50)
3227 fb.add_discovered(address, rssi=-60)
3228 owner._add_connecting(address)
3229 _make_due(sched, address)
3230 before = loop.time()
3231 await _run_worker_tick(sched, owner.source)
3232 entries = sched._schedule._due_at[address]
3233 for due in entries.values():
3234 # Advanced to roughly before + 90s, NOT before - 1.0.
3235 assert due == pytest.approx(before + 90.0, abs=0.5)
3236 assert due > loop.time()
3237 finally:
3238 owner._finished_connecting(address, connected=False)
3239 cancel()
3240 c_owner()
3241 c_fb()
3242
3243
3244 @pytest.mark.asyncio
3245 async def test_worker_tick_passive_plus_auto_uses_auto(
3246 caplog: pytest.LogCaptureFixture,
3247 ) -> None:
3248 """
3249 PASSIVE + AUTO mix: AUTO is used, PASSIVE ignored, no warning.
3250
3251 Confirms that a PASSIVE scanner alongside a viable AUTO fallback
3252 doesn't poison the result — we ignore PASSIVE and flip the AUTO.
3253 """
3254 manager = get_manager()
3255 sched = manager._auto_scheduler
3256 address = "11:22:33:44:55:19"
3257 cancel = manager.async_register_active_scan(
3258 address, scan_interval=120.0, scan_duration=6.0
3259 )
3260 owner = _DiscoverableAutoScanner("AA:00:00:00:19:01", BluetoothScanningMode.AUTO)
3261 passive = _DiscoverableAutoScanner(
3262 "AA:00:00:00:19:02", BluetoothScanningMode.PASSIVE
3263 )
3264 auto_fb = _DiscoverableAutoScanner("AA:00:00:00:19:03", BluetoothScanningMode.AUTO)
3265 c_owner = manager.async_register_scanner(owner)
3266 c_pass = manager.async_register_scanner(passive)
3267 c_auto = manager.async_register_scanner(auto_fb)
3268 try:
3269 _inject_with_rssi(owner, address, rssi=-50)
3270 # Passive has a much stronger RSSI to confirm we still ignore it.
3271 passive.add_discovered(address, rssi=-30)
3272 auto_fb.add_discovered(address, rssi=-70)
3273 owner._add_connecting(address)
3274 _make_due(sched, address)
3275 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
3276 await _run_worker_tick(sched, owner.source)
3277 assert owner.active_window_calls == []
3278 assert passive.active_window_calls == []
3279 assert auto_fb.active_window_calls == [6.0]
3280 assert not any(
3281 "no fallback scanner" in record.message for record in caplog.records
3282 )
3283 finally:
3284 owner._finished_connecting(address, connected=False)
3285 cancel()
3286 c_owner()
3287 c_pass()
3288 c_auto()
3289
3290
3291 @pytest.mark.asyncio
3292 async def test_worker_tick_passive_plus_active_active_covers(
3293 caplog: pytest.LogCaptureFixture,
3294 ) -> None:
3295 """
3296 PASSIVE + ACTIVE mix: ACTIVE covers, PASSIVE ignored, no warning.
3297
3298 No AUTO fallback exists, but an ACTIVE scanner sees the address —
3299 that's enough for "scan already in progress". The PASSIVE scanner
3300 is irrelevant.
3301 """
3302 manager = get_manager()
3303 sched = manager._auto_scheduler
3304 address = "11:22:33:44:55:1A"
3305 cancel = manager.async_register_active_scan(
3306 address, scan_interval=120.0, scan_duration=6.0
3307 )
3308 owner = _DiscoverableAutoScanner("AA:00:00:00:1A:01", BluetoothScanningMode.AUTO)
3309 passive = _DiscoverableAutoScanner(
3310 "AA:00:00:00:1A:02", BluetoothScanningMode.PASSIVE
3311 )
3312 active = _DiscoverableAutoScanner("AA:00:00:00:1A:03", BluetoothScanningMode.ACTIVE)
3313 c_owner = manager.async_register_scanner(owner)
3314 c_pass = manager.async_register_scanner(passive)
3315 c_active = manager.async_register_scanner(active)
3316 try:
3317 _inject_with_rssi(owner, address, rssi=-50)
3318 passive.add_discovered(address, rssi=-40)
3319 active.add_discovered(address, rssi=-70)
3320 owner._add_connecting(address)
3321 _make_due(sched, address)
3322 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
3323 await _run_worker_tick(sched, owner.source)
3324 assert owner.active_window_calls == []
3325 assert passive.active_window_calls == []
3326 assert active.active_window_calls == []
3327 assert not any(
3328 "no fallback scanner" in record.message for record in caplog.records
3329 )
3330 finally:
3331 owner._finished_connecting(address, connected=False)
3332 cancel()
3333 c_owner()
3334 c_pass()
3335 c_active()
3336
3337
3338 @pytest.mark.asyncio
3339 async def test_worker_tick_all_three_modes_active_wins(
3340 caplog: pytest.LogCaptureFixture,
3341 ) -> None:
3342 """
3343 PASSIVE + ACTIVE + AUTO all present: ACTIVE covers, no flip needed.
3344
3345 The dispatch must short-circuit on the ACTIVE coverage even when
3346 an AUTO fallback is also available. PASSIVE is ignored.
3347 """
3348 manager = get_manager()
3349 sched = manager._auto_scheduler
3350 address = "11:22:33:44:55:1B"
3351 cancel = manager.async_register_active_scan(
3352 address, scan_interval=120.0, scan_duration=6.0
3353 )
3354 owner = _DiscoverableAutoScanner("AA:00:00:00:1B:01", BluetoothScanningMode.AUTO)
3355 passive = _DiscoverableAutoScanner(
3356 "AA:00:00:00:1B:02", BluetoothScanningMode.PASSIVE
3357 )
3358 active = _DiscoverableAutoScanner("AA:00:00:00:1B:03", BluetoothScanningMode.ACTIVE)
3359 auto_fb = _DiscoverableAutoScanner("AA:00:00:00:1B:04", BluetoothScanningMode.AUTO)
3360 c_owner = manager.async_register_scanner(owner)
3361 c_pass = manager.async_register_scanner(passive)
3362 c_active = manager.async_register_scanner(active)
3363 c_auto = manager.async_register_scanner(auto_fb)
3364 try:
3365 _inject_with_rssi(owner, address, rssi=-50)
3366 passive.add_discovered(address, rssi=-40)
3367 active.add_discovered(address, rssi=-70)
3368 auto_fb.add_discovered(address, rssi=-55)
3369 owner._add_connecting(address)
3370 _make_due(sched, address)
3371 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
3372 await _run_worker_tick(sched, owner.source)
3373 # ACTIVE covers → no flip on anyone.
3374 assert owner.active_window_calls == []
3375 assert passive.active_window_calls == []
3376 assert active.active_window_calls == []
3377 assert auto_fb.active_window_calls == []
3378 assert not any(
3379 "no fallback scanner" in record.message for record in caplog.records
3380 )
3381 finally:
3382 owner._finished_connecting(address, connected=False)
3383 cancel()
3384 c_owner()
3385 c_pass()
3386 c_active()
3387 c_auto()
3388
3389
3390 @pytest.mark.asyncio
3391 async def test_worker_tick_three_way_mix_per_address(
3392 caplog: pytest.LogCaptureFixture,
3393 ) -> None:
3394 """
3395 Three addresses, three outcomes in one tick: covered, flipped, warned.
3396
3397 * addr_covered: only ACTIVE sees → covered, no flip, no warning.
3398 * addr_flipped: only AUTO sees → flipped on AUTO fallback.
3399 * addr_orphan: no fallback at all → single warning naming addr_orphan.
3400 """
3401 manager = get_manager()
3402 sched = manager._auto_scheduler
3403 addr_covered = "11:22:33:44:55:1C"
3404 addr_flipped = "11:22:33:44:55:1D"
3405 addr_orphan = "11:22:33:44:55:1E"
3406 c1 = manager.async_register_active_scan(
3407 addr_covered, scan_interval=120.0, scan_duration=6.0
3408 )
3409 c2 = manager.async_register_active_scan(
3410 addr_flipped, scan_interval=120.0, scan_duration=6.0
3411 )
3412 c3 = manager.async_register_active_scan(
3413 addr_orphan, scan_interval=120.0, scan_duration=6.0
3414 )
3415 owner = _DiscoverableAutoScanner("AA:00:00:00:1C:01", BluetoothScanningMode.AUTO)
3416 active = _DiscoverableAutoScanner("AA:00:00:00:1C:02", BluetoothScanningMode.ACTIVE)
3417 auto_fb = _DiscoverableAutoScanner("AA:00:00:00:1C:03", BluetoothScanningMode.AUTO)
3418 c_owner = manager.async_register_scanner(owner)
3419 c_active = manager.async_register_scanner(active)
3420 c_auto = manager.async_register_scanner(auto_fb)
3421 try:
3422 for addr in (addr_covered, addr_flipped, addr_orphan):
3423 _inject_with_rssi(owner, addr, rssi=-50)
3424 active.add_discovered(addr_covered, rssi=-60)
3425 auto_fb.add_discovered(addr_flipped, rssi=-60)
3426 owner._add_connecting(addr_covered)
3427 for addr in (addr_covered, addr_flipped, addr_orphan):
3428 _make_due(sched, addr)
3429 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
3430 await _run_worker_tick(sched, owner.source)
3431 assert owner.active_window_calls == []
3432 assert active.active_window_calls == []
3433 assert auto_fb.active_window_calls == [6.0]
3434 warnings_for_orphan = [
3435 record
3436 for record in caplog.records
3437 if "no fallback scanner" in record.message and addr_orphan in record.message
3438 ]
3439 assert len(warnings_for_orphan) == 1
3440 # Covered/flipped addresses must not appear in any no-fallback warning.
3441 assert not any(
3442 "no fallback scanner" in record.message and addr_covered in record.message
3443 for record in caplog.records
3444 )
3445 assert not any(
3446 "no fallback scanner" in record.message and addr_flipped in record.message
3447 for record in caplog.records
3448 )
3449 finally:
3450 owner._finished_connecting(addr_covered, connected=False)
3451 c1()
3452 c2()
3453 c3()
3454 c_owner()
3455 c_active()
3456 c_auto()
3457
3458
3459 @pytest.mark.asyncio
3460 async def test_worker_tick_owner_connecting_different_address_still_delegates() -> None:
3461 """
3462 The connecting-phase signal is per-scanner, not per-address.
3463
3464 The owner is in a connect attempt to address X, while the due
3465 per-device window is for address Y. The owner's radio is still
3466 busy with X's connect, so Y must be delegated to a fallback too.
3467 """
3468 manager = get_manager()
3469 sched = manager._auto_scheduler
3470 addr_due = "11:22:33:44:55:1F"
3471 addr_connecting = "AA:BB:CC:DD:EE:99"
3472 cancel = manager.async_register_active_scan(
3473 addr_due, scan_interval=120.0, scan_duration=6.0
3474 )
3475 owner = _DiscoverableAutoScanner("AA:00:00:00:1F:01", BluetoothScanningMode.AUTO)
3476 fb = _DiscoverableAutoScanner("AA:00:00:00:1F:02", BluetoothScanningMode.AUTO)
3477 c_owner = manager.async_register_scanner(owner)
3478 c_fb = manager.async_register_scanner(fb)
3479 try:
3480 _inject_with_rssi(owner, addr_due, rssi=-50)
3481 fb.add_discovered(addr_due, rssi=-60)
3482 # Connect-in-progress is for a different address.
3483 owner._add_connecting(addr_connecting)
3484 _make_due(sched, addr_due)
3485 await _run_worker_tick(sched, owner.source)
3486 assert owner.active_window_calls == []
3487 assert fb.active_window_calls == [6.0]
3488 finally:
3489 owner._finished_connecting(addr_connecting, connected=False)
3490 cancel()
3491 c_owner()
3492 c_fb()
3493
3494
3495 @pytest.mark.asyncio
3496 async def test_worker_tick_fallback_returning_false_does_not_warn(
3497 caplog: pytest.LogCaptureFixture,
3498 ) -> None:
3499 """
3500 A fallback returning False from async_request_active_window is silent.
3501
3502 The helper's contract is "True = window armed/extended,
3503 False = refused" — both are terminal answers. We consume the
3504 call without raising and without warning, consistent with the
3505 non-connecting path that also ignores the return value.
3506 """
3507 manager = get_manager()
3508 sched = manager._auto_scheduler
3509 address = "11:22:33:44:55:20"
3510 cancel = manager.async_register_active_scan(
3511 address, scan_interval=120.0, scan_duration=6.0
3512 )
3513 owner = _DiscoverableAutoScanner("AA:00:00:00:20:01", BluetoothScanningMode.AUTO)
3514 fb = _DiscoverableAutoScanner("AA:00:00:00:20:02", BluetoothScanningMode.AUTO)
3515 fb._return_value = False
3516 c_owner = manager.async_register_scanner(owner)
3517 c_fb = manager.async_register_scanner(fb)
3518 try:
3519 _inject_with_rssi(owner, address, rssi=-50)
3520 fb.add_discovered(address, rssi=-60)
3521 owner._add_connecting(address)
3522 _make_due(sched, address)
3523 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
3524 await _run_worker_tick(sched, owner.source)
3525 # Call was made, no warning, no exception escaped.
3526 assert fb.active_window_calls == [6.0]
3527 assert owner.active_window_calls == []
3528 assert not any(
3529 "no fallback scanner" in record.message for record in caplog.records
3530 )
3531 finally:
3532 owner._finished_connecting(address, connected=False)
3533 cancel()
3534 c_owner()
3535 c_fb()
3536
3537
3538 @pytest.mark.asyncio
3539 async def test_worker_tick_non_connectable_auto_fallback_is_eligible() -> None:
3540 """
3541 A non-connectable AUTO scanner is a valid fallback for scanning.
3542
3543 Fallback selection is about *scanning*, not connecting — a
3544 non-connectable scanner that can see the device is just as good
3545 for an active-window flip as a connectable one.
3546 ``async_scanner_devices_by_address(address, False)`` is called
3547 with ``connectable=False`` so both lists are considered.
3548 """
3549 manager = get_manager()
3550 sched = manager._auto_scheduler
3551 address = "11:22:33:44:55:21"
3552 cancel = manager.async_register_active_scan(
3553 address, scan_interval=120.0, scan_duration=6.0
3554 )
3555 owner = _DiscoverableAutoScanner("AA:00:00:00:21:01", BluetoothScanningMode.AUTO)
3556 fb = _DiscoverableAutoScanner(
3557 "AA:00:00:00:21:02", BluetoothScanningMode.AUTO, connectable=False
3558 )
3559 c_owner = manager.async_register_scanner(owner)
3560 c_fb = manager.async_register_scanner(fb)
3561 try:
3562 _inject_with_rssi(owner, address, rssi=-50)
3563 fb.add_discovered(address, rssi=-60)
3564 owner._add_connecting(address)
3565 _make_due(sched, address)
3566 await _run_worker_tick(sched, owner.source)
3567 assert owner.active_window_calls == []
3568 assert fb.active_window_calls == [6.0]
3569 finally:
3570 owner._finished_connecting(address, connected=False)
3571 cancel()
3572 c_owner()
3573 c_fb()
3574
3575
3576 @pytest.mark.asyncio
3577 async def test_worker_tick_connect_starting_after_check_still_runs_locally() -> None:
3578 """
3579 Race: a connect that starts AFTER the connecting check still hits the owner.
3580
3581 The connecting-state snapshot is taken once at the top of
3582 ``_tick``. If a connect begins between that check and the
3583 ``async_request_active_window`` await on the owner, the call has
3584 already been committed — we do not re-check mid-dispatch. The
3585 test pins this contract: ``_add_connecting`` after the call has
3586 started must not flip dispatch to a fallback for THIS tick.
3587 The next tick will see the new connecting state.
3588 """
3589 manager = get_manager()
3590 sched = manager._auto_scheduler
3591 address = "11:22:33:44:55:22"
3592 cancel = manager.async_register_active_scan(
3593 address, scan_interval=120.0, scan_duration=6.0
3594 )
3595 owner = _DiscoverableAutoScanner("AA:00:00:00:22:01", BluetoothScanningMode.AUTO)
3596 fb = _DiscoverableAutoScanner("AA:00:00:00:22:02", BluetoothScanningMode.AUTO)
3597 owner._block_event = asyncio.Event()
3598 c_owner = manager.async_register_scanner(owner)
3599 c_fb = manager.async_register_scanner(fb)
3600 try:
3601 _inject_with_rssi(owner, address, rssi=-50)
3602 fb.add_discovered(address, rssi=-60)
3603 # Owner NOT connecting at tick start.
3604 _make_due(sched, address)
3605 tick_task = asyncio.create_task(_run_worker_tick(sched, owner.source))
3606 # Yield so the worker enters its await on owner.async_request_active_window
3607 # (which is blocked on owner._block_event).
3608 await asyncio.sleep(0)
3609 assert owner.active_window_calls == [6.0]
3610 # Race window: connect starts after the check, while the
3611 # owner call is in flight. The mid-flight call must not be
3612 # diverted; the fallback must not be called for THIS tick.
3613 owner._add_connecting(address)
3614 owner._block_event.set()
3615 await tick_task
3616 assert fb.active_window_calls == []
3617 finally:
3618 owner._finished_connecting(address, connected=False)
3619 cancel()
3620 c_owner()
3621 c_fb()
3622
3623
3624 @pytest.mark.asyncio
3625 async def test_worker_tick_connect_finish_during_dispatch_keeps_dispatch() -> None:
3626 """
3627 Race: owner finishes connecting WHILE the fallback dispatch is awaiting.
3628
3629 The connecting state was True at tick start, so we entered the
3630 fallback branch and already advanced ``_due_at``. The connect
3631 completing mid-await must not cancel the in-flight fallback call
3632 nor cause a duplicate window on the owner.
3633 """
3634 manager = get_manager()
3635 sched = manager._auto_scheduler
3636 address = "11:22:33:44:55:23"
3637 cancel = manager.async_register_active_scan(
3638 address, scan_interval=120.0, scan_duration=6.0
3639 )
3640 owner = _DiscoverableAutoScanner("AA:00:00:00:23:01", BluetoothScanningMode.AUTO)
3641 fb = _DiscoverableAutoScanner("AA:00:00:00:23:02", BluetoothScanningMode.AUTO)
3642 fb._block_event = asyncio.Event()
3643 c_owner = manager.async_register_scanner(owner)
3644 c_fb = manager.async_register_scanner(fb)
3645 try:
3646 _inject_with_rssi(owner, address, rssi=-50)
3647 fb.add_discovered(address, rssi=-60)
3648 owner._add_connecting(address)
3649 _make_due(sched, address)
3650 tick_task = asyncio.create_task(_run_worker_tick(sched, owner.source))
3651 # Yield so the worker enters its await on the blocked fallback.
3652 await asyncio.sleep(0)
3653 assert fb.active_window_calls == [6.0]
3654 # Connect finishes mid-dispatch.
3655 owner._finished_connecting(address, connected=True)
3656 assert owner._connections_in_progress() == 0
3657 # Unblock the fallback so the dispatch can complete.
3658 fb._block_event.set()
3659 await tick_task
3660 # Dispatch completed on the fallback only; owner stayed
3661 # untouched for this tick.
3662 assert fb.active_window_calls == [6.0]
3663 assert owner.active_window_calls == []
3664 finally:
3665 cancel()
3666 c_owner()
3667 c_fb()
3668
3669
3670 @pytest.mark.asyncio
3671 async def test_worker_tick_two_owners_delegate_to_same_fallback_concurrently() -> None:
3672 """
3673 Cross-tick: two owner workers concurrently delegate to one fallback.
3674
3675 The auto_scheduler doesn't serialize across workers — both
3676 deliveries go through. The scanner-level
3677 ``_active_window_handle`` / ``_start_stop_lock`` extend-if-extends
3678 logic is what guarantees the radio doesn't double-flip. Here we
3679 verify the auto_scheduler delivers both calls cleanly without
3680 deadlock or exception.
3681 """
3682 manager = get_manager()
3683 sched = manager._auto_scheduler
3684 addr_a = "11:22:33:44:55:24"
3685 addr_b = "11:22:33:44:55:25"
3686 c1 = manager.async_register_active_scan(
3687 addr_a, scan_interval=120.0, scan_duration=6.0
3688 )
3689 c2 = manager.async_register_active_scan(
3690 addr_b, scan_interval=120.0, scan_duration=8.0
3691 )
3692 owner_a = _DiscoverableAutoScanner("AA:00:00:00:24:01", BluetoothScanningMode.AUTO)
3693 owner_b = _DiscoverableAutoScanner("AA:00:00:00:24:02", BluetoothScanningMode.AUTO)
3694 fb = _DiscoverableAutoScanner("AA:00:00:00:24:03", BluetoothScanningMode.AUTO)
3695 c_a = manager.async_register_scanner(owner_a)
3696 c_b = manager.async_register_scanner(owner_b)
3697 c_fb = manager.async_register_scanner(fb)
3698 try:
3699 _inject_with_rssi(owner_a, addr_a, rssi=-50)
3700 _inject_with_rssi(owner_b, addr_b, rssi=-50)
3701 fb.add_discovered(addr_a, rssi=-60)
3702 fb.add_discovered(addr_b, rssi=-60)
3703 owner_a._add_connecting(addr_a)
3704 owner_b._add_connecting(addr_b)
3705 _make_due(sched, addr_a)
3706 _make_due(sched, addr_b)
3707 await asyncio.gather(
3708 _run_worker_tick(sched, owner_a.source),
3709 _run_worker_tick(sched, owner_b.source),
3710 )
3711 # Both owners delegated to fb; both calls were delivered.
3712 assert sorted(fb.active_window_calls) == [6.0, 8.0]
3713 assert owner_a.active_window_calls == []
3714 assert owner_b.active_window_calls == []
3715 finally:
3716 owner_a._finished_connecting(addr_a, connected=False)
3717 owner_b._finished_connecting(addr_b, connected=False)
3718 c1()
3719 c2()
3720 c_a()
3721 c_b()
3722 c_fb()
3723
3724
3725 @pytest.mark.asyncio
3726 async def test_worker_tick_ownership_flip_during_dispatch_no_double_fire() -> None:
3727 """
3728 Race: ownership flips from owner to fallback during the dispatch.
3729
3730 Same protection as the non-connecting migration test: the
3731 pre-await ``_advance_due`` updates ``_due_at`` to ``now +
3732 scan_interval`` before the fallback await, so if RSSI causes
3733 ownership to shift to the fallback mid-dispatch, the fallback's
3734 own next tick sees a future due time and skips — no duplicate
3735 window fires on the new owner.
3736 """
3737 manager = get_manager()
3738 sched = manager._auto_scheduler
3739 loop = asyncio.get_running_loop()
3740 address = "11:22:33:44:55:26"
3741 cancel = manager.async_register_active_scan(
3742 address, scan_interval=90.0, scan_duration=6.0
3743 )
3744 owner = _DiscoverableAutoScanner("AA:00:00:00:26:01", BluetoothScanningMode.AUTO)
3745 fb = _DiscoverableAutoScanner("AA:00:00:00:26:02", BluetoothScanningMode.AUTO)
3746 fb._block_event = asyncio.Event()
3747 c_owner = manager.async_register_scanner(owner)
3748 c_fb = manager.async_register_scanner(fb)
3749 try:
3750 _inject_with_rssi(owner, address, rssi=-80)
3751 fb.add_discovered(address, rssi=-60)
3752 owner._add_connecting(address)
3753 _make_due(sched, address)
3754 before = loop.time()
3755 tick_task = asyncio.create_task(_run_worker_tick(sched, owner.source))
3756 await asyncio.sleep(0)
3757 # Confirm fallback call is in flight and entries advanced.
3758 assert fb.active_window_calls == [6.0]
3759 entries = sched._schedule._due_at[address]
3760 for due in entries.values():
3761 assert due == pytest.approx(before + 90.0, abs=0.5)
3762 # Ownership flips to fb mid-dispatch (much stronger RSSI).
3763 _inject_with_rssi(fb, address, rssi=-30)
3764 info = manager.async_last_service_info(address, False)
3765 assert info is not None
3766 assert info.source == fb.source
3767 # fb's own next tick must skip because entries are already advanced.
3768 fb._block_event.set()
3769 await tick_task
3770 await sched._workers[fb.source]._tick()
3771 # Only one call landed on fb; no double-fire.
3772 assert fb.active_window_calls == [6.0]
3773 assert owner.active_window_calls == []
3774 finally:
3775 owner._finished_connecting(address, connected=False)
3776 cancel()
3777 c_owner()
3778 c_fb()
3779
3780
3781 @pytest.mark.asyncio
3782 async def test_worker_tick_resolver_excludes_owner_when_owner_self_reports() -> None:
3783 """
3784 The owner's own source is skipped even if it appears in the scanner list.
3785
3786 If the owner's ``get_discovered_device_advertisement_data`` returns
3787 non-None for the address (so the manager lists it among the
3788 scanner-devices), the resolver must still skip it via the
3789 ``scanner.source == exclude_source`` guard rather than picking the
3790 busy owner as its own fallback.
3791 """
3792 manager = get_manager()
3793 sched = manager._auto_scheduler
3794 address = "11:22:33:44:55:27"
3795 cancel = manager.async_register_active_scan(
3796 address, scan_interval=120.0, scan_duration=6.0
3797 )
3798 owner = _DiscoverableAutoScanner("AA:00:00:00:27:01", BluetoothScanningMode.AUTO)
3799 fb = _DiscoverableAutoScanner("AA:00:00:00:27:02", BluetoothScanningMode.AUTO)
3800 c_owner = manager.async_register_scanner(owner)
3801 c_fb = manager.async_register_scanner(fb)
3802 try:
3803 _inject_with_rssi(owner, address, rssi=-50)
3804 # Owner self-reports: would normally be sorted as the highest-RSSI
3805 # candidate, but the resolver must exclude itself.
3806 owner.add_discovered(address, rssi=-30)
3807 fb.add_discovered(address, rssi=-70)
3808 owner._add_connecting(address)
3809 _make_due(sched, address)
3810 await _run_worker_tick(sched, owner.source)
3811 # Owner skipped despite self-reporting; weaker fallback wins.
3812 assert owner.active_window_calls == []
3813 assert fb.active_window_calls == [6.0]
3814 finally:
3815 owner._finished_connecting(address, connected=False)
3816 cancel()
3817 c_owner()
3818 c_fb()
3819
3820
3821 @pytest.mark.asyncio
3822 async def test_worker_tick_dispatch_advances_fallback_sweep_clock() -> None:
3823 """
3824 Delegating an active window to a fallback advances its sweep clock.
3825
3826 The fallback's radio is actively scanning for ``duration`` seconds,
3827 which subsumes the work its own rediscovery sweep would do. We
3828 bump ``_sweep_last_completed = now`` so the fallback doesn't
3829 immediately schedule another sweep window on top of the one we
3830 just triggered.
3831 """
3832 manager = get_manager()
3833 sched = manager._auto_scheduler
3834 loop = asyncio.get_running_loop()
3835 address = "11:22:33:44:55:28"
3836 cancel = manager.async_register_active_scan(
3837 address, scan_interval=120.0, scan_duration=6.0
3838 )
3839 owner = _DiscoverableAutoScanner("AA:00:00:00:28:01", BluetoothScanningMode.AUTO)
3840 fb = _DiscoverableAutoScanner("AA:00:00:00:28:02", BluetoothScanningMode.AUTO)
3841 c_owner = manager.async_register_scanner(owner)
3842 c_fb = manager.async_register_scanner(fb)
3843 try:
3844 _inject_with_rssi(owner, address, rssi=-50)
3845 fb.add_discovered(address, rssi=-60)
3846 # Make fb's own sweep imminent so we can detect the advance.
3847 fb_worker = sched._workers[fb.source]
3848 fb_worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
3849 sweep_before = fb_worker._sweep_last_completed
3850 owner._add_connecting(address)
3851 _make_due(sched, address)
3852 before = loop.time()
3853 await _run_worker_tick(sched, owner.source)
3854 assert fb.active_window_calls == [6.0]
3855 # Sweep clock advanced to ~now so fb won't immediately resweep.
3856 assert fb_worker._sweep_last_completed > sweep_before
3857 assert fb_worker._sweep_last_completed >= before
3858 finally:
3859 owner._finished_connecting(address, connected=False)
3860 cancel()
3861 c_owner()
3862 c_fb()
3863
3864
3865 @pytest.mark.asyncio
3866 async def test_worker_tick_dispatch_sets_fallback_window_end() -> None:
3867 """
3868 Delegation marks the fallback worker as in-window for ``duration``.
3869
3870 With ``fb._window_end > now``, the fallback's own ``_tick`` and
3871 ``_next_event_at`` short-circuit during the delegated window so
3872 the fallback doesn't redundantly tick on its own due work for the
3873 duration of the active scan it is already running.
3874 """
3875 manager = get_manager()
3876 sched = manager._auto_scheduler
3877 loop = asyncio.get_running_loop()
3878 address = "11:22:33:44:55:29"
3879 cancel = manager.async_register_active_scan(
3880 address, scan_interval=120.0, scan_duration=6.0
3881 )
3882 owner = _DiscoverableAutoScanner("AA:00:00:00:29:01", BluetoothScanningMode.AUTO)
3883 fb = _DiscoverableAutoScanner("AA:00:00:00:29:02", BluetoothScanningMode.AUTO)
3884 c_owner = manager.async_register_scanner(owner)
3885 c_fb = manager.async_register_scanner(fb)
3886 try:
3887 _inject_with_rssi(owner, address, rssi=-50)
3888 fb.add_discovered(address, rssi=-60)
3889 owner._add_connecting(address)
3890 _make_due(sched, address)
3891 before = loop.time()
3892 await _run_worker_tick(sched, owner.source)
3893 fb_worker = sched._workers[fb.source]
3894 # Window-end bumped roughly to before + duration.
3895 assert fb_worker._window_end >= before + 5.0
3896 assert fb_worker._window_end <= loop.time() + 7.0
3897 # A fb tick while _window_end > now must short-circuit
3898 # (no async_request_active_window call recorded).
3899 calls_before = list(fb.active_window_calls)
3900 await fb_worker._tick()
3901 assert fb.active_window_calls == calls_before
3902 finally:
3903 owner._finished_connecting(address, connected=False)
3904 cancel()
3905 c_owner()
3906 c_fb()
3907
3908
3909 @pytest.mark.asyncio
3910 async def test_worker_tick_dispatch_does_not_shrink_existing_fallback_window() -> None:
3911 """
3912 A larger pre-existing ``_window_end`` on the fallback is preserved.
3913
3914 If the fallback is already running a longer window when we
3915 delegate (e.g., a much earlier delegation from another owner
3916 extended its own ``_window_end``), our shorter delegation must
3917 not shrink it back.
3918 """
3919 manager = get_manager()
3920 sched = manager._auto_scheduler
3921 loop = asyncio.get_running_loop()
3922 address = "11:22:33:44:55:2A"
3923 cancel = manager.async_register_active_scan(
3924 address, scan_interval=120.0, scan_duration=5.0
3925 )
3926 owner = _DiscoverableAutoScanner("AA:00:00:00:2A:01", BluetoothScanningMode.AUTO)
3927 fb = _DiscoverableAutoScanner("AA:00:00:00:2A:02", BluetoothScanningMode.AUTO)
3928 c_owner = manager.async_register_scanner(owner)
3929 c_fb = manager.async_register_scanner(fb)
3930 try:
3931 _inject_with_rssi(owner, address, rssi=-50)
3932 fb.add_discovered(address, rssi=-60)
3933 fb_worker = sched._workers[fb.source]
3934 # Pre-seed a longer pending window on the fallback.
3935 existing_window_end = loop.time() + 60.0
3936 fb_worker._window_end = existing_window_end
3937 owner._add_connecting(address)
3938 _make_due(sched, address)
3939 await _run_worker_tick(sched, owner.source)
3940 # The shorter (5s) delegation must not have shrunk the
3941 # existing 60s window.
3942 assert fb_worker._window_end == existing_window_end
3943 finally:
3944 owner._finished_connecting(address, connected=False)
3945 cancel()
3946 c_owner()
3947 c_fb()
3948
3949
3950 @pytest.mark.asyncio
3951 async def test_worker_tick_three_addresses_same_fallback_coalesce_to_max() -> None:
3952 """
3953 Three due addresses with distinct durations on one fallback coalesce to max.
3954
3955 Confirms per-fallback coalescing picks the max
3956 ``scan_duration`` over all grouped requests, not the first.
3957 """
3958 manager = get_manager()
3959 sched = manager._auto_scheduler
3960 addr_a = "11:22:33:44:55:2B"
3961 addr_b = "11:22:33:44:55:2C"
3962 addr_c = "11:22:33:44:55:2D"
3963 c1 = manager.async_register_active_scan(
3964 addr_a, scan_interval=120.0, scan_duration=6.0
3965 )
3966 c2 = manager.async_register_active_scan(
3967 addr_b, scan_interval=120.0, scan_duration=11.0
3968 )
3969 c3 = manager.async_register_active_scan(
3970 addr_c, scan_interval=120.0, scan_duration=8.0
3971 )
3972 owner = _DiscoverableAutoScanner("AA:00:00:00:2B:01", BluetoothScanningMode.AUTO)
3973 fb = _DiscoverableAutoScanner("AA:00:00:00:2B:02", BluetoothScanningMode.AUTO)
3974 c_owner = manager.async_register_scanner(owner)
3975 c_fb = manager.async_register_scanner(fb)
3976 try:
3977 for addr in (addr_a, addr_b, addr_c):
3978 _inject_with_rssi(owner, addr, rssi=-50)
3979 fb.add_discovered(addr, rssi=-60)
3980 owner._add_connecting(addr_a)
3981 for addr in (addr_a, addr_b, addr_c):
3982 _make_due(sched, addr)
3983 await _run_worker_tick(sched, owner.source)
3984 # Single call to the shared fallback at max(6, 11, 8) = 11.
3985 assert fb.active_window_calls == [11.0]
3986 assert owner.active_window_calls == []
3987 finally:
3988 owner._finished_connecting(addr_a, connected=False)
3989 c1()
3990 c2()
3991 c3()
3992 c_owner()
3993 c_fb()
3994
3995
3996 @pytest.mark.asyncio
3997 async def test_worker_tick_three_addresses_three_fallbacks_each_own_duration() -> None:
3998 """Three due addresses on three fallbacks, each call uses its own duration."""
3999 manager = get_manager()
4000 sched = manager._auto_scheduler
4001 addr_a = "11:22:33:44:55:2E"
4002 addr_b = "11:22:33:44:55:2F"
4003 addr_c = "11:22:33:44:55:30"
4004 c1 = manager.async_register_active_scan(
4005 addr_a, scan_interval=120.0, scan_duration=6.0
4006 )
4007 c2 = manager.async_register_active_scan(
4008 addr_b, scan_interval=180.0, scan_duration=9.0
4009 )
4010 c3 = manager.async_register_active_scan(
4011 addr_c, scan_interval=240.0, scan_duration=12.0
4012 )
4013 owner = _DiscoverableAutoScanner("AA:00:00:00:2E:01", BluetoothScanningMode.AUTO)
4014 fb_a = _DiscoverableAutoScanner("AA:00:00:00:2E:02", BluetoothScanningMode.AUTO)
4015 fb_b = _DiscoverableAutoScanner("AA:00:00:00:2E:03", BluetoothScanningMode.AUTO)
4016 fb_c = _DiscoverableAutoScanner("AA:00:00:00:2E:04", BluetoothScanningMode.AUTO)
4017 c_owner = manager.async_register_scanner(owner)
4018 c_a = manager.async_register_scanner(fb_a)
4019 c_b = manager.async_register_scanner(fb_b)
4020 c_c = manager.async_register_scanner(fb_c)
4021 try:
4022 _inject_with_rssi(owner, addr_a, rssi=-50)
4023 _inject_with_rssi(owner, addr_b, rssi=-50)
4024 _inject_with_rssi(owner, addr_c, rssi=-50)
4025 fb_a.add_discovered(addr_a, rssi=-60)
4026 fb_b.add_discovered(addr_b, rssi=-60)
4027 fb_c.add_discovered(addr_c, rssi=-60)
4028 owner._add_connecting(addr_a)
4029 for addr in (addr_a, addr_b, addr_c):
4030 _make_due(sched, addr)
4031 await _run_worker_tick(sched, owner.source)
4032 assert fb_a.active_window_calls == [6.0]
4033 assert fb_b.active_window_calls == [9.0]
4034 assert fb_c.active_window_calls == [12.0]
4035 assert owner.active_window_calls == []
4036 finally:
4037 owner._finished_connecting(addr_a, connected=False)
4038 c1()
4039 c2()
4040 c3()
4041 c_owner()
4042 c_a()
4043 c_b()
4044 c_c()
4045
4046
4047 @pytest.mark.asyncio
4048 async def test_worker_tick_three_addresses_no_fallback_advance_by_defer() -> None:
4049 """
4050 No-fallback advance uses ``_AUTO_CONNECTING_DEFER``, not scan_interval.
4051
4052 Three addresses with very different ``scan_interval``s
4053 (120/600/3600s) must all be advanced to ~now + 30s so the next
4054 tick retries shortly after the connect completes.
4055 """
4056 manager = get_manager()
4057 sched = manager._auto_scheduler
4058 loop = asyncio.get_running_loop()
4059 addr_a = "11:22:33:44:55:31"
4060 addr_b = "11:22:33:44:55:32"
4061 addr_c = "11:22:33:44:55:33"
4062 c1 = manager.async_register_active_scan(
4063 addr_a, scan_interval=120.0, scan_duration=6.0
4064 )
4065 c2 = manager.async_register_active_scan(
4066 addr_b, scan_interval=600.0, scan_duration=9.0
4067 )
4068 c3 = manager.async_register_active_scan(
4069 addr_c, scan_interval=3600.0, scan_duration=12.0
4070 )
4071 owner = _DiscoverableAutoScanner("AA:00:00:00:31:01", BluetoothScanningMode.AUTO)
4072 c_owner = manager.async_register_scanner(owner)
4073 try:
4074 for addr in (addr_a, addr_b, addr_c):
4075 _inject_with_rssi(owner, addr, rssi=-50)
4076 _make_due(sched, addr)
4077 owner._add_connecting(addr_a)
4078 before = loop.time()
4079 await _run_worker_tick(sched, owner.source)
4080 for addr in (addr_a, addr_b, addr_c):
4081 entries = sched._schedule._due_at[addr]
4082 for due in entries.values():
4083 assert due == pytest.approx(before + 30.0, abs=0.5)
4084 assert due < before + 60.0
4085 finally:
4086 owner._finished_connecting(addr_a, connected=False)
4087 c1()
4088 c2()
4089 c3()
4090 c_owner()
4091
4092
4093 @pytest.mark.asyncio
4094 async def test_note_window_dispatched_preserves_more_recent_sweep() -> None:
4095 """
4096 ``note_window_dispatched`` does not move ``_sweep_last_completed`` backwards.
4097
4098 Covers the False branch of ``if self._sweep_last_completed < now``
4099 when the fallback's sweep clock is already further in the future
4100 than the ``now`` we're passing in.
4101 """
4102 manager = get_manager()
4103 sched = manager._auto_scheduler
4104 loop = asyncio.get_running_loop()
4105 address = "11:22:33:44:55:38"
4106 cancel = manager.async_register_active_scan(
4107 address, scan_interval=120.0, scan_duration=6.0
4108 )
4109 owner = _DiscoverableAutoScanner("AA:00:00:00:38:01", BluetoothScanningMode.AUTO)
4110 fb = _DiscoverableAutoScanner("AA:00:00:00:38:02", BluetoothScanningMode.AUTO)
4111 c_owner = manager.async_register_scanner(owner)
4112 c_fb = manager.async_register_scanner(fb)
4113 try:
4114 _inject_with_rssi(owner, address, rssi=-50)
4115 fb.add_discovered(address, rssi=-60)
4116 fb_worker = sched._workers[fb.source]
4117 future_sweep = loop.time() + 600.0
4118 fb_worker._sweep_last_completed = future_sweep
4119 owner._add_connecting(address)
4120 _make_due(sched, address)
4121 await _run_worker_tick(sched, owner.source)
4122 # Sweep clock not moved backwards by our note_window_dispatched.
4123 assert fb_worker._sweep_last_completed == future_sweep
4124 assert fb.active_window_calls == [6.0]
4125 finally:
4126 owner._finished_connecting(address, connected=False)
4127 cancel()
4128 c_owner()
4129 c_fb()
4130
4131
4132 @pytest.mark.asyncio
4133 async def test_worker_tick_dispatch_handles_missing_fallback_worker() -> None:
4134 """
4135 Dispatch tolerates ``workers.get(fb.source) is None``.
4136
4137 Covers the False branch of ``if fb_worker is not None``. Reachable
4138 when a fallback scanner is unregistered between resolution and the
4139 per-fallback iteration (sim: drop the worker entry between
4140 registration and tick to force the lookup miss). The dispatch
4141 should still call ``async_request_active_window`` on the fallback
4142 even with no worker available to receive ``note_window_dispatched``.
4143 """
4144 manager = get_manager()
4145 sched = manager._auto_scheduler
4146 address = "11:22:33:44:55:37"
4147 cancel = manager.async_register_active_scan(
4148 address, scan_interval=120.0, scan_duration=6.0
4149 )
4150 owner = _DiscoverableAutoScanner("AA:00:00:00:37:01", BluetoothScanningMode.AUTO)
4151 fb = _DiscoverableAutoScanner("AA:00:00:00:37:02", BluetoothScanningMode.AUTO)
4152 c_owner = manager.async_register_scanner(owner)
4153 c_fb = manager.async_register_scanner(fb)
4154 try:
4155 _inject_with_rssi(owner, address, rssi=-50)
4156 fb.add_discovered(address, rssi=-60)
4157 owner._add_connecting(address)
4158 _make_due(sched, address)
4159 # Drop fb's worker so workers.get(fb.source) is None during dispatch.
4160 # The fb scanner is still registered (so resolve still picks it)
4161 # and async_scanner_devices_by_address still returns it.
4162 sched._workers.pop(fb.source)
4163 await _run_worker_tick(sched, owner.source)
4164 # Dispatch still happened on the fallback's scanner even though
4165 # we couldn't notify the worker.
4166 assert fb.active_window_calls == [6.0]
4167 assert owner.active_window_calls == []
4168 finally:
4169 owner._finished_connecting(address, connected=False)
4170 cancel()
4171 c_owner()
4172 c_fb()
4173
4174
4175 @pytest.mark.asyncio
4176 async def test_worker_tick_three_addresses_mixed_outcomes_advance_correctly() -> None:
4177 """
4178 Three addresses, three outcomes, each advanced per its outcome.
4179
4180 covered (ACTIVE) -> ``scan_interval`` (full cadence).
4181 AUTO fallback -> ``scan_interval`` (full cadence).
4182 no fallback -> ``_AUTO_CONNECTING_DEFER`` (short retry).
4183 """
4184 manager = get_manager()
4185 sched = manager._auto_scheduler
4186 loop = asyncio.get_running_loop()
4187 addr_covered = "11:22:33:44:55:34"
4188 addr_flipped = "11:22:33:44:55:35"
4189 addr_orphan = "11:22:33:44:55:36"
4190 c1 = manager.async_register_active_scan(
4191 addr_covered, scan_interval=120.0, scan_duration=6.0
4192 )
4193 c2 = manager.async_register_active_scan(
4194 addr_flipped, scan_interval=240.0, scan_duration=9.0
4195 )
4196 c3 = manager.async_register_active_scan(
4197 addr_orphan, scan_interval=600.0, scan_duration=12.0
4198 )
4199 owner = _DiscoverableAutoScanner("AA:00:00:00:34:01", BluetoothScanningMode.AUTO)
4200 active = _DiscoverableAutoScanner("AA:00:00:00:34:02", BluetoothScanningMode.ACTIVE)
4201 fb = _DiscoverableAutoScanner("AA:00:00:00:34:03", BluetoothScanningMode.AUTO)
4202 c_owner = manager.async_register_scanner(owner)
4203 c_active = manager.async_register_scanner(active)
4204 c_fb = manager.async_register_scanner(fb)
4205 try:
4206 for addr in (addr_covered, addr_flipped, addr_orphan):
4207 _inject_with_rssi(owner, addr, rssi=-50)
4208 _make_due(sched, addr)
4209 active.add_discovered(addr_covered, rssi=-60)
4210 fb.add_discovered(addr_flipped, rssi=-60)
4211 owner._add_connecting(addr_covered)
4212 before = loop.time()
4213 await _run_worker_tick(sched, owner.source)
4214 for due in sched._schedule._due_at[addr_covered].values():
4215 assert due == pytest.approx(before + 120.0, abs=0.5)
4216 for due in sched._schedule._due_at[addr_flipped].values():
4217 assert due == pytest.approx(before + 240.0, abs=0.5)
4218 for due in sched._schedule._due_at[addr_orphan].values():
4219 assert due == pytest.approx(before + 30.0, abs=0.5)
4220 assert fb.active_window_calls == [9.0]
4221 assert active.active_window_calls == []
4222 assert owner.active_window_calls == []
4223 finally:
4224 owner._finished_connecting(addr_covered, connected=False)
4225 c1()
4226 c2()
4227 c3()
4228 c_owner()
4229 c_active()
4230 c_fb()
4231
4232
4233 @pytest.mark.asyncio
4234 async def test_worker_tick_fallback_with_none_rssi_is_still_dispatched() -> None:
4235 """
4236 A fallback whose last advertisement has ``rssi is None`` is usable.
4237
4238 Pins Kōan blocker #1: ``_resolve_fallback_for_address`` must not
4239 crash on ``None`` RSSI (would raise ``TypeError`` on ``None >
4240 -10_000``). The defensive ``rssi or NO_RSSI_VALUE`` normalization
4241 keeps the scanner in the candidate pool with the sentinel score.
4242 Here the single fallback has ``rssi=None`` and the dispatch must
4243 still fire on it.
4244 """
4245 manager = get_manager()
4246 sched = manager._auto_scheduler
4247 address = "11:22:33:44:55:39"
4248 cancel = manager.async_register_active_scan(
4249 address, scan_interval=120.0, scan_duration=6.0
4250 )
4251 owner = _DiscoverableAutoScanner("AA:00:00:00:39:01", BluetoothScanningMode.AUTO)
4252 fb = _DiscoverableAutoScanner("AA:00:00:00:39:02", BluetoothScanningMode.AUTO)
4253 c_owner = manager.async_register_scanner(owner)
4254 c_fb = manager.async_register_scanner(fb)
4255 try:
4256 _inject_with_rssi(owner, address, rssi=-50)
4257 fb.add_discovered(address, rssi=None)
4258 owner._add_connecting(address)
4259 _make_due(sched, address)
4260 await _run_worker_tick(sched, owner.source)
4261 assert owner.active_window_calls == []
4262 assert fb.active_window_calls == [6.0]
4263 finally:
4264 owner._finished_connecting(address, connected=False)
4265 cancel()
4266 c_owner()
4267 c_fb()
4268
4269
4270 @pytest.mark.asyncio
4271 async def test_worker_tick_fallback_with_rssi_loses_to_better_fallback() -> None:
4272 """
4273 A ``None``-RSSI fallback loses to a fallback with a real RSSI.
4274
4275 With ``None`` normalized to ``NO_RSSI_VALUE`` (-127), any
4276 real-world RSSI beats it, so the ``None``-RSSI scanner is only
4277 picked when nothing else is available.
4278 """
4279 manager = get_manager()
4280 sched = manager._auto_scheduler
4281 address = "11:22:33:44:55:3A"
4282 cancel = manager.async_register_active_scan(
4283 address, scan_interval=120.0, scan_duration=6.0
4284 )
4285 owner = _DiscoverableAutoScanner("AA:00:00:00:3A:01", BluetoothScanningMode.AUTO)
4286 fb_none = _DiscoverableAutoScanner("AA:00:00:00:3A:02", BluetoothScanningMode.AUTO)
4287 fb_real = _DiscoverableAutoScanner("AA:00:00:00:3A:03", BluetoothScanningMode.AUTO)
4288 c_owner = manager.async_register_scanner(owner)
4289 c_n = manager.async_register_scanner(fb_none)
4290 c_r = manager.async_register_scanner(fb_real)
4291 try:
4292 _inject_with_rssi(owner, address, rssi=-50)
4293 fb_none.add_discovered(address, rssi=None)
4294 fb_real.add_discovered(address, rssi=-90)
4295 owner._add_connecting(address)
4296 _make_due(sched, address)
4297 await _run_worker_tick(sched, owner.source)
4298 # Real RSSI (-90) beats the normalized None (-127).
4299 assert fb_real.active_window_calls == [6.0]
4300 assert fb_none.active_window_calls == []
4301 finally:
4302 owner._finished_connecting(address, connected=False)
4303 cancel()
4304 c_owner()
4305 c_n()
4306 c_r()
4307
4308
4309 @pytest.mark.asyncio
4310 async def test_worker_tick_failed_fallback_advances_entries_by_full_interval() -> None:
4311 """
4312 Failed fallback dispatch still advances entries by ``scan_interval``.
4313
4314 Pins Kōan suggestion #2 / the documented "advance on failure"
4315 semantics: when ``fb.async_request_active_window`` raises, the
4316 per-address entries have already been advanced by ``scan_interval``
4317 (NOT reset to ``retry_at``) and the fallback worker's
4318 ``_window_end`` / ``_sweep_last_completed`` bumps from
4319 ``note_window_dispatched`` are preserved. A failing fallback is
4320 treated like a successful one to avoid busy-looping on a stuck
4321 scanner.
4322 """
4323
4324 class _RaisingScanner(_DiscoverableAutoScanner):
4325 async def async_request_active_window(self, duration: float) -> bool:
4326 self.active_window_calls.append(duration)
4327 msg = "boom"
4328 raise RuntimeError(msg)
4329
4330 manager = get_manager()
4331 sched = manager._auto_scheduler
4332 loop = asyncio.get_running_loop()
4333 address = "11:22:33:44:55:3B"
4334 cancel = manager.async_register_active_scan(
4335 address, scan_interval=120.0, scan_duration=6.0
4336 )
4337 owner = _DiscoverableAutoScanner("AA:00:00:00:3B:01", BluetoothScanningMode.AUTO)
4338 fb = _RaisingScanner("AA:00:00:00:3B:02", BluetoothScanningMode.AUTO)
4339 c_owner = manager.async_register_scanner(owner)
4340 c_fb = manager.async_register_scanner(fb)
4341 try:
4342 _inject_with_rssi(owner, address, rssi=-50)
4343 fb.add_discovered(address, rssi=-60)
4344 owner._add_connecting(address)
4345 _make_due(sched, address)
4346 fb_worker = sched._workers[fb.source]
4347 sweep_before = fb_worker._sweep_last_completed
4348 before = loop.time()
4349 await _run_worker_tick(sched, owner.source)
4350 # Entries advanced by full scan_interval, NOT retry_at.
4351 for due in sched._schedule._due_at[address].values():
4352 assert due == pytest.approx(before + 120.0, abs=0.5)
4353 assert due > before + 60.0 # well past the 30s retry_at
4354 # fb_worker bumps from note_window_dispatched are preserved.
4355 assert fb_worker._sweep_last_completed > sweep_before
4356 assert fb_worker._sweep_last_completed >= before
4357 finally:
4358 owner._finished_connecting(address, connected=False)
4359 cancel()
4360 c_owner()
4361 c_fb()
4362
4363
4364 @pytest.mark.asyncio
4365 async def test_worker_tick_fallback_with_rssi_zero_is_strongest() -> None:
4366 """
4367 A fallback with ``rssi == 0`` beats a fallback with negative RSSI.
4368
4369 Pins the explicit ``rssi is None`` check (rather than ``rssi or
4370 NO_RSSI_VALUE``): an RSSI of 0 is a valid very-strong signal and
4371 must not be coerced to the missing-RSSI sentinel via ``0 or X``
4372 falsiness.
4373 """
4374 manager = get_manager()
4375 sched = manager._auto_scheduler
4376 address = "11:22:33:44:55:3D"
4377 cancel = manager.async_register_active_scan(
4378 address, scan_interval=120.0, scan_duration=6.0
4379 )
4380 owner = _DiscoverableAutoScanner("AA:00:00:00:3D:01", BluetoothScanningMode.AUTO)
4381 fb_zero = _DiscoverableAutoScanner("AA:00:00:00:3D:02", BluetoothScanningMode.AUTO)
4382 fb_neg = _DiscoverableAutoScanner("AA:00:00:00:3D:03", BluetoothScanningMode.AUTO)
4383 c_owner = manager.async_register_scanner(owner)
4384 c_zero = manager.async_register_scanner(fb_zero)
4385 c_neg = manager.async_register_scanner(fb_neg)
4386 try:
4387 _inject_with_rssi(owner, address, rssi=-50)
4388 fb_zero.add_discovered(address, rssi=0)
4389 fb_neg.add_discovered(address, rssi=-50)
4390 owner._add_connecting(address)
4391 _make_due(sched, address)
4392 await _run_worker_tick(sched, owner.source)
4393 # rssi=0 beats rssi=-50; the falsy-or pattern would have
4394 # incorrectly normalised 0 to NO_RSSI_VALUE and lost.
4395 assert fb_zero.active_window_calls == [6.0]
4396 assert fb_neg.active_window_calls == []
4397 finally:
4398 owner._finished_connecting(address, connected=False)
4399 cancel()
4400 c_owner()
4401 c_zero()
4402 c_neg()
4403
4404
4405 @pytest.mark.asyncio
4406 async def test_worker_tick_dispatch_short_window_still_resets_full_sweep() -> None:
4407 """
4408 A 5s delegated window resets the fallback's full 12h sweep cadence.
4409
4410 Pins the documented best-effort caveat: ``note_window_dispatched``
4411 advances ``_sweep_last_completed`` to ``now`` regardless of how
4412 short the delegated window is. With min duration (5s, well below
4413 ``AUTO_REDISCOVERY_SWEEP_DURATION`` of 15s), the next sweep is
4414 still pushed out a full ``AUTO_REDISCOVERY_INTERVAL`` (12h).
4415 """
4416 manager = get_manager()
4417 sched = manager._auto_scheduler
4418 loop = asyncio.get_running_loop()
4419 address = "11:22:33:44:55:3C"
4420 # Request duration well under MIN; coalesce_duration clamps to
4421 # _AUTO_WINDOW_MIN_DURATION (5.0).
4422 cancel = manager.async_register_active_scan(
4423 address, scan_interval=120.0, scan_duration=5.0
4424 )
4425 owner = _DiscoverableAutoScanner("AA:00:00:00:3C:01", BluetoothScanningMode.AUTO)
4426 fb = _DiscoverableAutoScanner("AA:00:00:00:3C:02", BluetoothScanningMode.AUTO)
4427 c_owner = manager.async_register_scanner(owner)
4428 c_fb = manager.async_register_scanner(fb)
4429 try:
4430 _inject_with_rssi(owner, address, rssi=-50)
4431 fb.add_discovered(address, rssi=-60)
4432 # Place fb's sweep clock far in the past so we can see the bump.
4433 fb_worker = sched._workers[fb.source]
4434 fb_worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL / 2
4435 owner._add_connecting(address)
4436 _make_due(sched, address)
4437 before = loop.time()
4438 await _run_worker_tick(sched, owner.source)
4439 # Delegated window was 5s; fb's next sweep was pushed to
4440 # roughly now + 12h regardless of the short window.
4441 next_sweep_due = fb_worker._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
4442 assert next_sweep_due == pytest.approx(
4443 before + AUTO_REDISCOVERY_INTERVAL, abs=1
4444 )
4445 assert fb.active_window_calls == [5.0]
4446 finally:
4447 owner._finished_connecting(address, connected=False)
4448 cancel()
4449 c_owner()
4450 c_fb()
4451
4452
4453 @pytest.mark.asyncio
4454 async def test_worker_tick_per_device_window_satisfies_sweep_floor() -> None:
4455 """
4456 A per-device active window advances ``_sweep_last_completed``.
4457
4458 The rediscovery sweep is a floor: scanners that haven't
4459 active-scanned in 12 h get a 15 s sweep. A scanner that just ran
4460 a per-device active window has already actively scanned, so its
4461 next sweep is pushed out a full ``AUTO_REDISCOVERY_INTERVAL``
4462 even when ``sweep_due`` was False at tick time.
4463 """
4464 manager = get_manager()
4465 sched = manager._auto_scheduler
4466 loop = asyncio.get_running_loop()
4467 address = "11:22:33:44:55:3E"
4468 cancel = manager.async_register_active_scan(
4469 address, scan_interval=120.0, scan_duration=6.0
4470 )
4471 scanner = _DiscoverableAutoScanner("AA:00:00:00:3E:01", BluetoothScanningMode.AUTO)
4472 register_cancel = manager.async_register_scanner(scanner)
4473 try:
4474 _inject_with_rssi(scanner, address, rssi=-50)
4475 worker = sched._workers[scanner.source]
4476 # Place sweep clock recent enough that sweep is NOT due — we
4477 # want to prove the per-device window still advances it.
4478 recent_sweep = loop.time() - 60.0
4479 worker._sweep_last_completed = recent_sweep
4480 _make_due(sched, address)
4481 before = loop.time()
4482 await _run_worker_tick(sched, scanner.source)
4483 assert scanner.active_window_calls == [6.0]
4484 # Per-device window pushed sweep clock from "60s ago" to "now",
4485 # demonstrating any active scan satisfies the sweep floor.
4486 assert worker._sweep_last_completed > recent_sweep
4487 assert worker._sweep_last_completed >= before
4488 finally:
4489 cancel()
4490 register_cancel()
4491
4492
4493 @pytest.mark.asyncio
4494 async def test_worker_tick_dispatch_samples_time_per_fallback() -> None:
4495 """
4496 Each fallback's ``window_end`` is anchored to its dispatch time.
4497
4498 Each ``await fb.async_request_active_window(duration)`` can take
4499 seconds in production (scanner stop/restart on Linux). Reusing
4500 the owner's tick-start ``now`` for every fallback's
4501 ``note_window_dispatched`` would leave later fallbacks'
4502 ``_window_end`` in the past — defeating the suppression. Use a
4503 first fallback that ``asyncio.sleep``s during its dispatch so the
4504 second fallback's ``loop.time()`` is strictly later than the
4505 owner's tick-start ``now``, then verify the second fallback's
4506 ``_window_end`` reflects its own dispatch time.
4507 """
4508
4509 class _SlowScanner(_DiscoverableAutoScanner):
4510 async def async_request_active_window(self, duration: float) -> bool:
4511 self.active_window_calls.append(duration)
4512 await asyncio.sleep(0.1)
4513 return self._return_value
4514
4515 manager = get_manager()
4516 sched = manager._auto_scheduler
4517 loop = asyncio.get_running_loop()
4518 addr_a = "11:22:33:44:55:3F"
4519 addr_b = "11:22:33:44:55:40"
4520 c1 = manager.async_register_active_scan(
4521 addr_a, scan_interval=120.0, scan_duration=6.0
4522 )
4523 c2 = manager.async_register_active_scan(
4524 addr_b, scan_interval=120.0, scan_duration=6.0
4525 )
4526 owner = _DiscoverableAutoScanner("AA:00:00:00:3F:01", BluetoothScanningMode.AUTO)
4527 fb_slow = _SlowScanner("AA:00:00:00:3F:02", BluetoothScanningMode.AUTO)
4528 fb_late = _DiscoverableAutoScanner("AA:00:00:00:3F:03", BluetoothScanningMode.AUTO)
4529 c_owner = manager.async_register_scanner(owner)
4530 c_s = manager.async_register_scanner(fb_slow)
4531 c_l = manager.async_register_scanner(fb_late)
4532 try:
4533 _inject_with_rssi(owner, addr_a, rssi=-50)
4534 _inject_with_rssi(owner, addr_b, rssi=-50)
4535 fb_slow.add_discovered(addr_a, rssi=-60)
4536 fb_late.add_discovered(addr_b, rssi=-60)
4537 owner._add_connecting(addr_a)
4538 _make_due(sched, addr_a)
4539 _make_due(sched, addr_b)
4540 tick_start = loop.time()
4541 await _run_worker_tick(sched, owner.source)
4542 # Both fallbacks were called.
4543 assert fb_slow.active_window_calls == [6.0]
4544 assert fb_late.active_window_calls == [6.0]
4545 # fb_late was dispatched AFTER fb_slow's 0.1s sleep, so its
4546 # _window_end is anchored to dispatch_now ≈ tick_start + 0.1,
4547 # i.e. > tick_start + duration (6.0). The owner's tick-start
4548 # ``now`` would have given tick_start + 6.0 ≈ tick_start + 6.0
4549 # exactly, which is < tick_start + 6.0 + 0.05.
4550 fb_late_worker = sched._workers[fb_late.source]
4551 assert fb_late_worker._window_end > tick_start + 6.0 + 0.05
4552 finally:
4553 owner._finished_connecting(addr_a, connected=False)
4554 c1()
4555 c2()
4556 c_owner()
4557 c_s()
4558 c_l()
4559
4560
4561 @pytest.mark.asyncio
4562 async def test_async_diagnostics() -> None:
4563 """Diagnostics expose per-worker sweep timing and per-address requests."""
4564 manager = get_manager()
4565 sched = manager._auto_scheduler
4566 loop = asyncio.get_running_loop()
4567 address = "11:22:33:44:55:66"
4568 cancel1 = manager.async_register_active_scan(
4569 address, scan_interval=120.0, scan_duration=5.0
4570 )
4571 cancel2 = manager.async_register_active_scan(
4572 address, scan_interval=240.0, scan_duration=10.0
4573 )
4574 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4575 register_cancel = manager.async_register_scanner(scanner)
4576 try:
4577 _inject(scanner, address)
4578 diagnostics = sched.async_diagnostics()
4579 assert diagnostics["running"] is True
4580 assert diagnostics["monotonic_time"] == pytest.approx(loop.time(), abs=0.5)
4581 workers = diagnostics["workers"]
4582 assert set(workers) == {scanner.source}
4583 worker_diag = workers[scanner.source]
4584 assert worker_diag["name"] == scanner.name
4585 assert worker_diag["window_end"] == 0.0
4586 assert worker_diag["last_window_at"] == 0.0
4587 assert worker_diag["last_window_duration"] == 0.0
4588 assert worker_diag["failed_window"] is False
4589 assert worker_diag["warned_no_fallback"] is False
4590 assert worker_diag["next_sweep_at"] == pytest.approx(
4591 worker_diag["sweep_last_completed"] + AUTO_REDISCOVERY_INTERVAL
4592 )
4593 assert worker_diag["next_event_at"] > 0.0
4594 requests = diagnostics["requests"]
4595 assert set(requests) == {address}
4596 entries = requests[address]
4597 assert len(entries) == 2
4598 pairs = sorted(
4599 (entry["scan_interval"], entry["scan_duration"]) for entry in entries
4600 )
4601 assert pairs == [(120.0, 5.0), (240.0, 10.0)]
4602 for entry in entries:
4603 assert entry["owner_source"] == scanner.source
4604 assert entry["next_due"] is not None
4605 assert entry["next_due"] > loop.time()
4606 assert entry["last_active_window"] is None
4607 assert entry["last_active_window_source"] is None
4608 finally:
4609 cancel1()
4610 cancel2()
4611 register_cancel()
4612 # After cancellation the address falls out of both indexes.
4613 post = sched.async_diagnostics()
4614 assert post["requests"] == {}
4615
4616
4617 @pytest.mark.asyncio
4618 async def test_async_diagnostics_last_active_window() -> None:
4619 """A fired window populates per-worker and per-address last-window timing."""
4620 manager = get_manager()
4621 sched = manager._auto_scheduler
4622 loop = asyncio.get_running_loop()
4623 address = "11:22:33:44:55:66"
4624 cancel = manager.async_register_active_scan(
4625 address, scan_interval=120.0, scan_duration=5.0
4626 )
4627 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4628 register_cancel = manager.async_register_scanner(scanner)
4629 try:
4630 _inject(scanner, address)
4631 entries = sched._schedule._due_at[address]
4632 request = next(iter(entries))
4633 entries[request] = loop.time() - 1.0
4634 tick_at = loop.time()
4635 await _run_worker_tick(sched, scanner.source)
4636 assert scanner.active_window_calls == [5.0]
4637 diagnostics = sched.async_diagnostics()
4638 worker_diag = diagnostics["workers"][scanner.source]
4639 assert worker_diag["last_window_at"] == pytest.approx(tick_at, abs=0.5)
4640 assert worker_diag["last_window_duration"] == 5.0
4641 entry = diagnostics["requests"][address][0]
4642 assert entry["last_active_window"] == pytest.approx(tick_at, abs=0.5)
4643 assert entry["last_active_window_source"] == scanner.source
4644 finally:
4645 cancel()
4646 register_cancel()
4647 # Pruned with the request so the map cannot grow without bound.
4648 assert sched._last_window_by_address == {}
4649
4650
4651 @pytest.mark.asyncio
4652 async def test_has_active_requests() -> None:
4653 """has_active_requests reflects whether any active-scan request exists."""
4654 manager = get_manager()
4655 sched = manager._auto_scheduler
4656 before = sched.has_active_requests
4657 cancel = manager.async_register_active_scan("11:22:33:44:55:66")
4658 during = sched.has_active_requests
4659 cancel()
4660 after = sched.has_active_requests
4661 assert before is False
4662 assert during is True
4663 assert after is False
4664
4665
4666 @contextlib.asynccontextmanager
4667 async def _no_real_sleep():
4668 """
4669 Replace ``asyncio.sleep`` with an immediate fake-time advance.
4670
4671 Sweeps clamp duration to AUTO_WINDOW_MIN_DURATION (5s); stubbing
4672 the sleep keeps tests fast while preserving the call shape so we
4673 can still observe what duration was requested. Each mocked sleep
4674 also advances ``loop.time()`` by ``duration`` so the on-demand
4675 sweep's sleep-until-end loop (which re-reads
4676 ``_on_demand_sweep_end`` on each wake) terminates instead of
4677 spinning forever against a frozen clock.
4678 """
4679 loop = asyncio.get_running_loop()
4680 real_time = loop.time
4681 fake_advance = [0.0]
4682
4683 async def _instant(duration: float) -> None:
4684 fake_advance[0] += duration
4685
4686 def _fake_time() -> float:
4687 return real_time() + fake_advance[0]
4688
4689 with (
4690 patch("asyncio.sleep", new=_instant),
4691 patch.object(loop, "time", _fake_time),
4692 ):
4693 yield
4694
4695
4696 @pytest.mark.asyncio
4697 async def test_async_request_active_scan_fires_active_window_on_each_auto_scanner() -> (
4698 None
4699 ):
4700 """A sweep flips every AUTO scanner into ACTIVE for the duration."""
4701 manager = get_manager()
4702 a = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4703 b = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
4704 c_a = manager.async_register_scanner(a)
4705 c_b = manager.async_register_scanner(b)
4706 try:
4707 async with _no_real_sleep():
4708 await manager.async_request_active_scan(duration=7.0)
4709 assert a.active_window_calls == [7.0]
4710 assert b.active_window_calls == [7.0]
4711 finally:
4712 c_a()
4713 c_b()
4714
4715
4716 @pytest.mark.asyncio
4717 async def test_async_request_active_scan_skips_connecting_scanner() -> None:
4718 """A scanner mid-connect is skipped; non-connecting peers still flip."""
4719 manager = get_manager()
4720 busy = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4721 free = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
4722 c_busy = manager.async_register_scanner(busy)
4723 c_free = manager.async_register_scanner(free)
4724 busy._add_connecting("11:22:33:44:55:66")
4725 try:
4726 async with _no_real_sleep():
4727 await manager.async_request_active_scan(duration=5.0)
4728 assert busy.active_window_calls == []
4729 assert free.active_window_calls == [5.0]
4730 finally:
4731 busy._finished_connecting("11:22:33:44:55:66", connected=False)
4732 c_busy()
4733 c_free()
4734
4735
4736 @pytest.mark.asyncio
4737 async def test_async_request_active_scan_resets_next_sweep_time() -> None:
4738 """A sweep advances each flipped worker's _sweep_last_completed to now."""
4739 manager = get_manager()
4740 sched = manager._auto_scheduler
4741 loop = asyncio.get_running_loop()
4742 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4743 register_cancel = manager.async_register_scanner(scanner)
4744 worker = sched._workers[scanner.source]
4745 # Backdate so we can observe the bump.
4746 worker._sweep_last_completed = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
4747 try:
4748 before = loop.time()
4749 async with _no_real_sleep():
4750 await manager.async_request_active_scan(duration=5.0)
4751 assert worker._sweep_last_completed >= before
4752 assert worker._sweep_last_completed <= loop.time() + 0.1
4753 finally:
4754 register_cancel()
4755
4756
4757 @pytest.mark.asyncio
4758 async def test_async_request_active_scan_mixed_durations_extends_to_longest() -> None:
4759 """
4760 Concurrent callers asking for (10, 15, 5, 20) all wait until T0+20.
4761
4762 The first caller to win the check-and-set runs a 10s sweep; the 15s
4763 and 20s callers extend the in-flight window (re-flipping the radio
4764 with the longer remaining duration); the 5s caller fits within the
4765 already-extended end and does not flip again. The scanner records
4766 each flip's duration so we can verify the extension chain.
4767 """
4768 manager = get_manager()
4769 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4770 register_cancel = manager.async_register_scanner(scanner)
4771 try:
4772 async with _no_real_sleep():
4773 await asyncio.gather(
4774 manager.async_request_active_scan(duration=10.0),
4775 manager.async_request_active_scan(duration=15.0),
4776 manager.async_request_active_scan(duration=5.0),
4777 manager.async_request_active_scan(duration=20.0),
4778 )
4779 # Exactly three flip durations: leader's 10s + two extensions
4780 # (approximately 15s and 20s, with sub-second drift from
4781 # task-start jitter — pytest.approx absorbs the drift, and
4782 # the ordering pins the chain.
4783 assert len(scanner.active_window_calls) == 3
4784 assert scanner.active_window_calls[0] == 10.0
4785 assert scanner.active_window_calls[1] == pytest.approx(15.0, abs=1.0)
4786 assert scanner.active_window_calls[2] == pytest.approx(20.0, abs=1.0)
4787 assert (
4788 scanner.active_window_calls[0]
4789 < scanner.active_window_calls[1]
4790 < scanner.active_window_calls[2]
4791 )
4792 # The future and end are cleared once the leader finishes.
4793 assert manager._auto_scheduler._on_demand_sweep_future is None
4794 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
4795 finally:
4796 register_cancel()
4797
4798
4799 @pytest.mark.asyncio
4800 async def test_async_request_active_scan_dedupes_concurrent_callers() -> None:
4801 """N concurrent sweep calls share one window; the bus flips once."""
4802 manager = get_manager()
4803 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4804 register_cancel = manager.async_register_scanner(scanner)
4805 try:
4806 async with _no_real_sleep():
4807 # Three concurrent callers, mirroring HA integrations each
4808 # opening their own config flow at the same time.
4809 await asyncio.gather(
4810 manager.async_request_active_scan(duration=5.0),
4811 manager.async_request_active_scan(duration=5.0),
4812 manager.async_request_active_scan(duration=5.0),
4813 )
4814 # Only one active window despite three callers.
4815 assert scanner.active_window_calls == [5.0]
4816 # The deduped future is cleared once the sweep finishes.
4817 assert manager._auto_scheduler._on_demand_sweep_future is None
4818 finally:
4819 register_cancel()
4820
4821
4822 @pytest.mark.asyncio
4823 async def test_async_request_active_scan_default_duration_is_10s() -> None:
4824 """Calling without a duration uses DEFAULT_ON_DEMAND_SWEEP_DURATION (10s)."""
4825 manager = get_manager()
4826 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4827 register_cancel = manager.async_register_scanner(scanner)
4828 try:
4829 async with _no_real_sleep():
4830 await manager.async_request_active_scan()
4831 assert scanner.active_window_calls == [DEFAULT_ON_DEMAND_SWEEP_DURATION]
4832 finally:
4833 register_cancel()
4834
4835
4836 @pytest.mark.asyncio
4837 async def test_async_request_active_scan_clamps_to_window_bounds() -> None:
4838 """Out-of-range durations are clamped to [MIN, MAX]."""
4839 manager = get_manager()
4840 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4841 register_cancel = manager.async_register_scanner(scanner)
4842 try:
4843 async with _no_real_sleep():
4844 await manager.async_request_active_scan(duration=0.5) # below MIN
4845 await manager.async_request_active_scan(duration=999.0) # above MAX
4846 assert scanner.active_window_calls == [
4847 AUTO_WINDOW_MIN_DURATION,
4848 AUTO_WINDOW_MAX_DURATION,
4849 ]
4850 finally:
4851 register_cancel()
4852
4853
4854 @pytest.mark.asyncio
4855 async def test_async_request_active_scan_rejects_invalid_duration() -> None:
4856 """NaN, inf, zero, and negative durations raise ValueError."""
4857 manager = get_manager()
4858 for bad in (float("nan"), float("inf"), float("-inf"), 0.0, -1.0):
4859 with pytest.raises(ValueError, match="finite positive"):
4860 await manager.async_request_active_scan(duration=bad)
4861
4862
4863 @pytest.mark.asyncio
4864 async def test_async_request_active_scan_no_op_when_scheduler_stopped() -> None:
4865 """After stop() the scheduler has no loop; the sweep returns immediately."""
4866 manager = get_manager()
4867 manager._auto_scheduler.stop()
4868 await manager.async_request_active_scan(duration=5.0)
4869
4870
4871 @pytest.mark.asyncio
4872 async def test_async_request_active_scan_no_op_without_auto_scanners() -> None:
4873 """With no AUTO workers the sweep returns immediately, no sleep."""
4874 manager = get_manager()
4875 loop = asyncio.get_running_loop()
4876
4877 async def _fail_on_sleep(delay: float) -> None:
4878 # Surface a regression as a clean assertion instead of a
4879 # pytest-timeout: if the leader's sleep loop runs at all,
4880 # fail now rather than spin / block on the patched sleep.
4881 pytest.fail(f"async_request_active_scan slept for {delay}s on NOOP")
4882
4883 before = loop.time()
4884 with patch("asyncio.sleep", new=_fail_on_sleep):
4885 await manager.async_request_active_scan(duration=5.0)
4886 # Bounded wall time confirms we did not block on the 5s duration.
4887 assert loop.time() - before < 0.5
4888 assert manager._auto_scheduler._on_demand_sweep_future is None
4889 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
4890
4891
4892 @pytest.mark.asyncio
4893 async def test_async_request_active_scan_no_op_when_all_scanners_connecting() -> None:
4894 """Every AUTO scanner mid-connect is the same NOOP; no sleep, fast-return."""
4895 manager = get_manager()
4896 loop = asyncio.get_running_loop()
4897 busy_a = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4898 busy_b = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
4899 c_a = manager.async_register_scanner(busy_a)
4900 c_b = manager.async_register_scanner(busy_b)
4901 busy_a._add_connecting("11:22:33:44:55:66")
4902 busy_b._add_connecting("11:22:33:44:55:77")
4903
4904 async def _fail_on_sleep(delay: float) -> None:
4905 pytest.fail(f"async_request_active_scan slept for {delay}s on NOOP")
4906
4907 try:
4908 before = loop.time()
4909 with patch("asyncio.sleep", new=_fail_on_sleep):
4910 await manager.async_request_active_scan(duration=5.0)
4911 assert busy_a.active_window_calls == []
4912 assert busy_b.active_window_calls == []
4913 assert loop.time() - before < 0.5
4914 assert manager._auto_scheduler._on_demand_sweep_future is None
4915 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
4916 finally:
4917 busy_a._finished_connecting("11:22:33:44:55:66", connected=False)
4918 busy_b._finished_connecting("11:22:33:44:55:77", connected=False)
4919 c_a()
4920 c_b()
4921
4922
4923 @pytest.mark.asyncio
4924 async def test_async_request_active_scan_awaits_the_full_duration() -> None:
4925 """
4926 The sweep awaits ``duration`` so the caller can read advertisements.
4927
4928 Freezegun patches ``time.monotonic`` (and thus ``loop.time``);
4929 advancing the frozen clock by the requested duration lets the
4930 scheduler's internal ``asyncio.sleep`` complete and the task
4931 finish. The scanner is registered inside the freeze so the
4932 worker's ``_sweep_last_completed`` is anchored to the frozen
4933 clock; the worker's background ``_run`` task is cancelled so it
4934 cannot tick during the on-demand window.
4935 """
4936 manager = get_manager()
4937 sched = manager._auto_scheduler
4938 with freeze_time() as frozen:
4939 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4940 register_cancel = manager.async_register_scanner(scanner)
4941 worker = sched._workers[scanner.source]
4942 worker.stop()
4943 await asyncio.sleep(0)
4944 try:
4945 task = asyncio.create_task(manager.async_request_active_scan(duration=5.0))
4946 # Let the task start, flip the radio, and enter asyncio.sleep.
4947 for _ in range(5):
4948 await asyncio.sleep(0)
4949 assert scanner.active_window_calls == [5.0]
4950 assert not task.done()
4951 # Advance past the sweep duration; the sleep wakes up.
4952 frozen.tick(5.1)
4953 await task
4954 assert task.done()
4955 finally:
4956 register_cancel()
4957
4958
4959 @pytest.mark.asyncio
4960 async def test_async_request_active_scan_extension_reverts_end_when_no_targets() -> (
4961 None
4962 ):
4963 """
4964 A joiner extension that finds every worker busy reverts the end push.
4965
4966 Leader dispatches successfully and parks in its sleep loop. The
4967 only scanner then goes mid-connect; the joiner's extension flip
4968 has no eligible targets and returns False. The eager
4969 ``_on_demand_sweep_end`` push must be reverted to the leader's
4970 original end so the leader does not sleep past the in-flight
4971 radio window for nothing.
4972 """
4973 manager = get_manager()
4974 sched = manager._auto_scheduler
4975 with freeze_time() as frozen:
4976 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
4977 register_cancel = manager.async_register_scanner(scanner)
4978 worker = sched._workers[scanner.source]
4979 worker.stop()
4980 await asyncio.sleep(0)
4981 try:
4982 leader = asyncio.create_task(
4983 manager.async_request_active_scan(duration=5.0)
4984 )
4985 for _ in range(5):
4986 await asyncio.sleep(0)
4987 assert scanner.active_window_calls == [5.0]
4988 leader_end = sched._on_demand_sweep_end
4989 # Mark the only worker busy before the joiner extension fires.
4990 scanner._add_connecting("11:22:33:44:55:66")
4991 try:
4992 joiner = asyncio.create_task(
4993 manager.async_request_active_scan(duration=20.0)
4994 )
4995 for _ in range(5):
4996 await asyncio.sleep(0)
4997 # Joiner's extension dispatched nothing; only the leader's
4998 # flip is recorded and the eager push was reverted.
4999 assert scanner.active_window_calls == [5.0]
5000 assert sched._on_demand_sweep_end == leader_end
5001 finally:
5002 scanner._finished_connecting("11:22:33:44:55:66", connected=False)
5003 # Advance past the leader's end; leader and joiner both wake.
5004 frozen.tick(5.1)
5005 await leader
5006 await joiner
5007 assert sched._on_demand_sweep_future is None
5008 finally:
5009 register_cancel()
5010
5011
5012 @pytest.mark.asyncio
5013 async def test_async_request_active_scan_logs_per_scanner_flip_failures(
5014 caplog: pytest.LogCaptureFixture,
5015 ) -> None:
5016 """A scanner whose flip raises is logged; the sweep still completes."""
5017 manager = get_manager()
5018
5019 class _FailingScanner(_RecordingAutoScanner):
5020 async def async_request_active_window(self, duration: float) -> bool:
5021 msg = "boom"
5022 raise RuntimeError(msg)
5023
5024 bad = _FailingScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5025 good = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
5026 c_bad = manager.async_register_scanner(bad)
5027 c_good = manager.async_register_scanner(good)
5028 try:
5029 with caplog.at_level(logging.WARNING, logger="habluetooth.auto_scheduler"):
5030 async with _no_real_sleep():
5031 await manager.async_request_active_scan(duration=5.0)
5032 assert good.active_window_calls == [5.0]
5033 assert any(
5034 "on-demand active window" in record.message and "boom" in record.message
5035 for record in caplog.records
5036 )
5037 finally:
5038 c_bad()
5039 c_good()
5040
5041
5042 @pytest.mark.asyncio
5043 async def test_async_request_active_scan_no_op_when_every_dispatch_declines() -> None:
5044 """
5045 All-False / all-raise from dispatched scanners is the same NOOP as no targets.
5046
5047 The flip dispatches but every scanner declines or raises so no
5048 radio window actually opens; the leader must skip the sleep loop
5049 rather than block on a window that never opened.
5050 """
5051 manager = get_manager()
5052 loop = asyncio.get_running_loop()
5053
5054 class _DecliningScanner(_RecordingAutoScanner):
5055 async def async_request_active_window(self, duration: float) -> bool:
5056 self.active_window_calls.append(duration)
5057 return False
5058
5059 class _FailingScanner(_RecordingAutoScanner):
5060 async def async_request_active_window(self, duration: float) -> bool:
5061 self.active_window_calls.append(duration)
5062 msg = "boom"
5063 raise RuntimeError(msg)
5064
5065 decliner = _DecliningScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5066 raiser = _FailingScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
5067 c_dec = manager.async_register_scanner(decliner)
5068 c_raise = manager.async_register_scanner(raiser)
5069
5070 async def _fail_on_sleep(delay: float) -> None:
5071 pytest.fail(f"async_request_active_scan slept for {delay}s on NOOP")
5072
5073 sched = manager._auto_scheduler
5074 dec_worker = sched._workers[decliner.source]
5075 raise_worker = sched._workers[raiser.source]
5076 try:
5077 before = loop.time()
5078 with patch("asyncio.sleep", new=_fail_on_sleep):
5079 await manager.async_request_active_scan(duration=5.0)
5080 # Both scanners were dispatched to; neither opened a window.
5081 assert decliner.active_window_calls == [5.0]
5082 assert raiser.active_window_calls == [5.0]
5083 assert loop.time() - before < 0.5
5084 assert manager._auto_scheduler._on_demand_sweep_future is None
5085 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
5086 # _window_end was pre-bumped for each worker but reverted post-result
5087 # so the worker is not locked out of its own ticks. New workers start
5088 # with _window_end == 0.0 and the flip should leave them there.
5089 assert dec_worker._window_end == 0.0
5090 assert raise_worker._window_end == 0.0
5091 finally:
5092 c_dec()
5093 c_raise()
5094
5095
5096 @pytest.mark.asyncio
5097 async def test_async_request_active_scan_revert_skipped_on_concurrent_push() -> None:
5098 """A concurrent _window_end push past our bump is not clobbered on revert."""
5099 manager = get_manager()
5100 sched = manager._auto_scheduler
5101 holder: list[Any] = []
5102
5103 class _MutatingScanner(_RecordingAutoScanner):
5104 async def async_request_active_window(self, duration: float) -> bool:
5105 self.active_window_calls.append(duration)
5106 # Simulate a concurrent extension pushing _window_end out
5107 # past the on-demand bump between pre-bump and result; the
5108 # revert guard must observe the mismatch and leave it alone.
5109 holder[0]._window_end = 1.0e12
5110 return False
5111
5112 scanner = _MutatingScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5113 register_cancel = manager.async_register_scanner(scanner)
5114 holder.append(sched._workers[scanner.source])
5115 try:
5116 async with _no_real_sleep():
5117 await manager.async_request_active_scan(duration=5.0)
5118 # The concurrent push survived our revert (guarded by exact
5119 # equality on the value we set).
5120 assert holder[0]._window_end == 1.0e12
5121 finally:
5122 register_cancel()
5123
5124
5125 @pytest.mark.asyncio
5126 async def test_async_request_active_scan_window_end_kept_for_succeeding() -> None:
5127 """
5128 Mixed True/False results: the True scanner keeps its bumped _window_end.
5129
5130 A decliner runs alongside a scanner that returns True. The
5131 decliner's pre-bumped _window_end is reverted while the True
5132 scanner keeps the bump so its periodic worker tick stays
5133 suppressed for the duration of the real radio window.
5134 """
5135 manager = get_manager()
5136 sched = manager._auto_scheduler
5137
5138 class _DecliningScanner(_RecordingAutoScanner):
5139 async def async_request_active_window(self, duration: float) -> bool:
5140 self.active_window_calls.append(duration)
5141 return False
5142
5143 decliner = _DecliningScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5144 good = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
5145 c_dec = manager.async_register_scanner(decliner)
5146 c_good = manager.async_register_scanner(good)
5147 dec_worker = sched._workers[decliner.source]
5148 good_worker = sched._workers[good.source]
5149 try:
5150 async with _no_real_sleep():
5151 await manager.async_request_active_scan(duration=5.0)
5152 assert decliner.active_window_calls == [5.0]
5153 assert good.active_window_calls == [5.0]
5154 # Decliner reverted to 0.0; succeeding scanner retains the bump.
5155 assert dec_worker._window_end == 0.0
5156 assert good_worker._window_end > 0.0
5157 finally:
5158 c_dec()
5159 c_good()
5160
5161
5162 @pytest.mark.asyncio
5163 async def test_async_request_active_scan_leader_honors_joiner_success_on_decline() -> (
5164 None
5165 ):
5166 """
5167 Leader's all-declined flip must not wipe state while a joiner has opened a window.
5168
5169 Sequence:
5170 1. Leader flips X (eligible, blocks on its window call); Y is
5171 mid-connect and skipped.
5172 2. While leader is parked in its gather, Y finishes connecting
5173 and a joiner arrives wanting a longer window. The joiner
5174 extends ``_on_demand_sweep_end`` and re-flips; Y returns
5175 True, the joiner does not revert, then parks on the shared
5176 future.
5177 3. X unblocks and returns False; the leader's flip therefore
5178 returns False (only X was dispatched, X declined).
5179 4. ``_on_demand_sweep_end`` was pushed past the leader's
5180 ``desired_end`` by the joiner, so the leader must NOT
5181 fast-return: it falls through to the sleep loop and sleeps
5182 until the joiner's end, otherwise the joiner is cut short
5183 and the radio window is orphaned from scheduler bookkeeping.
5184 """
5185 manager = get_manager()
5186 sched = manager._auto_scheduler
5187 with freeze_time() as frozen:
5188 x = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5189 y = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
5190 x._return_value = False
5191 x._block_event = asyncio.Event()
5192 c_x = manager.async_register_scanner(x)
5193 c_y = manager.async_register_scanner(y)
5194 wx = sched._workers[x.source]
5195 wy = sched._workers[y.source]
5196 # Silence each worker's own tick so it cannot pollute
5197 # active_window_calls during the on-demand sweep.
5198 wx.stop()
5199 wy.stop()
5200 await asyncio.sleep(0)
5201 # Y starts mid-connect so the leader's flip skips it entirely.
5202 y._add_connecting("11:22:33:44:55:66")
5203 try:
5204 leader = asyncio.create_task(
5205 manager.async_request_active_scan(duration=5.0)
5206 )
5207 for _ in range(3):
5208 await asyncio.sleep(0)
5209 # Leader is now blocked inside X's flip; Y was skipped.
5210 assert x.active_window_calls == [5.0]
5211 assert y.active_window_calls == []
5212 # Free Y so a joiner can dispatch it.
5213 y._finished_connecting("11:22:33:44:55:66", connected=False)
5214 joiner = asyncio.create_task(
5215 manager.async_request_active_scan(duration=20.0)
5216 )
5217 for _ in range(3):
5218 await asyncio.sleep(0)
5219 # Joiner extended end and dispatched Y; Y opened a window.
5220 assert y.active_window_calls == [20.0]
5221 joiner_end = sched._on_demand_sweep_end
5222 assert joiner_end > 0.0
5223 # Unblock X; leader's flip resolves with all-declined.
5224 x._block_event.set()
5225 for _ in range(5):
5226 await asyncio.sleep(0)
5227 # Without the joiner-extension guard, the leader would
5228 # have fast-returned and zeroed _on_demand_sweep_end /
5229 # resolved the shared future. With the guard, both tasks
5230 # are still parked and the end is intact.
5231 assert not leader.done()
5232 assert not joiner.done()
5233 assert sched._on_demand_sweep_end == joiner_end
5234 # Advance past the joiner's end; both tasks complete.
5235 frozen.tick(20.1)
5236 await leader
5237 await joiner
5238 assert sched._on_demand_sweep_future is None
5239 finally:
5240 c_x()
5241 c_y()
5242
5243
5244 @pytest.mark.asyncio
5245 async def test_async_request_active_scan_joiner_cancel_during_extension() -> None:
5246 """
5247 Joiner cancelled mid-extension still finishes the all-or-nothing re-flip.
5248
5249 Without ``asyncio.shield`` on the extension flip, a joiner
5250 cancelled while extending would leave ``_on_demand_sweep_end``
5251 pushed out past a partial re-flip, so the leader (and other
5252 joiners) would sleep until the extended end believing every
5253 scanner was active when some were not. With the shield, the
5254 re-flip runs to completion; the scanner records both the
5255 leader's original flip duration and the extension duration
5256 even after the joiner is cancelled.
5257 """
5258 manager = get_manager()
5259 sched = manager._auto_scheduler
5260 with freeze_time() as frozen:
5261 # Register inside freeze + stop the worker so the worker's
5262 # own periodic sweep does not fire and pollute the recorded
5263 # active_window_calls.
5264 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5265 register_cancel = manager.async_register_scanner(scanner)
5266 worker = sched._workers[scanner.source]
5267 worker.stop()
5268 await asyncio.sleep(0)
5269 try:
5270 # Block scanner flips so the leader stays in its first
5271 # flip await while the joiner extends and is cancelled.
5272 scanner._block_event = asyncio.Event()
5273 leader = asyncio.create_task(
5274 manager.async_request_active_scan(duration=5.0)
5275 )
5276 for _ in range(3):
5277 await asyncio.sleep(0)
5278 joiner = asyncio.create_task(
5279 manager.async_request_active_scan(duration=20.0)
5280 )
5281 # Yield enough for the joiner to enter its shielded
5282 # extension flip (which is now also blocked on the
5283 # scanner's block_event).
5284 for _ in range(3):
5285 await asyncio.sleep(0)
5286 assert len(scanner.active_window_calls) == 2
5287 joiner.cancel()
5288 with contextlib.suppress(asyncio.CancelledError):
5289 await joiner
5290 # Release the scanner; leader's flip returns, joiner's
5291 # shielded flip also completes as an orphan task.
5292 scanner._block_event.set()
5293 frozen.tick(20.1)
5294 await leader
5295 # Both leader's 5s flip and joiner's ~20s extension
5296 # recorded despite the cancel.
5297 assert scanner.active_window_calls[0] == 5.0
5298 assert scanner.active_window_calls[1] == pytest.approx(20.0, abs=1.0)
5299 assert sched._on_demand_sweep_future is None
5300 finally:
5301 register_cancel()
5302
5303
5304 @pytest.mark.asyncio
5305 async def test_async_request_active_scan_joiner_cancel_keeps_siblings() -> None:
5306 """
5307 Cancelling one joiner must not cancel the shared future.
5308
5309 Without ``asyncio.shield`` on the joiner's await, a cancelled
5310 joiner would cancel the underlying future, which then propagates
5311 ``CancelledError`` to sibling joiners and makes the leader's
5312 ``finally`` raise ``InvalidStateError`` on ``set_result``.
5313 """
5314 manager = get_manager()
5315 sched = manager._auto_scheduler
5316 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5317 register_cancel = manager.async_register_scanner(scanner)
5318 try:
5319 with freeze_time() as frozen:
5320 scanner._block_event = asyncio.Event()
5321 leader = asyncio.create_task(
5322 manager.async_request_active_scan(duration=5.0)
5323 )
5324 joiner_a = asyncio.create_task(
5325 manager.async_request_active_scan(duration=5.0)
5326 )
5327 joiner_b = asyncio.create_task(
5328 manager.async_request_active_scan(duration=5.0)
5329 )
5330 for _ in range(5):
5331 await asyncio.sleep(0)
5332 # Cancel one joiner; siblings and leader must continue.
5333 joiner_a.cancel()
5334 with contextlib.suppress(asyncio.CancelledError):
5335 await joiner_a
5336 scanner._block_event.set()
5337 frozen.tick(5.1)
5338 # Leader and the surviving joiner both complete normally.
5339 await leader
5340 await joiner_b
5341 assert joiner_b.result() is None
5342 assert sched._on_demand_sweep_future is None
5343 finally:
5344 register_cancel()
5345
5346
5347 @pytest.mark.asyncio
5348 async def test_async_request_active_scan_leader_cancellation_releases_joiners() -> None:
5349 """
5350 Cancelling the leader still resolves the future so joiners do not hang.
5351
5352 Joiners see ``None`` (no propagated ``CancelledError``) and benefit
5353 from whatever radio activity already happened; a subsequent sweep can
5354 run because ``_on_demand_sweep_future`` is cleared.
5355 """
5356 manager = get_manager()
5357 sched = manager._auto_scheduler
5358 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5359 register_cancel = manager.async_register_scanner(scanner)
5360 try:
5361 with freeze_time():
5362 # Block the leader inside its scanner-flip await so we know
5363 # we're past the gather and inside the leader's sleep when
5364 # we cancel.
5365 scanner._block_event = asyncio.Event()
5366 leader = asyncio.create_task(
5367 manager.async_request_active_scan(duration=5.0)
5368 )
5369 joiner = asyncio.create_task(
5370 manager.async_request_active_scan(duration=5.0)
5371 )
5372 for _ in range(5):
5373 await asyncio.sleep(0)
5374 # Both tasks are now waiting; joiner has latched onto the
5375 # leader's future.
5376 assert not leader.done()
5377 assert not joiner.done()
5378 scanner._block_event.set()
5379 leader.cancel()
5380 with contextlib.suppress(asyncio.CancelledError):
5381 await leader
5382 # Joiner completes normally with no exception.
5383 await joiner
5384 assert joiner.result() is None
5385 # Future is cleared so a fresh sweep can start.
5386 assert sched._on_demand_sweep_future is None
5387 finally:
5388 register_cancel()
5389
5390
5391 @pytest.mark.asyncio
5392 async def test_async_request_active_scan_declined_does_not_advance_sweep_floor() -> (
5393 None
5394 ):
5395 """A False flip leaves _sweep_last_completed alone so the periodic sweep retries."""
5396 manager = get_manager()
5397 sched = manager._auto_scheduler
5398 loop = asyncio.get_running_loop()
5399 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5400 scanner._return_value = False
5401 register_cancel = manager.async_register_scanner(scanner)
5402 worker = sched._workers[scanner.source]
5403 # Backdate so an erroneous bump would be visible.
5404 original = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
5405 worker._sweep_last_completed = original
5406 try:
5407 async with _no_real_sleep():
5408 await manager.async_request_active_scan(duration=5.0)
5409 assert scanner.active_window_calls == [5.0]
5410 assert worker._sweep_last_completed == original
5411 finally:
5412 register_cancel()
5413
5414
5415 @pytest.mark.asyncio
5416 async def test_async_request_active_scan_exception_does_not_advance_sweep_floor() -> (
5417 None
5418 ):
5419 """A flip that raises also leaves the sweep floor alone for that scanner."""
5420 manager = get_manager()
5421 sched = manager._auto_scheduler
5422 loop = asyncio.get_running_loop()
5423
5424 class _FailingScanner(_RecordingAutoScanner):
5425 async def async_request_active_window(self, duration: float) -> bool:
5426 msg = "boom"
5427 raise RuntimeError(msg)
5428
5429 bad = _FailingScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5430 good = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.AUTO)
5431 c_bad = manager.async_register_scanner(bad)
5432 c_good = manager.async_register_scanner(good)
5433 bad_worker = sched._workers[bad.source]
5434 good_worker = sched._workers[good.source]
5435 original = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
5436 bad_worker._sweep_last_completed = original
5437 good_worker._sweep_last_completed = original
5438 try:
5439 async with _no_real_sleep():
5440 await manager.async_request_active_scan(duration=5.0)
5441 # bad raised; floor stays put. good returned True; floor advances.
5442 assert bad_worker._sweep_last_completed == original
5443 assert good_worker._sweep_last_completed > original
5444 finally:
5445 c_bad()
5446 c_good()
5447
5448
5449 @pytest.mark.asyncio
5450 async def test_async_request_active_scan_cancelled_flip_logged_distinctly(
5451 caplog: pytest.LogCaptureFixture,
5452 ) -> None:
5453 """A CancelledError result is logged as cancelled, not as a False decline."""
5454 manager = get_manager()
5455 sched = manager._auto_scheduler
5456 loop = asyncio.get_running_loop()
5457
5458 class _CancellingScanner(_RecordingAutoScanner):
5459 async def async_request_active_window(self, duration: float) -> bool:
5460 raise asyncio.CancelledError
5461
5462 cancelling = _CancellingScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5463 register_cancel = manager.async_register_scanner(cancelling)
5464 worker = sched._workers[cancelling.source]
5465 original = loop.time() - AUTO_REDISCOVERY_INTERVAL - 1.0
5466 worker._sweep_last_completed = original
5467 try:
5468 with caplog.at_level(logging.DEBUG, logger="habluetooth.auto_scheduler"):
5469 async with _no_real_sleep():
5470 await manager.async_request_active_scan(duration=5.0)
5471 assert worker._sweep_last_completed == original
5472 assert any(
5473 "cancelled during on-demand active window" in record.message
5474 for record in caplog.records
5475 )
5476 assert not any(
5477 "declined on-demand active window" in record.message
5478 for record in caplog.records
5479 )
5480 finally:
5481 register_cancel()
5482
5483
5484 @pytest.mark.asyncio
5485 async def test_async_request_active_scan_does_not_shrink_existing_window_end() -> None:
5486 """A pre-existing longer _window_end is not shrunk by a new flip."""
5487 manager = get_manager()
5488 sched = manager._auto_scheduler
5489 loop = asyncio.get_running_loop()
5490 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5491 register_cancel = manager.async_register_scanner(scanner)
5492 worker = sched._workers[scanner.source]
5493 pre_existing = loop.time() + 9999.0
5494 worker._window_end = pre_existing
5495 try:
5496 async with _no_real_sleep():
5497 await manager.async_request_active_scan(duration=5.0)
5498 assert worker._window_end == pre_existing
5499 finally:
5500 register_cancel()
5501
5502
5503 @pytest.mark.asyncio
5504 async def test_async_request_active_scan_does_not_move_sweep_floor_backwards() -> None:
5505 """A pre-existing later _sweep_last_completed is not moved backwards."""
5506 manager = get_manager()
5507 sched = manager._auto_scheduler
5508 loop = asyncio.get_running_loop()
5509 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5510 register_cancel = manager.async_register_scanner(scanner)
5511 worker = sched._workers[scanner.source]
5512 pre_existing = loop.time() + 9999.0
5513 worker._sweep_last_completed = pre_existing
5514 try:
5515 async with _no_real_sleep():
5516 await manager.async_request_active_scan(duration=5.0)
5517 assert worker._sweep_last_completed == pre_existing
5518 finally:
5519 register_cancel()
5520
5521
5522 @pytest.mark.asyncio
5523 async def test_stop_resolves_in_flight_on_demand_sweep_future() -> None:
5524 """stop() resolves the future, frees joiners, leader's finally tolerates it."""
5525 manager = get_manager()
5526 sched = manager._auto_scheduler
5527 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5528 register_cancel = manager.async_register_scanner(scanner)
5529 worker = sched._workers[scanner.source]
5530 worker.stop()
5531 await asyncio.sleep(0)
5532 try:
5533 scanner._block_event = asyncio.Event()
5534 leader = asyncio.create_task(manager.async_request_active_scan(duration=5.0))
5535 joiner = asyncio.create_task(manager.async_request_active_scan(duration=5.0))
5536 for _ in range(5):
5537 await asyncio.sleep(0)
5538 assert sched._on_demand_sweep_future is not None
5539 assert not joiner.done()
5540 sched.stop()
5541 # Future resolved, state cleared, joiner wakes up to None.
5542 assert manager._auto_scheduler._on_demand_sweep_future is None
5543 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
5544 await joiner
5545 assert joiner.result() is None
5546 # Release the leader so its finally runs; the done() guard
5547 # absorbs ``stop()``'s already-resolved future.
5548 scanner._block_event.set()
5549 await asyncio.wait_for(leader, timeout=1.0)
5550 assert leader.result() is None
5551 finally:
5552 register_cancel()
5553
5554
5555 @pytest.mark.asyncio
5556 async def test_stop_is_safe_when_on_demand_future_already_done() -> None:
5557 """stop() does not raise InvalidStateError on an already-resolved future."""
5558 manager = get_manager()
5559 sched = manager._auto_scheduler
5560 loop = asyncio.get_running_loop()
5561 done_future: asyncio.Future[None] = loop.create_future()
5562 done_future.set_result(None)
5563 sched._on_demand_sweep_future = done_future
5564 sched.stop()
5565 assert manager._auto_scheduler._on_demand_sweep_future is None
5566 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
5567
5568
5569 @pytest.mark.asyncio
5570 async def test_stop_is_safe_without_in_flight_on_demand_sweep() -> None:
5571 """``stop()`` with no active sweep is a no-op for the sweep state."""
5572 manager = get_manager()
5573 sched = manager._auto_scheduler
5574 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5575 register_cancel = manager.async_register_scanner(scanner)
5576 try:
5577 assert sched._on_demand_sweep_future is None
5578 sched.stop()
5579 assert manager._auto_scheduler._on_demand_sweep_future is None
5580 assert manager._auto_scheduler._on_demand_sweep_end == 0.0
5581 finally:
5582 register_cancel()
5583
5584
5585 @pytest.mark.asyncio
5586 async def test_orphan_leader_does_not_clobber_fresh_sweep_state() -> None:
5587 """A leader orphaned by stop()+start() does not clear a fresh future."""
5588 manager = get_manager()
5589 sched = manager._auto_scheduler
5590 loop = asyncio.get_running_loop()
5591 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5592 register_cancel = manager.async_register_scanner(scanner)
5593 sched._workers[scanner.source].stop()
5594 await asyncio.sleep(0)
5595 try:
5596 # Start L1 and block it inside its flip await.
5597 scanner._block_event = asyncio.Event()
5598 l1 = asyncio.create_task(manager.async_request_active_scan(duration=5.0))
5599 for _ in range(5):
5600 await asyncio.sleep(0)
5601 assert sched._on_demand_sweep_future is not None
5602 # Tear down and re-arm against the same loop, then install
5603 # fresh sweep state as if L2 had won the next dedup check.
5604 # Stop the freshly-spawned worker so its periodic tick does
5605 # not interfere with the assertion below.
5606 sched.stop()
5607 sched.start(loop)
5608 sched._workers[scanner.source].stop()
5609 await asyncio.sleep(0)
5610 fresh_future: asyncio.Future[None] = loop.create_future()
5611 sched._on_demand_sweep_future = fresh_future
5612 # Past-end so L1's sleep loop exits immediately and runs
5613 # its finally; the fresh state below is what we check.
5614 sched._on_demand_sweep_end = loop.time() - 1.0
5615 # Release L1 so its finally runs; it must leave the fresh
5616 # future alone (identity check on ``_on_demand_sweep_future``)
5617 # and must not call ``set_result`` on the already-done L1
5618 # future (the ``done()`` guard).
5619 scanner._block_event.set()
5620 await asyncio.wait_for(l1, timeout=1.0)
5621 assert sched._on_demand_sweep_future is fresh_future
5622 assert not fresh_future.done()
5623 finally:
5624 if not fresh_future.done():
5625 fresh_future.set_result(None)
5626 sched._on_demand_sweep_future = None
5627 sched._on_demand_sweep_end = 0.0
5628 register_cancel()
5629
5630
5631 @pytest.mark.asyncio
5632 async def test_owned_due_at_populated_for_owner_on_add_request_with_history() -> None:
5633 """add_request hooks the entry into the owner's _owned_due_at view."""
5634 manager = get_manager()
5635 sched = manager._auto_scheduler
5636 address = "11:22:33:44:55:66"
5637 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5638 register_cancel = manager.async_register_scanner(scanner)
5639 try:
5640 # First seed history via an advertisement so add_request's
5641 # history-gating finds it.
5642 _inject(scanner, address)
5643 # Drop the entry add_request seeded so we can re-add through
5644 # add_request and observe its _schedule.assign side-effect.
5645 sched._schedule._due_at.pop(address, None)
5646 sched._schedule._owner_by_address.pop(address, None)
5647 sched._workers[scanner.source]._owned_due_at.pop(address, None)
5648 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5649 try:
5650 owned = sched._workers[scanner.source]._owned_due_at
5651 assert address in owned
5652 # Inner dict must be the SAME object aliased between
5653 # _due_at and _owned_due_at so _advance_due mutations apply
5654 # to both views.
5655 assert owned[address] is sched._schedule._due_at[address]
5656 assert sched._schedule._owner_by_address[address] == scanner.source
5657 finally:
5658 cancel()
5659 finally:
5660 register_cancel()
5661
5662
5663 @pytest.mark.asyncio
5664 async def test_add_request_without_history_leaves_owned_due_at_empty() -> None:
5665 """add_request without history defers seeding to on_advertisement."""
5666 manager = get_manager()
5667 sched = manager._auto_scheduler
5668 address = "11:22:33:44:55:66"
5669 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5670 register_cancel = manager.async_register_scanner(scanner)
5671 try:
5672 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5673 try:
5674 assert address not in sched._schedule._due_at
5675 assert address not in sched._schedule._owner_by_address
5676 assert address not in sched._workers[scanner.source]._owned_due_at
5677 finally:
5678 cancel()
5679 finally:
5680 register_cancel()
5681
5682
5683 @pytest.mark.asyncio
5684 async def test_on_advertisement_bootstraps_owned_due_at() -> None:
5685 """First advertisement for a tracked address populates owner's view."""
5686 manager = get_manager()
5687 sched = manager._auto_scheduler
5688 address = "11:22:33:44:55:66"
5689 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5690 register_cancel = manager.async_register_scanner(scanner)
5691 try:
5692 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5693 try:
5694 _inject(scanner, address)
5695 owned = sched._workers[scanner.source]._owned_due_at
5696 assert address in owned
5697 assert owned[address] is sched._schedule._due_at[address]
5698 assert sched._schedule._owner_by_address[address] == scanner.source
5699 finally:
5700 cancel()
5701 finally:
5702 register_cancel()
5703
5704
5705 @pytest.mark.asyncio
5706 async def test_ownership_flip_moves_entry_between_owned_due_at() -> None:
5707 """On migration, the entry moves from old owner's view to new owner's view."""
5708 manager = get_manager()
5709 sched = manager._auto_scheduler
5710 address = "11:22:33:44:55:99"
5711 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5712 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
5713 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
5714 c_a = manager.async_register_scanner(s_a)
5715 c_b = manager.async_register_scanner(s_b)
5716 try:
5717 _inject_with_rssi(s_a, address, rssi=-80)
5718 worker_a = sched._workers[s_a.source]
5719 worker_b = sched._workers[s_b.source]
5720 assert address in worker_a._owned_due_at
5721 assert address not in worker_b._owned_due_at
5722 assert sched._schedule._owner_by_address[address] == s_a.source
5723
5724 # B with much stronger RSSI triggers ownership flip in the
5725 # manager; scheduler's on_advertisement reassigns owner.
5726 _inject_with_rssi(s_b, address, rssi=-30)
5727 assert address not in worker_a._owned_due_at
5728 assert address in worker_b._owned_due_at
5729 assert worker_b._owned_due_at[address] is sched._schedule._due_at[address]
5730 assert sched._schedule._owner_by_address[address] == s_b.source
5731 finally:
5732 c_a()
5733 c_b()
5734 cancel()
5735
5736
5737 @pytest.mark.asyncio
5738 async def test_remove_request_clears_owner_when_bucket_empties() -> None:
5739 """The last remove_request for an address clears owner and _owned_due_at."""
5740 manager = get_manager()
5741 sched = manager._auto_scheduler
5742 address = "11:22:33:44:55:66"
5743 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5744 register_cancel = manager.async_register_scanner(scanner)
5745 try:
5746 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5747 _inject(scanner, address)
5748 worker = sched._workers[scanner.source]
5749 assert address in worker._owned_due_at
5750 cancel()
5751 assert address not in sched._schedule._due_at
5752 assert address not in sched._schedule._owner_by_address
5753 assert address not in worker._owned_due_at
5754 finally:
5755 register_cancel()
5756
5757
5758 @pytest.mark.asyncio
5759 async def test_remove_request_preserves_owner_when_other_requests_remain() -> None:
5760 """Removing one of N requests on an address keeps the owner mapping intact."""
5761 manager = get_manager()
5762 sched = manager._auto_scheduler
5763 address = "11:22:33:44:55:66"
5764 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5765 register_cancel = manager.async_register_scanner(scanner)
5766 try:
5767 cancel1 = manager.async_register_active_scan(address, scan_interval=60.0)
5768 cancel2 = manager.async_register_active_scan(address, scan_interval=120.0)
5769 _inject(scanner, address)
5770 worker = sched._workers[scanner.source]
5771 assert len(sched._schedule._due_at[address]) == 2
5772 cancel1()
5773 assert address in sched._schedule._due_at
5774 assert sched._schedule._owner_by_address[address] == scanner.source
5775 assert address in worker._owned_due_at
5776 cancel2()
5777 assert address not in sched._schedule._due_at
5778 assert address not in sched._schedule._owner_by_address
5779 assert address not in worker._owned_due_at
5780 finally:
5781 register_cancel()
5782
5783
5784 @pytest.mark.asyncio
5785 async def test_remove_scanner_clears_owner_and_due_at() -> None:
5786 """Removing the owning scanner drops the entry from _due_at and the owner index."""
5787 manager = get_manager()
5788 sched = manager._auto_scheduler
5789 address = "11:22:33:44:55:66"
5790 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5791 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5792 register_cancel = manager.async_register_scanner(scanner)
5793 try:
5794 _inject(scanner, address)
5795 assert address in sched._schedule._due_at
5796 assert sched._schedule._owner_by_address[address] == scanner.source
5797 register_cancel()
5798 assert address not in sched._schedule._due_at
5799 assert address not in sched._schedule._owner_by_address
5800 assert scanner.source not in sched._workers
5801 finally:
5802 cancel()
5803
5804
5805 @pytest.mark.asyncio
5806 async def test_stop_clears_all_owned_due_at_state() -> None:
5807 """stop() drains _due_at, _owner_by_address, and per-worker _owned_due_at."""
5808 manager = get_manager()
5809 sched = manager._auto_scheduler
5810 address = "11:22:33:44:55:66"
5811 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5812 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5813 register_cancel = manager.async_register_scanner(scanner)
5814 try:
5815 _inject(scanner, address)
5816 worker = sched._workers[scanner.source]
5817 assert address in worker._owned_due_at
5818 sched.stop()
5819 assert sched._schedule._due_at == {}
5820 assert sched._schedule._owner_by_address == {}
5821 # Worker dropped from registry; the cleared dict is on the
5822 # detached instance still held by the local. Confirm both.
5823 assert sched._workers == {}
5824 assert worker._owned_due_at == {}
5825 finally:
5826 cancel()
5827 # register_cancel() may double-call but is idempotent on the
5828 # manager side; guard against AttributeError nonetheless.
5829 with contextlib.suppress(KeyError, ValueError):
5830 register_cancel()
5831
5832
5833 @pytest.mark.asyncio
5834 async def test_start_replay_populates_owned_due_at() -> None:
5835 """A request registered before start() is hooked into the worker's view on start."""
5836 manager = get_manager()
5837 sched = manager._auto_scheduler
5838 loop = asyncio.get_running_loop()
5839 address = "11:22:33:44:55:66"
5840 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5841 register_cancel = manager.async_register_scanner(scanner)
5842 try:
5843 # Seed history via a real injection so the replay loop's
5844 # last_service_info check sees a source.
5845 _inject(scanner, address)
5846 # Wipe scheduler state and stop the running scheduler so we
5847 # can drive start() ourselves with pre-registered requests.
5848 sched._workers[scanner.source].stop()
5849 await asyncio.sleep(0)
5850 sched.stop()
5851 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5852 try:
5853 # Pre-start: only _requests_by_address is populated.
5854 assert address not in sched._schedule._due_at
5855 assert address not in sched._schedule._owner_by_address
5856 sched.start(loop)
5857 try:
5858 # After start, the replay seeded _due_at and assigned
5859 # the owner.
5860 worker = sched._workers[scanner.source]
5861 assert address in sched._schedule._due_at
5862 assert sched._schedule._owner_by_address[address] == scanner.source
5863 assert address in worker._owned_due_at
5864 assert worker._owned_due_at[address] is sched._schedule._due_at[address]
5865 finally:
5866 # Stop the spawned worker tasks so they do not leak.
5867 for w in list(sched._workers.values()):
5868 w.stop()
5869 await asyncio.sleep(0)
5870 finally:
5871 cancel()
5872 finally:
5873 register_cancel()
5874
5875
5876 @pytest.mark.asyncio
5877 async def test_spawn_worker_picks_up_preassigned_owner() -> None:
5878 """A scanner registering after on_advertisement gets the entry hooked up."""
5879 manager = get_manager()
5880 sched = manager._auto_scheduler
5881 loop = asyncio.get_running_loop()
5882 address = "11:22:33:44:55:66"
5883 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5884 source = "AA:BB:CC:DD:EE:00"
5885 # Forge an owner mapping for an unregistered source — the same
5886 # state that arises when on_advertisement seeds before its scanner
5887 # registers as AUTO. We bypass the manager here because plumbing a
5888 # synthetic history entry is more wiring than the invariant needs.
5889 request = next(iter(sched._requests_by_address[address]))
5890 sched._schedule._due_at[address] = {request: loop.time()}
5891 sched._schedule._owner_by_address[address] = source
5892 try:
5893 scanner = _RecordingAutoScanner(source, BluetoothScanningMode.AUTO)
5894 register_cancel = manager.async_register_scanner(scanner)
5895 try:
5896 worker = sched._workers[source]
5897 assert address in worker._owned_due_at
5898 assert worker._owned_due_at[address] is sched._schedule._due_at[address]
5899 finally:
5900 register_cancel()
5901 finally:
5902 cancel()
5903
5904
5905 @pytest.mark.asyncio
5906 async def test_next_event_at_skips_other_workers_entries() -> None:
5907 """An entry owned by scanner A doesn't lower scanner B's next event."""
5908 manager = get_manager()
5909 sched = manager._auto_scheduler
5910 loop = asyncio.get_running_loop()
5911 address = "11:22:33:44:55:66"
5912 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5913 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
5914 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
5915 c_a = manager.async_register_scanner(s_a)
5916 c_b = manager.async_register_scanner(s_b)
5917 try:
5918 _inject(s_a, address)
5919 # Drive the entry's due time well below A's sweep so any leak
5920 # of foreign entries would change B's next_at.
5921 entries = sched._schedule._due_at[address]
5922 for req in list(entries):
5923 entries[req] = loop.time() + 1.0
5924 worker_b = sched._workers[s_b.source]
5925 sweep_at_b = worker_b._sweep_last_completed + AUTO_REDISCOVERY_INTERVAL
5926 assert worker_b._next_event_at(loop.time()) == sweep_at_b
5927 finally:
5928 c_a()
5929 c_b()
5930 cancel()
5931
5932
5933 @pytest.mark.asyncio
5934 async def test_next_event_at_makes_no_history_calls() -> None:
5935 """The hot path no longer pays a per-entry async_last_service_info lookup."""
5936 manager = get_manager()
5937 sched = manager._auto_scheduler
5938 loop = asyncio.get_running_loop()
5939 address = "11:22:33:44:55:66"
5940 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5941 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
5942 register_cancel = manager.async_register_scanner(scanner)
5943 try:
5944 _inject(scanner, address)
5945 worker = sched._workers[scanner.source]
5946 with patch.object(
5947 manager, "async_last_service_info", side_effect=AssertionError
5948 ):
5949 # Must not consult the manager's history; iterates owned
5950 # entries exclusively.
5951 worker._next_event_at(loop.time())
5952 finally:
5953 cancel()
5954 register_cancel()
5955
5956
5957 @pytest.mark.asyncio
5958 async def test_collect_due_buckets_resyncs_owned_view_on_drift() -> None:
5959 """If owned view disagrees with manager history, _collect_due_buckets resyncs."""
5960 manager = get_manager()
5961 sched = manager._auto_scheduler
5962 loop = asyncio.get_running_loop()
5963 address = "11:22:33:44:55:66"
5964 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
5965 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
5966 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
5967 c_a = manager.async_register_scanner(s_a)
5968 c_b = manager.async_register_scanner(s_b)
5969 try:
5970 _inject(s_a, address)
5971 worker_a = sched._workers[s_a.source]
5972 worker_b = sched._workers[s_b.source]
5973 # Force a drift: manager's history says B owns the address,
5974 # scheduler still has it parked under A's view. (Simulates
5975 # any future code path that mutates history without notifying
5976 # on_advertisement.)
5977 info = manager.async_last_service_info(address, False)
5978 assert info is not None
5979 info.source = s_b.source
5980 entries = sched._schedule._due_at[address]
5981 for req in list(entries):
5982 entries[req] = loop.time() - 1.0
5983 await worker_a._tick()
5984 # A skipped (foreign), reassigned ownership to B.
5985 assert s_a.active_window_calls == []
5986 assert address not in worker_a._owned_due_at
5987 assert address in worker_b._owned_due_at
5988 assert sched._schedule._owner_by_address[address] == s_b.source
5989 finally:
5990 c_a()
5991 c_b()
5992 cancel()
5993
5994
5995 @pytest.mark.asyncio
5996 async def test_assign_owner_noop_when_source_unchanged() -> None:
5997 """Repeated on_advertisement from the same scanner is a no-op."""
5998 manager = get_manager()
5999 sched = manager._auto_scheduler
6000 address = "11:22:33:44:55:66"
6001 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6002 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6003 register_cancel = manager.async_register_scanner(scanner)
6004 try:
6005 _inject(scanner, address)
6006 worker = sched._workers[scanner.source]
6007 entries = sched._schedule._due_at[address]
6008 owned_before = worker._owned_due_at[address]
6009 # Second injection from the same scanner: owner unchanged,
6010 # owned-view aliasing preserved (same dict object).
6011 _inject(scanner, address)
6012 assert sched._schedule._owner_by_address[address] == scanner.source
6013 assert worker._owned_due_at[address] is owned_before
6014 assert sched._schedule._due_at[address] is entries
6015 finally:
6016 cancel()
6017 register_cancel()
6018
6019
6020 @pytest.mark.asyncio
6021 async def test_spawn_worker_skips_foreign_preassigned_owners() -> None:
6022 """_spawn_worker only attaches entries owned by the new scanner's source."""
6023 manager = get_manager()
6024 sched = manager._auto_scheduler
6025 loop = asyncio.get_running_loop()
6026 address_a = "11:22:33:44:55:66"
6027 address_b = "77:88:99:AA:BB:CC"
6028 cancel_a = manager.async_register_active_scan(address_a, scan_interval=60.0)
6029 cancel_b = manager.async_register_active_scan(address_b, scan_interval=60.0)
6030 foreign_source = "AA:BB:CC:DD:EE:FF"
6031 request_b = next(iter(sched._requests_by_address[address_b]))
6032 sched._schedule._due_at[address_b] = {request_b: loop.time()}
6033 sched._schedule._owner_by_address[address_b] = foreign_source
6034 try:
6035 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6036 register_cancel = manager.async_register_scanner(scanner)
6037 try:
6038 worker = sched._workers[scanner.source]
6039 # Foreign-owned address must not appear in this worker's view.
6040 assert address_b not in worker._owned_due_at
6041 finally:
6042 register_cancel()
6043 finally:
6044 cancel_a()
6045 cancel_b()
6046
6047
6048 @pytest.mark.asyncio
6049 async def test_ownership_index_clear_source_no_match() -> None:
6050 """clear_source over an index with no addresses for the source is a no-op."""
6051 manager = get_manager()
6052 sched = manager._auto_scheduler
6053 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6054 register_cancel = manager.async_register_scanner(scanner)
6055 try:
6056 worker = sched._workers[scanner.source]
6057 sched._schedule.clear_source(scanner.source)
6058 assert sched._schedule._owner_by_address == {}
6059 assert worker._owned_due_at == {}
6060 finally:
6061 register_cancel()
6062
6063
6064 def test_ownership_index_clear_no_workers() -> None:
6065 """clear() over an index with no workers leaves state empty."""
6066 workers: dict[str, Any] = {}
6067 idx = _ScanSchedule(workers)
6068 idx._owner_by_address["AA:00:00:00:00:99"] = "ghost"
6069 idx.clear()
6070 assert idx._owner_by_address == {}
6071
6072
6073 @pytest.mark.asyncio
6074 async def test_ownership_assign_records_non_auto_owner() -> None:
6075 """assign() records ownership for a non-AUTO source despite no worker."""
6076 manager = get_manager()
6077 sched = manager._auto_scheduler
6078 address = "11:22:33:44:55:66"
6079 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6080 # ACTIVE scanner does not get an AUTO worker; advertising from it
6081 # exercises the ``new_worker is None`` branch in assign().
6082 passive = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.PASSIVE)
6083 register_cancel = manager.async_register_scanner(passive)
6084 try:
6085 _inject(passive, address)
6086 assert sched._schedule._owner_by_address[address] == passive.source
6087 assert passive.source not in sched._workers
6088 finally:
6089 cancel()
6090 register_cancel()
6091
6092
6093 @pytest.mark.asyncio
6094 async def test_remove_non_auto_scanner_clears_its_owned_addresses() -> None:
6095 """clear_source's non-AUTO fallback prunes addresses owned by a PASSIVE source."""
6096 manager = get_manager()
6097 sched = manager._auto_scheduler
6098 own_addr = "11:22:33:44:55:66"
6099 other_addr = "11:22:33:44:55:77"
6100 cancel_own = manager.async_register_active_scan(own_addr, scan_interval=60.0)
6101 cancel_other = manager.async_register_active_scan(other_addr, scan_interval=60.0)
6102 passive = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.PASSIVE)
6103 auto = _RecordingAutoScanner("AA:BB:CC:DD:EE:02", BluetoothScanningMode.AUTO)
6104 c_passive = manager.async_register_scanner(passive)
6105 c_auto = manager.async_register_scanner(auto)
6106 try:
6107 # PASSIVE owns own_addr; AUTO owns other_addr. Both end up in
6108 # _owner_by_address, so the non-AUTO clear loop iterates past
6109 # other_addr without matching.
6110 _inject(passive, own_addr)
6111 _inject(auto, other_addr)
6112 assert sched._schedule._owner_by_address[own_addr] == passive.source
6113 assert sched._schedule._owner_by_address[other_addr] == auto.source
6114 c_passive()
6115 assert own_addr not in sched._schedule._owner_by_address
6116 assert own_addr not in sched._schedule._due_at
6117 # The AUTO-owned address is untouched.
6118 assert sched._schedule._owner_by_address[other_addr] == auto.source
6119 finally:
6120 cancel_own()
6121 cancel_other()
6122 c_auto()
6123
6124
6125 @pytest.mark.asyncio
6126 async def test_ownership_flip_from_non_auto_to_auto_owner() -> None:
6127 """assign() handles flipping from a non-AUTO owner whose worker is absent."""
6128 manager = get_manager()
6129 sched = manager._auto_scheduler
6130 address = "11:22:33:44:55:66"
6131 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6132 passive = _RecordingAutoScanner("AA:BB:CC:DD:EE:01", BluetoothScanningMode.PASSIVE)
6133 auto = _RecordingAutoScanner("AA:BB:CC:DD:EE:02", BluetoothScanningMode.AUTO)
6134 c_passive = manager.async_register_scanner(passive)
6135 c_auto = manager.async_register_scanner(auto)
6136 try:
6137 # PASSIVE first with weak RSSI; records owner mapping with no worker.
6138 _inject_with_rssi(passive, address, rssi=-80)
6139 assert sched._schedule._owner_by_address[address] == passive.source
6140 # AUTO flip with stronger RSSI: old_source has no worker (PASSIVE),
6141 # so the detach branch in assign() hits ``old_worker is None``.
6142 _inject_with_rssi(auto, address, rssi=-30)
6143 assert sched._schedule._owner_by_address[address] == auto.source
6144 assert address in sched._workers[auto.source]._owned_due_at
6145 finally:
6146 cancel()
6147 c_passive()
6148 c_auto()
6149
6150
6151 @pytest.mark.asyncio
6152 async def test_invariant_through_full_lifecycle() -> None:
6153 """Schedule invariant holds at every step of a typical request lifecycle."""
6154 manager = get_manager()
6155 sched = manager._auto_scheduler
6156 address = "11:22:33:44:55:66"
6157 _assert_schedule_invariant(sched)
6158 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6159 register_cancel = manager.async_register_scanner(scanner)
6160 _assert_schedule_invariant(sched)
6161 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6162 _assert_schedule_invariant(sched)
6163 _inject(scanner, address)
6164 _assert_schedule_invariant(sched)
6165 assert address in sched._schedule._due_at
6166 assert sched._schedule._owner_by_address[address] == scanner.source
6167 cancel()
6168 _assert_schedule_invariant(sched)
6169 assert address not in sched._schedule._due_at
6170 assert address not in sched._schedule._owner_by_address
6171 register_cancel()
6172 _assert_schedule_invariant(sched)
6173
6174
6175 @pytest.mark.asyncio
6176 async def test_invariant_through_ownership_flips() -> None:
6177 """Schedule invariant holds through a sequence of RSSI-driven flips."""
6178 manager = get_manager()
6179 sched = manager._auto_scheduler
6180 address = "11:22:33:44:55:66"
6181 s_a = _RecordingAutoScanner("AA:00:00:00:00:01", BluetoothScanningMode.AUTO)
6182 s_b = _RecordingAutoScanner("AA:00:00:00:00:02", BluetoothScanningMode.AUTO)
6183 s_c = _RecordingAutoScanner("AA:00:00:00:00:03", BluetoothScanningMode.AUTO)
6184 c_a = manager.async_register_scanner(s_a)
6185 c_b = manager.async_register_scanner(s_b)
6186 c_c = manager.async_register_scanner(s_c)
6187 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6188 try:
6189 _assert_schedule_invariant(sched)
6190 # Each step is a >= 40 dB jump (monotonically stronger) so the
6191 # manager flips ownership on every inject.
6192 for scanner, rssi in (
6193 (s_a, -100),
6194 (s_b, -60),
6195 (s_c, -20),
6196 ):
6197 _inject_with_rssi(scanner, address, rssi=rssi)
6198 _assert_schedule_invariant(sched)
6199 assert sched._schedule._owner_by_address[address] == scanner.source
6200 # Same scanner re-advertises: same owner; invariant holds.
6201 _inject_with_rssi(s_c, address, rssi=-15)
6202 _assert_schedule_invariant(sched)
6203 assert sched._schedule._owner_by_address[address] == s_c.source
6204 finally:
6205 cancel()
6206 c_a()
6207 c_b()
6208 c_c()
6209 _assert_schedule_invariant(sched)
6210
6211
6212 @pytest.mark.asyncio
6213 async def test_invariant_through_mixed_mode_flips() -> None:
6214 """
6215 Schedule invariant holds when ownership flips across all scanner modes.
6216
6217 Mix of ACTIVE, PASSIVE, and AUTO scanners; ownership migrates among
6218 them as RSSI climbs. Only the AUTO scanner has a worker, so the
6219 invariant exercises both the "owner has worker" and "owner has no
6220 worker" branches in the same scenario.
6221 """
6222 manager = get_manager()
6223 sched = manager._auto_scheduler
6224 address = "11:22:33:44:55:66"
6225 active = _RecordingAutoScanner("AA:00:00:00:00:0A", BluetoothScanningMode.ACTIVE)
6226 passive = _RecordingAutoScanner("AA:00:00:00:00:0B", BluetoothScanningMode.PASSIVE)
6227 auto = _RecordingAutoScanner("AA:00:00:00:00:0C", BluetoothScanningMode.AUTO)
6228 c_active = manager.async_register_scanner(active)
6229 c_passive = manager.async_register_scanner(passive)
6230 c_auto = manager.async_register_scanner(auto)
6231 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6232 try:
6233 _assert_schedule_invariant(sched)
6234 # Workers exist only for AUTO scanners.
6235 assert active.source not in sched._workers
6236 assert passive.source not in sched._workers
6237 assert auto.source in sched._workers
6238 auto_worker = sched._workers[auto.source]
6239 # ACTIVE first (no worker for the owner; address is in
6240 # _owner_by_address but not in any worker's _owned_due_at).
6241 _inject_with_rssi(active, address, rssi=-100)
6242 _assert_schedule_invariant(sched)
6243 assert sched._schedule._owner_by_address[address] == active.source
6244 assert address not in auto_worker._owned_due_at
6245 # PASSIVE with stronger RSSI: another non-AUTO owner.
6246 _inject_with_rssi(passive, address, rssi=-60)
6247 _assert_schedule_invariant(sched)
6248 assert sched._schedule._owner_by_address[address] == passive.source
6249 assert address not in auto_worker._owned_due_at
6250 # AUTO with stronger RSSI: ownership flips to the worker-having
6251 # source; the address now appears in the worker's owned view.
6252 _inject_with_rssi(auto, address, rssi=-20)
6253 _assert_schedule_invariant(sched)
6254 assert sched._schedule._owner_by_address[address] == auto.source
6255 assert address in auto_worker._owned_due_at
6256 # Flip BACK to PASSIVE by unregistering the AUTO scanner: its
6257 # owned-view entry is pruned via clear_source. The address goes
6258 # away from the schedule entirely (no other scanner advertised
6259 # since the AUTO claim).
6260 c_auto()
6261 _assert_schedule_invariant(sched)
6262 assert address not in sched._schedule._owner_by_address
6263 # A subsequent PASSIVE advertisement re-bootstraps ownership;
6264 # back to non-AUTO-owned state without a worker view.
6265 _inject_with_rssi(passive, address, rssi=-50)
6266 _assert_schedule_invariant(sched)
6267 assert sched._schedule._owner_by_address[address] == passive.source
6268 finally:
6269 cancel()
6270 c_active()
6271 c_passive()
6272 _assert_schedule_invariant(sched)
6273
6274
6275 @pytest.mark.asyncio
6276 async def test_invariant_through_orphan_prune() -> None:
6277 """Schedule invariant holds after a tick prunes an aged-out address."""
6278 manager = get_manager()
6279 sched = manager._auto_scheduler
6280 loop = asyncio.get_running_loop()
6281 address = "AA:BB:CC:DD:EE:FF"
6282 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6283 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6284 register_cancel = manager.async_register_scanner(scanner)
6285 try:
6286 _inject(scanner, address)
6287 _assert_schedule_invariant(sched)
6288 # Force the entry due so the tick actually inspects history.
6289 request = next(iter(sched._schedule._due_at[address]))
6290 sched._schedule._due_at[address][request] = loop.time() - 1.0
6291 # History ages out under the worker's feet; the tick's orphan
6292 # branch should clean every index in lock step.
6293 manager._all_history.pop(address, None)
6294 manager._connectable_history.pop(address, None)
6295 await _run_worker_tick(sched, scanner.source)
6296 _assert_schedule_invariant(sched)
6297 assert address not in sched._schedule._due_at
6298 assert address not in sched._schedule._owner_by_address
6299 finally:
6300 cancel()
6301 register_cancel()
6302
6303
6304 @pytest.mark.asyncio
6305 async def test_invariant_through_many_addresses_and_scanners() -> None:
6306 """Schedule invariant holds when many scanners and addresses interleave."""
6307 manager = get_manager()
6308 sched = manager._auto_scheduler
6309 scanners = [
6310 _RecordingAutoScanner(f"AA:00:00:00:00:{i:02X}", BluetoothScanningMode.AUTO)
6311 for i in range(4)
6312 ]
6313 register_cancels = [manager.async_register_scanner(s) for s in scanners]
6314 cancels = [
6315 manager.async_register_active_scan(
6316 f"BB:00:00:00:00:{i:02X}", scan_interval=60.0
6317 )
6318 for i in range(16)
6319 ]
6320 addresses = [f"BB:00:00:00:00:{i:02X}" for i in range(16)]
6321 try:
6322 _assert_schedule_invariant(sched)
6323 # Round-robin each address to a scanner, ramping RSSI by 30 dB
6324 # per round so every later inject flips ownership.
6325 for round_ix, scanner in enumerate(scanners):
6326 rssi = -100 + 30 * round_ix
6327 for address in addresses:
6328 _inject_with_rssi(scanner, address, rssi=rssi)
6329 _assert_schedule_invariant(sched)
6330 # All addresses now owned by the last scanner (strongest RSSI).
6331 last = scanners[-1]
6332 for address in addresses:
6333 assert sched._schedule._owner_by_address[address] == last.source
6334 # Removing the owner scanner prunes the addresses it owned;
6335 # the schedule cleans them out without surfacing them anywhere.
6336 register_cancels[-1]()
6337 _assert_schedule_invariant(sched)
6338 for address in addresses:
6339 assert address not in sched._schedule._due_at
6340 finally:
6341 for c in cancels:
6342 c()
6343 for rc in register_cancels[:-1]:
6344 rc()
6345 _assert_schedule_invariant(sched)
6346
6347
6348 @pytest.mark.asyncio
6349 async def test_unown_fails_fast_on_missing_due_at() -> None:
6350 """Pin the fail-fast contract: KeyError if ``_due_at`` lacks the address."""
6351 manager = get_manager()
6352 sched = manager._auto_scheduler
6353 sched._schedule._owner_by_address["AA:00:00:00:00:99"] = "ghost"
6354 try:
6355 with pytest.raises(KeyError):
6356 sched._schedule.unown("AA:00:00:00:00:99")
6357 finally:
6358 sched._schedule._owner_by_address.pop("AA:00:00:00:00:99", None)
6359
6360
6361 @pytest.mark.asyncio
6362 async def test_unown_fails_fast_on_missing_owner() -> None:
6363 """Pin the fail-fast contract: KeyError if ``_owner_by_address`` lacks address."""
6364 manager = get_manager()
6365 sched = manager._auto_scheduler
6366 sched._schedule._due_at["AA:00:00:00:00:99"] = {}
6367 try:
6368 with pytest.raises(KeyError):
6369 sched._schedule.unown("AA:00:00:00:00:99")
6370 finally:
6371 sched._schedule._due_at.pop("AA:00:00:00:00:99", None)
6372
6373
6374 @pytest.mark.asyncio
6375 async def test_detach_owned_fails_fast_on_missing_address() -> None:
6376 """Pin the fail-fast contract: KeyError if worker doesn't own the address."""
6377 manager = get_manager()
6378 sched = manager._auto_scheduler
6379 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6380 register_cancel = manager.async_register_scanner(scanner)
6381 try:
6382 worker = sched._workers[scanner.source]
6383 with pytest.raises(KeyError):
6384 worker._detach_owned("AA:00:00:00:00:99")
6385 finally:
6386 register_cancel()
6387
6388
6389 @pytest.mark.asyncio
6390 async def test_next_event_at_fails_fast_on_empty_owned_bucket() -> None:
6391 """Pin the fail-fast contract: ValueError on an empty owned bucket."""
6392 manager = get_manager()
6393 sched = manager._auto_scheduler
6394 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6395 register_cancel = manager.async_register_scanner(scanner)
6396 try:
6397 worker = sched._workers[scanner.source]
6398 worker._owned_due_at["AA:00:00:00:00:99"] = {}
6399 try:
6400 with pytest.raises(ValueError, match="min"):
6401 worker._next_event_at(asyncio.get_running_loop().time())
6402 finally:
6403 worker._owned_due_at.pop("AA:00:00:00:00:99", None)
6404 finally:
6405 register_cancel()
6406
6407
6408 @pytest.mark.asyncio
6409 async def test_invariant_through_mode_switches() -> None:
6410 """
6411 Schedule invariant holds across in-place scanner mode switches.
6412
6413 HA's UI mode switch is implemented as unregister-old + register-new
6414 with the same source. The scheduler has to (a) drop the worker when
6415 AUTO leaves, (b) spawn a fresh worker when AUTO arrives, and (c)
6416 keep ``_requests_by_address`` intact across the gap so the new
6417 worker can be re-bootstrapped. Walk through every transition with
6418 invariant checks at each step.
6419 """
6420 manager = get_manager()
6421 sched = manager._auto_scheduler
6422 source = "AA:BB:CC:DD:EE:32"
6423 address = "11:22:33:44:55:99"
6424 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6425 _assert_schedule_invariant(sched)
6426 try:
6427 # 1. PASSIVE first (entering as non-AUTO).
6428 passive = _RecordingAutoScanner(source, BluetoothScanningMode.PASSIVE)
6429 c_passive = manager.async_register_scanner(passive)
6430 _assert_schedule_invariant(sched)
6431 assert source not in sched._workers
6432 _inject(passive, address)
6433 _assert_schedule_invariant(sched)
6434 assert sched._schedule._owner_by_address[address] == source
6435 # 2. Switch INTO AUTO: unregister PASSIVE, register AUTO at same source.
6436 c_passive()
6437 _assert_schedule_invariant(sched)
6438 # PASSIVE's clear_source removed the owner mapping.
6439 assert address not in sched._schedule._owner_by_address
6440 # User's registration survived.
6441 assert address in sched._requests_by_address
6442 auto = _RecordingAutoScanner(source, BluetoothScanningMode.AUTO)
6443 c_auto = manager.async_register_scanner(auto)
6444 _assert_schedule_invariant(sched)
6445 assert source in sched._workers
6446 # 3. AUTO sees the device, becomes owner with a worker attached.
6447 _inject(auto, address)
6448 _assert_schedule_invariant(sched)
6449 assert sched._schedule._owner_by_address[address] == source
6450 assert address in sched._workers[source]._owned_due_at
6451 # 4. Switch OUT of AUTO: unregister AUTO, register ACTIVE same source.
6452 c_auto()
6453 _assert_schedule_invariant(sched)
6454 assert source not in sched._workers
6455 assert address not in sched._schedule._owner_by_address
6456 active = _RecordingAutoScanner(source, BluetoothScanningMode.ACTIVE)
6457 c_active = manager.async_register_scanner(active)
6458 _assert_schedule_invariant(sched)
6459 assert source not in sched._workers
6460 # 5. ACTIVE sees the device; back to a non-AUTO-owned state.
6461 _inject(active, address)
6462 _assert_schedule_invariant(sched)
6463 assert sched._schedule._owner_by_address[address] == source
6464 c_active()
6465 _assert_schedule_invariant(sched)
6466 finally:
6467 cancel()
6468 _assert_schedule_invariant(sched)
6469
6470
6471 @pytest.mark.asyncio
6472 async def test_invariant_through_stop_and_restart() -> None:
6473 """Schedule invariant holds across stop + start replay."""
6474 manager = get_manager()
6475 sched = manager._auto_scheduler
6476 address = "11:22:33:44:55:66"
6477 scanner = _RecordingAutoScanner("AA:BB:CC:DD:EE:00", BluetoothScanningMode.AUTO)
6478 register_cancel = manager.async_register_scanner(scanner)
6479 cancel = manager.async_register_active_scan(address, scan_interval=60.0)
6480 try:
6481 _inject(scanner, address)
6482 _assert_schedule_invariant(sched)
6483 sched.stop()
6484 _assert_schedule_invariant(sched)
6485 assert sched._schedule._due_at == {}
6486 assert sched._schedule._owner_by_address == {}
6487 # Give the previously running worker task a chance to fully exit
6488 # so the post-restart spawn doesn't share its source slot.
6489 await asyncio.sleep(0)
6490 loop = asyncio.get_running_loop()
6491 sched.start(loop)
6492 _assert_schedule_invariant(sched)
6493 # start() replayed the request and re-assigned via history.
6494 assert address in sched._schedule._due_at
6495 assert sched._schedule._owner_by_address[address] == scanner.source
6496 finally:
6497 cancel()
6498 register_cancel()
6499 _assert_schedule_invariant(sched)
6500
6501
6502 @pytest.mark.asyncio
6503 async def test_trigger_rescue_auto_owner_and_auto_challenger() -> None:
6504 """
6505 trigger_rescue serves both sides of a deferred stale handoff.
6506
6507 The AUTO owner's due times are clamped to now so its worker fires a
6508 window on its next tick; the AUTO challenger gets a directly delegated
6509 window and the rescue completion is recorded.
6510 """
6511 manager = get_manager()
6512 sched = manager._auto_scheduler
6513 loop = asyncio.get_running_loop()
6514 address = "11:22:33:44:66:01"
6515 cancel = manager.async_register_active_scan(
6516 address, scan_interval=120.0, scan_duration=7.0
6517 )
6518 owner = _DiscoverableAutoScanner("AA:00:00:00:91:01", BluetoothScanningMode.AUTO)
6519 challenger = _DiscoverableAutoScanner(
6520 "AA:00:00:00:91:02", BluetoothScanningMode.AUTO
6521 )
6522 c_owner = manager.async_register_scanner(owner)
6523 c_challenger = manager.async_register_scanner(challenger)
6524 try:
6525 _inject_with_rssi(owner, address, rssi=-50)
6526 manager._rescue_triggered[address] = 0.1
6527 before = monotonic_time_coarse()
6528 sched.trigger_rescue(address, challenger.source, owner.source)
6529 # Owner side: every due time clamped to now so the next tick fires.
6530 now = loop.time()
6531 assert all(due <= now for due in sched._schedule._due_at[address].values())
6532 # Challenger side: a directly delegated window.
6533 for task in list(sched._rescue_tasks):
6534 await task
6535 await asyncio.sleep(0)
6536 assert challenger.active_window_calls == [7.0]
6537 assert not sched._rescue_tasks
6538 # Accept time recorded at dispatch + RESCUE_SCAN_ACCEPT_SECONDS,
6539 # comparable with adv times; the handoff does not wait for the
6540 # full window to close.
6541 assert (
6542 sched._rescue_accept_after[address] >= before + RESCUE_SCAN_ACCEPT_SECONDS
6543 )
6544 assert sched._rescue_accept_after[address] < before + 7.0
6545 # Owner side actually fires on its tick and re-records completion.
6546 await _run_worker_tick(sched, owner.source)
6547 assert owner.active_window_calls == [7.0]
6548 finally:
6549 cancel()
6550 c_owner()
6551 c_challenger()
6552
6553
6554 @pytest.mark.asyncio
6555 async def test_trigger_rescue_active_challenger_counts_covered() -> None:
6556 """A weaker ACTIVE challenger gets no window; its side is covered now."""
6557 manager = get_manager()
6558 sched = manager._auto_scheduler
6559 address = "11:22:33:44:66:02"
6560 cancel = manager.async_register_active_scan(
6561 address, scan_interval=120.0, scan_duration=7.0
6562 )
6563 owner = _DiscoverableAutoScanner("AA:00:00:00:92:01", BluetoothScanningMode.AUTO)
6564 challenger = _DiscoverableAutoScanner(
6565 "AA:00:00:00:92:02", BluetoothScanningMode.ACTIVE
6566 )
6567 c_owner = manager.async_register_scanner(owner)
6568 c_challenger = manager.async_register_scanner(challenger)
6569 try:
6570 _inject_with_rssi(owner, address, rssi=-50)
6571 before = monotonic_time_coarse()
6572 sched.trigger_rescue(address, challenger.source, owner.source)
6573 after = monotonic_time_coarse()
6574 # Already actively scanning: no window, no task, covered with
6575 # the standard accept grace.
6576 assert challenger.active_window_calls == []
6577 assert owner.active_window_calls == []
6578 assert not sched._rescue_tasks
6579 assert (
6580 before + RESCUE_SCAN_ACCEPT_SECONDS
6581 <= sched._rescue_accept_after[address]
6582 <= after + RESCUE_SCAN_ACCEPT_SECONDS
6583 )
6584 # The owner side is still served: its scheduled due times are
6585 # clamped to now so its worker fires a window on the next tick.
6586 loop_now = asyncio.get_running_loop().time()
6587 assert all(due <= loop_now for due in sched._schedule._due_at[address].values())
6588 finally:
6589 cancel()
6590 c_owner()
6591 c_challenger()
6592
6593
6594 @pytest.mark.asyncio
6595 async def test_trigger_rescue_active_owner_counts_covered() -> None:
6596 """An ACTIVE owner is already scanning; its side completes now."""
6597 manager = get_manager()
6598 sched = manager._auto_scheduler
6599 address = "11:22:33:44:66:03"
6600 cancel = manager.async_register_active_scan(
6601 address, scan_interval=120.0, scan_duration=7.0
6602 )
6603 owner = _DiscoverableAutoScanner("AA:00:00:00:93:01", BluetoothScanningMode.ACTIVE)
6604 challenger = _DiscoverableAutoScanner(
6605 "AA:00:00:00:93:02", BluetoothScanningMode.PASSIVE
6606 )
6607 c_owner = manager.async_register_scanner(owner)
6608 c_challenger = manager.async_register_scanner(challenger)
6609 try:
6610 _inject_with_rssi(owner, address, rssi=-50)
6611 manager._rescue_triggered[address] = 0.1
6612 before = monotonic_time_coarse()
6613 sched.trigger_rescue(address, challenger.source, owner.source)
6614 after = monotonic_time_coarse()
6615 # PASSIVE challenger gets no window; the owner side is covered
6616 # with the standard accept grace.
6617 assert challenger.active_window_calls == []
6618 assert owner.active_window_calls == []
6619 assert (
6620 before + RESCUE_SCAN_ACCEPT_SECONDS
6621 <= sched._rescue_accept_after[address]
6622 <= after + RESCUE_SCAN_ACCEPT_SECONDS
6623 )
6624 finally:
6625 cancel()
6626 c_owner()
6627 c_challenger()
6628
6629
6630 @pytest.mark.asyncio
6631 async def test_trigger_rescue_connecting_challenger_not_delegated() -> None:
6632 """A mid-connect challenger cannot run a window; no completion is faked."""
6633 manager = get_manager()
6634 sched = manager._auto_scheduler
6635 address = "11:22:33:44:66:04"
6636 cancel = manager.async_register_active_scan(
6637 address, scan_interval=120.0, scan_duration=7.0
6638 )
6639 owner = _DiscoverableAutoScanner("AA:00:00:00:94:01", BluetoothScanningMode.AUTO)
6640 challenger = _DiscoverableAutoScanner(
6641 "AA:00:00:00:94:02", BluetoothScanningMode.AUTO
6642 )
6643 c_owner = manager.async_register_scanner(owner)
6644 c_challenger = manager.async_register_scanner(challenger)
6645 try:
6646 _inject_with_rssi(owner, address, rssi=-50)
6647 challenger._add_connecting(address)
6648 sched.trigger_rescue(address, challenger.source, owner.source)
6649 assert challenger.active_window_calls == []
6650 assert not sched._rescue_tasks
6651 # Owner is AUTO: its completion only lands when its tick runs, so
6652 # nothing has been recorded yet.
6653 assert address not in sched._rescue_accept_after
6654 finally:
6655 challenger._finished_connecting(address, connected=False)
6656 cancel()
6657 c_owner()
6658 c_challenger()
6659
6660
6661 @pytest.mark.asyncio
6662 async def test_trigger_rescue_noop_untracked_or_not_started() -> None:
6663 """Untracked addresses and a never-started scheduler are safe no-ops."""
6664 manager = get_manager()
6665 sched = manager._auto_scheduler
6666 sched.trigger_rescue("FF:FF:FF:FF:FF:FF", "AA:00:00:00:95:01", "AA:00:00:00:95:02")
6667 assert "FF:FF:FF:FF:FF:FF" not in sched._rescue_accept_after
6668 fresh = type(sched)(manager)
6669 fresh.trigger_rescue("FF:FF:FF:FF:FF:FF", "AA:00:00:00:95:01", "AA:00:00:00:95:02")
6670 assert fresh._rescue_accept_after == {}
6671
6672
6673 @pytest.mark.asyncio
6674 async def test_remove_request_prunes_rescue_accept_after() -> None:
6675 """The last request for an address prunes all rescue state."""
6676 manager = get_manager()
6677 sched = manager._auto_scheduler
6678 address = "11:22:33:44:66:05"
6679 cancel = manager.async_register_active_scan(address, scan_interval=120.0)
6680 sched._rescue_accept_after[address] = 1.0
6681 manager._rescue_triggered[address] = 1.0
6682 cancel()
6683 assert address not in sched._rescue_accept_after
6684 # The episode's lifetime is bounded by the need: a device that never
6685 # goes stale again must not keep an orphaned episode alive.
6686 assert address not in manager._rescue_triggered
6687
6688
6689 @pytest.mark.asyncio
6690 async def test_stop_clears_rescue_state() -> None:
6691 """stop() drops rescue completions and cancels in-flight rescue windows."""
6692 manager = get_manager()
6693 sched = manager._auto_scheduler
6694 sched._rescue_accept_after["11:22:33:44:66:06"] = 1.0
6695 task = asyncio.get_running_loop().create_task(asyncio.sleep(60, result=True))
6696 sched._rescue_tasks.add(task)
6697 sched.stop()
6698 assert sched._rescue_accept_after == {}
6699 assert not sched._rescue_tasks
6700 assert task.cancelled() or task.cancelling()
6701 with contextlib.suppress(asyncio.CancelledError):
6702 await task
6703
6704
6705 @pytest.mark.asyncio
6706 async def test_worker_tick_records_rescue_accept_after() -> None:
6707 """The owner tick path records accept times only during a rescue."""
6708 manager = get_manager()
6709 sched = manager._auto_scheduler
6710 address = "11:22:33:44:66:07"
6711 cancel = manager.async_register_active_scan(
6712 address, scan_interval=120.0, scan_duration=5.0
6713 )
6714 scanner = _DiscoverableAutoScanner("AA:00:00:00:97:01", BluetoothScanningMode.AUTO)
6715 register_cancel = manager.async_register_scanner(scanner)
6716 try:
6717 _inject_with_rssi(scanner, address, rssi=-50)
6718 _make_due(sched, address)
6719 # No rescue episode anywhere: the ordinary cadence records nothing.
6720 await _run_worker_tick(sched, scanner.source)
6721 assert scanner.active_window_calls == [5.0]
6722 assert address not in sched._rescue_accept_after
6723 # With an episode in flight the tick records the accept time.
6724 manager._rescue_triggered[address] = 0.1
6725 _make_due(sched, address)
6726 before = monotonic_time_coarse()
6727 await _run_worker_tick(sched, scanner.source)
6728 assert scanner.active_window_calls == [5.0, 5.0]
6729 assert (
6730 sched._rescue_accept_after[address] >= before + RESCUE_SCAN_ACCEPT_SECONDS
6731 )
6732 manager._rescue_triggered.pop(address, None)
6733 finally:
6734 cancel()
6735 register_cancel()
6736
6737
6738 @pytest.mark.asyncio
6739 async def test_fallback_dispatch_records_rescue_accept_after() -> None:
6740 """A window delegated to a fallback still records the rescue completion."""
6741 manager = get_manager()
6742 sched = manager._auto_scheduler
6743 address = "11:22:33:44:66:08"
6744 cancel = manager.async_register_active_scan(
6745 address, scan_interval=120.0, scan_duration=7.0
6746 )
6747 owner = _DiscoverableAutoScanner("AA:00:00:00:98:01", BluetoothScanningMode.AUTO)
6748 fallback = _DiscoverableAutoScanner("AA:00:00:00:98:02", BluetoothScanningMode.AUTO)
6749 c_owner = manager.async_register_scanner(owner)
6750 c_fallback = manager.async_register_scanner(fallback)
6751 try:
6752 _inject_with_rssi(owner, address, rssi=-50)
6753 fallback.add_discovered(address, rssi=-70)
6754 owner._add_connecting(address)
6755 _make_due(sched, address)
6756 manager._rescue_triggered[address] = 0.1
6757 before = monotonic_time_coarse()
6758 await _run_worker_tick(sched, owner.source)
6759 assert fallback.active_window_calls == [7.0]
6760 assert (
6761 sched._rescue_accept_after[address] >= before + RESCUE_SCAN_ACCEPT_SECONDS
6762 )
6763 finally:
6764 owner._finished_connecting(address, connected=False)
6765 cancel()
6766 c_owner()
6767 c_fallback()
6768
6769
6770 @pytest.mark.asyncio
6771 async def test_covered_by_active_records_rescue_accept_after() -> None:
6772 """Owner mid-connect but an ACTIVE scanner covers: completion is now."""
6773 manager = get_manager()
6774 sched = manager._auto_scheduler
6775 address = "11:22:33:44:66:09"
6776 cancel = manager.async_register_active_scan(
6777 address, scan_interval=120.0, scan_duration=7.0
6778 )
6779 owner = _DiscoverableAutoScanner("AA:00:00:00:99:01", BluetoothScanningMode.AUTO)
6780 active = _DiscoverableAutoScanner("AA:00:00:00:99:02", BluetoothScanningMode.ACTIVE)
6781 c_owner = manager.async_register_scanner(owner)
6782 c_active = manager.async_register_scanner(active)
6783 try:
6784 _inject_with_rssi(owner, address, rssi=-50)
6785 active.add_discovered(address, rssi=-70)
6786 owner._add_connecting(address)
6787 _make_due(sched, address)
6788 manager._rescue_triggered[address] = 0.1
6789 before = monotonic_time_coarse()
6790 await _run_worker_tick(sched, owner.source)
6791 after = monotonic_time_coarse()
6792 assert active.active_window_calls == []
6793 assert (
6794 before + RESCUE_SCAN_ACCEPT_SECONDS
6795 <= sched._rescue_accept_after[address]
6796 <= after + RESCUE_SCAN_ACCEPT_SECONDS
6797 )
6798 finally:
6799 owner._finished_connecting(address, connected=False)
6800 cancel()
6801 c_owner()
6802 c_active()
6803
6804
6805 @pytest.mark.asyncio
6806 async def test_trigger_rescue_unregistered_sides_are_skipped() -> None:
6807 """Unregistered owner or challenger sources are safe no-ops per side."""
6808 manager = get_manager()
6809 sched = manager._auto_scheduler
6810 address = "11:22:33:44:66:10"
6811 cancel = manager.async_register_active_scan(
6812 address, scan_interval=120.0, scan_duration=7.0
6813 )
6814 owner = _DiscoverableAutoScanner("AA:00:00:00:9A:01", BluetoothScanningMode.ACTIVE)
6815 c_owner = manager.async_register_scanner(owner)
6816 try:
6817 _inject_with_rssi(owner, address, rssi=-50)
6818 manager._rescue_triggered[address] = 0.1
6819 # Challenger never registered: only the owner side is served.
6820 before = monotonic_time_coarse()
6821 sched.trigger_rescue(address, "AA:00:00:00:9A:99", owner.source)
6822 assert sched._rescue_accept_after[address] >= before
6823 # Neither side registered: nothing is recorded and the owner
6824 # side's unregistered guard is exercised.
6825 recorded = sched._rescue_accept_after[address] + 1000.0
6826 sched._rescue_accept_after[address] = recorded
6827 sched.trigger_rescue(address, "AA:00:00:00:9A:99", "AA:00:00:00:9A:98")
6828 assert sched._rescue_accept_after[address] == recorded
6829 # A later accept time is never rolled back by an earlier one: the
6830 # ACTIVE owner side records coverage plus the accept grace, which
6831 # loses to the later value.
6832 sched.trigger_rescue(address, "AA:00:00:00:9A:99", owner.source)
6833 assert sched._rescue_accept_after[address] == recorded
6834 finally:
6835 cancel()
6836 c_owner()
6837
6838
6839 @pytest.mark.asyncio
6840 async def test_trigger_rescue_auto_challenger_without_worker() -> None:
6841 """A dispatch to an AUTO challenger whose worker is gone still works."""
6842 manager = get_manager()
6843 sched = manager._auto_scheduler
6844 address = "11:22:33:44:66:11"
6845 cancel = manager.async_register_active_scan(
6846 address, scan_interval=120.0, scan_duration=7.0
6847 )
6848 owner = _DiscoverableAutoScanner("AA:00:00:00:9B:01", BluetoothScanningMode.ACTIVE)
6849 challenger = _DiscoverableAutoScanner(
6850 "AA:00:00:00:9B:02", BluetoothScanningMode.AUTO
6851 )
6852 c_owner = manager.async_register_scanner(owner)
6853 c_challenger = manager.async_register_scanner(challenger)
6854 try:
6855 _inject_with_rssi(owner, address, rssi=-50)
6856 worker = sched._workers.pop(challenger.source)
6857 sched.trigger_rescue(address, challenger.source, owner.source)
6858 for task in list(sched._rescue_tasks):
6859 await task
6860 assert challenger.active_window_calls == [7.0]
6861 sched._workers[challenger.source] = worker
6862 finally:
6863 cancel()
6864 c_owner()
6865 c_challenger()
6866
6867
6868 @pytest.mark.asyncio
6869 async def test_schedule_advance_to_clamps_only_later_entries() -> None:
6870 """advance_to pulls later due times forward and ignores unknown addresses."""
6871 manager = get_manager()
6872 sched = manager._auto_scheduler
6873 schedule = sched._schedule
6874 address = "11:22:33:44:66:12"
6875 cancel_a = manager.async_register_active_scan(address, scan_interval=120.0)
6876 cancel_b = manager.async_register_active_scan(address, scan_interval=300.0)
6877 scanner = _DiscoverableAutoScanner("AA:00:00:00:9C:01", BluetoothScanningMode.AUTO)
6878 register_cancel = manager.async_register_scanner(scanner)
6879 try:
6880 _inject_with_rssi(scanner, address, rssi=-50)
6881 entries = schedule._due_at[address]
6882 assert len(entries) == 2
6883 earlier, later = sorted(entries.values())
6884 midpoint = (earlier + later) / 2
6885 schedule.advance_to(address, midpoint)
6886 assert sorted(entries.values()) == [earlier, midpoint]
6887 # Unknown address is a no-op.
6888 schedule.advance_to("FF:FF:FF:FF:FF:FF", midpoint)
6889 finally:
6890 cancel_a()
6891 cancel_b()
6892 register_cancel()
6893
6894
6895 @pytest.mark.asyncio
6896 async def test_trigger_rescue_challenger_window_failure_is_logged(
6897 caplog: pytest.LogCaptureFixture,
6898 ) -> None:
6899 """A failed challenger rescue window is logged, not left unretrieved."""
6900 manager = get_manager()
6901 sched = manager._auto_scheduler
6902 address = "11:22:33:44:66:13"
6903 cancel = manager.async_register_active_scan(
6904 address, scan_interval=120.0, scan_duration=7.0
6905 )
6906
6907 class _RaisingScanner(_DiscoverableAutoScanner):
6908 async def async_request_active_window(self, duration: float) -> bool:
6909 msg = "boom"
6910 raise ValueError(msg)
6911
6912 owner = _DiscoverableAutoScanner("AA:00:00:00:9D:01", BluetoothScanningMode.ACTIVE)
6913 challenger = _RaisingScanner("AA:00:00:00:9D:02", BluetoothScanningMode.AUTO)
6914 c_owner = manager.async_register_scanner(owner)
6915 c_challenger = manager.async_register_scanner(challenger)
6916 try:
6917 _inject_with_rssi(owner, address, rssi=-50)
6918 with caplog.at_level(logging.ERROR, logger="habluetooth.auto_scheduler"):
6919 sched.trigger_rescue(address, challenger.source, owner.source)
6920 for task in list(sched._rescue_tasks):
6921 with contextlib.suppress(ValueError):
6922 await task
6923 # Let the done callbacks run.
6924 await asyncio.sleep(0)
6925 assert not sched._rescue_tasks
6926 assert any(
6927 "error running rescue active window" in record.getMessage()
6928 and challenger.source in record.getMessage()
6929 for record in caplog.records
6930 )
6931 finally:
6932 cancel()
6933 c_owner()
6934 c_challenger()
6935
6936
6937 @pytest.mark.asyncio
6938 async def test_trigger_rescue_cancelled_window_logs_nothing(
6939 caplog: pytest.LogCaptureFixture,
6940 ) -> None:
6941 """A challenger rescue window cancelled by stop() produces no error log."""
6942 manager = get_manager()
6943 sched = manager._auto_scheduler
6944 address = "11:22:33:44:66:14"
6945 cancel = manager.async_register_active_scan(
6946 address, scan_interval=120.0, scan_duration=7.0
6947 )
6948 owner = _DiscoverableAutoScanner("AA:00:00:00:9E:01", BluetoothScanningMode.ACTIVE)
6949 challenger = _DiscoverableAutoScanner(
6950 "AA:00:00:00:9E:02", BluetoothScanningMode.AUTO
6951 )
6952 # Block the challenger's window so the task is still in flight when
6953 # the scheduler stops.
6954 challenger._block_event = asyncio.Event()
6955 c_owner = manager.async_register_scanner(owner)
6956 c_challenger = manager.async_register_scanner(challenger)
6957 try:
6958 _inject_with_rssi(owner, address, rssi=-50)
6959 manager._rescue_triggered[address] = 0.1
6960 with caplog.at_level(logging.ERROR, logger="habluetooth.auto_scheduler"):
6961 sched.trigger_rescue(address, challenger.source, owner.source)
6962 await asyncio.sleep(0)
6963 task = next(iter(sched._rescue_tasks))
6964 sched.stop()
6965 with contextlib.suppress(asyncio.CancelledError):
6966 await task
6967 # Let the done callback run.
6968 await asyncio.sleep(0)
6969 assert not sched._rescue_tasks
6970 assert not any(
6971 "error running rescue active window" in record.getMessage()
6972 for record in caplog.records
6973 )
6974 finally:
6975 cancel()
6976 c_owner()
6977 c_challenger()