From 902f1b9c2aa426a07c18d1056db10d8fa7cdcf94 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Fri, 20 Nov 2026 06:09:32 -0500 Subject: [PATCH] test(browser): check wait_for_change's detector over generated frames The calibration, noise-floor and threshold logic of page.wait_for_change was inline with its sleeps and screenshots, so only a real browser drawing canvases for many seconds reached it. pixels.ChangeDetector now holds that logic as a pure state machine fed block frames, and wait_for_change feeds it captures and sleeps for it. The behavior is unchanged. browser_change_test generates regions with random noise, blocks that flicker from the first frame, blocks that start moving while the floor is measured, and a change of some fraction from a frame after calibration, over generated calibration and floor lengths and tolerances. It checks the frame and fraction a change is seen at, the floor, and the timeout message against counts worked out from the scene. Deleted from browser_test.py (about 50 s of canvas sleeps), with the test that fails for each: - wait_for_change_waits_through_random_noise_for_the_bus, ..._ordered_dither_for_the_bus (noise taken for change): a_change_counts_only_above_the_noise_floor. - wait_for_change_counts_min_change_above_the_noise_floor (min_change not added to the floor): the same property. - wait_for_change_holds_to_min_change_and_says_what_it_saw: half_the_region_holds_to_min_change, the same case worked by hand. wait_for_change_sees_a_small_change_in_a_quiet_region stays as the one real-browser wiring check. Real Chrome screenshot noise is no longer measured; the generated noise models stand in for it. Planted: the floor not added to min_change, no tolerance, calibration noise not learned, one floor frame short. Each fails the property. --- e2e/browser_test.py | 108 --------------- python/albedo_plugins/browser/page.py | 34 ++--- python/albedo_plugins/browser/pixels.py | 72 ++++++++++ test/harness/browser_change_test.py | 172 ++++++++++++++++++++++++ 4 files changed, 252 insertions(+), 134 deletions(-) create mode 100644 test/harness/browser_change_test.py diff --git a/e2e/browser_test.py b/e2e/browser_test.py index 51dbe46e0..074caa885 100644 --- a/e2e/browser_test.py +++ b/e2e/browser_test.py @@ -277,80 +277,6 @@ document.querySelector('canvas').onmousemove = e => { window.pointer = [e.offset """ -# Every frame redraws random black and white noise, and the bus is a solid block. -NOISE = """""" - -# A retro shader: a slowly swaying scene in 1-bit Bayer dither, so dither -# crawls along every edge, and the bus is a dark patch of the same dither. The -# sway moves edges a few pixels: about 5% of pixels flip, yet no 8-pixel block's -# mean moves much past the tolerance. A wider sway moves whole blocks, and its -# 6 s cycle outlasts the two seconds of calibration, so it is motion, not dither. -DITHER = """""" - -# Each frame lights a fresh 10% of the blocks, so some always flicker that -# calibration never saw: a noise floor of about 6%. -TWINKLE = """""" - -# The bus covers 8% of the region (16% on TWINKLE). The wait must outlast the -# noise, then end. Calibration is 8 captures, and a loaded machine can take -# 0.4 s for each, so every change below waits 8 s to land after it. -BUS_ARRIVES = """ -waiting = asyncio.create_task(page.wait_for_change((0, 0, 400, 300), timeout=30)) -await asyncio.sleep(8) -assert not waiting.done(), waiting -await page.evaluate('window.bus = true; return true') -result = await waiting -""" - - class BrowserCanvasTests(unittest.TestCase): def browse(self, code, html=CANVAS): """Run code against a fresh page on html; it prints 'passed' when done.""" @@ -430,17 +356,6 @@ centre = await page.evaluate( assert centre == [255, 0, 0, 255], centre """) - def test_wait_for_change_waits_through_random_noise_for_the_bus(self): - self.browse(BUS_ARRIVES, NOISE) - - def test_wait_for_change_waits_through_ordered_dither_for_the_bus(self): - self.browse(BUS_ARRIVES, DITHER) - - def test_wait_for_change_counts_min_change_above_the_noise_floor(self): - self.browse( - BUS_ARRIVES + "assert result['noise_floor'] >= 0.03, result\n", TWINKLE - ) - def test_wait_for_change_sees_a_small_change_in_a_quiet_region(self): self.browse(""" waiting = asyncio.create_task(page.wait_for_change((0, 0, 120, 80), timeout=30)) @@ -448,29 +363,6 @@ await asyncio.sleep(8) await page.evaluate("pen.fillStyle = 'blue'; pen.fillRect(40, 24, 16, 16); return true") result = await waiting assert 0.02 <= result['changed'] < 0.1, result -""") - - def test_wait_for_change_holds_to_min_change_and_says_what_it_saw(self): - self.browse(""" -import re -from albedo_plugins.browser import WaitTimeout -async def half(min_change, timeout): - waiting = asyncio.create_task(page.wait_for_change((0, 0, 160, 80), min_change=min_change, timeout=timeout)) - await asyncio.sleep(8) - await page.evaluate("pen.fillStyle = 'blue'; pen.fillRect(0, 0, 80, 80); return true") - try: - return await waiting - finally: - await page.evaluate('pen.clearRect(0, 0, 160, 80); return true') -try: - await half(0.6, 11) -except WaitTimeout as error: - message = 'max change 50.0%, noise floor 0.0%, wanted 60.0%' - assert message in str(error), error -else: - raise AssertionError('half the region met min_change=0.6') -result = await half(0.4, 30) -assert result['changed'] == 0.5, result """) def test_a_screenshot_shown_again_attaches_once(self): diff --git a/python/albedo_plugins/browser/page.py b/python/albedo_plugins/browser/page.py index bb92994ef..b5e19773d 100644 --- a/python/albedo_plugins/browser/page.py +++ b/python/albedo_plugins/browser/page.py @@ -946,41 +946,23 @@ class Page: shot = await self.cdp.send("Page.captureScreenshot", params) return pixels.blocks(base64.b64decode(shot["data"])) - def changed(blocks: list[tuple[float, ...]]) -> float: - moved = pixels.difference(first, blocks) - return sum(m > limit for m, limit in zip(moved, limits)) / len(moved) - - most, floor = 0.0, None + detector = pixels.ChangeDetector(min_change, tolerance, CALIBRATION, FLOOR) try: async with asyncio.timeout(timeout): - first = await capture() - noise = [0.0] * len(first) - for _ in range(CALIBRATION): - await asyncio.sleep(CALIBRATION_STEP) - moved = pixels.difference(first, await capture()) - noise = list(map(max, noise, moved)) - limits = [n + tolerance for n in noise] - floor = 0.0 - for _ in range(FLOOR): - await asyncio.sleep(CALIBRATION_STEP) - floor = max(floor, changed(await capture())) + detector.feed(await capture()) while True: - await asyncio.sleep(interval) - fraction = changed(await capture()) - most = max(most, fraction) - if fraction >= floor + min_change: + measuring = detector.measuring + await asyncio.sleep(CALIBRATION_STEP if measuring else interval) + fraction = detector.feed(await capture()) + if fraction is not None: return { "waited": round(time.monotonic() - started, 2), "changed": round(fraction, 4), - "noise_floor": round(floor, 4), + "noise_floor": round(detector.floor or 0.0, 4), } except TimeoutError as exc: - measured = "unmeasured" if floor is None else f"{floor:.1%}" raise WaitTimeout( - f"Region did not change enough: max change {most:.1%}," - f" noise floor {measured}, wanted {min_change:.1%}.", - region=region, - timeout=timeout, + detector.shortfall(), region=region, timeout=timeout ) from exc async def _hit(self, cdp: CDPSession, x: float, y: float, viewport: JSON) -> JSON: diff --git a/python/albedo_plugins/browser/pixels.py b/python/albedo_plugins/browser/pixels.py index 55919ffa1..c596dc682 100644 --- a/python/albedo_plugins/browser/pixels.py +++ b/python/albedo_plugins/browser/pixels.py @@ -103,3 +103,75 @@ def blocks(png: bytes) -> list[tuple[float, ...]]: def difference(a: list[tuple[float, ...]], b: list[tuple[float, ...]]) -> list[float]: """How far each block's colour moved, in 0-255 channel units.""" return [max(abs(x - y) for x, y in zip(p, q)) for p, q in zip(a, b)] + + +class ChangeDetector: + """Decides wait_for_change from block frames, with no clock or browser. + + The first frame fed is the reference. The next `calibration` frames learn + how far each block moves on its own; from then on a block counts as + changed when it has moved more than that plus `tolerance`. The `floor` + frames after them measure the fraction that changes anyway, the noise + floor. Each later frame has changed enough once its fraction reaches the + noise floor plus `min_change`. + """ + + def __init__( + self, + min_change: float, + tolerance: float, + calibration: int, + floor: int, + ) -> None: + self.min_change = min_change + self.tolerance = tolerance + self.calibration = calibration + self.floor_frames = floor + self.fed = 0 + self.first: list[tuple[float, ...]] = [] + self.noise: list[float] = [] + self.limits: list[float] = [] + self.floor: float | None = None + self.most = 0.0 + + @property + def measuring(self) -> bool: + """Whether the next frame still calibrates or measures the floor.""" + return self.fed <= self.calibration + self.floor_frames + + def changed(self, frame: list[tuple[float, ...]]) -> float: + """The fraction of blocks that moved past their limits.""" + moved = difference(self.first, frame) + return sum(m > limit for m, limit in zip(moved, self.limits)) / len(moved) + + def feed(self, frame: list[tuple[float, ...]]) -> float | None: + """Take the next frame. Returns the changed fraction once a frame + after calibration changed enough, otherwise None.""" + self.fed += 1 + if self.fed == 1: + self.first = frame + self.noise = [0.0] * len(frame) + elif self.fed <= 1 + self.calibration: + self.noise = list(map(max, self.noise, difference(self.first, frame))) + if self.fed == 1 + self.calibration: + self.limits = [n + self.tolerance for n in self.noise] + self.floor = 0.0 + if self.fed <= 1 + self.calibration: + return None + floor = self.floor or 0.0 + if self.fed <= 1 + self.calibration + self.floor_frames: + self.floor = max(floor, self.changed(frame)) + return None + fraction = self.changed(frame) + self.most = max(self.most, fraction) + if fraction >= floor + self.min_change: + return fraction + return None + + def shortfall(self) -> str: + """What a wait that timed out saw, for its error.""" + measured = "unmeasured" if self.floor is None else f"{self.floor:.1%}" + return ( + f"Region did not change enough: max change {self.most:.1%}," + f" noise floor {measured}, wanted {self.min_change:.1%}." + ) diff --git a/test/harness/browser_change_test.py b/test/harness/browser_change_test.py new file mode 100644 index 000000000..77babd922 --- /dev/null +++ b/test/harness/browser_change_test.py @@ -0,0 +1,172 @@ +"""wait_for_change's detector over generated frames of noisy regions. + +The defects: noise counted as change (random noise, blocks that flicker from +the start, blocks that start moving while the floor is measured), a change +seen during calibration, min_change not added to the noise floor, a change +under min_change accepted or one over it missed, the wrong frame or fraction +reported, and a timeout message that misstates what was seen. The detector +is pure, so frames stand in for screenshots; a real browser only adds the +sleeps. +""" + +from dataclasses import dataclass +from pathlib import Path +import random +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python")) +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import hypothesis_profiles # noqa: E402, F401 +from hypothesis import given, settings, strategies as st # noqa: E402 +from albedo_plugins.browser.pixels import ChangeDetector # noqa: E402 + +# How far a changed block moves: past any noise and tolerance generated here. +DELTA = 130.0 +# How far a flickering block jumps every frame. +FLICKER = 90.0 + +Frame = list[tuple[float, ...]] + + +@dataclass(frozen=True) +class Scene: + blocks: int + calibration: int + floor: int + tolerance: float + # Random noise every frame, within this many channel units of the base. + amplitude: float + seed: int + # Disjoint block sets: flickering from the first frame, moving from the + # first floor frame on, and changing from frame `start` on. + flicker: frozenset[int] + drift: frozenset[int] + change: frozenset[int] + start: int + # min_change sits halfway between two block counts, so it is never a tie. + wanted: int + + @property + def min_change(self) -> float: + return (self.wanted + 0.5) / self.blocks + + def frames(self, count: int) -> list[Frame]: + rng = random.Random(self.seed) + base = [rng.uniform(0, 100) for _ in range(self.blocks)] + floor_start = 1 + self.calibration + frames: list[Frame] = [] + for n in range(count): + frame: Frame = [] + for b, value in enumerate(base): + value += rng.uniform(-self.amplitude, self.amplitude) + if b in self.flicker and n % 2: + value += FLICKER + if b in self.drift and n >= floor_start: + value += DELTA + if b in self.change and n >= self.start: + value += DELTA + frame.append((value,)) + frames.append(frame) + return frames + + +@st.composite +def scenes(draw): + blocks = draw(st.integers(4, 40)) + calibration = draw(st.integers(0, 5)) + floor = draw(st.integers(1, 4)) + tolerance = draw(st.sampled_from([0.0, 8.0, 24.0, 40.0])) + amplitude = draw(st.sampled_from([0.0, tolerance / 4, tolerance / 2])) + roles = draw( + st.lists( + st.sampled_from(["still", "still", "flicker", "drift", "change"]), + min_size=blocks, + max_size=blocks, + ) + ) + + def having(role): + return frozenset(b for b, r in enumerate(roles) if r == role) + + # Flicker is learned as noise from a calibration frame, and random noise + # around it must stay inside the tolerance that learning adds. + learnable = calibration and amplitude <= tolerance / 4 + flicker = having("flicker") if learnable else frozenset() + measured = 1 + calibration + floor + start = draw(st.integers(measured, measured + 4)) + wanted = draw(st.integers(0, blocks - 1)) + return Scene( + blocks, + calibration, + floor, + tolerance, + amplitude, + draw(st.integers(0, 2**32)), + flicker, + having("drift"), + having("change"), + start, + wanted, + ) + + +def run(scene, horizon): + """Feed frames until the detector answers; the frame index and fraction, + or None and the detector after `horizon` frames.""" + detector = ChangeDetector( + scene.min_change, scene.tolerance, scene.calibration, scene.floor + ) + for n, frame in enumerate(scene.frames(horizon)): + assert detector.measuring == (n <= scene.calibration + scene.floor) + fraction = detector.feed(frame) + if fraction is not None: + return n, fraction, detector + return None, None, detector + + +class ChangeDetectorTests(unittest.TestCase): + @settings(max_examples=hypothesis_profiles.cases(400)) + @given(scenes()) + def test_a_change_counts_only_above_the_noise_floor(self, scene): + floor = len(scene.drift) / scene.blocks + changed = len(scene.change) / scene.blocks + horizon = scene.start + 6 + found, fraction, detector = run(scene, horizon) + self.assertAlmostEqual(detector.floor, floor) + if changed >= scene.min_change: + # Seen on the frame it happened, with the floor's blocks counted. + self.assertEqual(found, scene.start) + self.assertAlmostEqual(fraction, changed + floor) + else: + self.assertIsNone(found) + self.assertAlmostEqual(detector.most, changed + floor) + self.assertEqual( + detector.shortfall(), + f"Region did not change enough: max change {changed + floor:.1%}," + f" noise floor {floor:.1%}, wanted {scene.min_change:.1%}.", + ) + + def test_a_timeout_during_calibration_reports_an_unmeasured_floor(self): + detector = ChangeDetector(0.02, 24, 4, 3) + detector.feed([(0.0,)]) + self.assertIn("noise floor unmeasured", detector.shortfall()) + + def test_half_the_region_holds_to_min_change(self): + """The old browser case: half of a quiet region turns blue.""" + quiet: Frame = [(0.0,)] * 8 + half: Frame = [(200.0,)] * 4 + [(0.0,)] * 4 + frames = [quiet] * 8 + [half] + short = ChangeDetector(0.6, 24, 4, 3) + self.assertEqual([short.feed(frame) for frame in frames][-1], None) + self.assertEqual( + short.shortfall(), + "Region did not change enough: max change 50.0%," + " noise floor 0.0%, wanted 60.0%.", + ) + enough = ChangeDetector(0.4, 24, 4, 3) + self.assertEqual([enough.feed(frame) for frame in frames][-1], 0.5) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1