Channels: bound the never-rejecting slot probe, cache the capacity

The channel manager still felt uncached: its capacity read walked all 64
slots one-by-one on firmware that never rejects an out-of-range index
(the Waymarker), on every open, outside the session cache.

Two fixes for the two slot probes:

- read_channel_slots now stops after a run of MAX_CHANNELS consecutive
  empty slots. The manager packs channels from slot 0 up, so an unbroken
  empty run that long means every configured channel has been seen — safe
  against within-capacity gaps, which can't reach that length. This cuts
  every (re)probe on never-rejecting firmware from 64 reads to ~11, felt
  after each channel edit (a mutation invalidates + reprobes).

- channel_capacity deliberately keeps walking to the firmware's rejection
  (it must discover a larger rejecting firmware's real ceiling — the
  empty-run guess would truncate an empty 12-slot device to 8). Its only
  slow case is never-rejecting firmware, bounded instead by caching: a new
  DeviceState.channel_capacity() holds it for the session (a hardware
  constant, dropped only on reconnect) and prewarm warms it after login,
  so the manager opens from cache like every other screen.

706 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 4.8 committed 2026-07-13 23:38:05 -04:00
1 parent 2f0e2687b0
commit 7d3e4b4412
5 files changed
+167 -23

No files matched your search

+14
View File
@@ -65,6 +65,20 @@ MAX_CHANNELS = 8
#: never rejects an out-of-range index (so the probe can't loop forever).
CHANNEL_SLOT_PROBE_CAP = 64
#: A run of this many consecutive *empty* slots ends a *configured-channel* scan (see
#: :func:`meshterm.ui.channels.read_channel_slots`) on firmware that never rejects an
#: out-of-range index — some builds answer every index with an empty payload instead of
#: raising, so the scan would otherwise walk all :data:`CHANNEL_SLOT_PROBE_CAP` slots on
#: every read. The channel manager packs channels from slot 0 up within the stock
#: :data:`MAX_CHANNELS` slots, so no real layout leaves this many empty slots *before* its
#: last channel — an unbroken run this long means the scan has passed the configured
#: channels. Firmware that *does* reject an out-of-range index still ends the scan at its
#: true ceiling first. (Deliberately not applied to
#: :meth:`meshterm.core.connection.Device.channel_capacity`, which must report a larger
#: rejecting firmware's real slot count and so has to reach the rejection, not guess from a
#: run of empties; its cost is bounded by caching it for the session instead.)
CHANNEL_SLOT_EMPTY_RUN = MAX_CHANNELS
#: The default public channel every MeshCore device ships with on slot 0.
DEFAULT_PUBLIC_NAME = "public"
+47 -11
View File
@@ -2,16 +2,20 @@
Opening a screen used to re-read the same stable facts from the companion every time —
the contacts table, the node's own self-info, the path-hash routing width, the configured
channel slots. Over Bluetooth each of those is a full request→reply round-trip, and the two
big ones dominate: ``get_contacts`` on a busy node (hundreds of contacts) and the channel
probe (:func:`~meshterm.ui.channels.read_channel_slots`, which walks every slot index) each
measured in *seconds* on real hardware. Firing them on every navigation is what made moving
between screens feel like it stalled.
channel slots, the channel-slot capacity. Over Bluetooth each of those is a full
request→reply round-trip, and the channel-slot reads dominate: ``get_contacts`` on a busy
node (hundreds of contacts), the slot probe (:func:`~meshterm.ui.channels.read_channel_slots`)
and the capacity probe (:meth:`~meshterm.core.connection.Device.channel_capacity`) each walk
the slot table one index at a time and are measured in *seconds* on firmware that never
rejects an out-of-range index. Firing them on every navigation is what made moving between
screens feel like it stalled.
None of that data actually changes mid-navigation:
* **self-info** and **path-hash mode** change only when the config editor writes them;
* **channel slots** change only when the channel editor saves one;
* **channel-slot capacity** is a fixed firmware build constant — it never changes at all
within a connection, so it is simply held for the session and only dropped on a reconnect;
* **contacts** grow as the mesh advertises, but a minute-stale list is harmless — the app
already resolves names from recorded history too.
@@ -76,11 +80,13 @@ class DeviceState:
self._self_info: Optional[dict] = None
self._path_hash_mode: Optional[int] = None
self._channels: Optional[list["ChannelSlot"]] = None
self._channel_capacity: Optional[int] = None
# One lock per slow fetch so overlapping first-access callers (two screens opened in
# quick succession) collapse onto a single round-trip instead of each firing their own.
self._contacts_lock = asyncio.Lock()
self._self_info_lock = asyncio.Lock()
self._channels_lock = asyncio.Lock()
self._capacity_lock = asyncio.Lock()
self._tasks: set[asyncio.Task] = set()
# -- contacts (stale-while-revalidate) --------------------------------------
@@ -187,16 +193,39 @@ class DeviceState:
self._channels = await read_channel_slots(device)
return self._channels
async def channel_capacity(self) -> int:
"""Return the device's channel-slot capacity, discovered once and held for the session.
The capacity is a fixed firmware build constant, so it is probed once and reused. The
probe (:meth:`~meshterm.core.connection.Device.channel_capacity`) reads slots upward
until the firmware rejects an index; on firmware that *never* rejects one it walks up
to :data:`~meshterm.core.channels.CHANNEL_SLOT_PROBE_CAP` slots — one of the slowest
reads on a screen open, and paid on *every* open of the channel manager before this
cache. Unlike the configured-slot list it cannot be safely bounded by a run of empty
slots (it must reach a larger firmware's real ceiling), so it is bounded by caching:
held until :meth:`reset` (a reconnect re-reads it) rather than invalidated on a channel
edit, since editing a channel never changes how many slots the hardware has.
Returns:
The number of addressable channel slots the firmware exposes.
"""
if self._channel_capacity is None:
async with self._capacity_lock:
if self._channel_capacity is None:
device = await self._ctx.device()
self._channel_capacity = await device.channel_capacity()
return self._channel_capacity
# -- prewarm (fill the slow caches in the background, off the navigation path) --
def prewarm(self) -> None:
"""Warm the slow caches (contacts, channel slots) in the background after connect.
"""Warm the slow caches (contacts, channel slots, capacity) in the background after connect.
Called once the session's link is up (see :func:`meshterm.ui.menu._resume_monitor`) so
the first screen that reads them — Chat, Trace, the Dashboard — is served from cache
instantly, rather than paying the round-trips in the navigation path where the user is
waiting on the screen to open. It folds the two unavoidable first reads into one quiet
wait behind the menu instead of surfacing them on the first open.
the first screen that reads them — Chat, Trace, the Dashboard, the channel manager — is
served from cache instantly, rather than paying the round-trips in the navigation path
where the user is waiting on the screen to open. It folds the unavoidable first reads
into one quiet wait behind the menu instead of surfacing them on the first open.
The work runs as a tracked background task: **sequential** (never gathered — concurrent
reads collide on the BLE UART; see the module note), best-effort (a failure just leaves
@@ -208,7 +237,11 @@ class DeviceState:
async def _prewarm(self) -> None:
"""Fetch the slow caches one after another, swallowing failures (best-effort warm)."""
for label, fetch in (("contacts", self.contacts), ("channel slots", self.channel_slots)):
for label, fetch in (
("contacts", self.contacts),
("channel slots", self.channel_slots),
("channel capacity", self.channel_capacity),
):
try:
await fetch()
except Exception as exc: # noqa: BLE001 - a warm miss just falls back to a lazy fetch
@@ -253,6 +286,9 @@ class DeviceState:
self.invalidate_self_info()
self.invalidate_path_hash_mode()
self.invalidate_channels()
# Capacity is a hardware constant (not touched by channel edits, so it has no per-write
# invalidator), but a reconnect may be to a different device — drop it too.
self._channel_capacity = None
for task in list(self._tasks):
task.cancel()
self._tasks.clear()
+20 -6
View File
@@ -36,6 +36,7 @@ from rich.console import Group
from rich.text import Text
from ..core.channels import (
CHANNEL_SLOT_EMPTY_RUN,
CHANNEL_SLOT_PROBE_CAP,
MAX_CHANNELS,
channel_hash,
@@ -144,9 +145,12 @@ async def manage_channels(ctx: "AppContext") -> int:
device = await ctx.device()
# The firmware's slot count is fixed for the session, so discover it once (a read-only
# probe) rather than assuming a hard-coded 8; it drives the free-slot check and the
# used/total display below. A device that can't report any slots falls back to the
# standard count so the manager stays usable instead of showing zero capacity.
capacity = await device.channel_capacity() or MAX_CHANNELS
# used/total display below. Read through the session cache: on firmware that never
# rejects an out-of-range index the probe walks every slot (slow), and the count never
# changes for a connection, so it is warmed once (prewarm/first open) and reused on every
# later open. A device that can't report any slots falls back to the standard count so the
# manager stays usable instead of showing zero capacity.
capacity = await ctx.devstate.channel_capacity() or MAX_CHANNELS
stats = _LiveStats(ctx)
changes = 0
highlight: Optional[object] = None
@@ -259,9 +263,13 @@ async def _refresh_chat_channels(ctx: "AppContext") -> None:
async def read_channel_slots(device: Device) -> list[ChannelSlot]:
"""Probe the channel slots and return the configured ones, in index order.
The scan runs up to :data:`CHANNEL_SLOT_PROBE_CAP` and stops as soon as the firmware
rejects a slot index, so it reads exactly the slots the device actually has regardless
of its capacity.
The scan stops as soon as the firmware rejects a slot index, so it reads exactly the
slots a well-behaved device has regardless of its capacity. Firmware that never rejects
an out-of-range index (it answers every slot with an empty payload instead of raising)
would otherwise walk all :data:`CHANNEL_SLOT_PROBE_CAP` slots on every read; a run of
:data:`CHANNEL_SLOT_EMPTY_RUN` consecutive empty slots ends the scan on such firmware.
That is safe because the manager packs channels from slot 0 up, so an unbroken empty run
that long means every configured channel has already been seen (see the constant's note).
Args:
device: The connected device to query.
@@ -270,12 +278,14 @@ async def read_channel_slots(device: Device) -> list[ChannelSlot]:
One :class:`ChannelSlot` per configured slot (an empty slot is skipped).
"""
slots: list[ChannelSlot] = []
empty_run = 0
for idx in range(CHANNEL_SLOT_PROBE_CAP):
try:
payload = await device.get_channel(idx)
except Exception: # noqa: BLE001 - firmware may not support channel reads
break
if payload and payload.get("channel_name"):
empty_run = 0
slots.append(
ChannelSlot(
idx=idx,
@@ -283,6 +293,10 @@ async def read_channel_slots(device: Device) -> list[ChannelSlot]:
secret=bytes(payload.get("channel_secret") or b"\x00" * 16),
)
)
else:
empty_run += 1
if empty_run >= CHANNEL_SLOT_EMPTY_RUN:
break # off the end of a never-rejecting firmware; nothing more to find
return slots
+58 -1
View File
@@ -17,6 +17,8 @@ from meshterm.context import AppContext
from meshterm.core.admin_store import AdminStore
from meshterm.core.channels import (
CHANNEL_SECRET_BYTES,
CHANNEL_SLOT_EMPTY_RUN,
CHANNEL_SLOT_PROBE_CAP,
DEFAULT_PUBLIC_SECRET,
channel_hash,
decrypt_channel_text,
@@ -257,12 +259,67 @@ async def test_channel_capacity_is_probed_not_assumed(ctx: AppContext) -> None:
async def test_channel_capacity_tracks_a_larger_ceiling(ctx: AppContext) -> None:
"""Firmware with more slots is discovered as such — no hard-coded 8 anywhere."""
"""Firmware with more slots is discovered as such — no hard-coded 8 anywhere.
This is exactly why the empty-run bound is *not* applied to capacity discovery: a larger
firmware whose upper slots are empty must still be found by reaching its rejection, not
guessed short from a run of empties.
"""
device = await ctx.device()
device._max_channels = 12 # simulate a firmware build with a larger slot table
assert await device.channel_capacity() == 12
async def test_read_channel_slots_bounds_a_never_rejecting_probe() -> None:
"""On firmware that answers every slot (never rejecting an index), the configured-slot
scan stops after a run of empty slots instead of walking all CHANNEL_SLOT_PROBE_CAP."""
class NeverRejects:
"""A device that reports two channels then empty slots forever, never raising."""
def __init__(self) -> None:
self.reads = 0
async def get_channel(self, idx: int):
self.reads += 1
if idx in (0, 1):
return {"channel_name": f"c{idx}", "channel_secret": b"\x00" * 16}
return None # an empty slot — and it will never reject a higher index
device = NeverRejects()
slots = await read_channel_slots(device) # type: ignore[arg-type]
assert [s.name for s in slots] == ["c0", "c1"] # both real channels found
# Stopped after the two channels plus one run of empties — not the full 64-slot walk.
assert device.reads == 2 + CHANNEL_SLOT_EMPTY_RUN
assert device.reads < CHANNEL_SLOT_PROBE_CAP
async def test_read_channel_slots_scans_past_gaps_within_capacity() -> None:
"""A cleared middle slot (a gap) never truncates the scan: channels above it are still read.
The empty-run bound only ends the scan after a full stock-capacity's worth of consecutive
empties, which a within-capacity gap can never reach — so a channel sitting above a gap on
never-rejecting firmware is still found.
"""
class NeverRejects:
def __init__(self, occupied: dict[int, str]) -> None:
self.occupied = occupied
self.reads = 0
async def get_channel(self, idx: int):
self.reads += 1
name = self.occupied.get(idx)
if name is None:
return None
return {"channel_name": name, "channel_secret": b"\x00" * 16}
# Channels at slots 0 and 7 with 1..6 empty (a 6-slot gap, one short of the stop run).
device = NeverRejects({0: "low", 7: "high"})
slots = await read_channel_slots(device) # type: ignore[arg-type]
assert [s.idx for s in slots] == [0, 7] # the gap did not end the scan early
async def test_apply_order_relays_channels_into_new_positions(ctx: AppContext) -> None:
"""Applying a new order re-lays channels across the same slots in display order."""
device = await ctx.device()
+28 -5
View File
@@ -24,6 +24,7 @@ class FakeDevice:
self.self_info_calls = 0
self.mode_calls = 0
self.channel_calls = 0
self.capacity_calls = 0
async def get_contacts(self) -> list:
self.contacts_calls += 1
@@ -44,6 +45,11 @@ class FakeDevice:
return {"channel_name": "public", "channel_secret": b"\x00" * 16}
raise RuntimeError("out of range")
async def channel_capacity(self) -> int:
# A fixed hardware constant; the cache must read it exactly once for the session.
self.capacity_calls += 1
return 8
def _devstate(device: FakeDevice) -> DeviceState:
"""A DeviceState over a fake ctx exposing just device() and a silent logger."""
@@ -150,32 +156,49 @@ def test_reset_clears_everything() -> None:
ds = _devstate(dev)
async def run() -> None:
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode()
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode(); await ds.channel_capacity()
ds.reset()
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode()
await ds.self_info(); await ds.contacts(); await ds.path_hash_mode(); await ds.channel_capacity()
asyncio.run(run())
assert dev.self_info_calls == 2
assert dev.contacts_calls == 2
assert dev.mode_calls == 2
assert dev.capacity_calls == 2 # capacity is a hardware constant, but a reconnect re-reads it
def test_channel_capacity_is_fetched_once_and_served_from_cache() -> None:
"""Capacity is a hardware constant: probed once, then reused for the session."""
dev = FakeDevice()
ds = _devstate(dev)
async def run() -> None:
for _ in range(3):
assert await ds.channel_capacity() == 8
asyncio.run(run())
assert dev.capacity_calls == 1
def test_prewarm_fills_the_slow_caches_off_the_read_path() -> None:
"""prewarm() warms contacts and channels in the background so the first read hits no wire."""
"""prewarm() warms contacts, channels, and capacity so the first read hits no wire."""
dev = FakeDevice()
ds = _devstate(dev)
async def run() -> None:
ds.prewarm()
await asyncio.gather(*list(ds._tasks)) # let the background warm finish
# Both slow caches were filled by the prewarm: contacts once, the channel probe once
# (idx 0 ok, idx 1 rejected).
# Every slow cache was filled by the prewarm: contacts once, the channel probe once
# (idx 0 ok, idx 1 rejected), and the capacity probe once.
assert dev.contacts_calls == 1
assert dev.channel_calls == 2
assert dev.capacity_calls == 1
# A screen opening now is served from cache — no additional round-trips.
await ds.contacts()
await ds.channel_slots()
await ds.channel_capacity()
assert dev.contacts_calls == 1
assert dev.channel_calls == 2
assert dev.capacity_calls == 1
asyncio.run(run())