A trace to a companion turns at its last relay

A companion, a room server, or a sensor does not relay a trace with the
firmware defaults (allowPacketForward in Mesh.cpp: client repeat is off,
and allowed only on 433.000, 869.495, and 918.000 MHz; disable_fwd is on).
A walk that turned at one of them never came home: the history held 36
companion traces and no reply from a real one.

The route to such a node is the same. Only the walk changes: it turns at
the last relay of the route, and the node is not in the spec. The route
out of a walk that comes home is still the full route to the node, so
the Device route row can offer it for DMs and admin.

- relays_traces() in models states the rule. render_forced_spec takes
  relays=False, and forced_outbound reads the route back from a walk.
- services/trace_plan holds the route choice that the trace screen made
  inline (radio route, outbound paths, best observed, last trace,
  direct), so the CLI uses the same one.
- The trace screen names the relay where the walk turns, in a line under
  the route. With no relay to turn at, Trace is dim. A neighbour that
  does not relay gets "no relays" offered on the Device route row, with
  the packets heard directly as its proof.
- The trace session turns a caller's spec (node page, Message paths) at
  the last relay, so the callers do not need the rule. A sender that is
  not a contact gets its type from its stored adverts.
- The composer and Explore paths turn the walk at the last hop.
- `meshterm trace -t NAME` with no --path walks the menu's route and says
  on stderr where it turns. With no known relay, it is a usage error.
- The connection turns a device-routed trace at the last learned relay.
  The simulator now stops a walk at a node that does not relay, as the
  mesh does, and the tests that walked through Alice walk repeaters.

