From f5d0fb3677d9bd8c885ea89a4a67fb772abf9dd6 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 18 Aug 2026 20:28:34 -0400 Subject: [PATCH] Map: silence about a tile is not the source saying it's empty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tile fetch that gets no answer was being remembered as one that did. BasemapSource is careful about the difference — a timeout is never written to disk, precisely so the next pan can ask again — and both callers then threw it away, filing every None as "fetched, empty/absent" and never asking again for the life of the screen. The same latch sat one level up: _resolve() marked itself done whether or not it had resolved anything, so one failed TileJSON round-trip made `available` False, and _ensure_tiles skipped every fetch, for the whole session. That is a desktop no-op and a PicoCalc bug. The device brings its Wi-Fi up some forty seconds into the boot, well after an app started alongside it reaches the menu and warms the tile source — so the map answers "offline" before the answer can be true and draws the entire session from whatever the cache already held. JP, 2026-08-18: black tiles at the two highest zooms, where one z14 tile is the whole screen and a hole is the picture. VE2RAD_FH_50m's tile (14/4842/5861) was simply absent from the device cache; nothing there had been written in ten days of using the map, and it fetched in 1.4s the moment it was asked for. So: `available` reports what is known and never itself goes to the network (it is read on the paint path), a failed resolve stands for 30s rather than for ever, `answered_empty` lets a caller tell the two Nones apart, and a tile nobody answered about waits out a 20s cooldown instead of a restart. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/services/basemap.py | 68 ++++++++++++-- meshterm/ui/map_screen.py | 67 +++++++++++--- meshterm/ui/minimap.py | 57 +++++++++--- tests/test_config_editor.py | 3 + tests/test_gallery.py | 3 + tests/test_map.py | 166 +++++++++++++++++++++++++++++++++-- 6 files changed, 330 insertions(+), 34 deletions(-) diff --git a/meshterm/services/basemap.py b/meshterm/services/basemap.py index 6ee7c31..429152c 100644 --- a/meshterm/services/basemap.py +++ b/meshterm/services/basemap.py @@ -20,7 +20,10 @@ costs only the decode it was saving. The default source is **OpenFreeMap** (openfreemap.org) — full-planet OpenStreetMap vector tiles, free and requiring no API key. Everything here is best-effort: with no network and no cached tiles the loader simply returns ``None`` and the map falls back to plotting nodes on a -blank grid, never raising into the UI. +blank grid, never raising into the UI. Best-effort, and **never given up on**: neither a +failed tile fetch nor a failed metadata resolve is remembered as a verdict on the source, +because the app can perfectly well open before the device it runs on has finished bringing +its network up (see :meth:`BasemapSource._resolve`). **Only tiles that decode to real geometry are ever written to disk.** A cache is a memory, and the one thing it must not remember is a lie: on a flaky link (the PicoCalc's Wi-Fi, most @@ -41,6 +44,7 @@ import json import logging import os import threading +import time import urllib.error import urllib.request from collections import OrderedDict @@ -76,6 +80,13 @@ _PRUNE_AFTER_BYTES = 8 * 1024 * 1024 #: has 100 MB of RAM in total and decoded layers are not small. _MEMO_TILES = 24 +#: How long a failed TileJSON resolve stands before the source will ask again. The PicoCalc +#: brings its Wi-Fi up some 40 seconds into the boot, well after the app it was started +#: alongside can reach the menu — so "offline" asked once at open is a verdict on the +#: *device's boot order*, not on the network, and latching it costs the whole session's +#: basemap. Long enough that a genuinely offline session isn't retrying into a void. +_RESOLVE_RETRY_SECONDS = 30.0 + _log = logging.getLogger(__name__) @@ -137,7 +148,9 @@ class BasemapSource: self._stamp = "all" if layers is None else ",".join(sorted(layers)) # type: ignore[arg-type] self._template: Optional[str] = None self._max_zoom: Optional[int] = None - self._resolved = False # whether we've tried (success or offline) this session + # When the source may next try to resolve its template. Zero means "now"; + # a success sets the template and this is never consulted again. + self._resolve_after = 0.0 # Tiles the source answered "nothing here" for this session. Held in memory rather # than on disk so the claim expires with the process: a blank tile is cheap to # re-ask about, and a stale one on disk is a permanent hole in the map. @@ -155,10 +168,30 @@ class BasemapSource: return self.cache_dir / "tilejson.json" def _resolve(self) -> None: - """Resolve and cache the tile-URL template and max zoom (best-effort, once).""" - if self._resolved: + """Resolve and cache the tile-URL template and max zoom (best-effort, retried). + + Latched on **success only**. A failed resolve is the absence of an answer, exactly + as a failed tile fetch is (see :class:`_Response`), and remembering it as "this + source is offline" is the same lie in a costlier place: it is asked once, seconds + after the app opens, and its verdict then governs every tile for the rest of the + session. On the PicoCalc the Wi-Fi associates some forty seconds into the boot, so + an app started with it answers that question before the answer can be true and + draws the whole session's map from whatever was already on disk — which is exactly + a scatter of black tiles at the zooms whose ground the cache happens not to hold. + + So a failure only stands for :data:`_RESOLVE_RETRY_SECONDS`, and the next caller + past that asks again. The deadline is claimed *before* the round-trip, so the + several worker threads a map frame puts through here don't all make the same call. + + Blocking, and called from worker threads (a tile fetch, the menu's warm) — never + from the paint path, which reads :attr:`available` instead. + """ + if self._template is not None: return - self._resolved = True + now = time.monotonic() + if now < self._resolve_after: + return + self._resolve_after = now + _RESOLVE_RETRY_SECONDS # Prefer a freshly fetched TileJSON (the template is versioned and rotates), but fall # back to a previously cached copy so a session started offline can still use disk # tiles and even re-fetch if the template is still valid. @@ -194,10 +227,31 @@ class BasemapSource: @property def available(self) -> bool: - """Whether a tile-URL template is known (network reachable, or one was cached).""" - self._resolve() + """Whether a tile-URL template is already known — asking nothing to find out. + + Read on the paint path (the map's title, the mini-map's caption), so it must never + be the thing that goes to the network: a resolve is a blocking round-trip, and one + answered from a repaint would stall the UI for its whole timeout. Touching + :attr:`max_zoom` — which every map surface does, off the loop, before it opens — + is what resolves; a tile fetch resolves too, in its own thread. This only reports. + + False therefore means "no template *yet*", not "give up": a caller that skips its + fetches on it will never let one happen (see + :meth:`meshterm.ui.map_screen.MapScreen._ensure_tiles`, which asks regardless). + """ return self._template is not None + def answered_empty(self, z: int, x: int, y: int) -> bool: + """Whether the source *answered* that there is no tile at these coordinates. + + The one way to tell the two ``None`` returns of :meth:`load_tile` apart: a tile the + source served as absent (a 404, or bytes holding no layer at all) will never + become anything else, while a tile we simply got no answer about is worth asking + again. Callers that cache the ``None`` need the difference — see + :meth:`meshterm.ui.map_screen.MapScreen._load`. + """ + return (z, x, y) in self._blank + # -- tiles ------------------------------------------------------------------ def _tile_path(self, z: int, x: int, y: int) -> Path: diff --git a/meshterm/ui/map_screen.py b/meshterm/ui/map_screen.py index c6f4ea8..1f5fab3 100644 --- a/meshterm/ui/map_screen.py +++ b/meshterm/ui/map_screen.py @@ -32,6 +32,7 @@ from __future__ import annotations import asyncio import math from collections import OrderedDict +from time import monotonic from typing import TYPE_CHECKING, Callable, Optional from ..core.geo import DEFAULT_VIEW_FRACTION, EARTH_RADIUS_KM, Viewport, clamp_lat @@ -87,6 +88,12 @@ _TILE_CACHE_SCREENS = 2 #: history for a pan away and back to be instant. _MIN_TILE_CACHE = 8 +#: How long a tile the source gave no answer about is left alone before it is asked for +#: again. Long enough that a genuinely offline map isn't retrying every visible tile on a +#: loop, short enough that a Wi-Fi blip costs a few seconds of missing streets rather than +#: the rest of the session (see :meth:`MapScreen._load`). +_TILE_RETRY_SECONDS = 20.0 + #: The zoom a frame homes in at when the matches set no extent of their own — a #: single node (or several at one spot) has nothing to frame, so ^Enter zooms to this #: street-level closeness rather than the fit's neutral default. Capped at the tile @@ -199,10 +206,13 @@ class MapScreen(Screen): # :meth:`consume_edge_scrub`). Seeded ``True`` so the first braille frame's edge is # cleaned even before the first pan. self._needs_scrub = True - # Decoded tiles keyed by (z, x, y); a stored ``None`` means "fetched, empty/absent". - # Decoded tiles, least-recently-shown first — see :meth:`_trim_tiles`. + # Decoded tiles, least-recently-shown first — see :meth:`_trim_tiles`. A stored + # ``None`` is the source's own answer that there is nothing at those coordinates. self._tiles: OrderedDict[tuple[int, int, int], Optional[list[Layer]]] = OrderedDict() self._pending: set[tuple[int, int, int]] = set() + # Tiles the source gave no answer about, and when each may be asked for again — + # a cooldown, not a verdict (see :meth:`_load`). + self._unanswered: dict[tuple[int, int, int], float] = {} # The last finished ground frame and what it was drawn for — see :meth:`render_body`. # Rasterizing a downtown view is ~0.5-1 s of pure Python (tens of thousands of # vector features), far too slow to sit on a keystroke, so it happens off the paint @@ -487,29 +497,47 @@ class MapScreen(Screen): # --- tiles --------------------------------------------------------------- def _ensure_tiles(self, vp: Viewport) -> None: - """Schedule background fetches for any visible tiles not yet loaded or pending.""" + """Schedule background fetches for any visible tile we don't have and aren't owed. + + Asked on every paint, and deliberately **not** gated on + :attr:`~meshterm.services.basemap.BasemapSource.available`: that only reports + whether a template is known *yet*, and skipping the fetch while it isn't is how a + map that opened a moment too early stays empty for the rest of the session. The + fetch resolves the source itself, in its own thread, so asking is what un-sticks it. + + A tile the source never answered about waits out :data:`_TILE_RETRY_SECONDS` in + :attr:`_unanswered` and is then asked for again — see :meth:`_load` for why that + isn't the same as a tile it answered "nothing here" about. + """ wanted = vp.tiles(self._max_tile_zoom) for t in wanted: if t in self._tiles: self._tiles.move_to_end(t) # on screen now, so last in line to be dropped self._trim_tiles(len(wanted)) - if not self._source.available: # offline (resolved at open time) — nodes only - return if not _loop_running(): # nothing to fetch onto — a static render draws what it has return + self._expire_cooldowns() for t in wanted: - if t in self._tiles or t in self._pending: + if t in self._tiles or t in self._pending or t in self._unanswered: continue self._pending.add(t) asyncio.ensure_future(self._load(t)) + def _expire_cooldowns(self) -> None: + """Forget the silences that have served their time, so a long pan can't hoard them.""" + if not self._unanswered: + return + now = monotonic() + self._unanswered = {t: at for t, at in self._unanswered.items() if at > now} + def _trim_tiles(self, in_view: int) -> None: """Release the least recently shown tiles once the view's budget is exceeded. Only tiles holding geometry are counted or dropped. An entry whose value is - ``None`` is the memory of having *asked* — the tile was absent, or the source - never answered — and it costs a dict slot rather than a megabyte, so it stays; - dropping it would only buy a pointless re-request on the next repaint. + ``None`` is the source's word that the tile is absent — a settled answer costing a + dict slot rather than a megabyte, so it stays; dropping it would only buy a + pointless re-request on the next repaint. A tile we got no answer about isn't here + at all: it waits out its cooldown in :attr:`_unanswered` and is asked for again. Args: in_view: How many tiles the current viewport needs, which sets the budget. @@ -527,13 +555,30 @@ class MapScreen(Screen): loaded -= 1 async def _load(self, t: tuple[int, int, int]) -> None: - """Fetch+decode one tile off the event loop, then repaint.""" + """Fetch+decode one tile off the event loop, then repaint. + + What comes back is filed under the same distinction the tile source keeps (see + :class:`~meshterm.services.basemap._Response`), because this is where forgetting it + costs a picture. Geometry, or the source's own word that there is nothing at those + coordinates, is an answer: it goes in :attr:`_tiles` and is never asked about + again. Silence — offline, a timeout, a body the Wi-Fi cut short — is *not* an + answer, and filing it as one turns one bad moment into a black square that stays + black until the app is restarted. It goes in :attr:`_unanswered` instead, which is + a cooldown rather than a verdict. + + That distinction is only visible on a link that actually drops. On the PicoCalc it + is the difference between a map and a map with holes in it (JP, 2026-08-18: tiles + black at the two highest zooms, where one z14 tile is the whole screen). + """ try: layers = await asyncio.to_thread(self._source.load_tile, *t) except Exception: # noqa: BLE001 - a failed tile is just an absent one layers = None - self._tiles[t] = layers self._pending.discard(t) + if layers is not None or self._source.answered_empty(*t): + self._tiles[t] = layers + else: + self._unanswered[t] = monotonic() + _TILE_RETRY_SECONDS self._session.invalidate() # --- input --------------------------------------------------------------- diff --git a/meshterm/ui/minimap.py b/meshterm/ui/minimap.py index 53a0230..4b86c68 100644 --- a/meshterm/ui/minimap.py +++ b/meshterm/ui/minimap.py @@ -18,6 +18,7 @@ calls :meth:`render` from its own ``render_body`` and forwards nothing back. from __future__ import annotations import asyncio +from time import monotonic from typing import TYPE_CHECKING, Optional from ..core.geo import Viewport, clamp_lat @@ -32,6 +33,26 @@ if TYPE_CHECKING: # pragma: no cover - typing only #: (blurred) basemap rather than blank tiles. _OVERZOOM = 2 +#: How long a tile the source gave no answer about is left alone before the preview asks +#: for it again — the big map's cooldown, for the same reason (see +#: :meth:`meshterm.ui.map_screen.MapScreen._load`). +_TILE_RETRY_SECONDS = 20.0 + + +def _loop_running() -> bool: + """Whether there is an event loop to hand background work to. + + Asked *before* building a coroutine, not after: ``ensure_future`` without a loop + raises, but by then the coroutine exists and never gets awaited, which Python reports + as a resource warning on a path that is otherwise perfectly correct (a screen rendered + in a test, or a one-shot CLI draw). + """ + try: + asyncio.get_running_loop() + except RuntimeError: + return False + return True + class MiniMap: """A fixed, non-interactive slippy-map region drawn into a host screen's body. @@ -74,13 +95,20 @@ class MiniMap: self._center_lon = center_lon self._zoom = max(2, min(int(zoom), max_tile_zoom + _OVERZOOM)) self._markers = markers - # Decoded tiles keyed by (z, x, y); a stored ``None`` means "fetched, empty/absent". + # Decoded tiles keyed by (z, x, y); a stored ``None`` is the source's own word that + # there is no tile there. Silence is not that answer and is not stored here. self._tiles: dict[tuple[int, int, int], Optional[list[Layer]]] = {} self._pending: set[tuple[int, int, int]] = set() + # Tiles we got no answer about, and when each may be asked for again. + self._unanswered: dict[tuple[int, int, int], float] = {} @property def has_basemap(self) -> bool: - """Whether the source can serve a basemap at all (network reachable, or cached).""" + """Whether the source has resolved a basemap to draw from — not yet is not never. + + The preview keeps asking either way (see :meth:`_ensure_tiles`); this is for a + host that wants to caption the wait. + """ return self._source.available @property @@ -112,17 +140,23 @@ class MiniMap: return render_map(viewport, tiles, self._markers) def _ensure_tiles(self, viewport: Viewport) -> None: - """Schedule background fetches for any visible tiles not yet loaded or pending.""" - if not self._source.available: # offline (resolved at open time) — markers only + """Schedule background fetches for any visible tile we don't have and aren't owed. + + Not gated on :attr:`~meshterm.services.basemap.BasemapSource.available`, and a + tile the source gave no answer about is asked for again once its cooldown runs + out — the big map's rules, and for its reasons (see + :meth:`meshterm.ui.map_screen.MapScreen._ensure_tiles`). + """ + if not _loop_running(): # nothing to fetch onto — draw whatever is already here return + if self._unanswered: # the silences that have served their time + now = monotonic() + self._unanswered = {t: at for t, at in self._unanswered.items() if at > now} for t in viewport.tiles(self._max_tile_zoom): - if t in self._tiles or t in self._pending: + if t in self._tiles or t in self._pending or t in self._unanswered: continue self._pending.add(t) - try: - asyncio.ensure_future(self._load(t)) - except RuntimeError: # pragma: no cover - no running loop (non-interactive) - self._pending.discard(t) + asyncio.ensure_future(self._load(t)) async def _load(self, t: tuple[int, int, int]) -> None: """Fetch+decode one tile off the event loop, then repaint the host screen.""" @@ -130,6 +164,9 @@ class MiniMap: layers = await asyncio.to_thread(self._source.load_tile, *t) except Exception: # noqa: BLE001 - a failed tile is just an absent one layers = None - self._tiles[t] = layers self._pending.discard(t) + if layers is not None or self._source.answered_empty(*t): + self._tiles[t] = layers # an answer, settled for the session + else: + self._unanswered[t] = monotonic() + _TILE_RETRY_SECONDS # silence — ask again self._session.invalidate() diff --git a/tests/test_config_editor.py b/tests/test_config_editor.py index 4ace191..4da4dd6 100644 --- a/tests/test_config_editor.py +++ b/tests/test_config_editor.py @@ -186,6 +186,9 @@ class _StubSource: def load_tile(self, z: int, x: int, y: int): return None + def answered_empty(self, z: int, x: int, y: int) -> bool: + return False # offline is silence, never the source saying "nothing there" + def _picker(markers=None, initial=None): from meshterm.ui.map_screen import LocationPickScreen diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 842a10b..ca3d524 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -190,6 +190,9 @@ class _StubTileSource: def load_tile(self, z: int, x: int, y: int): # noqa: ANN001 return None + def answered_empty(self, z: int, x: int, y: int) -> bool: # noqa: ANN001 + return False # offline is silence, never the source saying "nothing there" + def _map(cols: int, rows: int) -> Screen: session = _GallerySession(cols, rows) diff --git a/tests/test_map.py b/tests/test_map.py index c13ccc8..bd38fcb 100644 --- a/tests/test_map.py +++ b/tests/test_map.py @@ -8,10 +8,12 @@ against the :class:`MockDevice` simulator with the basemap disabled (no network from __future__ import annotations +import asyncio import io import os import re from pathlib import Path +from time import monotonic import pytest from rich.cells import cell_len @@ -25,6 +27,7 @@ from meshterm.core.models import ( ) from meshterm.core.mvt import GEOM_LINE, GEOM_POLYGON, Layer, decode_tile from meshterm.tools.map import MapTool +from meshterm.ui.map_screen import _TILE_RETRY_SECONDS as _TILE_RETRY from meshterm.ui.mapcanvas import MapCanvas, parse_hex _FIXTURE = Path(__file__).parent / "fixtures" / "tile_14_4843_5861.mvt" @@ -681,8 +684,7 @@ def test_basemap_source_never_caches_an_unanswered_fetch(tmp_path: Path) -> None # The same, with the source resolved and the *fetch* the thing that fails — the flaky # link the PicoCalc lives on. The tile stays unknown, so the next pan asks again. src = _offline_source(cache) - src._template = "http://tiles.invalid/{z}/{x}/{y}.pbf" - src._resolved = True + src._template = "http://tiles.invalid/{z}/{x}/{y}.pbf" # resolved: the fetch is what fails calls: list[str] = [] def _get(url: str): @@ -696,6 +698,54 @@ def test_basemap_source_never_caches_an_unanswered_fetch(tmp_path: Path) -> None assert list(cache.rglob("*.pbf")) == [] +def test_basemap_source_asks_again_after_a_failed_resolve(tmp_path: Path) -> None: + """Offline at open is a moment, not a verdict — the PicoCalc's Wi-Fi lands after boot. + + Latching the first failure meant an app started alongside the device's network drew + every tile of every session from whatever the cache already held (JP, 2026-08-18). + """ + from meshterm.services import basemap as basemap_mod + + src = _offline_source(tmp_path / "cache") + assert src.available is False + assert src.max_zoom == 14 # the default, because nothing was resolved + + doc = b'{"tiles": ["http://tiles.invalid/{z}/{x}/{y}.pbf"], "maxzoom": 14}' + src._http_get = lambda url: basemap_mod._Response(True, doc) # type: ignore[method-assign] + src._resolve_after = 0.0 # the cooldown, stepped over rather than slept through + assert src.max_zoom == 14 + assert src.available is True, "the source never asked again" + + +def test_basemap_source_holds_a_failed_resolve_for_its_cooldown(tmp_path: Path) -> None: + """Asking again is not asking constantly: a genuinely offline map isn't a retry loop.""" + from meshterm.services import basemap as basemap_mod + + src = _offline_source(tmp_path / "cache") + calls: list[str] = [] + src._http_get = lambda url: ( # type: ignore[method-assign] + calls.append(url), basemap_mod._Response(False, b"") + )[1] + for _ in range(5): + assert src.available is False + assert calls == [] # the constructor's own failed resolve still stands + + +def test_basemap_source_tells_an_empty_answer_from_silence(tmp_path: Path) -> None: + """The two ``None`` returns of ``load_tile``, told apart — a caching caller needs it.""" + from meshterm.services import basemap as basemap_mod + + src = _offline_source(tmp_path / "cache") + src._template = "http://tiles.invalid/{z}/{x}/{y}.pbf" + src._http_get = lambda url: basemap_mod._Response(False, b"") # type: ignore[method-assign] + assert src.load_tile(14, 4843, 5861) is None + assert src.answered_empty(14, 4843, 5861) is False # no answer — worth asking again + + src._http_get = lambda url: basemap_mod._Response(True, b"") # type: ignore[method-assign] + assert src.load_tile(14, 1, 1) is None + assert src.answered_empty(14, 1, 1) is True # the source said so; that settles it + + def test_basemap_source_prunes_a_blank_cached_tile(tmp_path: Path) -> None: """A zero-byte entry (an older build's failure marker) is dropped rather than drawn.""" cache = tmp_path / "cache" @@ -1080,6 +1130,9 @@ class _StubSource: def load_tile(self, z: int, x: int, y: int): return None + def answered_empty(self, z: int, x: int, y: int) -> bool: + return False # offline is silence, never the source saying "nothing there" + def _loaded_tile() -> list[Layer]: """A stand-in for a decoded tile: truthy, which is all the budget cares about.""" @@ -1398,7 +1451,6 @@ def test_map_frame_chip_lights_only_with_matches_to_frame() -> None: def test_map_screen_find_filters_frames_and_clears() -> None: """Typing builds the query; ^Enter frames matches; Enter/Esc drop it; Esc then leaves.""" - import asyncio from meshterm.ui.map_render import MapMarker from meshterm.ui.map_screen import MapScreen @@ -1584,7 +1636,6 @@ def test_map_screen_scrubs_right_edge_after_move() -> None: def test_map_screen_escape_dismisses() -> None: """Esc resolves the screen's future with None (backs out to the menu).""" - import asyncio from meshterm.ui.map_render import MapMarker from meshterm.ui.map_screen import MapScreen @@ -1640,6 +1691,104 @@ def test_render_map_find_matches_still_label_white() -> None: assert _glyph_color(lines, "TARGET") == (255, 255, 255) +# --- a tile nobody answered about is asked for again ---------------------------------- + + +def _map_over(source) -> "MapScreen": # noqa: ANN001 + """A map screen fetching from ``source``, with an event loop it can hand work to.""" + from meshterm.ui.map_render import MapMarker + from meshterm.ui.map_screen import MapScreen + + return MapScreen( + _StubSession(80, 24), [MapMarker("A", 45.5, -73.6)], source, 14 + ) + + +class _SilentSource(_StubSource): + """A source that never answers — the flaky Wi-Fi, not an empty planet.""" + + def __init__(self) -> None: + self.asked: list[tuple[int, int, int]] = [] + + def load_tile(self, z: int, x: int, y: int): + self.asked.append((z, x, y)) + return None + + +class _EmptySource(_SilentSource): + """A source that answers, and the answer is that there is nothing at those tiles.""" + + def answered_empty(self, z: int, x: int, y: int) -> bool: + return True + + +def test_map_asks_again_for_a_tile_it_got_no_answer_about(monkeypatch) -> None: # noqa: ANN001 + """One Wi-Fi blip must not black out that ground until the app is restarted. + + On the PicoCalc a missing z14 tile *is* the picture at the two highest zooms, where + one tile covers the whole screen many times over (JP, 2026-08-18). + """ + from meshterm.ui import map_screen as ms + + source = _SilentSource() + screen = _map_over(source) + + async def drive() -> None: + screen.render_body(80) + while screen._pending: + await asyncio.sleep(0) + first = len(source.asked) + assert first, "no tile was ever asked for" + + screen.render_body(80) # still inside the cooldown + await asyncio.sleep(0) + assert len(source.asked) == first, "the source is being hammered" + + monkeypatch.setattr(ms, "monotonic", lambda: monotonic() + _TILE_RETRY + 1) + screen.render_body(80) + while screen._pending: + await asyncio.sleep(0) + assert len(source.asked) > first, "the unanswered tile was written off for good" + + asyncio.run(drive()) + + +def test_map_takes_the_sources_word_that_a_tile_is_empty(monkeypatch) -> None: # noqa: ANN001 + """An answer settles it: ocean tiles must not be re-requested for ever.""" + from meshterm.ui import map_screen as ms + + source = _EmptySource() + screen = _map_over(source) + + async def drive() -> None: + screen.render_body(80) + while screen._pending: + await asyncio.sleep(0) + asked = len(source.asked) + + monkeypatch.setattr(ms, "monotonic", lambda: monotonic() + _TILE_RETRY * 10) + screen.render_body(80) + await asyncio.sleep(0) + assert len(source.asked) == asked, "a settled answer was asked about again" + + asyncio.run(drive()) + + +def test_map_fetches_before_the_source_has_resolved(monkeypatch) -> None: # noqa: ANN001 + """``available`` says "not yet", never "don't bother" — a fetch is what resolves it.""" + source = _SilentSource() + assert source.available is False # nothing has reached the network at open time + screen = _map_over(source) + + async def drive() -> None: + screen.render_body(80) + while screen._pending: + await asyncio.sleep(0) + assert source.asked, "the map wrote the source off instead of asking it" + + asyncio.run(drive()) + + # --- the ground raster runs off the paint path --------------------------------------- @@ -1677,18 +1826,23 @@ def test_map_paints_without_waiting_for_the_ground(monkeypatch) -> None: # noqa assert screen._drawing is not None, "no background raster was scheduled" +def _rasters(started: list) -> list: + """Just the ground-rasterizing coroutines — a pan also schedules its tile fetches.""" + return [c for c in started[0] if "_draw_ground" in c.__qualname__] + + def test_map_keeps_one_raster_in_flight_while_panning(monkeypatch) -> None: # noqa: ANN001 """A held arrow key must not queue a second of thread work per keypress.""" started: list = [] screen = _async_map(monkeypatch, started) screen.render_body(80) - scheduled = len(started[0]) + scheduled = len(_rasters(started)) for _ in range(8): screen.handle("right") screen.render_body(80) - assert len(started[0]) == scheduled, "a second raster started before the first finished" + assert len(_rasters(started)) == scheduled, "a second raster started before the first finished" assert screen._wanted is not None, "the newest view was not remembered for next"