Relay marks count every repeater; near relays are gone

The first build counted only the relays past the first hops of the
outbound paths. On JP's Public channel, 23 of 23 sent messages came back
only through the two home repeaters: each repeater relays one time, and
the next hop (8 km away) is too far for the companion to hear. So every
message showed the warning mark, and nothing was ever confirmed.

Now each repeater that sends a copy back counts, the same as a DM ack:
spinner, then a check with the number of repeaters, or a cross. The
warning state, the near-relay snapshot of each send, the ^P atom, and
heard_via are removed. heard_relays keeps only the paths; a database with
the first build of the table gets it made again (derived data only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-20 21:21:11 -05:00
1 parent f4b1d659d1
commit 5dc62cdc5b
13 files changed
+164 -379

No files matched your search

-11
View File
@@ -834,17 +834,6 @@ class ChatService:
scope=await self._sent_under(asked),
)
chat.row_id = self._ctx.repo.record_chat_message(chat, run_id=self._run_id)
# The near relays of this send, so that a later change of site does not change
# whether the message went past them (refer to meshterm.services.heard_by).
if getattr(self._ctx, "outbound_store", None) is not None:
try:
from .heard_by import near_relays
from .outbound import current_choice
choice = await current_choice(self._ctx)
self._ctx.repo.set_near_hops(chat.row_id, near_relays(choice.paths))
except Exception as exc: # noqa: BLE001 - the message went out. Only the mark is less exact
self._ctx.log.debug("couldn't keep the near relays of a send: %s", exc)
return chat
async def _sent_under(self, asked: str | None) -> str | None:
+40 -116
View File
@@ -1,30 +1,23 @@
# SPDX-License-Identifier: Apache-2.0
"""Tell whether a channel message that we sent went past our own repeaters (issue #38).
"""Tell whether a repeater relayed a channel message that we sent (issue #38).
A channel broadcast has no acknowledgement. But the device hears the relay of our
broadcast by each repeater in range, and its RX log records each copy with the path that
the copy went through (refer to :mod:`~meshterm.services.message_paths`). Each hop in that
path heard the message. Thus the copies that come back are the proof that somebody heard
it.
path heard the message. Thus a copy that comes back is the proof that a repeater heard the
message and sent it on.
A copy from a repeater next to us proves little: it shows that the message left our
radio. The user names these repeaters already, as the first hops of the **outbound
paths** of the active site or of a fixed device (refer to
:mod:`~meshterm.core.outbound_store`). This module calls them the **near relays**. Each
other hop in a copy is a relay that is not near, and it proves that the message went
farther. A near relay is near by its identity, not by its place in a path: the path
``UpperSalaberry → Cartierville`` has two near relays at home, and no other relay.
Each relay counts, the repeater next to us too. A first version counted only the relays
past the first hops of the outbound paths. In practice, nothing past them ever came back:
each repeater relays a packet one time, and the relays farther out are too far for our
radio to hear (JP, 2026-11-20, from 23 of 23 messages on his Public channel).
A managed node is not a near relay. The user can manage a repeater on the other side of
the city, and a relay by that repeater is good proof that the message went out.
The verdict of a message has three states, the same as the delivery of a direct message:
The verdict of a message has four states:
* :data:`WAITING`: no relay that is not near was heard yet, and the wait
(``heard_wait_s``) is not over. The chat shows a spinner.
* :data:`BEYOND`: one or more relays that are not near heard it. The chat shows ``✓`` and
the number of these relays.
* :data:`NEARBY`: after the wait, only near relays sent a copy back. The chat shows ``⚠``.
* :data:`WAITING`: no copy came back yet, and the wait (``heard_wait_s``) is not over. The
chat shows a spinner.
* :data:`HEARD`: one or more relays sent a copy back. The chat shows ``✓`` and the number
of the relays.
* :data:`UNHEARD`: after the wait, no copy came back. The chat shows ``✗``.
A copy that comes back late changes the verdict, as a late acknowledgement does for a
@@ -32,8 +25,8 @@ direct message. After the match window of the packet log
(:data:`~meshterm.services.message_paths.CHANNEL_WINDOW`), nothing can change it, and
MeshTerm stores the paths, so that the next visit does not decrypt the log again.
Two limits stay. MeshTerm sees only the relays that our radio hears, so a relay farther
away than that never shows. And MeshTerm must be connected while the copies come back.
Two limits stay. MeshTerm sees only the relays that our radio hears. And MeshTerm must be
connected while the copies come back.
Nothing in this module transmits. It is a read-model over the repository.
"""
@@ -55,8 +48,7 @@ if TYPE_CHECKING:
#: The verdict states (refer to the module docstring).
WAITING = "waiting"
BEYOND = "beyond"
NEARBY = "nearby"
HEARD = "heard"
UNHEARD = "unheard"
#: The number of messages that :meth:`HeardTracker.fill` examines before each yield to the
@@ -72,52 +64,17 @@ class HeardBy:
"""The verdict on one channel message that we sent.
Attributes:
state: :data:`WAITING`, :data:`BEYOND`, :data:`NEARBY`, or :data:`UNHEARD`.
beyond: The hashes of the relays that are not near, in the order first heard.
Each one heard the message.
via: The near relays that started the copies that went farther, in the order first
heard. Thus the user sees which of the repeaters at home carried the message
out.
state: :data:`WAITING`, :data:`HEARD`, or :data:`UNHEARD`.
relays: The hashes of the relays in the copies, in the order first heard. Each one
heard the message.
copies: The number of copies that came back.
"""
state: str
beyond: tuple[str, ...] = ()
via: tuple[str, ...] = ()
relays: tuple[str, ...] = ()
copies: int = 0
def near_relays(paths: Iterable[Sequence[str]]) -> tuple[str, ...]:
"""The first hop of each outbound path, without duplicates, in order.
Args:
paths: The outbound paths that apply
(:attr:`~meshterm.core.outbound_store.OutboundChoice.paths`).
Returns:
The near relays, as lowercase hex.
"""
out: list[str] = []
for path in paths:
if path:
hop = str(path[0]).lower()
if hop not in out:
out.append(hop)
return tuple(out)
def is_near(hop: str, near: Sequence[str]) -> bool:
"""Whether a hop of a path is one of the near relays.
A hop in a packet path is a hash: one to three bytes of the key. A near relay is a
longer key prefix. The hop matches when one starts with the other. When two
repeaters share a one-byte hash, a relay that is not near can match a near relay. Then
the count is too low, but it never claims a relay that did not occur.
"""
hop = hop.lower()
return bool(hop) and any(n.startswith(hop) or hop.startswith(n) for n in near)
def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]:
"""The paths of the copies that tell which relays heard the message.
@@ -128,49 +85,35 @@ def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]:
return [a.hops for a in arrivals if a.hops and a.route_known]
def judge(
paths: Sequence[RelayPath], near: Sequence[str], *, age_s: float, wait_s: float
) -> HeardBy:
def judge(paths: Sequence[RelayPath], *, age_s: float, wait_s: float) -> HeardBy:
"""The verdict on a message from the paths of its copies.
Args:
paths: The relay paths of the copies that came back, in the order heard.
near: The near relays at the time of the send.
age_s: The time since the send, in seconds.
wait_s: The wait before "no relay" becomes the verdict (``heard_wait_s``).
Returns:
The verdict.
"""
beyond: list[str] = []
via: list[str] = []
relays: list[str] = []
for path in paths:
far = [hop.lower() for hop in path if not is_near(hop, near)]
for hop in far:
if hop not in beyond:
beyond.append(hop)
if far:
for hop in path:
if hop.lower() == far[0]:
break
if hop.lower() not in via:
via.append(hop.lower())
if beyond:
state = BEYOND
for hop in path:
if hop.lower() not in relays:
relays.append(hop.lower())
if relays:
state = HEARD
elif age_s < wait_s:
state = WAITING
elif paths:
state = NEARBY
else:
state = UNHEARD
return HeardBy(state, tuple(beyond), tuple(via), len(paths))
return HeardBy(state, tuple(relays), len(paths))
@dataclass(slots=True)
class _Record:
"""What the tracker knows about one message: its near relays, and the copies so far."""
"""What the tracker knows about one message: the copies so far, and if more can come."""
near: tuple[str, ...]
paths: list[RelayPath] = field(default_factory=list)
settled: bool = False
@@ -191,7 +134,6 @@ class HeardTracker:
*,
channel_name: str,
secret: bytes | None,
near_now: tuple[str, ...],
wait_s: Callable[[], float],
clock: Callable[[], datetime] = utcnow,
) -> None:
@@ -202,15 +144,12 @@ class HeardTracker:
channel_name: The name of the channel (for the decryption).
secret: The key of the channel. With no key, nothing can be matched, and each
verdict is ``None``.
near_now: The near relays that apply now. A message sent before MeshTerm kept
the near relays of each send uses these.
wait_s: Gives the ``heard_wait_s`` preference, read at each verdict.
clock: Gives the current time (a fixed clock in the tests).
"""
self._repo = repo
self._channel_name = channel_name
self._secret = secret
self._near_now = near_now
self._wait_s = wait_s
self._clock = clock
self._records: dict[int, _Record] = {}
@@ -238,12 +177,12 @@ class HeardTracker:
record = self._records.get(message.row_id) # type: ignore[arg-type]
if record is None:
return None
return judge(record.paths, record.near, age_s=self._age_s(message), wait_s=self._wait_s())
return judge(record.paths, age_s=self._age_s(message), wait_s=self._wait_s())
def note_sent(self, message: ChatMessage) -> None:
"""Start the verdict of a message that was sent while the screen is open."""
if self._ours(message):
self._records[message.row_id] = _Record(near=self._near_now) # type: ignore[index]
self._records[message.row_id] = _Record() # type: ignore[index]
self._revision += 1
async def fill(self, messages: Sequence[ChatMessage]) -> None:
@@ -258,19 +197,14 @@ class HeardTracker:
ours = [m for m in messages if self._ours(m)]
stored = self._repo.heard_records([m.row_id for m in ours]) # type: ignore[misc]
for message in ours:
near, paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type]
paths = stored.get(message.row_id) # type: ignore[arg-type]
if paths is not None:
self._records[message.row_id] = _Record( # type: ignore[index]
near=near if near is not None else self._near_now,
paths=list(paths),
settled=True,
)
self._records[message.row_id] = _Record(paths=list(paths), settled=True) # type: ignore[index]
self._revision += 1
todo = [m for m in reversed(ours) if m.row_id not in self._records]
for start in range(0, len(todo), _CHUNK):
for message in todo[start : start + _CHUNK]:
near, _paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type]
self._examine(message, near if near is not None else self._near_now)
self._examine(message)
self._revision += 1
await asyncio.sleep(0)
@@ -291,7 +225,7 @@ class HeardTracker:
if record is None or record.settled:
continue
before = list(record.paths)
self._examine(message, record.near)
self._examine(message)
changed = changed or self._records[message.row_id].paths != before # type: ignore[index]
if changed:
self._revision += 1
@@ -301,7 +235,7 @@ class HeardTracker:
"""Whether one of the messages shows the spinner now."""
return any((v := self.verdict(m)) is not None and v.state == WAITING for m in messages)
def _examine(self, message: ChatMessage, near: tuple[str, ...]) -> None:
def _examine(self, message: ChatMessage) -> None:
"""Match the copies of one message in the packet log, and settle it if it is old."""
assert self._secret is not None and message.row_id is not None
arrivals = channel_arrivals(
@@ -309,19 +243,18 @@ class HeardTracker:
)
paths = relay_paths(arrivals)
settled = self._age_s(message) > CHANNEL_WINDOW.total_seconds()
self._records[message.row_id] = _Record(near=near, paths=paths, settled=settled)
self._records[message.row_id] = _Record(paths=paths, settled=settled)
if settled:
self._repo.settle_heard(message.row_id, near, paths)
self._repo.settle_heard(message.row_id, paths)
async def make_tracker(
def make_tracker(
ctx: AppContext, *, channel_name: str, secret: bytes | None
) -> HeardTracker | None:
"""A tracker for one channel, with the near relays that apply now.
"""A tracker for one channel.
Args:
ctx: The shared application context (the repository, the outbound paths, and the
preferences).
ctx: The shared application context (the repository and the preferences).
channel_name: The name of the channel.
secret: The key of the channel. With no key, there is no tracker.
@@ -330,18 +263,9 @@ async def make_tracker(
"""
if not secret:
return None
from .outbound import current_choice
near: tuple[str, ...] = ()
if getattr(ctx, "outbound_store", None) is not None:
try:
near = near_relays((await current_choice(ctx)).paths)
except Exception: # noqa: BLE001 - with no outbound paths, each relay counts
near = ()
return HeardTracker(
ctx.repo,
channel_name=channel_name,
secret=secret,
near_now=near,
wait_s=lambda: float(ctx.preferences.heard_wait_s),
)