The picker keeps one list with no mark, sorted as before (JP's choice).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-08 03:42:56 -05:00
1 parent fe8a70d516
commit d3166170ff
18 files changed
+1118 -229

No files matched your search

+41 -21
View File
@@ -156,8 +156,9 @@ samples:
matching width, they match.
- **A `trace` that the device routes invents its hop names.** If you give
`trace --target NAME` with no `--path`, the simulator router returns placeholder hops.
A forced path (`--path "a1,d4"`) resolves correctly. The samples use the forced form.
Use the forced form also to build a golden file.
A forced path (`--path "a1,b2,a1"`) resolves correctly. The samples use the forced
form. Use the forced form also to build a golden file. As on the real mesh, a forced
path through a simulated companion or room server never comes home.
> **`--mock` records into its own history, not yours, but it still writes the caches.**
> The simulator is a fake radio. It is not a fake MeshTerm. MeshTerm stores what the
@@ -230,8 +231,8 @@ would be a behaviour that nobody can find.
different. These are two lines from the facts block of a trace:
```
path a1,d4
route MockCompanion (00) → Yagi-Repeater (a1) → Alice (d4) → MockCompanion (00)
path a1,b2
route MockCompanion (00) → Yagi-Repeater (a1) → Local-Repeater (b2) → MockCompanion (00)
```
A **path** is a spec. It is the list of hops that you write and force. It is the one line
@@ -1547,19 +1548,20 @@ Walk the path to a target one time and report what came back.
without a target is [`trace-path`](#meshterm-trace-path).
```console
$ meshterm trace --target Alice --path "a1,d4"
target Alice
path a1,d4
$ meshterm trace --target Local-Repeater --path "a1,b2,a1"
target Local-Repeater
path a1,b2,a1
success yes
hops 3
hops 4
min_snr_db +2.0
rtt_ms 123
route MockCompanion (00) → Yagi-Repeater (a1) → Alice (d4) → MockCompanion (00)
rtt_ms 458
route MockCompanion (00) → Yagi-Repeater (a1) → Local-Repeater (b2) → Yagi-Repeater (a1) → MockCompanion (00)
HOP FROM TO SNR_DB
0 00 a1 +6.0
1 a1 d4 +2.0
2 d4 00 +6.0
1 a1 b2 +2.0
2 b2 a1 +2.4
3 a1 00 +6.0
```
The output has two blocks. The first block shows what the walk did. It has the drawn
@@ -1572,6 +1574,24 @@ and the hash joins the two blocks.
A trace that never came home is **not** a failure of the command. The radio transmitted,
and the walk ran. The command reports `success no` and returns `5`.
A companion, a room server, or a sensor does not relay a trace, so a walk that turns at
one of them never comes home. When the target is one of these and you omit `--path`,
MeshTerm chooses the route as the menu does. Then the walk turns at the last repeater of
that route. A line on stderr names that repeater, and `path` shows the walk:
```console
$ meshterm trace --target Alice
Alice can't relay a trace, so the trace turns at Yagi-Repeater (device route)
target Alice
path a1
success yes
...
```
The route out of that walk is also the route that the radio can use to send to the
target. If MeshTerm knows no repeater on the way to the target, nothing is transmitted,
and the command returns `2`.
#### `meshterm trace-path`
The other half of tracing. It has no target. You compose a path by hand, out and back, in
@@ -1582,19 +1602,19 @@ any way that you choose. The path only has to end where this node can hear it.
| `--path SPEC` | **Required.** The whole walk, comma-separated. |
```console
$ meshterm trace-path --path "a1,d4,a1"
$ meshterm trace-path --path "a1,b2,a1"
target -
path a1,d4,a1
path a1,b2,a1
success yes
hops 4
min_snr_db +2.0
rtt_ms 458
route MockCompanion (00) → Yagi-Repeater (a1) → Alice (d4) → Yagi-Repeater (a1) → MockCompanion (00)
route MockCompanion (00) → Yagi-Repeater (a1) → Local-Repeater (b2) → Yagi-Repeater (a1) → MockCompanion (00)
HOP FROM TO SNR_DB
0 00 a1 +6.0
1 a1 d4 +2.0
2 d4 a1 +2.4
1 a1 b2 +2.0
2 b2 a1 +2.4
3 a1 00 +6.0
```
@@ -1618,8 +1638,8 @@ table of hops is under `edges`.
| `edges` | array | The `edge` shape, one for each hop, in the order of the walk. `[]` when nothing came home. |
```console
$ meshterm trace-path --path "a1,d4" --json | jq -r '.edges | min_by(.snr_db) | "\(.from.hash) -> \(.to.hash) \(.snr_db) dB"'
a1 -> d4 2.0 dB
$ meshterm trace-path --path "a1,b2" --json | jq -r '.edges | min_by(.snr_db) | "\(.from.hash) -> \(.to.hash) \(.snr_db) dB"'
a1 -> b2 2.0 dB
```
#### `meshterm outbound`
@@ -2331,14 +2351,14 @@ fi
are about:
```bash
meshterm trace-path --path "a1,d4" --json \
meshterm trace-path --path "a1,b2" --json \
| jq -r '.edges | min_by(.snr_db) | "\(.from.hash) -> \(.to.hash) \(.snr_db) dB"'
```
**A route as one line**, with our node, as the plain face draws it:
```bash
meshterm trace-path --path "a1,d4,a1" --json \
meshterm trace-path --path "a1,b2,a1" --json \
| jq -r '.route | map(.name // .hash) | join(" -> ")'
```
+1 -1
View File
@@ -38,7 +38,7 @@ This page lists each interactive screen with its scripted equivalent, where one
| --- | --- | --- |
| **🌍 Map** | The nodes that have a position, plotted on a real OpenStreetMap street map. The map is drawn as Unicode braille (streets, rivers, and place names). You can pan and zoom. Repeaters are highlighted and drawn on top. When you are offline, the map shows a blank grid. | none (a map is a picture, but `meshterm contacts` lists the same nodes) |
| **🌐 Mesh walk** | The observed shape of the mesh, which you walk one node at a time. It is a graph of evidence from trace walks, firmware routes, overheard relay chains, and the neighbour tables of repeaters. It has braille edges that are coloured by SNR, and quality bars. Press Enter to walk to a node. Press ⌫ to go back. Type to find any node. The map shows where the nodes are. The walk shows how the nodes connect. | none |
| **🎯 Trace target** | A live trace screen. Select a target, and each trace streams in, hop by hop. The screen shows the running median and the reliability of each hop. You can compose a route through specific repeaters, or force one. A trace transmits **exactly once**, because repeaters can blacklist nodes that send bursts. To get more samples, run the trace again. A trace that came home proves its route out and back. Thus, when the radio uses another route to the target, the Device route row turns green and offers the traced route for direct messages and admin. A route that Explore paths measured with a probe counts too: when you adopt it, the row offers it at once, with no second transmission. | `meshterm trace --target …` |
| **🎯 Trace target** | A live trace screen. Select a target, and each trace streams in, hop by hop. The screen shows the running median and the reliability of each hop. You can compose a route through specific repeaters, or force one. A trace transmits **exactly once**, because repeaters can blacklist nodes that send bursts. To get more samples, run the trace again. A trace that came home proves its route out and back. Thus, when the radio uses another route to the target, the Device route row turns green and offers the traced route for direct messages and admin. A route that Explore paths measured with a probe counts too: when you adopt it, the row offers it at once, with no second transmission. A companion, a room server, or a sensor does not relay a trace, so a trace to it turns at the last repeater on its route. A line under the route names that repeater. The route that comes home is still the full route to the node, so the row can offer it. A neighbour with no repeater between you has nothing to trace, and the row offers no relays. | `meshterm trace --target …` |
| **👣 Trace path** | The other half of tracing. You compose the whole circuit by hand, out and back, by the way that you choose. Then you walk it. The path composer suggests each next hop from the links that MeshTerm observed, strongest first. If you have the admin password of a repeater, the composer can also get the neighbour table of that repeater over the mesh. | `meshterm trace-path --path …` |
| **🧭 Outbound paths** | The ways out of your node that you trust, in your order. A radio link is not the same in the two directions: a repeater that your node hears well can hear your node badly, and most of what MeshTerm knows comes from what your node hears. Thus you name the way out, one or more hops long. Each site where you take the computer (Home, Work) has its own list, and one site is active. A companion that never moves can keep its own list. The trace features then start their suggested routes on your paths. Each path shows how well its first hop hears you (`out`) and how well you hear it (`in`). Measure sends one trace out along a path and back. When your radio hears the way out of another site, the menu asks if you want to use that site. | `meshterm outbound …` |
| **🧭 Device route** | The route that your radio holds for each contact, on the Routes tab of the node page. The radio keeps one route for each contact and replaces it with each new one that it learns, good or bad. A route that stopped to work loses each message on it, with no error. Here you see the route and how the radio got it. You can set it (your suggested route comes first), forget it so that the next message floods, or keep it: MeshTerm then writes it back each time that the radio replaces it. A kept route belongs to the site where you are. When you change site, MeshTerm saves the routes that the radio learned at the old site, and writes them back when you return. Discover routes sends one request and shows the route in each direction. When a direct message or an admin login gets no answer on a route, its retry can go by flood. | `meshterm route …` |
+59 -4
View File
@@ -54,6 +54,7 @@ from .models import (
advert_gate,
advert_time,
clock_tolerance_s,
relays_traces,
utcnow,
)
from .privatekey import normalize as normalize_key
@@ -4083,8 +4084,10 @@ class MeshCoreDevice(Device):
else:
# No forced path: build a path that ends at the target's own hash (with
# any learned ``out_path`` repeaters before it), because a trace replies only
# when its destination is the last hop. It is ``None`` only when the contact
# is unknown, and then the trace runs without a path.
# when its destination is the last hop. A target that does not relay turns at
# its last learned repeater instead. It is ``None`` when the contact is
# unknown, or when it does not relay and has no learned repeater. Then the
# trace runs without a path.
resolved = await self._trace_path_to_contact(mc, target)
if resolved is not None:
path_bytes, flags = resolved
@@ -4180,6 +4183,11 @@ class MeshCoreDevice(Device):
repeaters to mirror, so the outbound leg is the full path).
* learned multi-hop route → ``[repeater…, destination, repeater… (reversed)]``.
A destination that does not relay (a companion, a room server, or a sensor, refer
to :func:`~meshterm.core.models.relays_traces`) stops the trace. Then the walk turns
at the last repeater of the learned route, and the destination is not in it. With
no learned repeater, there is no turn, and the function returns ``None``.
Each hash is encoded again at the trace's own width (``1 << flags``, only
1/2/4/8 bytes). This changes the routing width of a region (for example 3) to the
widest value that the trace can represent (2). The firmware matches by hash
@@ -4190,8 +4198,8 @@ class MeshCoreDevice(Device):
target: The contact name (not case-sensitive), or a key prefix.
Returns:
``(path_bytes, flags)`` to walk, or ``None`` only when the contact is
unknown or has no public key to address.
``(path_bytes, flags)`` to walk, or ``None`` when the contact is unknown, has
no public key to address, or does not relay and has no learned repeater.
"""
payload = await self._contacts_payload(mc)
needle = target.casefold()
@@ -4223,6 +4231,11 @@ class MeshCoreDevice(Device):
route = bytes.fromhex(out_path)[: out_path_len * size]
repeaters = [route[i * size : i * size + trace_size] for i in range(out_path_len)]
dest = bytes.fromhex(pub)[:trace_size]
if not relays_traces(_as_int(info.get("type", info.get("adv_type")))):
# The destination does not relay, so the walk turns at the last repeater.
if not repeaters:
return None
dest, repeaters = repeaters[-1], repeaters[:-1]
# The outbound leg always ends at the destination's own hash, so the
# destination recognizes the trace and replies. The return leg mirrors the same
# repeaters back to us, because nothing sends the packet back automatically.
@@ -5975,6 +5988,42 @@ class MockDevice(Device):
offset = (remote_tx - self.optimal_remote_tx) / span
return 9.0 - 24.0 * (offset**2)
def _stops_trace(self, target: str, forced: list[str] | None) -> bool:
"""Whether a simulated contact that does not relay is in the walk, so that it stops.
With a forced path, a hop stops the walk when it names a contact that does not
relay, and no contact that relays. (On the real mesh, a repeater with the same hash
relays the trace.) With no path, the device routes the trace as the real device
does (refer to :meth:`MeshCoreDevice._trace_path_to_contact`): for a target that
does not relay, the walk turns at the last relay of its learned route. Thus only
such a target with no learned relay stops it.
Args:
target: The target of the trace, as a name or a key prefix.
forced: The hops of the forced path, or ``None`` when the device routes.
Returns:
Whether the trace stops before it comes home.
"""
def named(contact: Contact, token: str) -> bool:
key = (contact.public_key or contact.key_prefix or "").lower()
return bool(token) and key.startswith(token.strip().lower())
if forced is None:
needle = target.casefold()
return any(
not relays_traces(c.node_type)
and not c.route_hops
and (c.name.casefold() == needle or named(c, target))
for c in self._contacts
)
for token in forced:
matches = [c for c in self._contacts if named(c, token)]
if matches and not any(relays_traces(c.node_type) for c in matches):
return True
return False
async def run_trace( # noqa: D102 - inherited docstring
self,
target: str,
@@ -5987,6 +6036,12 @@ class MockDevice(Device):
forced = [h for h in path.split(",") if h.strip()] if path else None
# As on the real device: the path-hash width is the byte length of a forced hop.
hash_bytes = len(bytes.fromhex(forced[0])) if forced else None
if self._stops_trace(target, forced):
# As on the real mesh: a node that does not relay ends the walk there, and
# nothing comes back (refer to relays_traces).
return TraceResult(
target=target, success=False, tx_power=self._tx_power, path_hash_bytes=hash_bytes
)
depth = len(forced) if forced else self._rng.randint(1, 3)
hops: list[Hop] = []
for i in range(depth):
+26
View File
@@ -69,6 +69,32 @@ def node_type_label(node_type: int | None) -> str | None:
return NODE_TYPE_LABELS.get(int(node_type), f"type {node_type}")
#: The advert types whose stock firmware does not relay a packet. A trace comes back only
#: when each node of its path relays it (``allowPacketForward`` in ``Mesh.cpp``). Thus a
#: trace cannot turn at one of these nodes. The defaults of the firmware:
#:
#: * A companion relays only with "client repeat" on. This setting is off by default, and
#: the firmware accepts it only on the off-grid frequencies (433.000, 869.495, and
#: 918.000 MHz).
#: * A room server and a sensor relay only when their admin sets ``disable_fwd`` off. It
#: is on by default.
#:
#: MeshTerm cannot read these settings on a remote node. Thus it uses the defaults.
_NO_RELAY_TYPES = frozenset({NODE_TYPE_CHAT, NODE_TYPE_ROOM, NODE_TYPE_SENSOR})
def relays_traces(node_type: int | None) -> bool:
"""Whether a node of this advert type relays a trace, so that a trace can turn at it.
A repeater relays. A companion, a room server, and a sensor do not, by default (refer
to :data:`_NO_RELAY_TYPES`). A trace to such a node turns at the last relay before it.
The route that the trace walks out is then the full route to the node, because the node
itself is never a hop of its own route. An unknown type returns ``True``: MeshTerm
cannot tell, so it traces the node itself, as it did before it knew the rule.
"""
return node_type not in _NO_RELAY_TYPES
class LoginResult(Enum):
"""How an admin login ended, and also whether the node was there to end it.
+36
View File
@@ -1379,6 +1379,42 @@ class Repository:
)
return observations
def node_type(self, node: str) -> int | None:
"""The advert type that a node announced the last time MeshTerm heard it say one.
Trace target asks this for a node that is not a contact (the sender of a message),
because a node that does not relay changes the walk (refer to
:func:`~meshterm.core.models.relays_traces`).
Args:
node: The key of the node, or a prefix of it, in hex. Observations store the
first 12 hex digits. A shorter prefix can name more than one node. Then it
gives a type only when all these nodes announced the same type.
Returns:
The ``NODE_TYPE_*`` value, or ``None`` when no stored advert of the node has a
type, or when a short prefix names nodes of different types.
"""
prefix = node.lower().removeprefix("0x")[:12]
if not prefix:
return None
# A range, not LIKE, so that the index on ``node`` finds the rows. Each hex digit
# sorts before "g".
span = (prefix, prefix + "g")
if len(prefix) < 12:
types = self._conn.execute(
"SELECT DISTINCT node_type FROM observations WHERE node >= ? AND node < ? "
"AND node_type IS NOT NULL LIMIT 2",
span,
).fetchall()
return int(types[0]["node_type"]) if len(types) == 1 else None
row = self._conn.execute(
"SELECT node_type FROM observations WHERE node >= ? AND node < ? "
"AND node_type IS NOT NULL ORDER BY observed_at DESC LIMIT 1",
span,
).fetchone()
return int(row["node_type"]) if row is not None else None
def node_observations(
self, node: str, *, since: datetime | None = None, limit: int = 50000
) -> list[Observation]:
+63 -9
View File
@@ -118,7 +118,9 @@ def is_path_hash(value: str) -> bool:
return bool(value) and len(value) % 2 == 0 and all(c in _HEX_DIGITS for c in value)
def render_forced_spec(hops: tuple[str, ...], target_hash: str, width_bytes: int) -> str:
def render_forced_spec(
hops: tuple[str, ...], target_hash: str, width_bytes: int, *, relays: bool = True
) -> str:
"""Render a symmetric forced-path spec: the outbound hops, the target, the mirror back.
The MeshCore trace protocol has no separate "return path" field. The full boomerang
@@ -129,6 +131,12 @@ def render_forced_spec(hops: tuple[str, ...], target_hash: str, width_bytes: int
route that the user composed, and that comes back on a different path, is rendered
exactly as given by :func:`render_custom_spec` instead.
A target that does not relay (a companion, a room server, or a sensor, refer to
:func:`~meshterm.core.models.relays_traces`) cannot be the turn of a walk, because the
trace stops there. Then the walk turns at the last hop of the route, the relay that
hears the target, and the target is not in the spec. The hops are the same route to
the target in the two cases. Only the walk on the air is different.
Args:
hops: Intermediate repeaters, in order from our node outward, without the two
endpoints (empty means to trace the target directly, with no forced hops).
@@ -136,16 +144,59 @@ def render_forced_spec(hops: tuple[str, ...], target_hash: str, width_bytes: int
width_bytes: The preferred path-hash width for each hop, in bytes (1, 2, 4, or
8). :func:`collapse_width` makes it smaller when the known hash of a hop is
narrower.
relays: Whether the target relays a trace. ``False`` turns the walk at the last
hop.
Returns:
A comma-separated hex spec, for example ``"3d,f2,3d"`` for one forced hop.
A comma-separated hex spec, for example ``"3d,f2,3d"`` for one forced hop. It is
``""`` for a target that does not relay with no hops: there is no relay at which
the walk can turn.
"""
width = collapse_width(*hops, target_hash, ceiling=width_bytes)
outbound = [h[: width * 2] for h in (*hops, target_hash)]
outbound.extend(h[: width * 2] for h in reversed(hops))
if relays:
turn, legs = target_hash, hops
elif hops:
turn, legs = hops[-1], hops[:-1]
else:
return ""
width = collapse_width(*legs, turn, ceiling=width_bytes)
outbound = [h[: width * 2] for h in (*legs, turn)]
outbound.extend(h[: width * 2] for h in reversed(legs))
return ",".join(outbound)
def forced_outbound(
tokens: Sequence[str], target_hash: str, *, relays: bool = True
) -> tuple[str, ...] | None:
"""The route to the target that a symmetric walk carries: the inverse of the forced spec.
:func:`render_forced_spec` makes a walk from a route. This function finds the route
again in a walk. The walk must be a palindrome of odd length, the shape of each walk
that the forced spec makes. For a target that relays, the middle hop must be the
target, and the route is the hops before it. For a target that does not relay, the
middle hop is the last relay of the route, and the route is the hops up to and with
it.
Args:
tokens: The hop hashes of the walk, in walk order, without our node.
target_hash: The hex hash of the target (any width). The middle hop of a walk to a
target that relays must be a prefix of it.
relays: Whether the target relays a trace.
Returns:
The hop hashes of the route, in order from our node outward (empty means that the
target is a neighbour). ``None`` when the walk is not a boomerang of this shape.
"""
hops = [t.lower() for t in tokens]
if not hops or len(hops) % 2 == 0 or hops != hops[::-1]:
return None
mid = len(hops) // 2
if not relays:
return tuple(hops[: mid + 1])
if not target_hash.lower().startswith(hops[mid]):
return None
return tuple(hops[:mid])
def render_custom_spec(hops: tuple[str, ...], width_bytes: int) -> str:
"""Render a path spec that the user composed (asymmetric), exactly as given.
@@ -328,20 +379,23 @@ class PathScenario:
samples: int = 0
rank: int = 0
def spec(self, target_hash: str, width_bytes: int) -> str:
def spec(self, target_hash: str, width_bytes: int, *, relays: bool = True) -> str:
"""Render the scenario as a forced-path spec, with the return leg.
Refer to :func:`render_forced_spec` for the rules of the width and the return leg.
Refer to :func:`render_forced_spec` for the rules of the width, the return leg,
and a target that does not relay.
Args:
target_hash: The hex hash of the target (any width ≥ 1 byte).
width_bytes: The preferred path-hash width for each hop, in bytes (1, 2, 4,
or 8).
relays: Whether the target relays a trace.
Returns:
A comma-separated hex spec, for example ``"3d,f2,3d"``.
A comma-separated hex spec, for example ``"3d,f2,3d"``. It is ``""`` when the
walk has no relay at which to turn.
"""
return render_forced_spec(self.hops, target_hash, width_bytes)
return render_forced_spec(self.hops, target_hash, width_bytes, relays=relays)
class MeshTopology:
+215
View File
@@ -0,0 +1,215 @@
# SPDX-License-Identifier: Apache-2.0
"""The route that an automatic *Trace target* walks, for the menu and for the CLI.
A trace is one walked path, and the protocol has no destination field. Thus a trace to a
target must force a full boomerang: out to the target on a route, and back home on its
mirror. The radio rarely has a route to give. The firmware learns the route of a contact
only from addressed traffic in the two directions, and most repeater contacts flood. This
module chooses the route from all that MeshTerm knows, in this order:
1. The route of the radio, when it starts with an outbound path of the user (or when the
user has no outbound path).
2. The best route through an outbound path of the user.
3. The route of the radio.
4. The strongest route that MeshTerm observed (traces, relay chains, neighbour tables).
5. The route out of the last walk to the target that came home.
6. No relay: a direct attempt, which says clearly that it is one.
The menu (:mod:`meshterm.ui.trace_screen`) and the CLI (:mod:`meshterm.tools.trace`)
both call :func:`plan_route`. Thus ``meshterm trace NTon1`` walks the same route that the
menu shows for NTon1.
A target that does not relay (a companion, a room server, or a sensor, refer to
:func:`~meshterm.core.models.relays_traces`) has the same route. Only the walk changes:
it turns at the last relay of the route (refer to
:func:`~meshterm.services.topology.render_forced_spec`). Thus a route that comes home is
also a route that the radio can use to send to the node.
"""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from ..core.models import TraceResult
from .topology import MeshTopology, forced_outbound
@dataclass(frozen=True, slots=True)
class RoutePlan:
"""The route that an automatic trace walks to a target, and where it came from.
Attributes:
hops: The relays from our node to the target, in order from our node outward,
without the two ends. Empty means no relay (a direct attempt).
source: Where the route came from, in short words for the screen
(``device route``, ``best observed · 3× · −7 dB``, ``last trace · Nov 08 01:42``).
"""
hops: tuple[str, ...]
source: str
def previous_outbound(
previous: TraceResult | None, target_hash: str, *, relays: bool = True
) -> tuple[str, ...] | None:
"""Get the route out of the last walk to a target that came home.
A trace in target mode walks the symmetric boomerang. Thus its stored hop hashes (the
last hop, with no hash, is our node) are a palindrome of odd length. For a target that
relays, the middle hop is the target, and the route is the first half. For a target
that does not relay, the middle hop is the last relay, and the route is the first half
with it (refer to :func:`~meshterm.services.topology.forced_outbound`). When the stored
walk has that shape, its route is a route that the mesh already proved, ready to force
again.
Args:
previous: The most recent successful stored trace, if one exists.
target_hash: The full hex hash of the target, to make sure that the walk turned at
this target (the hop hashes are prefixes of it).
relays: Whether the target relays a trace.
Returns:
The route in order, from our node outward (empty means that the target answered
directly). ``None`` when there is no stored walk, or when it is not a boomerang
that this function can recognize.
"""
if previous is None or not previous.success:
return None
tokens = [h.node for h in previous.hops if h.node]
return forced_outbound(tokens, target_hash, relays=relays)
def best_observed(topo: MeshTopology, target_hash: str) -> tuple[tuple[str, ...], str] | None:
"""The strongest route to ``target_hash`` in the evidence, if the data has one.
This is the observed-topology counterpart of the route that the firmware learned. The
device often knows no route to a contact, because repeater contacts flood. In that
case, the evidence of the recorder (traces, relay chains heard from other traffic,
neighbour tables that MeshTerm got) may still give a route for which there is proof
that it carried traffic. The ranking is done by
:meth:`~meshterm.services.topology.MeshTopology.suggested`. It counts each node once,
whatever width its hash had, and it gives recent evidence more weight. This function
returns the canonical outbound hops of the winner, with a short source line
(``best observed · 3× · −7 dB``) for the route line and the summary. It returns
``None`` when no route is better than a direct attempt.
Args:
topo: The newly built evidence graph.
target_hash: The hex hash of the target (any width ≥ 1 byte).
Returns:
``(outbound_hops, provenance)`` for the suggested route, or ``None``.
"""
scenario = topo.suggested(topo.canonical(target_hash) or target_hash[:12])
if scenario is None:
return None
source = f"best observed · {scenario.samples}×"
if scenario.weakest_snr is not None:
source += f" · {scenario.weakest_snr:+.0f} dB"
return scenario.hops, source
def best_outbound(
topo: MeshTopology,
target_hash: str,
outbound: tuple[tuple[str, ...], ...],
silent_before: datetime,
choice: Any,
) -> tuple[tuple[str, ...], str] | None:
"""The best route to ``target_hash`` through an outbound path of the user, if one exists.
The ranking is :meth:`~meshterm.services.topology.MeshTopology.outbound_scenarios`: the
best score from the link after the path, the order of the user in a near tie, and no
path whose first hop went silent. The source line names the path and where the list
came from (``outbound path 1 · Foulab · 3× · −7 dB``).
Args:
topo: The newly built evidence graph.
target_hash: The hex hash of the target (any width ≥ 1 byte).
outbound: The outbound paths that apply, as canonical ids.
silent_before: The time before which a first hop counts as silent.
choice: The :class:`~meshterm.core.outbound_store.OutboundChoice` that gave the
paths, for the name of the site or the fixed device.
Returns:
``(outbound_hops, provenance)``, or ``None`` when no outbound path reaches the
target.
"""
target_id = topo.canonical(target_hash) or target_hash[:12]
found = topo.outbound_scenarios(target_id, outbound, silent_before=silent_before)
if not found:
return None
best = found[0]
source = f"outbound path {best.rank}"
if choice is not None and choice.name:
source += f" · {choice.name}"
if best.samples:
source += f" · {best.samples}×"
if best.weakest_snr is not None:
source += f" · {best.weakest_snr:+.0f} dB"
return best.hops, source
def plan_route(
target_hash: str,
*,
topology: Callable[[], MeshTopology],
device_route: tuple[str, ...] | None,
outbound: tuple[tuple[str, ...], ...],
choice: Any,
silent_before: datetime,
previous: TraceResult | None,
relays: bool = True,
) -> RoutePlan:
"""Choose the route that an automatic trace walks to a target (refer to the module).
The outbound paths of the user come before all the evidence, with one exception: a
device route that starts with one of them. The firmware learns its route from floods
that our node received, and a radio link is not symmetric (refer to
:mod:`meshterm.core.outbound_store`).
Args:
target_hash: The hex hash of the target (any width ≥ 1 byte).
topology: Builds the evidence graph. It is a callable, because the build reads all
the stored evidence, and the route of the radio often makes it unnecessary.
device_route: The route that the radio holds for the target, as canonical ids, or
``None`` when it holds none.
outbound: The outbound paths that apply now, as canonical ids.
choice: The :class:`~meshterm.core.outbound_store.OutboundChoice` that gave the
paths, or ``None``.
silent_before: The time before which the first hop of an outbound path counts as
silent.
previous: The most recent successful stored trace to the target, if one exists.
relays: Whether the target relays a trace. It changes only how the last walk is
read back.
Returns:
The route, and where it came from.
"""
device_first = device_route is not None and (
not outbound or any(device_route[: len(path)] == path for path in outbound)
)
if device_first:
assert device_route is not None
return RoutePlan(device_route, "device route")
if outbound:
through = best_outbound(topology(), target_hash, outbound, silent_before, choice)
if through is not None:
return RoutePlan(*through)
if device_route is not None:
return RoutePlan(device_route, "device route")
observed = best_observed(topology(), target_hash)
if observed is not None:
# The firmware has no route, but the evidence of the recorder gives one: the
# strongest observed path. Because of this, Trace target *suggests* a route from
# the data. It does not use a flood with no path by default, which fails after the
# first neighbour.
return RoutePlan(*observed)
hops = previous_outbound(previous, target_hash, relays=relays)
if hops is not None and previous is not None:
stamp = previous.timestamp.astimezone().strftime("%b %d %H:%M")
return RoutePlan(hops, f"last trace · {stamp}")
return RoutePlan((), "direct — no known route")
+128 -7
View File
@@ -6,9 +6,11 @@ a UX concept. The menu divides the feature at exactly that line:
* **Trace target** (``trace``): *can I get to this node?* Select a target from a list in
the order of recency. The live screen composes and explores symmetric routes that turn
at the target and come back over the mirrored hops. The list stays pushed below for
the full visit. Thus Esc from a walk goes back to the row that started it (sorted
again by the last trace), and the next node is one Enter away.
at the target and come back over the mirrored hops. A target that does not relay (a
companion, a room server, or a sensor) stops a trace, so its walk turns at the last
relay before it. The list stays pushed below for the full visit. Thus Esc from a walk
goes back to the row that started it (sorted again by the last trace), and the next
node is one Enter away.
* **Trace path** (``trace-path``): *how far can a route that I make go?* No target and
no picker. The user composes the full walk hop by hop, and it must only end at a node
that our node can hear. The traces are stored under the ``(path)`` sentinel, so the
@@ -27,7 +29,7 @@ stored under it. Thus the stored history is the same, wherever it came from.
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any
import typer
@@ -40,6 +42,7 @@ from ..core.models import (
Contact,
TraceResult,
TraceStats,
utcnow,
)
from ..services import trace_runner
from ..ui.widgets import stats_panel
@@ -169,8 +172,12 @@ class TraceTool(Tool):
It has the same ``NAME · TRACED · HEARD · PKTS · KEY`` lanes, Ctrl+arrow sort ring,
and type-to-filter as the Contacts screen and the courier recipient. But it lists
all the node types (a trace answers *can I get to this node?* for a repeater or a
room, the same as for a companion). It also has one more lane, ``TRACED``: how
all the node types, because a trace answers *can I get to this node?* for each
type. A repeater relays the trace itself. A companion, a room server, or a sensor
does not relay (refer to :func:`~meshterm.core.models.relays_traces`). Thus its
walk turns at the last relay of its route, which is also a route that the radio
can send to it on. The trace screen says so, so the list does not mark these
rows (JP, 2026-11-08). It also has one more lane, ``TRACED``: how
long ago each node was last traced. The list opens sorted by ``TRACED``, in
descending order. Thus the most recently traced node comes first, and the nodes
that were never traced are at the bottom. Enter commits the highlighted node as
@@ -422,10 +429,13 @@ async def _trace_once_cli(
# Resolve an optional forced path (names or hex) to the hex string that the radio
# accepts. A blank path is fully supported for a *target* trace: the device uses again
# the route that it already learned (or floods if it has no route). A path walk always
# has a path.
# has a path. A target that does not relay gets the walk that the menu gives it, which
# turns at its last relay.
path: str | None = None
if path_spec:
path = trace_runner.parse_trace_path(path_spec, contacts)
elif not is_walk:
path = await _turned_path(ctx, device, contacts, target, device_hash, resolve)
with ctx.ui.progress("trace") as progress:
task = progress.add_task("walking the path" if is_walk else f"tracing {target}", total=1)
@@ -481,6 +491,117 @@ async def _trace_once_cli(
)
async def _turned_path(
ctx: AppContext,
device: Any,
contacts: list[Contact],
target: str,
device_hash: str | None,
resolve: Any,
) -> str | None:
"""The forced walk for a target that does not relay: the walk of the menu, or ``None``.
A companion, a room server, or a sensor stops a trace (refer to
:func:`~meshterm.core.models.relays_traces`). Thus the device cannot route a trace to
it. This function chooses the route as the menu does
(:func:`~meshterm.services.trace_plan.plan_route`), and turns the walk at the last
relay of that route. A line on stderr names that relay. For a target that relays, or
that MeshTerm cannot identify, the function returns ``None``, and the device routes
the trace as before.
Args:
ctx: The shared application context.
device: The connected device.
contacts: The contacts of the device.
target: The target as the user typed it: a contact name or a key prefix.
device_hash: The public key of our node, or ``None``.
resolve: Names a hop hash, for the line on stderr.
Returns:
The forced spec, or ``None`` when the device can route the trace.
Raises:
typer.BadParameter: When the target does not relay and no relay on the way to it
is known. Nothing is transmitted, so this is a usage error.
"""
from rich.markup import escape
from ..core.models import relays_traces
from ..services.topology import (
MeshTopology,
build_topology,
collapse_width,
is_path_hash,
render_forced_spec,
)
from ..services.trace_plan import plan_route
needle, prefix = target.casefold(), target.lower()
contact = next(
(
c
for c in contacts
if c.name.casefold() == needle or (c.public_key or "").lower().startswith(prefix)
),
None,
)
raw = ((contact.public_key or contact.key_prefix) if contact else target).lower()
raw = raw.removeprefix("0x")
if not is_path_hash(raw):
return None
node_type = contact.node_type if contact is not None else ctx.repo.node_type(raw[:12])
if relays_traces(node_type):
return None
ident = MeshTopology(device_hash or "local", contacts)
store = getattr(ctx, "outbound_store", None)
choice = store.lookup(device_hash) if store is not None else None
outbound = (
tuple(tuple(ident.canonical(h) or h for h in path) for path in choice.paths)
if choice is not None
else ()
)
device_route = None
if contact is not None and contact.route_hops is not None:
device_route = tuple(ident.canonical(h) or h for h in contact.route_hops)
plan = plan_route(
raw,
topology=lambda: build_topology(
self_id=device_hash or "local",
contacts=contacts,
trace_paths=ctx.repo.trace_paths(),
packet_paths=ctx.repo.packet_paths(),
neighbour_links=ctx.repo.neighbour_links(),
),
device_route=device_route,
outbound=outbound,
choice=choice,
silent_before=utcnow() - timedelta(hours=ctx.preferences.outbound_silent_hours),
previous=ctx.repo.latest_trace(target),
relays=False,
)
try:
mode = int(await device.get_path_hash_mode())
except Exception: # noqa: BLE001 - an optional read. The 1-byte default always works.
mode = 0
width = collapse_width(ceiling=max(mode + 1, 1))
spec = render_forced_spec(plan.hops, raw, width, relays=False)
name = contact.name if contact is not None else target
if not spec:
raise typer.BadParameter(
f"{name} can't relay a trace, and no relay on the way to it is known — "
"trace a repeater near it, or give --path",
param_hint="'--target'",
)
tokens = spec.split(",")
turn = tokens[len(tokens) // 2]
ctx.ui.ack(
f"{escape(name)} can't relay a trace, so the trace turns at "
f"{escape(resolve(turn) or turn)} ({plan.source})"
)
return spec
def _trace_report(
result: TraceResult,
target: str,
+30 -7
View File
@@ -27,6 +27,9 @@ Trace target has the same row (:class:`RouteRow`). A trace that came home walked
out and back, which is the best proof that MeshTerm can have for a route. Thus, after such
a trace, the row offers the route that the trace walked (a :class:`ProvenRoute`), and the
popup gets two rows before the others: **Use the traced route** and **Use and keep it**.
A contact that does not relay a trace and that our node hears directly has no relay at
which a walk can turn. There, the row offers no relays at once, with the packets heard as
its proof, and the first row of the popup is **Use no relays**.
"""
from __future__ import annotations
@@ -139,7 +142,11 @@ class RouteEnv:
@dataclass(frozen=True, slots=True)
class ProvenRoute:
"""A route out to a contact that traces walked, and on which they came home.
"""A route out to a contact with proof: traces that came home on it, or a neighbour heard.
The usual proof is a trace. A contact that does not relay a trace and that MeshTerm
hears directly has no relay at which a walk can turn. Its proof is the packets that our
node heard from it with no relay, and its route is no relays.
Attributes:
hops: The relays from our node to the contact, as canonical ids. Empty means no
@@ -147,15 +154,25 @@ class ProvenRoute:
home: How many traces came home on the route.
sent: How many traces went out on it.
worst_snr: The median bottleneck SNR (dB) of the traces that came home, if known.
heard: How many times our node heard the contact directly, for a route with no
relays and no trace. It is 0 for a route that traces proved.
"""
hops: tuple[str, ...]
home: int
sent: int
worst_snr: float | None = None
heard: int = 0
@property
def proved(self) -> bool:
"""Whether there is proof to offer the route on: a trace came home, or a neighbour heard."""
return self.home > 0 or (not self.hops and self.heard > 0)
def evidence(self) -> str:
"""The proof in words: ``came home 5 of 5 · worst +3.5 dB``."""
"""The proof in words: ``came home 5 of 5 · worst +3.5 dB``, or ``heard directly 4×``."""
if not self.home:
return f"heard directly {self.heard}×"
text = f"came home {self.home} of {self.sent}"
if self.worst_snr is not None:
text += f" · worst {self.worst_snr:+.1f} dB"
@@ -255,23 +272,27 @@ def _status_rows(
)
if _offers_traced(status, proven):
assert proven is not None
rows.append(_note(f"the trace {proven.evidence()} on:"))
if proven.home:
rows.append(_note(f"the trace {proven.evidence()} on:"))
else:
rows.append(_note(f"{env.label} can't relay a trace, and it was {proven.evidence()}:"))
rows.append(_route_note(env.line(proven.hops)))
return rows
def _offers_traced(status: RouteStatus, proven: ProvenRoute | None) -> bool:
"""Whether the traced route is a change: it came home, and the radio holds another."""
return proven is not None and proven.home > 0 and not same_route(status.hops, proven.hops)
"""Whether the proven route is a change: it has its proof, and the radio holds another."""
return proven is not None and proven.proved and not same_route(status.hops, proven.hops)
def _action_rows(status: RouteStatus, proven: ProvenRoute | None = None) -> list[Any]:
"""The actions of the first page, for the state of the route and a traced route."""
"""The actions of the first page, for the state of the route and a proven route."""
rows: list[tuple[str, str, str]] = []
if _offers_traced(status, proven):
assert proven is not None
rows.append(
(
"Use the traced route",
"Use the traced route" if proven.home else "Use no relays",
"the kept route changes too" if status.kept is not None else "set it now",
_USE_TRACED,
)
@@ -573,6 +594,8 @@ class RouteRow:
"""
if _offers_traced(self._status, proven):
assert proven is not None
if not proven.home:
return f"Use no relays for DMs and admin — {proven.evidence()}…", True
came = f"{proven.home}/{proven.sent} came home"
return f"Use this route for DMs and admin — {came}…", True
label = row_label(self._status, sep=" — ")
+22 -3
View File
@@ -222,6 +222,7 @@ class PathComposerScreen(Screen):
target_id: str | None = None,
target_hash: str | None = None,
target_label: str | None = None,
target_relays: bool = True,
device_hash: str | None = None,
hops: list[str] | None = None,
cursor: int | None = None,
@@ -250,6 +251,11 @@ class PathComposerScreen(Screen):
the symmetric spec. When the user confirms the path, it is truncated to the
width of the spec.
target_label: The name of the target to show in the route preview.
target_relays: Whether the target relays a trace. ``False`` turns the walk at
the last composed hop, and the target is not in the spec or the preview
(refer to :func:`~meshterm.services.topology.render_forced_spec`). The
user then composes the route up to and with the relay that hears the
target.
device_hash: The public key of our node. Thus the endpoints of the preview have
a hash, exactly like the route line of the trace screen.
hops: The canonical ids of the hops that are already composed (when the
@@ -280,6 +286,7 @@ class PathComposerScreen(Screen):
self._target_id = target_id
self._target_hash = (target_hash or "").lower().removeprefix("0x")
self._target_label = target_label
self._target_relays = target_relays
self._device_label = device_label
self._device_hash = (device_hash or "").lower().removeprefix("0x")
self._topology = topology
@@ -520,7 +527,12 @@ class PathComposerScreen(Screen):
The spec is empty until the walk has one hop or more.
"""
if self._mirrored:
return render_forced_spec(tuple(self._hops), self._target_hash, self._width_bytes)
return render_forced_spec(
tuple(self._hops),
self._target_hash,
self._width_bytes,
relays=self._target_relays,
)
if self._outbound: # the stored form: each hop at its full width
return ",".join(self._hops)
return render_custom_spec(tuple(self._hops), self._width_bytes)
@@ -534,6 +546,9 @@ class PathComposerScreen(Screen):
are important, because a repeated section of the outbound leg also repeats on the
return leg.
"""
if self._mirrored and not self._target_relays:
# The walk turns at the last hop: the target is not in it.
return [*self._hops, *reversed(self._hops[:-1])]
if self._mirrored:
return [*self._hops, str(self._target_id), *reversed(self._hops)]
return list(self._hops)
@@ -637,7 +652,11 @@ class PathComposerScreen(Screen):
"""
entries: list[str | None] = [None]
entries.extend(self._path_entry(hop) for hop in self._hops)
if self._mirrored:
turn = 1 # the target, at the turn. A target that does not relay is not in the walk
if self._mirrored and not self._target_relays:
turn = 0
entries.extend(self._path_entry(hop) for hop in reversed(self._hops[:-1]))
elif self._mirrored:
entries.append(self._path_entry(self._target_id))
entries.extend(self._path_entry(hop) for hop in reversed(self._hops))
if self._outbound:
@@ -665,7 +684,7 @@ class PathComposerScreen(Screen):
self_name=self._device_label,
hash_bytes=self._width_bytes,
device_hash=self._device_hash or None,
dim_from=(2 if self._mirrored else 1) + len(self._hops),
dim_from=(1 + turn if self._mirrored else 1) + len(self._hops),
bare_self=True,
# The entries start with our ★, so arrow index k (the slot after shown node k)
# is rendered-hop index k + 1.
+179 -161
View File
@@ -7,7 +7,11 @@ field, so "target" is only a UX concept. The two menu features divide on that li
* **Trace target** (:func:`open_trace`) answers the question *can I reach this node?*
The route is symmetric: the user composes (or explores) the outbound leg, and the
return leg is those hops in mirror order around the pinned target.
return leg is those hops in mirror order around the pinned target. A target that does
not relay (a companion, a room server, or a sensor, refer to
:func:`~meshterm.core.models.relays_traces`) stops a trace. Thus its walk turns at the
last relay of the route, and a line under the route names that relay. The route out of
such a walk is still the full route to the target, so the Device route row can offer it.
* **Trace path** (:func:`open_trace_path`) answers the question *how far can a route
that I build go?* It has no target. The user composes the full walk by hand, out and
back by any way. The only condition is that the walk ends at a node that our node can
@@ -116,17 +120,25 @@ from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable, Sequence
from datetime import datetime, timedelta
from datetime import timedelta
from typing import TYPE_CHECKING, Any
from rich.cells import cell_len
from rich.console import Group, RenderableType
from rich.text import Text
from ..core.models import PATH_TRACE_TARGET, HopAggregate, TraceResult, TraceStats, utcnow
from ..core.models import (
PATH_TRACE_TARGET,
HopAggregate,
TraceResult,
TraceStats,
relays_traces,
utcnow,
)
from ..services import trace_runner
from ..services.records import first_repeated_edge
from ..services.topology import render_forced_spec
from ..services.topology import forced_outbound, render_forced_spec
from ..services.trace_plan import plan_route, previous_outbound
from .braillechart import meter
from .device_route_screen import ICON as ROUTE_ICON
from .device_route_screen import ProvenRoute, RouteRow
@@ -144,7 +156,7 @@ from .pathline import (
from .placemode import ACTION as PLACES_ACTION
from .placemode import PlaceToggle, node_of, placed, places_of_session
from .theme import snr_style
from .tui.render import crop_cells, render_lines, render_to_ansi
from .tui.render import crop_cells, render_hanging, render_lines, render_to_ansi
from .tui.screen import Screen
from .tui.spinner import Spinner, spinner_interval
from .widgets import NodeResolver, highlighted_hash, link_text, route_path
@@ -505,6 +517,10 @@ class TraceScreen(Screen):
route_row: RouteRow | None = None,
prove: Callable[[list[TraceResult]], ProvenRoute | None] | None = None,
seed_traces: Callable[[str], list[TraceResult]] | None = None,
relays: bool = True,
target_label: str | None = None,
neighbour: bool = False,
offer: ProvenRoute | None = None,
) -> None:
"""Create the screen (nothing transmits until the user runs Trace).
@@ -569,6 +585,15 @@ class TraceScreen(Screen):
seed_traces: Gives the traces that this session already walked on a spec (the
traces of a probe). When the screen adopts that spec, they become its
first traces. ``None`` starts each adopted path with no traces.
relays: Whether the target relays a trace (refer to
:func:`~meshterm.core.models.relays_traces`). ``False`` means that each walk
turns at the last relay before the target, and a line under the route says
so. With no relay to turn at, Trace has nothing to walk.
target_label: The name of the target, for that line. ``None`` uses ``target``.
neighbour: Whether MeshTerm hears the target directly. It changes the line
when a target that does not relay has no relay to turn at.
offer: A route for the Device route row to offer before any trace came home:
no relays, for a neighbour that does not relay. ``None`` offers nothing.
"""
super().__init__()
self.title = f"Trace — {target}" if mode == "target" else "Trace path"
@@ -595,6 +620,10 @@ class TraceScreen(Screen):
self._route_row = route_row if mode == "target" else None
self._prove = prove
self._seed_traces = seed_traces
self._relays = relays or mode != "target"
self._target_label = target_label or target
self._neighbour = neighbour
self._offer = offer
#: The trophy case disciplines that the current run placed in. The key is the
#: title of the discipline, so that a run with more than one sample that
#: improves keeps only its latest ``"Title — score"`` label for each board.
@@ -642,7 +671,7 @@ class TraceScreen(Screen):
actions.append("route")
actions += ["width", "samples", "trace"]
self._actions: tuple[str, ...] = tuple(actions)
ready = mode == "target" or bool(self._effective_spec()[0])
ready = not self._needs_spec() or bool(self._effective_spec()[0])
self._index = self._actions.index("trace" if ready else "compose")
self._pin_cursor = False # pin the viewport only while ↑/↓ are in use
#: How far ←→ slid the paths of the hops (in cells), and how far they can slide:
@@ -897,8 +926,9 @@ class TraceScreen(Screen):
if key == "trace":
# A path walk has nothing to transmit until a path is available (composed,
# or the last stored walk). It has no target, so an empty spec cannot use
# device routing instead.
if self._mode == "path" and not self._effective_spec()[0]:
# device routing instead. A target that does not relay is the same: the walk
# must turn at a relay of the spec.
if self._needs_spec() and not self._effective_spec()[0]:
return
edge = first_repeated_edge(self._spec_tokens())
if edge is not None:
@@ -927,10 +957,58 @@ class TraceScreen(Screen):
self._open_route()
def proven(self) -> ProvenRoute | None:
"""The route out that the traces of this route came home on, or ``None``."""
if self._prove is None or not self._traces:
return None
return self._prove(self._traces)
"""The route out that the traces of this route came home on, or ``None``.
Before the screen has traces, it is the route that the session offers at once (no
relays, for a neighbour that does not relay), while no spec gives a walk.
"""
if self._prove is not None and self._traces:
return self._prove(self._traces)
if self._offer is not None and not self._effective_spec()[0]:
return self._offer
return None
def _needs_spec(self) -> bool:
"""Whether Trace must have a spec to walk: no device routing can stand in for one.
A path walk has no target to route to. A target that does not relay has no turn
unless a spec gives a relay. In target mode, a target that relays can go without a
spec, because the device then routes the trace.
"""
return self._mode == "path" or not self._relays
def _turn_note(self, current: TraceResult | None) -> str:
"""The line under the route that says where the walk to a target that does not relay turns.
Such a target stops a trace, so each walk turns at the relay before it (refer to
:func:`~meshterm.core.models.relays_traces`). The line names that relay, from the
walk that the route lane shows. With no relay to turn at, the line says why: the
target is a neighbour, or MeshTerm knows no relay on the way to it.
Args:
current: The newest successful trace of this session, if one exists.
Returns:
The line, or ``""`` for a target that relays.
"""
if self._relays:
return ""
name = self._target_label
if current is not None:
tokens = [h.node for h in current.hops if h.node]
else:
tokens = self._spec_tokens()
if not tokens and self._previous is not None and self._previous.success:
tokens = [h.node for h in self._previous.hops if h.node]
stops = f"{name} can't relay a trace"
if not tokens:
if self._neighbour:
return f"{stops}, and it's a direct neighbour: no relay to turn at"
return f"{stops}, and no relay on the way to it is known"
if len(tokens) % 2 and tokens == tokens[::-1]:
turn = tokens[len(tokens) // 2]
return f"{stops}, so the trace turns at {self._resolve(turn) or turn}"
return f"{stops}, so the trace turns before it"
def _open_route(self) -> None:
"""Open the Device route popup over the screen, with the traced route to offer.
@@ -1055,6 +1133,14 @@ class TraceScreen(Screen):
# zero. It never separates a name from its hash, and never breaks a wire spec
# in the middle of a hash.
lines = _lane_lines(_ROUTE_LANE, self._route_value(current, width), width)
turn = self._turn_note(current)
if turn:
# The line is a sentence that can be long, so it wraps under the column of the
# lane, and is not cropped as the route lines are.
indent = len(_ROUTE_LANE)
lines.extend(
render_hanging(Text(" " * indent), Text(turn, style="muted"), width, indent=indent)
)
lines.extend(render_lines(Group(Text(), self._summary(stats)), width))
lines.extend(_lane_lines(_PATH_LANE, self._path_value(current, width), width))
lines.append("")
@@ -1154,6 +1240,8 @@ class TraceScreen(Screen):
_icon(text, "▶", "ok")
if self._mode == "path" and not self._effective_spec()[0]:
text.append("Trace — compose a path first", style="muted")
elif self._needs_spec() and not self._effective_spec()[0]:
text.append("Trace — no relay to turn at", style="muted")
else:
n = self._sample_count()
if n > 1:
@@ -1200,6 +1288,8 @@ class TraceScreen(Screen):
return lines
if self._mode == "path":
return [Text("none — compose a path to walk", style="muted")]
if not self._relays:
return [Text("none — no relay to turn at", style="muted")]
return [Text("unknown — press Enter to trace", style="muted")]
def _shown_route(self, current: TraceResult | None) -> tuple[PathLine, str] | None:
@@ -1567,36 +1657,6 @@ def collapse_trace_width(mode: int) -> int:
return max(s for s in (1, 2, 4, 8) if s <= size)
def _previous_outbound(previous: TraceResult | None, target_hash: str) -> tuple[str, ...] | None:
"""Extract the outbound repeaters from the last successful walk to a target.
A trace in target mode walks the symmetric boomerang. Thus its stored hop hashes
(the last hop, with no hash, is our node) are ``[out…, target, out reversed…]``:
a palindrome of odd length whose middle entry is the target. When the stored walk
has that shape, its first half is a route that the mesh already proved, ready to
force again.
Args:
previous: The most recent successful stored trace, if one exists.
target_hash: The full hex hash of the target, to make sure that the walk
turned at this target (the hop hashes are prefixes of it).
Returns:
The outbound repeater hashes in order, from our node outward (empty = the
target answered directly). ``None`` when there is no stored walk, or when it
is not a boomerang that this function can recognize.
"""
if previous is None or not previous.success:
return None
tokens = [h.node.lower() for h in previous.hops if h.node]
if not tokens or len(tokens) % 2 == 0 or tokens != tokens[::-1]:
return None
mid = len(tokens) // 2
if not target_hash.lower().startswith(tokens[mid]):
return None
return tuple(tokens[:mid])
def _previous_walk(previous: TraceResult | None) -> tuple[str, ...] | None:
"""Extract the full walked route from the last successful stored path walk.
@@ -1620,76 +1680,6 @@ def _previous_walk(previous: TraceResult | None) -> tuple[str, ...] | None:
return tokens or None
def _best_observed(topo: Any, target_hash: str) -> tuple[tuple[str, ...], str] | None:
"""The strongest outbound route to ``target_hash`` in the evidence, if the data has one.
This is the observed-topology counterpart of the route that the firmware learned.
The device often knows no route to a contact, because repeater contacts flood. In
that case, the evidence of the recorder (traces, relay chains heard from other
traffic, neighbour tables that MeshTerm got) may still give a route for which there
is proof that it carried traffic. The ranking is done by
:meth:`~meshterm.services.topology.MeshTopology.suggested`. This function returns
the canonical outbound hops of the winner, with a short source line
(``best observed · 3× · −7 dB``) for the route line and the summary. It returns
``None`` when no route is better than a direct attempt.
Args:
topo: The newly built :class:`~meshterm.services.topology.MeshTopology`.
target_hash: The hex hash of the target (any width ≥ 1 byte).
Returns:
``(outbound_hops, provenance)`` for the suggested route, or ``None``.
"""
scenario = topo.suggested(topo.canonical(target_hash) or target_hash[:12])
if scenario is None:
return None
source = f"best observed · {scenario.samples}×"
if scenario.weakest_snr is not None:
source += f" · {scenario.weakest_snr:+.0f} dB"
return scenario.hops, source
def _best_outbound(
topo: Any,
target_hash: str,
outbound: tuple[tuple[str, ...], ...],
silent_before: datetime,
choice: Any,
) -> tuple[tuple[str, ...], str] | None:
"""The best route to ``target_hash`` through an outbound path of the user, if one exists.
The ranking is :meth:`~meshterm.services.topology.MeshTopology.outbound_scenarios`:
the best score from the link after the path, the order of the user in a near tie, and
no path whose first hop went silent. The source line names the path and where the list
came from (``outbound path 1 · Foulab · 3× · −7 dB``).
Args:
topo: The newly built evidence graph.
target_hash: The hex hash of the target (any width ≥ 1 byte).
outbound: The outbound paths that apply, as canonical ids.
silent_before: The time before which a first hop counts as silent.
choice: The :class:`~meshterm.core.outbound_store.OutboundChoice` that gave the
paths, for the name of the site or the fixed device.
Returns:
``(outbound_hops, provenance)``, or ``None`` when no outbound path reaches the
target.
"""
target_id = topo.canonical(target_hash) or target_hash[:12]
found = topo.outbound_scenarios(target_id, outbound, silent_before=silent_before)
if not found:
return None
best = found[0]
source = f"outbound path {best.rank}"
if choice is not None and choice.name:
source += f" · {choice.name}"
if best.samples:
source += f" · {best.samples}×"
if best.weakest_snr is not None:
source += f" · {best.weakest_snr:+.0f} dB"
return best.hops, source
def _scenario_path(
scenario: Any,
topo: Any,
@@ -1929,6 +1919,15 @@ async def _open_session(
target_hash = raw_hash if is_path_hash(raw_hash) else None
target_label = target_contact.name if target_contact else (label or target)
# Whether the target relays a trace (refer to relays_traces). A contact gives its type.
# A node that is not a contact (the sender of a message, opened from Message paths)
# gives the type of its last advert that MeshTerm heard. A node with no known type is
# traced itself, as before.
target_type = target_contact.node_type if target_contact is not None else None
if target_type is None and target_hash is not None and target_contact is None:
target_type = ctx.repo.node_type(target_hash[:12])
target_relays = mode == "path" or relays_traces(target_type)
def fresh_topology() -> MeshTopology:
"""Build the evidence graph from all the data that is stored now and on the device."""
return build_topology(
@@ -1942,21 +1941,8 @@ async def _open_session(
previous = ctx.repo.latest_trace(record_target)
# What an *auto* trace (with no composed path) forces on the air, and where that
# route came from. A trace replies only when its destination is the last outbound
# hop of the path and nothing reflects it back home. Thus auto must always give a
# full boomerang. But the device rarely has one to give. The firmware learns the
# ``out_path`` of a contact only from addressed traffic in the two directions
# (checked on hardware: each repeater contact reported ``out_path_len`` -1,
# flood). Thus a trace with device routing to a node farther than a direct
# neighbour goes out with no repeaters, and fails. The order of priority: the route
# that the device learned, when it really has one. If not, the outbound leg of the
# last successful stored walk (the route that the screen shows). If not, the bare
# destination: a direct attempt, which says clearly that it is one.
#
# The outbound paths of the user come before all of these, with one exception: a
# device route that starts with one of them. The firmware learns its route from floods
# that our node received, and a radio link is not symmetric (refer to
# meshterm.core.outbound_store).
# route came from. A trace comes back only on a full boomerang, which the device
# rarely has to give (refer to meshterm.services.trace_plan, which the CLI uses too).
# To make hop hashes canonical, only the contact index is necessary. Thus an *empty*
# graph does it. The full evidence build of fresh_topology() (stored traces, packet
# paths, neighbour tables) is necessary only for a suggestion from the evidence.
@@ -1972,36 +1958,20 @@ async def _open_session(
device_route: tuple[str, ...] | None = None
if target_contact is not None and target_contact.route_hops is not None:
device_route = tuple(ident.canonical(h) or h for h in target_contact.route_hops)
device_first = device_route is not None and (
not outbound or any(device_route[: len(path)] == path for path in outbound)
)
auto_hops: tuple[str, ...] | None = None
auto_source = ""
if target_hash is not None:
through = (
None
if device_first or not outbound
else _best_outbound(fresh_topology(), target_hash, outbound, silent_before, choice)
plan = plan_route(
target_hash,
topology=fresh_topology,
device_route=device_route,
outbound=outbound,
choice=choice,
silent_before=silent_before,
previous=previous,
relays=target_relays,
)
if device_first:
auto_hops, auto_source = device_route, "device route"
elif through is not None:
auto_hops, auto_source = through
elif device_route is not None:
auto_hops, auto_source = device_route, "device route"
elif (observed := _best_observed(fresh_topology(), target_hash)) is not None:
# The firmware has no route, but the evidence of the recorder gives one: the
# strongest observed path (the ranking uses sample counts and SNR). Because
# of this, Trace target *suggests* a route from the data. It does not use a
# flood with no path by default, which fails after the first neighbour.
auto_hops, auto_source = observed
else:
auto_hops = _previous_outbound(previous, target_hash)
if auto_hops is not None and previous is not None:
stamp = previous.timestamp.astimezone().strftime("%b %d %H:%M")
auto_source = f"last trace · {stamp}"
else:
auto_hops, auto_source = (), "direct — no known route"
auto_hops, auto_source = plan.hops, plan.source
elif mode == "path":
auto_hops = _previous_walk(previous)
if auto_hops is not None and previous is not None:
@@ -2018,7 +1988,20 @@ async def _open_session(
return ""
if target_hash is None:
return ",".join(auto_hops)
return render_forced_spec(auto_hops, target_hash, width_bytes)
return render_forced_spec(auto_hops, target_hash, width_bytes, relays=target_relays)
# A caller (the node page, Message paths) gives a route as the forced spec that turns
# at the target. When the target does not relay, the trace stops there. Thus the spec
# turns at the last relay of the same route instead, and the callers do not have to
# know the rule. With no relay, nothing is left to walk, and the screen opens on the
# automatic route.
if mode == "target" and target_hash is not None and not target_relays and initial_spec:
tokens = [t.strip() for t in initial_spec.split(",") if t.strip()]
route = forced_outbound(tokens, target_hash)
if route is not None:
initial_spec = render_forced_spec(
route, target_hash, max(1, len(tokens[0]) // 2), relays=False
)
async def unaddressable() -> None:
"""Explain why the path features of target mode must have a target that resolves."""
@@ -2176,7 +2159,9 @@ async def _open_session(
if mode == "path":
seed = ids
elif ids and len(ids) % 2 == 1 and ids == ids[::-1]:
seed = ids[: len(ids) // 2]
# A target that does not relay is not in its walk: the middle hop is the last
# relay of the route, and the user composes the route up to and with it.
seed = ids[: len(ids) // 2 + (0 if target_relays else 1)]
elif target_id in ids:
seed = ids[: ids.index(target_id)] # an old walk by hand: keep the outbound
else:
@@ -2200,6 +2185,7 @@ async def _open_session(
target_id=target_id,
target_hash=target_hash,
target_label=target_label,
target_relays=target_relays,
hops=seed,
cursor=seed_cursor,
fetch_nodes=frozenset(fetchable),
@@ -2444,11 +2430,18 @@ async def _open_session(
scenarios = topo.scenarios(
target_id, device_route=device_route, outbound=outbound, silent_before=silent_before
)
if not target_relays:
# A walk to a target that does not relay turns at the last relay of the route.
# A route with no relay has no turn, so no trace can walk it.
scenarios = [s for s in scenarios if s.hops]
if not scenarios:
await session.message_dialog(
Text(
"no observed evidence involving this target yet — run a trace or "
"let monitoring accumulate paths first.",
"let monitoring accumulate paths first."
if target_relays
else f"{target_label} can't relay a trace, and no relay on the way to "
"it has been heard yet — let monitoring accumulate paths first.",
style="muted",
),
title="Explore paths",
@@ -2490,7 +2483,9 @@ async def _open_session(
SelectScreen(
f"Explore paths — {target_label}",
items,
prompt="Choose the outbound leg — the return mirrors it.",
prompt="Choose the outbound leg — the return mirrors it."
if target_relays
else "Choose the route — the trace turns at its last relay.",
footer_hint="↑↓ move · Enter adopt/probe · Esc back",
hscroll=True, # a long candidate row slides under ←→, and is not truncated
)
@@ -2498,14 +2493,14 @@ async def _open_session(
if picked is CANCEL or picked is None: # Esc
return None
if picked[0] == "use":
return picked[1].spec(target_hash, width_bytes)
return picked[1].spec(target_hash, width_bytes, relays=target_relays)
# Probe all: measure each different spec. (Scenarios can collapse to the same
# spec after they are truncated to the trace width, and the radio must not walk
# one spec two times.)
candidates: list[ProbeCandidate] = []
for scenario in scenarios:
spec = scenario.spec(target_hash, width_bytes)
spec = scenario.spec(target_hash, width_bytes, relays=target_relays)
if all(c.spec != spec for c in candidates):
candidates.append(ProbeCandidate(label=scenario.label, spec=spec))
outcomes = await run_probe(candidates)
@@ -2684,11 +2679,16 @@ async def _open_session(
)
def prove(traces: list[TraceResult]) -> ProvenRoute | None:
"""The route out of the newest trace that came home, with the proof of the run."""
"""The route out of the newest trace that came home, with the proof of the run.
A walk to a target that does not relay turned at the last relay of the route.
Thus its route is the hops up to and with that relay, which is a route that the
radio can send to the target on.
"""
home = [t for t in traces if t.success]
if not home:
return None
hops = _previous_outbound(home[-1], target_key)
hops = previous_outbound(home[-1], target_key, relays=target_relays)
if hops is None:
return None
stats = TraceStats.from_traces(record_target, traces)
@@ -2706,6 +2706,20 @@ async def _open_session(
build_env=build_route_env,
)
# A target that does not relay, with no relay on its route, gives the walk no place to
# turn. The screen says why (refer to TraceScreen._turn_note). A node that MeshTerm
# hears directly is a neighbour: the radio's route to it is no relays, and the Device
# route row offers that route at once, with no trace to prove it.
neighbour = False
offer: ProvenRoute | None = None
if mode == "target" and target_hash is not None and not target_relays and not auto_hops:
topo = fresh_topology()
link = topo.link(topo.self_id, topo.canonical(target_hash) or target_hash[:12])
heard = link.samples if link is not None else 0
neighbour = heard > 0 or device_route == ()
if heard and route_row is not None:
offer = ProvenRoute(hops=(), home=0, sent=0, heard=heard)
screen = TraceScreen(
record_target,
mode=mode,
@@ -2733,6 +2747,10 @@ async def _open_session(
route_row=route_row,
prove=prove,
seed_traces=lambda spec: list(probe_traces.get(spec, [])),
relays=target_relays,
target_label=target_label,
neighbour=neighbour,
offer=offer,
)
try:
await session.run_screen(screen)
+16 -2
View File
@@ -520,7 +520,7 @@ def test_a_trace_draws_its_route_with_arrows_and_keeps_its_path_in_commas(run) -
name like each other hop. The ``★`` of the menu says "you already know who this is".
This is true for the user, and it is not true for a person who opens the file later.
"""
result = run("trace-path", "--path", "a1,d4,a1")
result = run("trace-path", "--path", "a1,b2,a1")
assert result.exit_code == exitcodes.OK, result.output
facts = dict(line.split(None, 1) for line in result_lines(result) if line and " " in line)
assert facts["success"] == "yes"
@@ -534,9 +534,23 @@ def test_a_trace_draws_its_route_with_arrows_and_keeps_its_path_in_commas(run) -
assert "→" not in facts["path"]
def test_a_trace_to_a_companion_turns_at_its_relay_and_says_so(run) -> None: # noqa: ANN001
"""Alice is a companion, which stops a trace. The walk turns at her relay, Yagi-Repeater.
The CLI chooses the route as the menu does, and says on stderr where the walk turns.
stdout keeps only the answer, with the walk in its ``path`` fact.
"""
result = run("trace", "--target", "Alice")
assert result.exit_code in (exitcodes.OK, exitcodes.NO_RESULT), result.output
assert "Alice can't relay a trace, so the trace turns at Yagi-Repeater" in result.stderr
assert "relay a trace" not in result.stdout
facts = dict(line.split(None, 1) for line in result_lines(result) if line and " " in line)
assert "," not in facts["path"] and "a1b2c3d4".startswith(facts["path"])
def test_a_trace_reports_its_per_hop_readings_under_a_header(run) -> None: # noqa: ANN001
"""The second block has one record for each hop. The hash joins it to the route line."""
lines = result_lines(run("trace-path", "--path", "a1,d4,a1"))
lines = result_lines(run("trace-path", "--path", "a1,b2,a1"))
header = next(line for line in lines if line.startswith("HOP"))
assert header.split() == ["HOP", "FROM", "TO", "SNR_DB"]
+22
View File
@@ -223,6 +223,28 @@ def test_the_trace_row_lights_only_for_a_route_that_is_a_change() -> None:
assert not _row(("3d",)).text(failed)[1]
def test_a_neighbour_that_does_not_relay_is_offered_no_relays() -> None:
"""A companion heard directly has no relay at which a walk turns. Its proof is the packets.
The row offers no relays at once, and the popup's first row says so. A radio that
already holds no relays offers nothing. A route with relays needs a trace as its proof.
"""
from meshterm.ui.device_route_screen import ProvenRoute
heard = ProvenRoute(hops=(), home=0, sent=0, heard=4)
assert heard.proved and heard.evidence() == "heard directly 4×"
assert _row(("3d",)).text(heard) == (
"Use no relays for DMs and admin — heard directly 4×…",
True,
)
assert not _row(()).text(heard)[1]
assert not ProvenRoute(hops=("3d",), home=0, sent=0, heard=4).proved
learned = RouteStatus(("3d",), ORIGIN_LEARNED, owner=HOME)
rows = [row for row in _action_rows(learned, heard) if isinstance(row, Choice)]
assert rows[0].value == "traced"
assert "Use no relays" in str(rows[0].title)
def test_the_popup_offers_the_traced_route_first() -> None:
"""Use the traced route, then Use and keep it (with a site), then the usual rows."""
from meshterm.ui.device_route_screen import ProvenRoute
+85 -10
View File
@@ -148,7 +148,7 @@ def test_snr_bar_unlit_track_dims_to_a_distinct_style() -> None:
assert snr_bar(10.0).plain == _BAR_FULL * _BAR_WIDTH # top of range: every cell full
# --- _previous_outbound -----------------------------------------------------------
# --- previous_outbound ------------------------------------------------------------
def _walk(*nodes: str, success: bool = True) -> TraceResult:
@@ -167,30 +167,45 @@ def test_previous_outbound_extracts_the_proven_route() -> None:
report flood). Thus this stored evidence is what auto mode walks for a target that
has more than one hop.
"""
from meshterm.ui.trace_screen import _previous_outbound
from meshterm.services.trace_plan import previous_outbound
walk = _walk("3d63", "f2c2", "aabb", "f2c2", "3d63")
assert _previous_outbound(walk, "aabb" + "00" * 30) == ("3d63", "f2c2")
assert previous_outbound(walk, "aabb" + "00" * 30) == ("3d63", "f2c2")
def test_previous_outbound_direct_walk_yields_no_repeaters() -> None:
"""A direct answer (the target only) gives an empty outbound leg: destination only again."""
from meshterm.ui.trace_screen import _previous_outbound
from meshterm.services.trace_plan import previous_outbound
assert _previous_outbound(_walk("aabb"), "aabb" + "00" * 30) == ()
assert previous_outbound(_walk("aabb"), "aabb" + "00" * 30) == ()
def test_previous_outbound_rejects_unusable_history() -> None:
"""MeshTerm never reuses failures, asymmetric walks, and walks that turned elsewhere."""
from meshterm.ui.trace_screen import _previous_outbound
from meshterm.services.trace_plan import previous_outbound
target = "aabb" + "00" * 30
assert _previous_outbound(None, target) is None
assert _previous_outbound(_walk("3d63", "aabb", "3d63", success=False), target) is None
assert previous_outbound(None, target) is None
assert previous_outbound(_walk("3d63", "aabb", "3d63", success=False), target) is None
# Asymmetric: it came home a different way, so it is not a boomerang to this target.
assert _previous_outbound(_walk("3d63", "aabb", "f2c2"), target) is None
assert previous_outbound(_walk("3d63", "aabb", "f2c2"), target) is None
# Palindromic, but it turned at some other node and not at our target.
assert _previous_outbound(_walk("3d63", "9999", "3d63"), target) is None
assert previous_outbound(_walk("3d63", "9999", "3d63"), target) is None
def test_previous_outbound_of_a_target_that_does_not_relay_keeps_the_turn() -> None:
"""A walk to a companion turned at its last relay. That relay ends the route to it.
The companion stops a trace, so it is never in the walk. The middle hop is the relay
that hears it, and the route to the companion goes up to and with that relay.
"""
from meshterm.services.trace_plan import previous_outbound
target = "aabb" + "00" * 30
walk = _walk("3d63", "f2c2", "3d63")
assert previous_outbound(walk, target, relays=False) == ("3d63", "f2c2")
assert previous_outbound(_walk("3d63"), target, relays=False) == ("3d63",)
assert previous_outbound(_walk("3d63", "f2c2", "9999"), target, relays=False) is None
# --- _previous_walk ---------------------------------------------------------------
@@ -234,6 +249,7 @@ def _trace_screen(
auto_source="",
open_trophy_case=None,
route_row=None,
**extra, # noqa: ANN003 - more TraceScreen arguments, as given
) -> tuple[TraceScreen, _FakeSession]:
session = _FakeSession()
@@ -263,11 +279,70 @@ def _trace_screen(
auto_source=auto_source,
open_trophy_case=open_trophy_case,
route_row=route_row,
**extra,
)
screen.note_viewport(40) # the frame records this before each real paint
return screen, session
def test_trace_screen_names_the_relay_where_a_companions_walk_turns() -> None:
"""Alice stops a trace, so her walk turns at f2c2. A line under the route says so."""
screen, _ = _trace_screen(
auto_spec=lambda: "3d63,f2c2,3d63", auto_source="best observed · 5×", relays=False
)
body = _plain(screen.render_body(72))
assert "Alice can't relay a trace, so the trace turns at f2c2" in body
assert screen._actions[screen._index] == "trace" # a turn: Enter traces at once
def test_trace_screen_wraps_the_turn_line_under_the_route_lane() -> None:
"""The line is a sentence, so it wraps at 53 cells, and no line of the page is wider."""
from rich.cells import cell_len
screen, _ = _trace_screen(
auto_spec=lambda: "3d63,f2c2,3d63", relays=False, target_label="A-companion-name"
)
lines = _plain(screen.render_body(53)).splitlines()
assert all(cell_len(line) <= 53 for line in lines)
note = [line for line in lines if "relay a trace" in line or "turns at" in line]
assert len(note) == 2 and all(line.startswith(" " * 7) for line in note)
async def test_trace_screen_with_no_relay_to_turn_at_has_nothing_to_walk() -> None:
"""A companion with no relay on its route: Trace is dim, and Enter on it sends nothing."""
ran: list[str] = []
async def trace(path_spec, on_trace): # noqa: ANN001
ran.append(path_spec)
screen, _ = _trace_screen(trace=trace, relays=False)
body = " ".join(_plain(screen.render_body(72)).split()) # the line wraps at 72 cells
assert "none — no relay to turn at" in body
assert "Alice can't relay a trace, and no relay on the way to it is known" in body
assert "Trace — no relay to turn at" in body
assert screen._actions[screen._index] == "compose" # the highlight starts where it can act
screen._index = screen._actions.index("trace")
screen.handle("enter")
assert ran == [] and screen._worker is None
def test_trace_screen_offers_no_relays_for_a_neighbour_that_does_not_relay() -> None:
"""A neighbour companion has no relay to turn at, and its route is no relays.
The Device route row offers that route at once. When a spec gives a walk, the offer
goes away, because the screen then proves a route of its own.
"""
from meshterm.ui.device_route_screen import ProvenRoute
offer = ProvenRoute(hops=(), home=0, sent=0, heard=4)
screen, _ = _trace_screen(relays=False, neighbour=True, offer=offer)
body = " ".join(_plain(screen.render_body(72)).split()) # the line wraps at 72 cells
assert "it's a direct neighbour: no relay to turn at" in body
assert screen.proven() == offer
armed, _ = _trace_screen(auto_spec=lambda: "3d63", relays=False, offer=offer)
assert armed.proven() is None
class _RouteRowStub:
"""The Device route row of Trace target, as the screen reads it (refer to RouteRow)."""
+30
View File
@@ -311,3 +311,33 @@ def test_list_runs_newest_first(repo: Repository) -> None:
tools = [r.tool for r in repo.list_runs()]
assert tools == ["third", "second", "first"]
def test_node_type_is_the_last_type_that_a_node_announced(repo: Repository) -> None:
"""Trace target asks for the type of a sender that is not a contact.
A full id gives the newest type that the node announced. A short prefix gives a type
only when each node that it names announced the same type, because a hash of one byte
can name a companion and a repeater at the same time.
"""
from datetime import timedelta
from meshterm.core.models import NODE_TYPE_CHAT, NODE_TYPE_REPEATER, Observation, utcnow
run = repo.start_run("monitor", {}, None)
late, early = utcnow(), utcnow() - timedelta(days=1)
for node, node_type, when in (
("aa11bb22cc33", NODE_TYPE_REPEATER, early),
("aa11bb22cc33", NODE_TYPE_CHAT, late), # reflashed as a companion
("aa99bb22cc33", NODE_TYPE_CHAT, late),
("dd44ee55ff66", NODE_TYPE_REPEATER, late),
):
repo.record_observation(
run, Observation(node=node, name="n", node_type=node_type, observed_at=when)
)
assert repo.node_type("aa11bb22cc33") == NODE_TYPE_CHAT
assert repo.node_type("AA11BB22CC33" + "00" * 26) == NODE_TYPE_CHAT # a full key
assert repo.node_type("aa") is None # a repeater and a companion: no single type
assert repo.node_type("aa99") == NODE_TYPE_CHAT
assert repo.node_type("dd44") == NODE_TYPE_REPEATER
assert repo.node_type("ee") is None
+22 -3
View File
@@ -347,10 +347,28 @@ async def test_mock_device_blank_path_traces() -> None:
device = MockDevice()
await device.connect()
# Try several times, because the simulator sometimes drops very weak links.
results = [await device.run_trace("Alice") for _ in range(10)]
results = [await device.run_trace("Yagi-Repeater") for _ in range(10)]
assert any(r.success and r.hops for r in results)
async def test_mock_device_node_that_does_not_relay_stops_a_trace() -> None:
"""As on the real mesh, a simulated companion or room server never relays a trace.
Alice is a companion and Lakeside BBS is a room server. A forced walk that turns at
either one, or that goes through either one, never comes back. A walk that turns at
Alice's repeater (``a1b2``) comes back, which is the walk that Trace target gives her.
With no path, the simulator routes as the real device does: it turns the walk at the
last relay of her learned route, so the trace can come back.
"""
device = MockDevice()
await device.connect()
assert not (await device.run_trace("Alice", path="a1b2,d4e5,a1b2")).success
assert not (await device.run_trace("Lakeside BBS", path="f6a7")).success
for path in ("a1b2", None):
results = [await device.run_trace("Alice", path=path) for _ in range(10)]
assert any(r.success for r in results), path
def test_trace_timeout_scales_with_hops() -> None:
"""The reply wait grows by one allowance for each hop, within its documented limits."""
from meshterm.services.trace_runner import (
@@ -528,13 +546,14 @@ async def _setup_link(optimal_remote_tx: int = 20):
"""Return a connected mock device, the (admin, target) contacts, and the forced path.
The path goes admin → target. Thus the optimizer tunes the admin node and reads the
SNR that the target receives from it.
SNR that the target receives from it. The target is a repeater, because the walk ends
there and must come back: a companion does not relay a trace.
"""
device = MockDevice(optimal_remote_tx=optimal_remote_tx)
await device.connect()
contacts = await device.get_contacts()
admin = next(c for c in contacts if c.name == "Yagi-Repeater")
target = next(c for c in contacts if c.name == "Alice")
target = next(c for c in contacts if c.name == "Local-Repeater")
path = trace_runner.parse_trace_path(f"{admin.name},{target.name}", contacts)
assert await device.admin_login(admin, "admin")
return device, admin, target, path
+60 -1
View File
@@ -599,7 +599,7 @@ async def test_probe_paths_defaults_to_one_trace_per_candidate() -> None:
def _composer( # noqa: ANN001
topo, hops=None, fetch_nodes=frozenset(), target=True, cursor=None, resolve=None
topo, hops=None, fetch_nodes=frozenset(), target=True, cursor=None, resolve=None, relays=True
):
"""A composer over ``topo``, pinned on Far (target mode) or with no target."""
pinned = (
@@ -607,6 +607,7 @@ def _composer( # noqa: ANN001
target_id="f2c24f54551e",
target_hash="f2c24f54551e" + "0" * 52,
target_label="Far",
target_relays=relays,
)
if target
else {}
@@ -1231,3 +1232,61 @@ def test_composer_row_cursor_clamps_at_both_ends() -> None:
for _ in range(last + 5):
screen.handle("down")
assert screen._index == last
# --- a target that does not relay -------------------------------------------------------
def test_only_a_repeater_or_an_unknown_type_relays_a_trace() -> None:
"""A companion, a room server, and a sensor stop a trace with the firmware defaults."""
from meshterm.core.models import (
NODE_TYPE_CHAT,
NODE_TYPE_REPEATER,
NODE_TYPE_ROOM,
NODE_TYPE_SENSOR,
relays_traces,
)
assert relays_traces(NODE_TYPE_REPEATER)
assert relays_traces(None) # MeshTerm cannot tell, so it traces the node itself
assert not any(relays_traces(t) for t in (NODE_TYPE_CHAT, NODE_TYPE_ROOM, NODE_TYPE_SENSOR))
def test_a_target_that_does_not_relay_turns_the_walk_at_its_last_relay() -> None:
"""A companion stops a trace, so the walk turns at the relay that hears it.
The route to the companion stays the same. Only the walk changes: the companion is not
in it, and its hash does not limit the width of the walk.
"""
from meshterm.services.topology import render_forced_spec
target = "d4e5" + "00" * 30
hops = ("3d63c6429436", "f2c24f54551e")
assert render_forced_spec(hops, target, 2) == "3d63,f2c2,d4e5,f2c2,3d63"
assert render_forced_spec(hops, target, 2, relays=False) == "3d63,f2c2,3d63"
assert render_forced_spec(hops[:1], target, 2, relays=False) == "3d63"
assert render_forced_spec((), target, 2, relays=False) == "" # no relay: no turn
assert render_forced_spec(hops, "d4", 2) == "3d,f2,d4,f2,3d"
assert render_forced_spec(hops, "d4", 2, relays=False) == "3d63,f2c2,3d63"
@pytest.mark.parametrize("relays", [True, False])
def test_forced_outbound_finds_the_route_that_the_forced_spec_walks(relays: bool) -> None:
"""The two functions are inverses, for a target that relays and for one that does not."""
from meshterm.services.topology import forced_outbound, render_forced_spec
target = "d4e5" + "00" * 30
for hops in (("3d63",), ("3d63", "f2c2"), ("3d63", "f2c2", "27d4")):
spec = render_forced_spec(hops, target, 2, relays=relays)
assert forced_outbound(spec.split(","), target, relays=relays) == hops
assert forced_outbound(["3d63", "f2c2"], target, relays=relays) is None # even: no turn
assert forced_outbound(["3d63", "f2c2", "27d4"], target, relays=relays) is None
def test_composer_for_a_target_that_does_not_relay_turns_at_the_last_hop() -> None:
"""The walk turns at the last composed hop. Far is not in the spec or in the preview."""
screen = _composer(_topo(), hops=["3d63c6429436", "27d4396a2967"], relays=False)
assert screen._spec() == "3d,27,3d"
assert screen._walk_nodes() == ["3d63c6429436", "27d4396a2967", "3d63c6429436"]
assert "Far" not in screen._route_preview().text().plain
assert _composer(_topo(), relays=False)._spec() == "" # no relay: nothing to walk
+83
View File
@@ -0,0 +1,83 @@
# SPDX-License-Identifier: Apache-2.0
"""The route that an automatic Trace target walks (refer to meshterm.services.trace_plan)."""
from __future__ import annotations
from datetime import timedelta
from meshterm.core.models import Contact, Hop, TraceResult, utcnow
from meshterm.persistence.repository import PacketPath
from meshterm.services.topology import build_topology
from meshterm.services.trace_plan import RoutePlan, plan_route
US = "aabb" + "00" * 30
HUB = Contact(name="Hub", public_key="3d63c6429436" + "0" * 52, key_prefix="3d63c6429436")
FAR = Contact(name="Far", public_key="f2c24f54551e" + "0" * 52, key_prefix="f2c24f54551e")
ALICE = Contact(
name="Alice", public_key="d4e5f6a7b8c9" + "0" * 52, key_prefix="d4e5f6a7b8c9", node_type=1
)
def _topology(packets=()): # noqa: ANN001, ANN202
return lambda: build_topology(
self_id=US,
contacts=[HUB, FAR, ALICE],
trace_paths=[],
packet_paths=list(packets),
neighbour_links=[],
)
def _plan(**overrides) -> RoutePlan: # noqa: ANN003
args = dict(
topology=_topology(),
device_route=None,
outbound=(),
choice=None,
silent_before=utcnow() - timedelta(hours=1),
previous=None,
)
args.update(overrides)
return plan_route(ALICE.public_key, **args)
def _walk(*nodes: str) -> TraceResult:
"""A walk that came home on ``nodes`` (the last hop is our node, with no hash)."""
hops = [Hop(index=i, node=n, snr=1.0) for i, n in enumerate(nodes)]
hops.append(Hop(index=len(nodes), node=None, snr=1.0))
return TraceResult(
target="Alice", success=True, hops=hops, round_trip_ms=200.0, path_hash_bytes=2
)
def test_the_radio_route_comes_first() -> None:
"""With no outbound path of the user, the route that the radio holds wins."""
assert _plan(device_route=("3d63c6429436",)) == RoutePlan(("3d63c6429436",), "device route")
def test_the_strongest_heard_relay_of_a_companion_gives_its_route() -> None:
"""Alice's packets came in through Hub five times and through Far once.
The evidence graph counts each relay by node and gives recent packets more weight.
Thus the route to Alice goes through Hub, the relay that hears her most.
"""
now = utcnow()
packets = [PacketPath(now, "d4e5f6a7b8c9", 5.0, ["3d63c6429436"]) for _ in range(5)]
packets.append(PacketPath(now, "d4e5f6a7b8c9", 5.0, ["f2c24f54551e"]))
plan = _plan(topology=_topology(packets), relays=False)
assert plan.hops == ("3d63c6429436",)
assert plan.source.startswith("best observed · ")
def test_with_no_evidence_the_last_walk_home_gives_the_route() -> None:
"""A walk to a companion turned at its relay, so that relay ends the route to it."""
relays = _plan(previous=_walk("3d63", "d4e5", "3d63"))
assert relays.hops == ("3d63",)
assert relays.source.startswith("last trace · ")
companion = _plan(previous=_walk("3d63", "f2c2", "3d63"), relays=False)
assert companion.hops == ("3d63", "f2c2")
def test_with_nothing_known_the_plan_is_a_direct_attempt() -> None:
"""No route anywhere: no relay, and the source says so."""
assert _plan() == RoutePlan((), "direct — no known route")