From 3502a2e09d5c31b5dcb0f4a0c5f0c48f22b197e5 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 10 Jul 2026 21:00:00 -0400 Subject: [PATCH] Trace opens idle: compose the path from received topology, probe scenarios MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Everything we receive carries a fragment of the mesh's shape: successful traces crossed every link in their path (out and back — the reply retraces the reverse path, so links read both ways), each contact's out_path is a route the firmware distilled from received floods, and RX-logged packets report the relay chain they rode in on. A new topology service folds those into one undirected evidence graph (schema v7 persists packet paths). The trace screen stops auto-starting on target pick. Enter runs a burst under a floating tracing dialog (spinner chip, live progress, Abort); "p" opens a hop-by-hop path composer whose suggestions are the tail's observed neighbours, strongest link first, with raw hex entry for unseen nodes; "x" browses ranked path scenarios (device route, direct, best observed alternatives) and can probe them all — a measured burst per candidate, recorded as path_candidates rows, reliability-first ranking, winner offered for adoption. Composed specs are outbound-only, always ending at the target's hash: the stored data shows the firmware auto-replies along the reversed path, and user-composed "there and back" loops (3d,f2,3d) never succeeded. Specs collapse to a uniform per-hop width the narrowest known hash can honour. Co-Authored-By: Claude Fable 5 --- meshterm/core/connection.py | 140 ++++++- meshterm/core/models.py | 15 + meshterm/persistence/db.py | 7 +- meshterm/persistence/repository.py | 162 +++++++- meshterm/services/path_probe.py | 121 ++++++ meshterm/services/topology.py | 546 ++++++++++++++++++++++++++ meshterm/tools/trace.py | 11 +- meshterm/ui/path_composer.py | 315 +++++++++++++++ meshterm/ui/trace_screen.py | 599 +++++++++++++++++++++++++---- tests/test_live_screens.py | 102 ++++- tests/test_monitor.py | 9 +- tests/test_topology.py | 246 ++++++++++++ 12 files changed, 2176 insertions(+), 97 deletions(-) create mode 100644 meshterm/services/path_probe.py create mode 100644 meshterm/services/topology.py create mode 100644 meshterm/ui/path_composer.py create mode 100644 tests/test_topology.py diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index f3f5231..ce425fa 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -1169,6 +1169,7 @@ class MeshCoreDevice(Device): node_type=_as_int(info.get("type", info.get("adv_type"))), lat=lat, lon=lon, + route_hops=_contact_route(info), ) ) return contacts @@ -1414,6 +1415,11 @@ class MeshCoreDevice(Device): def ack_handler(event) -> None: # noqa: ANN001 on_event(MeshEvent.ack_event(ack_from_event(event))) + def packet_handler(event) -> None: # noqa: ANN001 + obs = packet_observation_from_event(event) + if obs is not None: + on_event(MeshEvent.observation_event(obs)) + # Subscribe to whichever event types this firmware/library build exposes. The # event payload field names the mappers read are best-effort and, like the trace # mapping, should be validated against your firmware's event schema. @@ -1427,6 +1433,13 @@ class MeshCoreDevice(Device): etype = getattr(EventType, attr, None) if etype is not None: subs.append(subscribe(etype, observation_handler(kind))) + # The companion's RX packet log, when its firmware has packet logging enabled: + # every overheard frame arrives with the relay path it traversed — the passive + # topology evidence the trace path composer suggests hops from. Firmware without + # RX logging simply never pushes these; subscribing is free either way. + etype = getattr(EventType, "RX_LOG_DATA", None) + if etype is not None: + subs.append(subscribe(etype, packet_handler)) for attr in ("CONTACT_MSG_RECV", "CHANNEL_MSG_RECV"): etype = getattr(EventType, attr, None) if etype is not None: @@ -1756,15 +1769,19 @@ class MockDevice(Device): self._rng = random.Random(seed) self._tx_power = 20 self._connected = False + # Routes mirror what real firmware learns from received floods: the repeaters are + # direct neighbours, the leaf nodes sit one hop behind one of them — so the trace + # path composer and its topology suggestions are fully exercisable without radio. self._contacts = [ Contact(name="Yagi-Repeater", public_key=_mock_pub("a1b2c3d4"), key_prefix="a1b2c3d4", - node_type=NODE_TYPE_REPEATER, lat=45.5019, lon=-73.5674), + node_type=NODE_TYPE_REPEATER, lat=45.5019, lon=-73.5674, route_hops=()), Contact(name="Local-Repeater", public_key=_mock_pub("b2c3d4e5"), key_prefix="b2c3d4e5", - node_type=NODE_TYPE_REPEATER, lat=45.4768, lon=-73.5990), + node_type=NODE_TYPE_REPEATER, lat=45.4768, lon=-73.5990, route_hops=()), Contact(name="Observer-Bot", public_key=_mock_pub("c3d4e5f6"), key_prefix="c3d4e5f6", - node_type=NODE_TYPE_CHAT, lat=45.4880, lon=-73.5810), + node_type=NODE_TYPE_CHAT, lat=45.4880, lon=-73.5810, + route_hops=("b2c3d4e5",)), Contact(name="Alice", public_key=_mock_pub("d4e5f6a7"), key_prefix="d4e5f6a7", - node_type=NODE_TYPE_CHAT), + node_type=NODE_TYPE_CHAT, route_hops=("a1b2c3d4",)), ] # Remote-admin simulation: which nodes we're "logged in" to, and each tuned # node's transmit power keyed by full public key. ``_default_remote_tx`` is the @@ -2045,6 +2062,12 @@ class MockDevice(Device): for contact in self._contacts: on_event(MeshEvent.observation_event(self._synth_observation(contact, seq))) seq += 1 + # Simulate the companion's RX packet log: overheard packets from the routed + # leaf nodes, each carrying the relay path it crossed — so topology capture + # accumulates passive path evidence on the simulator exactly as on hardware + # with packet logging enabled. The first burst always includes one. + if burst % 4 == 0: + on_event(MeshEvent.observation_event(self._synth_packet(burst // 4))) # Periodically simulate an inbound direct message so message-driven features # (and their tests) have traffic to react to; the first burst always includes # one so a subscriber sees a message without waiting. @@ -2105,6 +2128,29 @@ class MockDevice(Device): lon=lat_lon[1] if lat_lon else None, ) + def _synth_packet(self, seq: int) -> Observation: + """Build one plausible RX-logged packet observation (simulator only). + + Rotates over the leaf contacts that sit behind a repeater, emitting the packet + with the relay path its route implies — matching how a real companion reports an + overheard relayed frame. + + Args: + seq: Monotonic emission counter, used to rotate the originating contact. + + Returns: + A ``packet``-kind :class:`Observation` carrying a one-hop relay path. + """ + routed = [c for c in self._contacts if c.route_hops] + contact = routed[seq % len(routed)] + return Observation( + node=contact.key_prefix or contact.public_key[:12], + kind="packet", + snr=round(self._rng.gauss(6.0, 3.0), 1), + rssi=round(self._rng.gauss(-95.0, 8.0), 1), + path=",".join(contact.route_hops or ()), + ) + def _synth_message(self, seq: int) -> Message: """Build one plausible synthetic inbound direct message (simulator only). @@ -2267,6 +2313,58 @@ def observation_from_event(event, kind: str) -> Optional[Observation]: # noqa: ) +def packet_observation_from_event(event) -> Optional[Observation]: # noqa: ANN001 + """Map a meshcore ``RX_LOG_DATA`` event into a ``packet``-kind :class:`Observation`. + + The companion's RX packet log reports every frame it overhears together with the + header's relay path — the repeaters the packet crossed before reaching us, nearest + the originator first. That path is the passive topology evidence the trace path + composer runs on, so it is preserved verbatim (as comma-separated per-hop hex). + + The originating node is only knowable when the payload class reveals it: the library + decodes adverts inline (``adv_key``/``adv_name``), so those carry an origin; other + packet classes are recorded origin-less — their path (plus our reception of its last + relay) is still adjacency evidence. Frames that carry neither an origin nor any path + teach us nothing about topology and map to ``None``. + + Args: + event: A meshcore ``RX_LOG_DATA`` event (anything exposing a ``payload`` mapping). + + Returns: + The parsed :class:`Observation` (``kind="packet"``), or ``None`` for frames with + no topology content or an unparsable path. + """ + payload = dict(getattr(event, "payload", {}) or {}) + path_len = _as_int(payload.get("path_len")) or 0 + hash_size = _as_int(payload.get("path_hash_size")) or 1 + path_hex = str(payload.get("path") or "").lower().removeprefix("0x") + hops: list[str] = [] + if path_len > 0: + width = hash_size * 2 + hops = [path_hex[i * width : (i + 1) * width] for i in range(path_len)] + if any(len(h) != width for h in hops): + return None # a truncated path would fabricate adjacency between wrong nodes + + origin = payload.get("adv_key") + if not origin and not hops: + return None # neither endpoint nor relays: no topology content + node = str(origin).lower().removeprefix("0x")[:12] if origin else None + lat = payload.get("adv_lat") + lon = payload.get("adv_lon") + return Observation( + node=node, + name=payload.get("adv_name"), + kind="packet", + node_type=_as_int(payload.get("adv_type")), + snr=_as_float(payload.get("snr")), + rssi=_as_float(payload.get("rssi")), + lat=_as_float(lat) if lat else None, + lon=_as_float(lon) if lon else None, + path=",".join(hops), + raw=payload, + ) + + def message_from_event(event) -> Optional[Message]: # noqa: ANN001 """Map a meshcore ``CONTACT_MSG_RECV`` / ``CHANNEL_MSG_RECV`` event into a message. @@ -2349,6 +2447,40 @@ def _advert_time(last_advert: object) -> Optional[datetime]: return datetime.fromtimestamp(seconds, tz=timezone.utc) +def _contact_route(info: dict) -> Optional[tuple[str, ...]]: + """Extract a contact's device-learned outbound route as per-hop hex hashes. + + The firmware distills the paths of received flood packets into each contact's + ``out_path``: the repeater chain to send through, one path-hash per hop, from us + outward. The wire reports the hop count and hash width packed into one byte + (``0xFF`` = no learned route, i.e. flood) and the path itself as a fixed 64-byte + field, so the real route is the leading ``out_path_len × size`` bytes. + + Args: + info: One contact's raw info mapping from the companion's contacts payload. + + Returns: + The route as a tuple of per-hop hex hashes (empty = a learned *direct* route), + or ``None`` when no route is learned or the report is unparsable. + """ + out_path_len = _as_int(info.get("out_path_len")) + if out_path_len is None or out_path_len < 0: + return None # 0xFF on the wire: flood routing, no learned path + if out_path_len == 0: + return () + mode = _as_int(info.get("out_path_hash_mode")) + size = max((mode if mode is not None and mode >= 0 else 0) + 1, 1) + out_path = str(info.get("out_path") or "").lower().removeprefix("0x") + try: + route = bytes.fromhex(out_path)[: out_path_len * size] + except ValueError: + return None + hops = tuple(route[i * size : (i + 1) * size].hex() for i in range(out_path_len)) + if any(len(h) != size * 2 for h in hops): + return None # the field was shorter than the declared route; don't guess + return hops + + def _contact_location(info: dict) -> tuple[Optional[float], Optional[float]]: """Extract a contact's advertised ``(lat, lon)``, or ``(None, None)`` if it has none. diff --git a/meshterm/core/models.py b/meshterm/core/models.py index 344e4ad..6846275 100644 --- a/meshterm/core/models.py +++ b/meshterm/core/models.py @@ -53,6 +53,11 @@ class Contact: node_type: Advert type of the node (see the ``NODE_TYPE_*`` constants), if known. lat: Latitude the node last advertised (decimal degrees), if it shared one. lon: Longitude the node last advertised (decimal degrees), if it shared one. + route_hops: The device-learned outbound route to this contact, one hex path-hash + per repeater in order from us outward — knowledge the firmware distilled from + the paths of *received* flood packets. An empty tuple means the firmware + considers the contact a direct neighbour (a zero-hop route); ``None`` means + no route has been learned (or the transport didn't report one). """ name: str @@ -62,6 +67,7 @@ class Contact: node_type: Optional[int] = None lat: Optional[float] = None lon: Optional[float] = None + route_hops: Optional[tuple[str, ...]] = None @property def has_location(self) -> bool: @@ -92,6 +98,14 @@ class Observation: rssi: Received signal strength (dBm), if reported. lat: Advertised latitude (decimal degrees), when the node shares location. lon: Advertised longitude (decimal degrees), when the node shares location. + path: For ``packet`` observations (the companion's RX packet log), the relay + path the packet traversed before reaching us: comma-separated per-hop hex + hashes in propagation order, nearest the *originator* first and the repeater + we actually heard last. An empty string means the packet arrived direct + (zero hops); ``None`` means the packet class carries no path. For packets, + :attr:`snr`/:attr:`rssi` describe our reception from the *last relay* in + this path — not the originating :attr:`node` — which is why packet rows are + kept out of per-node reception statistics and feed topology instead. observed_at: When the packet was heard. raw: Optional raw event payload for debugging/replay. """ @@ -104,6 +118,7 @@ class Observation: rssi: Optional[float] = None lat: Optional[float] = None lon: Optional[float] = None + path: Optional[str] = None observed_at: datetime = field(default_factory=utcnow) raw: Optional[dict] = None diff --git a/meshterm/persistence/db.py b/meshterm/persistence/db.py index 19f3629..f45ad4c 100644 --- a/meshterm/persistence/db.py +++ b/meshterm/persistence/db.py @@ -10,7 +10,7 @@ from __future__ import annotations import sqlite3 from pathlib import Path -SCHEMA_VERSION = 6 +SCHEMA_VERSION = 7 _SCHEMA = """ CREATE TABLE IF NOT EXISTS schema_meta ( @@ -95,6 +95,7 @@ CREATE TABLE IF NOT EXISTS observations ( rssi REAL, lat REAL, lon REAL, + path TEXT, -- 'packet' rows: comma-separated relay-hop hex hashes observed_at TEXT NOT NULL ); @@ -172,3 +173,7 @@ def _migrate(conn: sqlite3.Connection) -> None: # v4 -> v5: observations gained the transmitting node's advert type, so the map can # tell repeaters from leaf nodes. Older rows simply carry NULL (type unknown). conn.execute("ALTER TABLE observations ADD COLUMN node_type INTEGER") + if "path" not in observation_cols: + # v6 -> v7: observations gained the relay path of RX-logged packets, the passive + # evidence the mesh topology graph is built from. Older rows carry NULL (no path). + conn.execute("ALTER TABLE observations ADD COLUMN path TEXT") diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index 614f0a2..8ea824f 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -57,6 +57,42 @@ class ChannelStats: histogram: tuple[int, ...] +@dataclass(slots=True) +class TracedPath: + """One successful trace's walked path, as evidence for the topology graph. + + Attributes: + when: When the trace completed. + hops: The per-hop readings in path order, each ``(node, snr)`` — ``node`` is the + hop's raw hex hash (``None`` for the final hash-less hop, our own device) and + ``snr`` the reception measured *arriving at* that hop. Because trace replies + retrace the path, the sequence covers the outbound and return legs alike. + """ + + when: datetime + hops: list[tuple[Optional[str], float]] + + +@dataclass(slots=True) +class PacketPath: + """One RX-logged packet's relay path, as evidence for the topology graph. + + Attributes: + when: When the packet was overheard. + origin: The originating node's hex hash, when the packet class reveals it + (adverts do); ``None`` otherwise. + snr: Our reception SNR (dB) — a reading on the link from the *last relay* + (or, with no relays, the origin) to us. + hops: The relay hashes in propagation order, nearest the origin first and the + repeater we actually heard last; empty for a direct (zero-hop) packet. + """ + + when: datetime + origin: Optional[str] + snr: Optional[float] + hops: list[str] + + @dataclass(slots=True) class RunRecord: """A summary row from the ``runs`` table. @@ -299,6 +335,74 @@ class Repository: ).fetchall() return [row["target"] for row in rows] + def trace_paths(self, *, limit: int = 2000) -> list[TracedPath]: + """Return the walked paths of recent successful traces, newest first. + + This is the trace side of the topology evidence: every successful trace is a + packet that demonstrably crossed each link in its path (out and back), with an + SNR reading at every hop. Hops are returned raw — hex hashes at whatever width + the original command addressed them — for the topology layer to canonicalize. + + Args: + limit: Maximum number of traces to load. + + Returns: + One :class:`TracedPath` per successful trace that recorded hops. + """ + rows = self._conn.execute( + "SELECT t.id, t.created_at FROM traces t " + "WHERE t.success = 1 ORDER BY t.id DESC LIMIT ?", + (limit,), + ).fetchall() + paths: list[TracedPath] = [] + for row in rows: + hop_rows = self._conn.execute( + "SELECT node, snr FROM trace_hops WHERE trace_id = ? ORDER BY hop_index", + (row["id"],), + ).fetchall() + if not hop_rows: + continue + try: + when = datetime.fromisoformat(row["created_at"]) + except (TypeError, ValueError): + continue # a malformed stray contributes no evidence + paths.append( + TracedPath(when=when, hops=[(h["node"], h["snr"]) for h in hop_rows]) + ) + return paths + + def packet_paths(self, *, limit: int = 5000) -> list[PacketPath]: + """Return the relay paths of recent RX-logged packets, newest first. + + The passive side of the topology evidence: each row is a packet the companion + overheard whose header carried the repeater path it had traversed so far. Only + ``packet``-kind observations carry one (see :meth:`record_observation`); rows + whose path is NULL are skipped, and an empty path (a direct packet) is returned + with no hops so a known origin still yields a direct-link reading. + + Args: + limit: Maximum number of packet observations to load. + + Returns: + One :class:`PacketPath` per stored packet observation. + """ + rows = self._conn.execute( + "SELECT node, snr, path, observed_at FROM observations " + "WHERE kind = 'packet' AND path IS NOT NULL ORDER BY id DESC LIMIT ?", + (limit,), + ).fetchall() + paths: list[PacketPath] = [] + for row in rows: + try: + when = datetime.fromisoformat(row["observed_at"]) + except (TypeError, ValueError): + continue # a malformed stray contributes no evidence + hops = [h for h in (row["path"] or "").split(",") if h] + paths.append( + PacketPath(when=when, origin=row["node"], snr=row["snr"], hops=hops) + ) + return paths + def record_tx_sample(self, run_id: int, level: TxLevelResult) -> None: """Persist one robust TX-power level from an optimization sweep. @@ -325,19 +429,60 @@ class Repository: ) self._conn.commit() + def record_path_candidate( + self, + run_id: int, + target: str, + path: str, + *, + bottleneck_snr: Optional[float], + success_rate: float, + median_rtt_ms: Optional[float], + ) -> None: + """Persist one measured candidate path from a path-probe sweep. + + Args: + run_id: The owning probe run. + target: The node the candidate paths lead to. + path: The forced outbound path measured (comma-separated hex hashes). + bottleneck_snr: Median of the candidate's per-trace bottleneck SNRs (dB), + or ``None`` when no trace over it succeeded. + success_rate: Fraction of traces over this path that replied, ``[0, 1]``. + median_rtt_ms: Median round-trip time over this path, if measured. + """ + self._conn.execute( + "INSERT INTO path_candidates " + "(run_id, target, path_json, bottleneck_snr, success_rate, median_rtt_ms, " + "created_at) VALUES (?, ?, ?, ?, ?, ?, ?)", + ( + run_id, + target, + json.dumps(path.split(",")), + bottleneck_snr, + success_rate, + median_rtt_ms, + utcnow().isoformat(), + ), + ) + self._conn.commit() + # -- observations (passive monitoring) -------------------------------------- def record_observation(self, run_id: int, obs: Observation) -> None: """Persist one overheard packet from a monitoring run. + ``packet``-kind observations (the companion's RX packet log) also carry the relay + path the packet traversed — the raw material of the topology graph (see + :meth:`packet_paths`). + Args: run_id: The owning run. obs: The observation to store. """ self._conn.execute( "INSERT INTO observations " - "(run_id, node, name, kind, node_type, snr, rssi, lat, lon, observed_at) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "(run_id, node, name, kind, node_type, snr, rssi, lat, lon, path, observed_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_id, obs.node, @@ -348,6 +493,7 @@ class Repository: obs.rssi, obs.lat, obs.lon, + obs.path, obs.observed_at.isoformat(), ), ) @@ -370,7 +516,10 @@ class Repository: Spans every monitoring run (optionally limited to recent history), so the result is a longitudinal view of which nodes have been heard, how strongly, and where — - the substrate for the monitor summary and the coverage map. + the substrate for the monitor summary and the coverage map. ``packet``-kind rows + are excluded: their SNR describes our link to the packet's *last relay*, not to + the originating node, so folding them in would misattribute reception quality + (they feed the topology graph instead — see :meth:`packet_paths`). Args: since: Only include observations at or after this time, if given. @@ -378,10 +527,13 @@ class Repository: Returns: One :class:`HeardNode` per distinct node, ordered by most-recently heard. """ - sql = "SELECT node, name, node_type, snr, rssi, lat, lon, observed_at FROM observations" + sql = ( + "SELECT node, name, node_type, snr, rssi, lat, lon, observed_at " + "FROM observations WHERE kind != 'packet'" + ) params: list[Any] = [] if since is not None: - sql += " WHERE observed_at >= ?" + sql += " AND observed_at >= ?" params.append(since.isoformat()) rows = self._conn.execute(sql, params).fetchall() diff --git a/meshterm/services/path_probe.py b/meshterm/services/path_probe.py new file mode 100644 index 0000000..ec02020 --- /dev/null +++ b/meshterm/services/path_probe.py @@ -0,0 +1,121 @@ +"""Multi-path probing: measure candidate routes to a target and rank what actually works. + +The topology graph (:mod:`~meshterm.services.topology`) proposes routes from *received* +evidence; this module puts them to the test. Each candidate outbound path is traced a few +times, every trace is persisted exactly like a normal burst, the per-candidate aggregate +is recorded as a ``path_candidates`` row, and the outcomes come back ranked the way the +TX optimizer ranks its levels: reliability first, bottleneck SNR as the tie-breaker, then +round-trip time. The caller (the live trace screen) shows the ranking and offers to adopt +the winner — measurement proposes, the user disposes. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Awaitable, Callable, Optional + +from ..core.connection import Device +from ..core.models import TraceResult, TraceStats + +ProbeProgress = Callable[[int, int, TraceResult], None] +PersistTrace = Callable[[TraceResult], None] +PersistCandidate = Callable[["ProbeOutcome"], None] + + +@dataclass(slots=True) +class ProbeCandidate: + """One route to measure. + + Attributes: + label: Short description of where the route came from (shown in the results). + spec: The forced-path spec to trace — comma-separated hex hashes, outbound + only, ending at the target's own hash (the reply retraces it in reverse). + """ + + label: str + spec: str + + +@dataclass(slots=True) +class ProbeOutcome: + """One candidate's measured result. + + Attributes: + candidate: The route that was measured. + stats: The aggregated trace statistics over its burst. + """ + + candidate: ProbeCandidate + stats: TraceStats + + @property + def sort_key(self) -> tuple: + """Ranking key, best-first under ascending sort: reliability, then bottleneck + SNR, then RTT — the same priority order the TX optimizer applies.""" + snr = self.stats.median_min_snr + rtt = self.stats.median_rtt_ms + return ( + -self.stats.success_rate, + -(snr if snr is not None else float("-inf")), + rtt if rtt is not None else float("inf"), + ) + + +async def probe_paths( + device: Device, + target: str, + candidates: list[ProbeCandidate], + *, + samples: int = 3, + cooldown_s: float = 1.0, + on_result: Optional[ProbeProgress] = None, + persist_trace: Optional[Callable[[TraceResult], Awaitable[None] | None]] = None, + persist_candidate: Optional[PersistCandidate] = None, +) -> list[ProbeOutcome]: + """Trace every candidate path and return the outcomes ranked best-first. + + Runs the candidates sequentially (one radio, duty cycle applies), a small burst + each. Persistence is delegated through callbacks so this stays pure measurement: + the caller owns the run row and decides where traces and candidate aggregates go. + Cancelling the surrounding task stops mid-candidate; everything persisted so far + stays persisted. + + Args: + device: The connected device to trace through. + target: The destination (for :class:`TraceStats` labelling). + candidates: The routes to measure, in the order to try them. + samples: Traces per candidate. + cooldown_s: Pause between traces (and between candidates). + on_result: Optional callback ``(candidate_index, done_in_candidate, result)`` + invoked as each trace lands, e.g. to advance the probe dialog. + persist_trace: Optional per-trace persistence callback (sync or async). + persist_candidate: Optional callback invoked with each candidate's finished + :class:`ProbeOutcome` (e.g. to record a ``path_candidates`` row). + + Returns: + One :class:`ProbeOutcome` per candidate, ranked by :attr:`ProbeOutcome.sort_key`. + """ + from . import trace_runner + + outcomes: list[ProbeOutcome] = [] + for index, candidate in enumerate(candidates): + results = await trace_runner.run_traces( + device, + target, + samples=samples, + path=candidate.spec, + cooldown_s=cooldown_s, + on_result=( + (lambda done, _total, result, i=index: on_result(i, done, result)) + if on_result is not None + else None + ), + persist=persist_trace, + ) + outcome = ProbeOutcome( + candidate=candidate, stats=TraceStats.from_traces(target, results) + ) + outcomes.append(outcome) + if persist_candidate is not None: + persist_candidate(outcome) + return sorted(outcomes, key=lambda o: o.sort_key) diff --git a/meshterm/services/topology.py b/meshterm/services/topology.py new file mode 100644 index 0000000..96b7e62 --- /dev/null +++ b/meshterm/services/topology.py @@ -0,0 +1,546 @@ +"""The observed mesh topology: a link graph distilled from every path we ever received. + +MeshCore never tells us the network's shape outright, but almost everything we *receive* +carries a fragment of it: a successful trace demonstrably crossed every link in its path +(out and back, with an SNR reading at each hop), the firmware's per-contact ``out_path`` +is a route distilled from received floods, and — when the companion's packet logging is +on — every overheard frame reports the relay chain it rode in on. This module folds those +fragments into one undirected evidence graph and answers the questions the trace path +composer asks of it: + +* *who neighbours whom* — :meth:`MeshTopology.next_hops`, the suggestion list while + composing a path hop by hop, sorted by the strongest observed link first; +* *how might we reach a target* — :meth:`MeshTopology.scenarios`, ranked candidate + outbound paths (the device's learned route, the direct shot, and the best alternatives + the evidence supports) ready to be traced or probed. + +Links are deliberately undirected: radio paths work both ways, and every reading — an SNR +measured at either end, a route learned from the opposite direction — is evidence for the +same physical link. Node identity is canonicalized against the contact list, because the +same node appears in different sources at different hash widths (a 1-byte trace hop, a +12-hex observation id, a full public key). + +Everything here is pure data-in/data-out: the callers supply repository rows and contacts, +so the graph is unit-testable without a device or a database. +""" + +from __future__ import annotations + +import heapq +import math +import statistics +from dataclasses import dataclass, field +from datetime import datetime +from typing import Optional + +from ..core.models import Contact, utcnow +from ..persistence.repository import PacketPath, TracedPath + +#: Canonical id for our own device in the graph (its 12-hex key prefix when known). +#: Kept distinct from hop hashes by construction: it is derived from the full public key. + +#: Half-life, in days, of link evidence: a reading a week old counts half as much as one +#: from just now. Old links stay suggestible but fresh observations dominate the ranking. +_EVIDENCE_HALF_LIFE_DAYS = 7.0 + +#: SNR range mapped onto the link-quality factor: -15 dB (barely readable) scores the +#: floor, +10 dB (excellent) the ceiling. Matches the trace screen's quality-bar span. +_SNR_FLOOR_DB = -15.0 +_SNR_CEIL_DB = 10.0 +_QUALITY_MIN = 0.15 +_QUALITY_MAX = 1.5 + +#: Per-hop cost added when ranking candidate paths, so a marginally "stronger" long way +#: around doesn't beat a short path — every extra hop is real airtime and a real failure +#: point (and a trace crosses it twice: out and back). +_HOP_PENALTY = 0.35 + +#: Bounds for scenario generation: how many alternatives to offer and how deep a +#: suggested route may go (each hop is crossed twice by the trace's boomerang). +_MAX_SCENARIOS = 5 +_MAX_SCENARIO_HOPS = 5 + +_HEX_DIGITS = frozenset("0123456789abcdef") + + +def _is_hex(value: str) -> bool: + """Whether ``value`` is non-empty, even-length hex (a plausible path hash).""" + return bool(value) and len(value) % 2 == 0 and all(c in _HEX_DIGITS for c in value) + + +def collapse_width(*hashes: str, ceiling: int) -> int: + """The widest representable per-hop hash width every given hash can honour. + + Trace paths transmit hops at a uniform width of 1, 2, 4, or 8 bytes. Canonical node + ids are usually 6 bytes, but an unidentified hop may be as short as the width it was + once traced at — the spec must shrink to what its narrowest hash can supply. + + Args: + *hashes: The hex hashes destined for one spec. + ceiling: The width the caller would prefer (bytes, itself 1/2/4/8). + + Returns: + The largest of 1/2/4/8 that is ≤ ``ceiling`` and ≤ every hash's byte length. + """ + limit = min([ceiling, *(len(h) // 2 for h in hashes if h)] or [ceiling]) + return max(s for s in (1, 2, 4, 8) if s <= max(limit, 1)) + + +@dataclass(slots=True) +class Link: + """The accumulated evidence for one undirected link between two nodes. + + Attributes: + a: Canonical id of one endpoint (the lexically smaller, so the pair is a key). + b: Canonical id of the other endpoint. + samples: How many independent readings crossed this link, any source. + snrs: The SNR readings (dB) attributed to the link, either direction. + last_seen: When the link was most recently observed. + sources: Which evidence classes saw it (``trace`` / ``route`` / ``packet``). + """ + + a: str + b: str + samples: int = 0 + snrs: list[float] = field(default_factory=list) + last_seen: Optional[datetime] = None + sources: set[str] = field(default_factory=set) + + @property + def median_snr(self) -> Optional[float]: + """Median SNR (dB) across the link's readings, or ``None`` without any.""" + return statistics.median(self.snrs) if self.snrs else None + + def strength(self, now: Optional[datetime] = None) -> float: + """Score the link's observed reliability for ranking (higher = stronger). + + Three factors multiply: *evidence* (log-scaled sample count, so ten sightings + beat one but a thousand don't drown everything), *recency* (exponential decay + with a :data:`one-week half-life <_EVIDENCE_HALF_LIFE_DAYS>`), and *quality* + (median SNR mapped linearly from -15 dB → :data:`_QUALITY_MIN` to +10 dB → + beyond 1.0; links with no SNR reading — e.g. known only from a firmware route — + score a neutral 1.0 rather than being punished for missing data). + + Args: + now: The reference time for recency (defaults to the current time). + + Returns: + The link's strength score, ``> 0``. + """ + now = now or utcnow() + evidence = 1.0 + math.log2(1 + self.samples) + recency = 1.0 + if self.last_seen is not None and getattr(self.last_seen, "tzinfo", None): + age_days = max(0.0, (now - self.last_seen).total_seconds() / 86400.0) + recency = 0.5 ** (age_days / _EVIDENCE_HALF_LIFE_DAYS) + snr = self.median_snr + quality = 1.0 + if snr is not None: + span = _SNR_CEIL_DB - _SNR_FLOOR_DB + frac = (snr - _SNR_FLOOR_DB) / span + quality = min(_QUALITY_MAX, max(_QUALITY_MIN, _QUALITY_MIN + frac * (_QUALITY_MAX - _QUALITY_MIN))) + return evidence * recency * quality + + +@dataclass(slots=True) +class HopSuggestion: + """One suggested next hop while composing a path. + + Attributes: + node: Canonical id of the suggested node. + link: The evidence for the link from the path's current tail to ``node``. + strength: The link's precomputed strength (the sort key), so the UI can render + a stable ranking without re-scoring per repaint. + """ + + node: str + link: Link + strength: float + + +@dataclass(slots=True) +class PathScenario: + """One candidate outbound route to a target, ready to trace. + + A scenario describes only the *outbound* leg, ending at the target: the trace + protocol replies along the reversed path automatically, so the return is always the + symmetric mirror and is never part of the spec. + + Attributes: + label: Short human description of where the route came from. + hops: Canonical ids of the intermediate repeaters, in order from us outward — + excluding both endpoints (empty = trace the target directly). + source: The evidence class that proposed it (``device`` / ``direct`` / + ``observed``). + score: Ranking score (higher first): the path's weakest-link strength, hop count + penalized. Direct/device scenarios with no observed evidence score 0. + weakest_snr: The lowest per-link median SNR (dB) along the route, when known — + the bottleneck the trace is expected to measure. + samples: Total readings across the route's links (a rough confidence figure). + """ + + label: str + hops: tuple[str, ...] + source: str + score: float + weakest_snr: Optional[float] = None + samples: int = 0 + + def spec(self, target_hash: str, width_bytes: int) -> str: + """Render the scenario as a forced-path spec ending at the target. + + Every hop (and the target's own hash, always the final hop so the destination + recognizes the trace and replies) is truncated to one uniform per-hop width — + ``width_bytes``, shrunk via :func:`collapse_width` when a hop's known hash is + narrower, since a trace transmits every hop at the same width (see + :func:`~meshterm.services.trace_runner.parse_trace_path`). + + Args: + target_hash: The target's hex hash (any width ≥ 1 byte). + width_bytes: Preferred per-hop path-hash width in bytes (1, 2, 4, or 8). + + Returns: + A comma-separated hex spec, e.g. ``"3d,f2"``. + """ + width = collapse_width(*self.hops, target_hash, ceiling=width_bytes) + return ",".join(h[: width * 2] for h in (*self.hops, target_hash)) + + +class MeshTopology: + """The evidence graph over observed mesh links, queryable for routing suggestions. + + Build one with :func:`build_topology`; instances are cheap, immutable-in-spirit + snapshots — rebuild rather than mutate when fresh evidence lands. + """ + + def __init__(self, self_id: str, contacts: list[Contact]) -> None: + """Create an empty graph rooted at our own node. + + Args: + self_id: Canonical id of our own device (12-hex key prefix, lowercased). + contacts: Known contacts, used to canonicalize hop hashes of any width to + stable node ids and to name nodes for display. + """ + self.self_id = self_id.lower().removeprefix("0x")[:12] + self._links: dict[tuple[str, str], Link] = {} + self._now = utcnow() + # Contact index for canonicalization: full lowercased public keys (falling back + # to the stored prefix) mapped to the 12-hex canonical id and display name. + self._known: list[tuple[str, str, str]] = [] # (full_key, canonical, name) + for c in contacts: + key = (c.public_key or c.key_prefix or "").lower().removeprefix("0x") + if key: + self._known.append((key, key[:12], c.name)) + + # --- identity ---------------------------------------------------------------- + + def canonical(self, hop: Optional[str]) -> Optional[str]: + """Collapse a hop hash of any width onto a stable node id. + + Trace hops arrive at the command's path-hash width (1-8 bytes), observation ids + at 12 hex, routes at the region's width — all naming the same nodes. A hash that + prefix-matches exactly one known contact adopts that contact's 12-hex id; an + ambiguous or unknown hash stays as itself, so evidence about nodes we can't + identify is kept (under the short id) rather than guessed onto the wrong node. + + Args: + hop: The raw hex hash (any case, optional ``0x``), or ``None``/empty. + + Returns: + The canonical id, or ``None`` for a missing/non-hex hop (non-hex covers + legacy simulator artefacts like ``hop0``). + """ + if not hop: + return None + needle = hop.lower().removeprefix("0x") + if not _is_hex(needle): + return None + matches = { + canonical + for key, canonical, _name in self._known + if key.startswith(needle) or needle.startswith(key[:12]) + } + if len(matches) == 1: + return next(iter(matches)) + return needle[:12] + + def display_name(self, node: str) -> Optional[str]: + """The contact name for a canonical id, or ``None`` when unknown.""" + for key, canonical, name in self._known: + if canonical == node: + return name + return None + + # --- construction ------------------------------------------------------------ + + def add_walk( + self, + nodes: list[Optional[str]], + *, + snrs: Optional[list[Optional[float]]] = None, + when: Optional[datetime] = None, + source: str, + ) -> None: + """Record one walked node sequence as a set of link readings. + + Consecutive nodes become one reading each on their undirected link. ``nodes`` + holds canonical ids (``None`` entries — unresolvable hops — break the chain, so + no false adjacency is invented across them). Self-loops (a hash repeated + back-to-back, e.g. a manually forced there-and-back) are skipped. + + Args: + nodes: The walked sequence, endpoints included, in order. + snrs: Optional per-link SNR readings aligned with the links (``snrs[i]`` + belongs to the ``nodes[i] → nodes[i+1]`` link, measured at arrival). + when: When the walk was observed (stamps every touched link's recency). + source: Evidence class tag (``trace`` / ``route`` / ``packet``). + """ + for i in range(len(nodes) - 1): + a, b = nodes[i], nodes[i + 1] + if not a or not b or a == b: + continue + key = (a, b) if a < b else (b, a) + link = self._links.get(key) + if link is None: + link = self._links[key] = Link(a=key[0], b=key[1]) + link.samples += 1 + link.sources.add(source) + snr = snrs[i] if snrs and i < len(snrs) else None + if snr is not None: + link.snrs.append(snr) + if when is not None and ( + link.last_seen is None or when > link.last_seen + ): + link.last_seen = when + + # --- queries ----------------------------------------------------------------- + + @property + def link_count(self) -> int: + """How many distinct links the graph holds evidence for.""" + return len(self._links) + + def link(self, a: str, b: str) -> Optional[Link]: + """The evidence for the undirected link between ``a`` and ``b``, if any.""" + return self._links.get((a, b) if a < b else (b, a)) + + def next_hops(self, tail: str, *, exclude: frozenset[str] = frozenset()) -> list[HopSuggestion]: + """Suggest nodes reachable from ``tail``, strongest observed link first. + + This is the composer's step-by-step feed: standing at the path's current tail, + every node the evidence says ``tail`` can hear (links are bidirectional, so a + path observed in either direction qualifies) — minus the nodes already used. + + Args: + tail: Canonical id the path currently ends at (our own id to start). + exclude: Canonical ids to omit (nodes already in the path; revisiting one + is never useful and duplicated hops are dropped by repeaters anyway). + + Returns: + Suggestions sorted by descending link strength. + """ + out: list[HopSuggestion] = [] + for (a, b), link in self._links.items(): + other = b if a == tail else a if b == tail else None + if other is None or other in exclude: + continue + out.append(HopSuggestion(node=other, link=link, strength=link.strength(self._now))) + out.sort(key=lambda s: (-s.strength, s.node)) + return out + + def scenarios(self, target: str, *, device_route: Optional[tuple[str, ...]] = None) -> list[PathScenario]: + """Rank the candidate outbound routes for reaching ``target``. + + Three families, deduplicated in this priority order: + + 1. **device** — the route the firmware itself learned from received floods (what + an auto-routed trace would walk), when the caller supplies one; + 2. **direct** — no repeaters at all, always offered as the baseline; + 3. **observed** — the strongest simple paths through the evidence graph + (weakest-link scoring with a per-hop penalty), which is where a path the + device never learned — but the data supports — comes from. + + Every scenario is an *outbound* leg only: the trace reply retraces it in + reverse automatically, so intermediate links are implicitly crossed twice. + + Args: + target: The target's canonical id. + device_route: The firmware's learned route (canonical intermediate hops), + if the contact has one. + + Returns: + Scenarios ranked best-evidence first (the device route, when present, is + always listed first regardless of score — it is what "auto" would do). + """ + seen: set[tuple[str, ...]] = set() + out: list[PathScenario] = [] + + def add(label: str, hops: tuple[str, ...], source: str) -> None: + if hops in seen or len(hops) > _MAX_SCENARIO_HOPS or target in hops: + return + seen.add(hops) + score, weakest, samples = self._score_route(hops, target) + out.append( + PathScenario( + label=label, hops=hops, source=source, score=score, + weakest_snr=weakest, samples=samples, + ) + ) + + if device_route is not None: + add("device route", device_route, "device") + add("direct", (), "direct") + for hops in self._best_routes(target, k=_MAX_SCENARIOS): + add("observed path", hops, "observed") + + # Rank observed evidence, but keep the device route pinned on top: it is the + # reference point every alternative is compared against. + head = [s for s in out if s.source == "device"] + rest = sorted( + (s for s in out if s.source != "device"), + key=lambda s: (-s.score, len(s.hops)), + ) + return (head + rest)[:_MAX_SCENARIOS] + + # --- internals ----------------------------------------------------------------- + + def _score_route( + self, hops: tuple[str, ...], target: str + ) -> tuple[float, Optional[float], int]: + """Score one outbound route by its weakest observed link. + + A chain is only as reliable as its weakest link, so the route's score is the + minimum link strength along ``us → hops… → target``, discounted per hop (see + :data:`_HOP_PENALTY`). A route containing a link we have *no* evidence for + scores 0 — offerable, but ranked below anything actually observed. + + Args: + hops: Intermediate canonical ids (may be empty for a direct route). + target: The destination's canonical id. + + Returns: + ``(score, weakest_median_snr, total_samples)``. + """ + chain = [self.self_id, *hops, target] + weakest_strength: Optional[float] = None + weakest_snr: Optional[float] = None + samples = 0 + for a, b in zip(chain, chain[1:]): + link = self.link(a, b) + if link is None: + return 0.0, None, samples + strength = link.strength(self._now) + samples += link.samples + if weakest_strength is None or strength < weakest_strength: + weakest_strength = strength + snr = link.median_snr + if snr is not None and (weakest_snr is None or snr < weakest_snr): + weakest_snr = snr + score = (weakest_strength or 0.0) / (1.0 + _HOP_PENALTY * len(hops)) + return score, weakest_snr, samples + + def _best_routes(self, target: str, *, k: int) -> list[tuple[str, ...]]: + """Find up to ``k`` strong simple paths from us to ``target`` in the graph. + + A best-first search over path cost (each link contributes ``1/strength``, plus + the per-hop penalty), expanding the cheapest partial path until ``k`` complete + routes emerge. The graph is small (tens of nodes), so exhaustive-ish search is + fine; simple paths only, since revisiting a node is never useful. + + Args: + target: The destination's canonical id. + k: Maximum number of routes to return. + + Returns: + The intermediate-hop tuples of the found routes, cheapest first. + """ + neighbors: dict[str, list[tuple[str, float]]] = {} + for (a, b), link in self._links.items(): + cost = 1.0 / max(link.strength(self._now), 1e-6) + _HOP_PENALTY + neighbors.setdefault(a, []).append((b, cost)) + neighbors.setdefault(b, []).append((a, cost)) + + found: list[tuple[str, ...]] = [] + counter = 0 # heap tiebreaker so equal-cost paths never compare tuples of str + heap: list[tuple[float, int, tuple[str, ...]]] = [(0.0, counter, (self.self_id,))] + while heap and len(found) < k: + cost, _tie, path = heapq.heappop(heap) + tail = path[-1] + if tail == target: + found.append(path[1:-1]) # strip both endpoints: hops only + continue + if len(path) - 1 > _MAX_SCENARIO_HOPS: + continue + for node, edge_cost in neighbors.get(tail, ()): + if node in path: + continue + counter += 1 + heapq.heappush(heap, (cost + edge_cost, counter, (*path, node))) + return found + + +def build_topology( + *, + self_id: str, + contacts: list[Contact], + trace_paths: list[TracedPath], + packet_paths: list[PacketPath], +) -> MeshTopology: + """Assemble the evidence graph from everything we have received. + + Three sources fold in, each one walked through :meth:`MeshTopology.add_walk`: + + * **traces** — each successful trace's hop sequence, bracketed by us at both ends + (the boomerang leaves us and returns to us; the final hash-less hop *is* us). + Every hop's SNR is a reading on the link it arrived over. + * **contact routes** — the firmware's learned ``out_path`` per contact: a chain from + us through its repeaters to the contact. No SNR, but it is the distillation of + real received floods, so it counts as one reading per link (stamped with the + contact's last-heard time). A learned *direct* route is a direct link to us. + * **packets** — RX-logged frames: the relay chain, prefixed by the originator when + known and always ending at us (we heard the last relay). The measured SNR belongs + to that final link only. + + Args: + self_id: Our device's key/hash (any width; canonicalized to 12 hex). + contacts: The device's known contacts (canonicalization + route evidence). + trace_paths: Stored successful trace walks (see ``Repository.trace_paths``). + packet_paths: Stored RX-logged packet paths (see ``Repository.packet_paths``). + + Returns: + The populated :class:`MeshTopology`. + """ + topo = MeshTopology(self_id, contacts) + us = topo.self_id + + for traced in trace_paths: + nodes: list[Optional[str]] = [us] + snrs: list[Optional[float]] = [] + for hop, snr in traced.hops: + # The final hash-less hop is the reply landing back at us. + nodes.append(topo.canonical(hop) if hop is not None else us) + snrs.append(snr) + topo.add_walk(nodes, snrs=snrs, when=traced.when, source="trace") + + for contact in contacts: + if contact.route_hops is None: + continue + contact_id = topo.canonical(contact.public_key or contact.key_prefix) + route = [topo.canonical(h) for h in contact.route_hops] + topo.add_walk( + [us, *route, contact_id], when=contact.last_seen, source="route" + ) + + for packet in packet_paths: + nodes = [] + if packet.origin: + nodes.append(topo.canonical(packet.origin)) + nodes.extend(topo.canonical(h) for h in packet.hops) + nodes.append(us) + if len(nodes) < 2: + continue + # Only the last link (last relay → us) carries the measured reception SNR. + snrs = [None] * (len(nodes) - 2) + [packet.snr] + topo.add_walk(nodes, snrs=snrs, when=packet.when, source="packet") + + return topo diff --git a/meshterm/tools/trace.py b/meshterm/tools/trace.py index 465f094..382eda6 100644 --- a/meshterm/tools/trace.py +++ b/meshterm/tools/trace.py @@ -1,11 +1,12 @@ """The ``trace`` tool: path traces to a target, live in the menu, one-shot on the CLI. In the interactive menu this opens the live trace screen -(:mod:`meshterm.ui.trace_screen`): pick a target from a recency-ordered list and traces -start streaming immediately — further bursts, sample counts, and a forced path are -keystrokes inside the screen, following the same living-screen pattern as chat and the -nodes list. On the CLI it stays a scriptable one-shot: run N traces, print the per-trace -table and the aggregate summary, exit. +(:mod:`meshterm.ui.trace_screen`): pick a target from a recency-ordered list and the +screen opens armed but idle — Enter runs a burst under an abortable tracing dialog, ``p`` +composes a forced path hop by hop from the topology observed in received traffic, and +``x`` explores ranked path scenarios (with an optional probe that measures each candidate +and offers the winner). On the CLI it stays a scriptable one-shot: run N traces, print +the per-trace table and the aggregate summary, exit. Both front ends persist identically: one ``runs`` row per burst with every trace recorded under it, so stored history reads the same no matter where it came from. diff --git a/meshterm/ui/path_composer.py b/meshterm/ui/path_composer.py new file mode 100644 index 0000000..a208f9b --- /dev/null +++ b/meshterm/ui/path_composer.py @@ -0,0 +1,315 @@ +"""The trace path composer: build a forced route hop by hop, guided by observed links. + +A floating dialog over the live trace screen. The route under construction reads across +the top — ``us → hop → … → target`` with the target pinned as the final hop, since a +trace only replies when the destination's own hash ends the path — and beneath it sits a +suggestion list: the nodes the topology evidence says the path's current tail can hear, +strongest observed link first (see :meth:`~meshterm.services.topology.MeshTopology. +next_hops`). Every link is bidirectional evidence, so a path that was ever *received* +through two nodes proposes that link in either direction. + +Interaction, following the reorder screen's cursor-over-rows-and-actions pattern: + +* ↑/↓ move over suggestions and the action rows; Enter on a suggestion appends it. +* Typing filters the suggestions by name or hash — and when the typed text is itself + even-length hex, an *add custom hop* row appears, so a node we have never observed + (or a bare hash from another tool) can be forced into the route. +* Backspace erases the filter first; with the filter empty it removes the last hop. +* Enter on **Use this path** commits the composed spec; **Auto** hands routing back to + the device; Esc cancels with no change. + +The return leg is never composed: the trace protocol replies along the reversed path +automatically, so the dialog shows the outbound route only and says so. +""" + +from __future__ import annotations + +from typing import Optional + +from rich.cells import cell_len +from rich.text import Text + +from ..services.topology import MeshTopology, _is_hex, collapse_width +from .theme import snr_style +from .tui.render import render_lines, render_to_ansi +from .tui.screen import Screen +from .widgets import _age_seconds, _format_age + +#: Sentinel spec meaning "no forced path — let the device route" (the trace screen's +#: empty-spec convention). +AUTO_SPEC = "" + +#: How many suggestions to show at most; beyond this the evidence is too weak to matter +#: and the dialog would outgrow the screen. +_MAX_SUGGESTIONS = 12 + +#: Action-row sentinels (kept distinct from suggestion rows, which carry node ids). +_USE = "use" +_AUTO = "auto" +_CANCEL = "cancel" + +#: One-letter tags for the evidence classes backing a link, shown beside each +#: suggestion: T(race), R(oute — the firmware's learned out_path), P(acket log). +_SOURCE_TAGS = {"trace": "T", "route": "R", "packet": "P"} + + +class PathComposerScreen(Screen): + """Compose a forced outbound trace path step by step. + + Resolves with the finished spec (comma-separated hex, ending at the target), + :data:`AUTO_SPEC` for device routing, or :data:`~meshterm.ui.tui.screen.CANCEL`. + """ + + footer_hint = ( + "↑↓ move · Enter add/select · type to filter or enter hex · ⌫ remove · Esc cancel" + ) + + def __init__( + self, + *, + target_id: str, + target_hash: str, + target_label: str, + device_label: str, + topology: MeshTopology, + width_bytes: int, + hops: Optional[list[str]] = None, + ) -> None: + """Build the composer. + + Args: + target_id: The target's canonical id (excluded from suggestions; the path + implicitly ends at it). + target_hash: The target's hex hash used as the spec's final hop (its full + key prefix; truncated to the spec width at commit). + target_label: The target's display name for the route preview. + device_label: Our own node's name, opening the route preview. + topology: The evidence graph suggestions are drawn from. + width_bytes: Preferred per-hop path-hash width (bytes) for the emitted spec. + hops: Canonical ids of already-composed intermediate hops (reopening the + dialog resumes where the user left off). + """ + super().__init__() + self.title = f"compose path · {target_label}" + self._target_id = target_id + self._target_hash = target_hash.lower().removeprefix("0x") + self._target_label = target_label + self._device_label = device_label + self._topology = topology + self._width_bytes = width_bytes + self._hops: list[str] = list(hops or []) + self._entry = "" + self._index = 0 + + # --- state ----------------------------------------------------------------- + + def _tail(self) -> str: + """The node the path currently ends at (us until a hop is added).""" + return self._hops[-1] if self._hops else self._topology.self_id + + def _suggestions(self) -> list: + """The current suggestion rows, filtered by the typed entry. + + Returns: + The (possibly filtered) :class:`~meshterm.services.topology.HopSuggestion` + list for the path's tail, capped at :data:`_MAX_SUGGESTIONS`. + """ + exclude = frozenset( + {self._topology.self_id, self._target_id, *self._hops} + ) + suggestions = self._topology.next_hops(self._tail(), exclude=exclude) + needle = self._entry.lower() + if needle: + suggestions = [ + s + for s in suggestions + if s.node.startswith(needle) + or needle in (self._topology.display_name(s.node) or "").lower() + ] + return suggestions[:_MAX_SUGGESTIONS] + + def _custom_hex(self) -> Optional[str]: + """The typed entry as an addable hex hop, or ``None`` when it isn't one.""" + needle = self._entry.lower().removeprefix("0x") + return needle if _is_hex(needle) else None + + def _rows(self) -> list[tuple[str, object]]: + """The cursor-addressable rows: custom hop, suggestions, then the actions.""" + rows: list[tuple[str, object]] = [] + custom = self._custom_hex() + if custom: + rows.append(("custom", custom)) + rows.extend(("hop", s) for s in self._suggestions()) + rows.append(("action", _USE)) + rows.append(("action", _AUTO)) + rows.append(("action", _CANCEL)) + return rows + + def _spec(self) -> str: + """Render the composed route as the forced-path spec, target hash appended. + + The width shrinks below the preferred one only when a composed hop's known hash + is narrower (see :func:`collapse_width`), keeping every hop representable. + """ + width = collapse_width(*self._hops, self._target_hash, ceiling=self._width_bytes) + return ",".join(h[: width * 2] for h in (*self._hops, self._target_hash)) + + # --- rendering --------------------------------------------------------------- + + def _node_text(self, node: str) -> Text: + """A node as ``Name (hash)`` when known, else its bare hash, brand-tinted.""" + if node == self._topology.self_id: + return Text(self._device_label, style="accent") + name = self._topology.display_name(node) + if name: + text = Text(name, style="brand") + text.append(f" ({node[:6]})", style="muted") + return text + return Text(node, style="brand") + + def _route_preview(self) -> Text: + """The outbound route under construction, target pinned as the final hop.""" + text = Text(self._device_label, style="accent") + for hop in self._hops: + text.append(" → ", style="muted") + text.append_text(self._node_text(hop)) + text.append(" → ", style="muted") + text.append(self._target_label, style="ok") + return text + + def _suggestion_text(self, suggestion) -> Text: # noqa: ANN001 + """One suggestion row: node, then its link's evidence trail.""" + text = self._node_text(suggestion.node) + link = suggestion.link + snr = link.median_snr + if snr is not None: + text.append(" ↔ ", style="muted") + text.append(f"{snr:+.1f} dB", style=snr_style(snr)) + text.append(f" {link.samples}×", style="muted") + age = _format_age(_age_seconds(link.last_seen)) + text.append(f" · {age}", style="muted") + tags = "".join(_SOURCE_TAGS[s] for s in sorted(link.sources & _SOURCE_TAGS.keys())) + if tags: + text.append(f" · {tags}", style="faint") + return text + + def _row_text(self, kind: str, payload: object) -> Text: + """The display text for one cursor-addressable row.""" + if kind == "custom": + text = Text("+ add hop ", style="warn") + text.append(str(payload), style="brand") + text.append(" (typed hex)", style="muted") + return text + if kind == "hop": + return self._suggestion_text(payload) + if payload == _USE: + label = Text.assemble(("✓ ", "ok"), "Use this path") + label.append(f" ({self._spec()})", style="muted") + return label + if payload == _AUTO: + return Text("Auto — let the device route") + return Text.assemble(("✗ ", "err"), "Cancel") + + @property + def dialog_width(self) -> int: + """Natural outer width hugging the widest row (compositor still caps it).""" + widths = [cell_len(self.title), cell_len(self.footer_hint)] + widths.append(cell_len(self._route_preview().plain)) + for kind, payload in self._rows(): + widths.append(cell_len(self._row_text(kind, payload).plain) + 2) + return max(widths, default=20) + 8 + + def render_body(self, width: int) -> list[str]: + """Render the route preview, filter/hint line, suggestions, and actions.""" + rows = self._rows() + self._index = max(0, min(self._index, len(rows) - 1)) + + lines = render_lines(self._route_preview(), width) + lines.extend( + render_lines( + Text("return: automatic — the reply retraces the path in reverse", style="faint"), + width, + ) + ) + lines.append("") + if self._entry: + lines.append(render_to_ansi(Text(f"/{self._entry}", style="warn"), width)) + else: + heading = Text("Next hop from ", style="muted") + heading.append_text(self._node_text(self._tail())) + heading.append(" — strongest first", style="muted") + lines.extend(render_lines(heading, width)) + + cursor_at: Optional[int] = None + for i, (kind, payload) in enumerate(rows): + if kind == "action" and (i == 0 or rows[i - 1][0] != "action"): + lines.append("") # a spacer sets the action group apart + is_sel = i == self._index + text = Text("❯ " if is_sel else " ", style="brand" if is_sel else "") + text.append_text(self._row_text(kind, payload)) + if is_sel: + text.style = "brand" + text.no_wrap = True + text.truncate(width, overflow="ellipsis") + if is_sel: + cursor_at = len(lines) + lines.append(render_to_ansi(text, width)) + if not any(kind == "hop" for kind, _ in rows): + note = "(no observed links from here — type a hex hash to force a hop)" + lines.append(render_to_ansi(Text(note, style="muted"), width)) + + self._cursor = cursor_at + self._scroll_total = max(1, len(lines)) + return lines + + def cursor_line(self) -> Optional[int]: + """The body line of the highlighted row, so the session keeps it visible.""" + return getattr(self, "_cursor", None) + + # --- input --------------------------------------------------------------------- + + def _commit_row(self) -> None: + """Apply the highlighted row: append a hop or run an action.""" + rows = self._rows() + if not rows: + return + kind, payload = rows[self._index] + if kind == "custom": + self._hops.append(str(payload)) + self._entry = "" + self._index = 0 + elif kind == "hop": + self._hops.append(payload.node) # type: ignore[union-attr] + self._entry = "" + self._index = 0 + elif payload == _USE: + self.resolve(self._spec()) + elif payload == _AUTO: + self.resolve(AUTO_SPEC) + else: + super().handle("escape") + + def handle(self, action: str, data: str = "") -> None: + """Move the cursor, edit the entry, add/remove hops, or commit/cancel.""" + rows = self._rows() + if action == "up" and rows: + self._index = (self._index - 1) % len(rows) + elif action == "down" and rows: + self._index = (self._index + 1) % len(rows) + elif action in ("home", "ctrl_home"): + self._index = 0 + elif action in ("end", "ctrl_end"): + self._index = max(0, len(rows) - 1) + elif action == "enter": + self._commit_row() + elif action == "backspace": + if self._entry: + self._entry = self._entry[:-1] + elif self._hops: + self._hops.pop() + self._index = 0 + elif action == "text" and data.isprintable() and data not in ("/",): + self._entry += data + self._index = 0 + elif action == "escape": + super().handle("escape") diff --git a/meshterm/ui/trace_screen.py b/meshterm/ui/trace_screen.py index e020cad..11631ca 100644 --- a/meshterm/ui/trace_screen.py +++ b/meshterm/ui/trace_screen.py @@ -1,16 +1,27 @@ -"""The live trace screen: watch repeated path traces stream in, hop by hop. +"""The live trace screen: compose a route from observed topology, then watch it answer. This is the interactive face of the ``trace`` tool (the scripted CLI keeps its one-shot -table output). Where the old flow chained three prompts into a progress bar and a static -result window, this screen follows the app's living-screen pattern (chat, nodes, map): -pick a target, and the screen opens tracing immediately — each reply lands in a running -log as it arrives, the route line and per-hop medians update live, and further bursts, -sample-count changes, and a forced path are all one keystroke away without ever leaving -the screen. +table output). Where the old flow started tracing the instant a target was picked, the +screen now opens *armed but idle*: the target's last-known route shows, the path is +whatever you make it, and nothing transmits until you say so. Three verbs drive it: -Layout, top to bottom: the walked route (seeded from the target's last stored trace until -a fresh reply arrives), the run's robust aggregates (success rate, median bottleneck SNR, -median RTT), per-hop median SNR with quality bars, and the individual traces newest-first. +* **Enter** runs a burst. While it flies, a floating *tracing* dialog (spinner, live + reply count, Abort) sits over the screen — replies keep streaming into the log behind + it, and Esc in the dialog cancels the burst without leaving the screen. +* **p** opens the path composer (:mod:`~meshterm.ui.path_composer`): build the outbound + route hop by hop, each step suggested from the links observed in *received* traffic — + traces, firmware-learned contact routes, and RX-logged packet paths — strongest first, + with raw hex entry for nodes the data has never seen. Only the outbound leg is + composed: the trace protocol replies back along the reversed path automatically. +* **x** explores scenarios: ranked candidate routes to the target straight from the + topology evidence (the device's own learned route, the direct shot, and the strongest + observed alternatives). Adopt one directly — or probe them all, a small measured burst + per candidate, persisted as ``path_candidates`` rows and ranked reliability-first, with + the winner offered for adoption. Evidence proposes, measurement decides, you dispose. + +Layout, top to bottom: the walked route (live when a reply has landed, else the planned +composed path, else the target's last stored trace), the run's robust aggregates, per-hop +median SNR with quality bars, and the individual traces newest-first. Every burst is persisted exactly like a scripted run: one ``runs`` row per burst, each trace recorded under it, so the stored history reads the same no matter which front end @@ -22,6 +33,7 @@ from __future__ import annotations import asyncio from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional +from rich.cells import cell_len from rich.console import Group, RenderableType from rich.table import Table from rich.text import Text @@ -29,7 +41,7 @@ from rich.text import Text from ..core.models import TraceResult, TraceStats from ..services import trace_runner from .theme import snr_style -from .tui.render import render_lines +from .tui.render import render_lines, render_to_ansi from .tui.screen import Screen from .tui.spinner import Spinner from .widgets import NodeResolver, _link_text, _route_text @@ -37,13 +49,17 @@ from .widgets import NodeResolver, _link_text, _route_text if TYPE_CHECKING: from ..context import AppContext -#: Seconds between spinner frames while a burst is in flight. +#: Seconds between spinner frames while a burst or probe is in flight. _SPINNER_INTERVAL = 0.12 #: The sample counts the ``s`` key cycles through — small odd numbers, so the median is #: always a real reading and the radio's duty cycle stays polite. _SAMPLE_CYCLE = (1, 3, 5, 9) +#: Traces per candidate during a scenario probe, capped below the burst size so probing +#: several paths stays within the airtime budget of a single ordinary burst. +_PROBE_SAMPLES_CAP = 3 + #: How wide the per-hop SNR quality bars draw, in cells. _BAR_WIDTH = 16 @@ -57,6 +73,10 @@ _BAR_SNR_MAX = 10.0 #: the device, repository, and settings so the screen stays free of persistence concerns. BurstRunner = Callable[[int, str, Callable[[TraceResult], None]], Awaitable[None]] +#: A path picker flow: takes the current spec, runs its own dialogs over the screen, and +#: resolves to the new spec (``""`` = device-routed) or ``None`` to keep the current one. +PathFlow = Callable[[str], Awaitable[Optional[str]]] + def snr_bar(snr: Optional[float], width: int = _BAR_WIDTH) -> Text: """Render an SNR reading as a horizontal quality bar in the shared SNR colours. @@ -79,12 +99,85 @@ def snr_bar(snr: Optional[float], width: int = _BAR_WIDTH) -> Text: return bar -class TraceScreen(Screen): - """A full-screen live trace session for one target. +class TracingDialog(Screen): + """The floating in-flight dialog: a spinner chip, live progress, and Abort. - Keys: Enter runs another burst, ``s`` cycles the burst's sample count, ``p`` edits the - forced path in a floating prompt, the usual scroll keys move the view, and Esc backs - out (cancelling any in-flight burst; already-recorded traces are kept). + Pushed over the trace screen while a burst (or scenario probe) transmits, so the + activity — and the way out — is unmissable while replies keep streaming into the + screen behind it. Enter, Esc, or Space aborts via the injected callback; the owner + pops the dialog when the work finishes, so it never resolves a value of its own. + """ + + footer_hint = "Enter/Esc abort" + + def __init__(self, title: str, *, spinner: Spinner, on_abort: Callable[[], None]) -> None: + """Build the dialog. + + Args: + title: Heading for the dialog border (e.g. ``tracing · YUL-Poly``). + spinner: The spinner to animate (shared with the owner's ticker). + on_abort: Invoked when the user asks to abort (idempotent expected). + """ + super().__init__() + self.title = title + self._spinner = spinner + #: Invoked when the user aborts. Public so an owner whose task only exists + #: after the dialog does (the probe sweep) can rewire it. + self.on_abort = on_abort + #: One-line progress, updated by the owner as replies land. + self.status = "transmitting…" + #: The most recent trace result, echoed beneath the status line. + self.last: Optional[TraceResult] = None + + @property + def dialog_width(self) -> int: + """Natural outer width hugging the widest line (compositor still caps it).""" + widths = [cell_len(self.title), cell_len(self.footer_hint), + cell_len(self.status) + 4, len("last ✗ no reply — will retry"), + len("[ Abort ]")] + return max(widths) + 8 + + def _last_line(self) -> Text: + """The most recent reply, or a waiting note before the first one lands.""" + line = Text("last ", style="muted") + if self.last is None: + line.append("waiting for the first reply…", style="muted") + elif not self.last.success: + line.append("✗ no reply", style="err") + else: + line.append("✓ ", style="ok") + line.append(f"{self.last.hop_count} hop{'s' if self.last.hop_count != 1 else ''}") + if self.last.min_snr is not None: + line.append(" min ", style="muted") + line.append(f"{self.last.min_snr:+.1f} dB", style=snr_style(self.last.min_snr)) + if self.last.round_trip_ms is not None: + line.append(f" {self.last.round_trip_ms:.0f} ms", style="muted") + return line + + def render_body(self, width: int) -> list[str]: + """Render the spinner chip, the last reply, and the Abort button.""" + chip = self._spinner.text() + chip.append(f" {self.status}", style="") + lines = render_lines(chip, width) + lines.extend(render_lines(self._last_line(), width)) + lines.append("") + lines.append(render_to_ansi(Text("❯ [ Abort ]", style="selected"), width)) + return lines + + def handle(self, action: str, data: str = "") -> None: + """Any commit/dismiss key aborts the in-flight work; everything else is inert.""" + if action in ("enter", "escape", "space"): + self.on_abort() + + +class TraceScreen(Screen): + """A full-screen live trace session for one target — armed, but idle until told. + + Keys: Enter runs a burst (a floating dialog with Abort rides on top while it flies), + ``p`` composes the forced path hop by hop from observed topology, ``x`` explores and + probes ranked path scenarios, ``s`` cycles the burst's sample count, the usual scroll + keys move the view, and Esc backs out (cancelling any in-flight burst; + already-recorded traces are kept). """ floating = False @@ -98,21 +191,24 @@ class TraceScreen(Screen): resolve: NodeResolver, session: Any, burst: BurstRunner, - edit_path: Callable[[str], Awaitable[Optional[str]]], + compose_path: PathFlow, + explore: PathFlow, previous: Optional[TraceResult] = None, samples: int = 3, ) -> None: - """Create the screen (traces start when :meth:`start_burst` is first called). + """Create the screen (nothing transmits until the user presses Enter). Args: target: The trace destination (contact name or key prefix). device_label: Our own node's name, labelling the route's endpoints. device_hash: Our own public key, so the endpoints carry a hash like every hop. resolve: Maps a hop's raw hash to a friendly contact name when known. - session: The running TUI session (for repaints). + session: The running TUI session (for repaints and the floating dialog). burst: Runs one burst of traces, streaming results (see :data:`BurstRunner`). - edit_path: Shows the floating forced-path prompt over this screen, seeded with - the current spec; resolves to the new spec or ``None`` when cancelled. + compose_path: Opens the hop-by-hop path composer over this screen, seeded + with the current spec; resolves to the new spec or ``None`` if cancelled. + explore: Opens the scenario browser/probe flow over this screen; resolves to + an adopted spec or ``None`` to keep the current one. previous: The target's most recent stored trace, if any — its route seeds the route line so the screen opens knowing the path history last saw. samples: Traces per burst to start with. @@ -125,7 +221,8 @@ class TraceScreen(Screen): self._resolve = resolve self._session = session self._burst = burst - self._edit_path = edit_path + self._compose_path = compose_path + self._explore = explore self._previous = previous self._samples = samples if samples in _SAMPLE_CYCLE else 3 self._path_spec = "" @@ -133,8 +230,10 @@ class TraceScreen(Screen): self._running = False self._dialog_open = False self._status = "" + self._burst_done = 0 self._spinner = Spinner() self._worker: Optional[asyncio.Task] = None + self._flight: Optional[TracingDialog] = None # --- state ----------------------------------------------------------------- @@ -143,7 +242,10 @@ class TraceScreen(Screen): """The footer keys, tracking whether a burst is in flight.""" if self._running: return "tracing… · ↑↓ PgUp/PgDn scroll · Esc back" - return "Enter trace · s samples · p path · ↑↓ PgUp/PgDn scroll · Esc back" + return ( + "Enter trace · p compose path · x explore paths · s samples · " + "↑↓ scroll · Esc back" + ) def start_burst(self) -> None: """Kick off one burst of traces in the background (no-op while one is running).""" @@ -151,12 +253,25 @@ class TraceScreen(Screen): return self._running = True self._status = "" + self._burst_done = 0 self._spinner.reset() self._worker = asyncio.ensure_future(self._run_burst()) self._session.invalidate() async def _run_burst(self) -> None: - """Drive one burst to completion, animating the spinner and reporting failures.""" + """Drive one burst to completion under the floating tracing dialog. + + The dialog is pushed for the duration and popped however the burst ends — + completion, failure, or abort — and its Abort wires straight to :meth:`cancel`, + so the burst's cancellation path is the same whether Esc lands on the dialog or + the screen. + """ + dialog = TracingDialog( + f"tracing · {self._target}", spinner=self._spinner, on_abort=self.cancel + ) + dialog.status = self._flight_status(0) + self._flight = dialog + self._session.push(dialog) ticker = asyncio.ensure_future(self._animate()) try: await self._burst(self._samples, self._path_spec, self._on_trace) @@ -172,9 +287,16 @@ class TraceScreen(Screen): pass except Exception: # noqa: BLE001 - a spinner hiccup must never break a burst pass + self._session.pop(dialog) + self._flight = None self._running = False self._session.invalidate() + def _flight_status(self, done: int) -> str: + """The dialog's progress line after ``done`` replies of the burst have landed.""" + current = min(done + 1, self._samples) + return f"trace {current}/{self._samples} · {self._target}" + async def _animate(self) -> None: """Advance the in-flight spinner and repaint on a steady cadence, until cancelled.""" while True: @@ -183,8 +305,12 @@ class TraceScreen(Screen): self._session.invalidate() def _on_trace(self, result: TraceResult) -> None: - """Append one landed trace and repaint (called by the burst as replies arrive).""" + """Append one landed trace, advance the dialog, and repaint.""" self._traces.append(result) + self._burst_done += 1 + if self._flight is not None: + self._flight.last = result + self._flight.status = self._flight_status(self._burst_done) self._session.invalidate() def cancel(self) -> None: @@ -195,7 +321,7 @@ class TraceScreen(Screen): # --- input ------------------------------------------------------------------- def handle(self, action: str, data: str = "") -> None: - """Run bursts, tweak samples/path, scroll, or dismiss.""" + """Run bursts, compose/explore paths, tweak samples, scroll, or dismiss.""" if action == "enter": self.start_burst() elif action == "text" and data.lower() == "s": @@ -203,7 +329,9 @@ class TraceScreen(Screen): idx = _SAMPLE_CYCLE.index(self._samples) self._samples = _SAMPLE_CYCLE[(idx + 1) % len(_SAMPLE_CYCLE)] elif action == "text" and data.lower() == "p": - self._open_path_dialog() + self._open_flow(self._compose_path) + elif action == "text" and data.lower() == "x": + self._open_flow(self._explore) elif action == "up": self.scroll_lines(-1) elif action == "down": @@ -220,22 +348,30 @@ class TraceScreen(Screen): self.cancel() self.resolve(None) - def _open_path_dialog(self) -> None: - """Float the forced-path prompt over the screen (one at a time, not mid-burst).""" + def _open_flow(self, flow: PathFlow) -> None: + """Float a path-picking flow over the screen (one at a time, not mid-burst). + + Both the composer and the scenario explorer resolve the same way: a new spec to + adopt (``""`` returns routing to the device), or ``None`` to leave the current + path untouched. + + Args: + flow: The dialog flow to run with the current spec. + """ if self._dialog_open or self._running: return self._dialog_open = True - async def edit() -> None: + async def run() -> None: try: - spec = await self._edit_path(self._path_spec) + spec = await flow(self._path_spec) if spec is not None: self._path_spec = spec.strip() finally: self._dialog_open = False self._session.invalidate() - asyncio.ensure_future(edit()) + asyncio.ensure_future(run()) # --- rendering ----------------------------------------------------------------- @@ -263,20 +399,50 @@ class TraceScreen(Screen): return sections def _route_line(self, current: Optional[TraceResult]) -> Text: - """The walked route: fresh when a reply has landed, else the stored previous one.""" + """The route: live when a reply has landed, else planned, else the stored one.""" line = Text("route ", style="muted") - shown = current or self._previous - if shown is None: - line.append("unknown — waiting for the first reply", style="muted") + if current is not None: + line.append_text( + _route_text(current, self._device_label, self._resolve, self._device_hash) + ) return line - line.append_text( - _route_text(shown, self._device_label, self._resolve, self._device_hash) - ) - if current is None: - stamp = shown.timestamp.astimezone().strftime("%b %d %H:%M") + planned = self._planned_route() + if planned is not None: + line.append_text(planned) + return line + if self._previous is not None: + line.append_text( + _route_text( + self._previous, self._device_label, self._resolve, self._device_hash + ) + ) + stamp = self._previous.timestamp.astimezone().strftime("%b %d %H:%M") line.append(f" (previous · {stamp})", style="faint") + return line + line.append("unknown — press Enter to trace", style="muted") return line + def _planned_route(self) -> Optional[Text]: + """The composed outbound path as a route preview, or ``None`` without one. + + Only the outbound leg exists in the spec; the reply retraces it in reverse, so + the preview says so instead of drawing a mirrored (and redundant) return chain. + """ + hops = [h.strip() for h in self._path_spec.split(",") if h.strip()] + if not hops: + return None + text = Text(self._device_label, style="accent") + for hop in hops: + text.append(" → ", style="muted") + named = self._resolve(hop) + if named and named != hop: + text.append(named, style="brand") + text.append(f" ({hop})", style="muted") + else: + text.append(hop, style="brand") + text.append(" ⟲ auto return (planned)", style="faint") + return text + def _summary(self, stats: TraceStats) -> Text: """The run's aggregates plus the current burst configuration, label-aligned.""" snr = stats.median_min_snr @@ -350,15 +516,33 @@ class TraceScreen(Screen): return row +def _collapse_trace_width(mode: int) -> int: + """Collapse a routing hash mode to the widest trace-representable hop width. + + Routing widths are ``mode + 1`` bytes, but a trace's flags can only encode 1, 2, 4, + or 8 (see :func:`~meshterm.services.trace_runner.path_hash_flags`); the firmware + matches by prefix, so collapsing down addresses the same nodes. + + Args: + mode: The path-hash mode (``size - 1``); negative means unknown. + + Returns: + The per-hop width in bytes (1, 2, 4, or 8). + """ + size = max(mode + 1, 1) + return max(s for s in (1, 2, 4, 8) if s <= size) + + async def open_trace(ctx: "AppContext", target: str) -> int: """Open the live trace screen for ``target`` and run it until dismissed. - Wires the screen to the radio and the database: each burst opens its own ``runs`` - row, records every trace under it, and closes it with the same summary a scripted - ``meshterm trace`` writes — so history stays uniform across front ends. The first - burst starts immediately; the screen's route line is seeded from the target's most - recent stored trace so the path history last saw shows while the first reply is - still in flight. + Wires the screen to the radio, the database, and the observed-topology services: + each burst opens its own ``runs`` row and records every trace under it (same shape a + scripted ``meshterm trace`` writes); the composer and scenario flows build a fresh + :class:`~meshterm.services.topology.MeshTopology` from stored evidence on each open, + so suggestions always reflect the latest received traffic. Nothing transmits until + the user asks — the screen opens idle, its route line seeded from the target's most + recent stored trace. Args: ctx: The shared application context (must be running the interactive TUI surface). @@ -370,7 +554,12 @@ async def open_trace(ctx: "AppContext", target: str) -> int: Raises: RuntimeError: If called outside the interactive menu (no full-screen session). """ + from ..core.models import LOCAL_DEVICE_LABEL + from ..services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths + from ..services.topology import MeshTopology, PathScenario, _is_hex, build_topology + from .path_composer import PathComposerScreen from .surface import TuiUi + from .tui import CANCEL, Choice, SelectScreen, Separator if not isinstance(ctx.ui, TuiUi): # pragma: no cover - guarded by the menu-only caller raise RuntimeError("the live trace screen is only available in the menu") @@ -380,11 +569,299 @@ async def open_trace(ctx: "AppContext", target: str) -> int: contacts = await device.get_contacts() resolve = trace_runner.make_node_resolver(contacts) self_info = await device.get_self_info() - from ..core.models import LOCAL_DEVICE_LABEL device_label = str(self_info.get("name") or LOCAL_DEVICE_LABEL) device_hash = str(self_info.get("public_key") or "") or None + # The per-hop width composed/scenario specs are emitted at: the region's routing + # width, collapsed to what a trace can encode. Unknown (old firmware) → 1 byte, the + # protocol default and what all stored evidence uses anyway. + try: + width_bytes = _collapse_trace_width(int(await device.get_path_hash_mode())) + except Exception: # noqa: BLE001 - optional read; the 1-byte default always works + width_bytes = 1 + + # The target as an addressable hash: a known contact's full key, or the typed hex + # prefix itself. A non-hex unknown target can still be traced device-routed, but + # composing/exploring needs a destination hash to pin the path on. + needle = target.casefold() + target_contact = next( + ( + c + for c in contacts + if c.name.casefold() == needle + or ((c.public_key or "").lower().startswith(target.lower())) + ), + None, + ) + raw_hash = ( + (target_contact.public_key or target_contact.key_prefix) + if target_contact + else target + ).lower().removeprefix("0x") + target_hash = raw_hash if _is_hex(raw_hash) else None + target_label = target_contact.name if target_contact else target + + def fresh_topology() -> MeshTopology: + """Build the evidence graph from everything currently stored + on the device.""" + return build_topology( + self_id=device_hash or "local", + contacts=contacts, + trace_paths=ctx.repo.trace_paths(), + packet_paths=ctx.repo.packet_paths(), + ) + + async def unaddressable() -> None: + """Explain why path features need a resolvable target, in a small dialog.""" + await session.message_dialog( + Text( + f"{target!r} isn't a known contact or a hex key prefix, so a forced " + "path can't end at it. Trace it device-routed, or pick a contact.", + ), + title="no destination hash", + ) + + async def compose(current: str) -> Optional[str]: + """Open the hop-by-hop composer seeded with the current spec's hops.""" + if target_hash is None: + await unaddressable() + return None + topo = fresh_topology() + target_id = topo.canonical(target_hash) or target_hash[:12] + # Re-seed from the current spec, dropping its final hop (the target itself). + seed = [ + cid + for h in [p for p in current.split(",") if p.strip()][:-1] + if (cid := topo.canonical(h.strip())) is not None + ] + result = await session.run_screen( + PathComposerScreen( + target_id=target_id, + target_hash=target_hash, + target_label=target_label, + device_label=device_label, + topology=topo, + width_bytes=width_bytes, + hops=seed, + ) + ) + return None if result is CANCEL else result + + def scenario_title(scenario: PathScenario, topo: MeshTopology) -> Text: + """One scenario as a select row: source, route, and its observed evidence.""" + styles = {"device": "accent", "direct": "muted", "observed": "brand"} + text = Text(scenario.label, style=styles.get(scenario.source, "")) + if scenario.hops: + text.append(" via ", style="muted") + names = [topo.display_name(h) or h for h in scenario.hops] + text.append(" → ".join(names)) + else: + text.append(" no repeaters", style="muted") + if scenario.weakest_snr is not None: + text.append(" · weakest ", style="muted") + text.append(f"{scenario.weakest_snr:+.1f} dB", style=snr_style(scenario.weakest_snr)) + if scenario.samples: + text.append(f" · {scenario.samples}×", style="muted") + elif scenario.score == 0: + text.append(" · unobserved", style="faint") + return text + + def outcome_title(rank: int, outcome: ProbeOutcome) -> Text: + """One probed candidate as a ranked select row: measured, not guessed.""" + stats = outcome.stats + rate_style = "ok" if stats.success_rate >= 1.0 else ("warn" if stats.successes else "err") + text = Text(f"#{rank} ", style="muted") + text.append(f"{stats.success_rate:.0%}", style=rate_style) + snr = stats.median_min_snr + if snr is not None: + text.append(" min ", style="muted") + text.append(f"{snr:+.1f} dB", style=snr_style(snr)) + if stats.median_rtt_ms is not None: + text.append(f" {stats.median_rtt_ms:.0f} ms", style="muted") + text.append(" via ", style="muted") + text.append(outcome.candidate.spec, style="brand") + text.append(f" ({outcome.candidate.label})", style="faint") + return text + + async def run_probe( + candidates: list[ProbeCandidate], samples: int + ) -> Optional[list[ProbeOutcome]]: + """Measure every candidate under an abortable dialog; ``None`` when aborted. + + One ``runs`` row spans the sweep; each trace and each candidate aggregate is + recorded under it, so an aborted probe still keeps everything it measured. + """ + run_id = ctx.repo.start_run( + "trace", + { + "target": target, + "mode": "probe", + "samples": samples, + "paths": [c.spec for c in candidates], + }, + ctx.profile_name, + ) + spinner = Spinner() + dialog = TracingDialog(f"probing · {target_label}", spinner=spinner, on_abort=lambda: None) + dialog.status = f"path 1/{len(candidates)} · trace 1/{samples}" + + def on_result(index: int, done: int, result: TraceResult) -> None: + current = min(done + 1, samples) + dialog.status = f"path {index + 1}/{len(candidates)} · trace {current}/{samples}" + dialog.last = result + session.invalidate() + + sweep = asyncio.ensure_future( + probe_paths( + device, + target, + candidates, + samples=samples, + cooldown_s=ctx.settings.trace_cooldown_s, + on_result=on_result, + persist_trace=lambda t: ctx.repo.record_trace(run_id, t), + persist_candidate=lambda o: ctx.repo.record_path_candidate( + run_id, + target, + o.candidate.spec, + bottleneck_snr=o.stats.median_min_snr, + success_rate=o.stats.success_rate, + median_rtt_ms=o.stats.median_rtt_ms, + ), + ) + ) + dialog.on_abort = sweep.cancel # the task exists only now; rewire the button + + async def animate() -> None: + while True: + await asyncio.sleep(_SPINNER_INTERVAL) + spinner.tick() + session.invalidate() + + ticker = asyncio.ensure_future(animate()) + session.push(dialog) + error: Optional[BaseException] = None + aborted = False + outcomes: list[ProbeOutcome] = [] + try: + outcomes = await sweep + except asyncio.CancelledError: + aborted = True + except Exception as exc: # noqa: BLE001 - surface in a dialog, keep the screen + error = exc + finally: + ticker.cancel() + try: + await ticker + except asyncio.CancelledError: + pass + except Exception: # noqa: BLE001 - a spinner hiccup must never break a probe + pass + session.pop(dialog) + if aborted: + # Everything measured before the abort is already persisted; the run row + # just records that the sweep didn't finish. + ctx.repo.finish_run(run_id, "error", {"error": "aborted"}) + return None + if error is not None: + ctx.repo.finish_run( + run_id, "error", {"error": str(error) or type(error).__name__} + ) + await session.message_dialog( + Text(f"probe failed: {error}", style="err"), title="path probe" + ) + return None + best = outcomes[0] if outcomes else None + ctx.repo.finish_run( + run_id, + "ok", + { + "target": target, + "paths": len(candidates), + "best_path": best.candidate.spec if best else None, + "best_success_rate": round(best.stats.success_rate, 3) if best else None, + "best_median_min_snr": best.stats.median_min_snr if best else None, + }, + ) + return outcomes + + async def explore(current: str) -> Optional[str]: + """The scenario flow: browse ranked candidate routes, adopt one, or probe all.""" + if target_hash is None: + await unaddressable() + return None + topo = fresh_topology() + target_id = topo.canonical(target_hash) or target_hash[:12] + device_route: Optional[tuple[str, ...]] = None + if target_contact is not None and target_contact.route_hops is not None: + device_route = tuple( + topo.canonical(h) or h for h in target_contact.route_hops + ) + scenarios = topo.scenarios(target_id, device_route=device_route) + if not scenarios: + await session.message_dialog( + Text("no observed evidence involving this target yet — run a trace or " + "let monitoring accumulate paths first.", style="muted"), + title="explore paths", + ) + return None + + items: list = [Separator("── Candidate paths · from received evidence ──", style="accent")] + for scenario in scenarios: + items.append( + Choice(title=scenario_title(scenario, topo), value=("use", scenario)) + ) + items.append(Separator(" ")) + items.append( + Choice( + title=Text.assemble(("⚡ ", "warn"), "Probe all — trace each path and rank"), + value=("probe", None), + ) + ) + items.append(Choice(title="Back", value=("back", None))) + picked = await session.run_screen( + SelectScreen( + f"reach {target_label} · scenarios", + items, + prompt="Outbound path only — the reply always retraces it in reverse.", + footer_hint="↑↓ move · Enter adopt/probe · Esc back", + wrap=False, + ) + ) + if picked is CANCEL or picked is None or picked[0] == "back": + return None + if picked[0] == "use": + return picked[1].spec(target_hash, width_bytes) + + # Probe all: measure each distinct spec (scenarios can collapse to the same + # spec once truncated to the trace width — the radio must not walk one twice). + candidates: list[ProbeCandidate] = [] + for scenario in scenarios: + spec = scenario.spec(target_hash, width_bytes) + if all(c.spec != spec for c in candidates): + candidates.append(ProbeCandidate(label=scenario.label, spec=spec)) + outcomes = await run_probe(candidates, _PROBE_SAMPLES_CAP) + if not outcomes: + return None + result_items: list = [ + Separator("── Ranked · reliability, then bottleneck SNR ──", style="accent") + ] + for rank, outcome in enumerate(outcomes, start=1): + result_items.append(Choice(title=outcome_title(rank, outcome), value=outcome)) + result_items.append(Separator(" ")) + result_items.append(Choice(title="Keep current path", value=None)) + adopted = await session.run_screen( + SelectScreen( + f"probe results · {target_label}", + result_items, + footer_hint="↑↓ move · Enter adopt path · Esc keep current", + wrap=False, + ) + ) + if adopted is CANCEL or adopted is None: + return None + return adopted.candidate.spec + async def burst(samples: int, path_spec: str, on_trace: Callable[[TraceResult], None]) -> None: """Run one persisted burst, streaming each landed trace to the screen.""" path = trace_runner.parse_trace_path(path_spec, contacts) if path_spec.strip() else None @@ -420,26 +897,6 @@ async def open_trace(ctx: "AppContext", target: str) -> int: }, ) - async def edit_path(current: str) -> Optional[str]: - """Float the forced-path prompt over the screen; blank means device-routed.""" - - def validate(value: str) -> bool | str: - if not value.strip(): - return True - try: - trace_runner.parse_trace_path(value, contacts) - return True - except ValueError as exc: - return str(exc) - - return await session.autocomplete( - "Force a path", - [c.name for c in contacts], - prompt="Comma-separated contacts/hex prefixes · blank = device-routed", - default=current, - validate=validate, - ) - screen = TraceScreen( target, device_label=device_label, @@ -447,10 +904,10 @@ async def open_trace(ctx: "AppContext", target: str) -> int: resolve=resolve, session=session, burst=burst, - edit_path=edit_path, + compose_path=compose, + explore=explore, previous=ctx.repo.latest_trace(target), ) - screen.start_burst() try: await session.run_screen(screen) finally: diff --git a/tests/test_live_screens.py b/tests/test_live_screens.py index cbe06fa..828701e 100644 --- a/tests/test_live_screens.py +++ b/tests/test_live_screens.py @@ -18,14 +18,24 @@ from meshterm.ui.tx_screen import TxSweepScreen class _FakeSession: - """The one session capability the screens use directly: requesting a repaint.""" + """The session capabilities the screens use directly: repaints and the dialog stack.""" def __init__(self) -> None: self.repaints = 0 + self.stack: list = [] def invalidate(self) -> None: self.repaints += 1 + def push(self, screen) -> None: # noqa: ANN001 + self.stack.append(screen) + + def pop(self, screen=None) -> None: # noqa: ANN001 + if screen is None: + self.stack.pop() + elif screen in self.stack: + self.stack.remove(screen) + def _trace(*snrs: float, success: bool = True, target: str = "Alice") -> TraceResult: """Build a trace with one hop per SNR reading.""" @@ -61,14 +71,16 @@ def test_snr_bar_clamps_out_of_range_readings() -> None: # --- TraceScreen ---------------------------------------------------------------- -def _trace_screen(burst=None, edit_path=None, previous=None) -> tuple[TraceScreen, _FakeSession]: +def _trace_screen( + burst=None, compose_path=None, explore=None, previous=None +) -> tuple[TraceScreen, _FakeSession]: session = _FakeSession() async def default_burst(samples, path_spec, on_trace): # noqa: ANN001 for _ in range(samples): on_trace(_trace(5.0, 2.0)) - async def default_edit(current): # noqa: ANN001 + async def default_flow(current): # noqa: ANN001 return current screen = TraceScreen( @@ -78,7 +90,8 @@ def _trace_screen(burst=None, edit_path=None, previous=None) -> tuple[TraceScree resolve=lambda label: label, session=session, burst=burst or default_burst, - edit_path=edit_path or default_edit, + compose_path=compose_path or default_flow, + explore=explore or default_flow, previous=previous, ) return screen, session @@ -152,20 +165,91 @@ async def test_trace_screen_samples_cycle_only_when_idle() -> None: assert screen._samples == 5 # locked while a burst is in flight -async def test_trace_screen_path_dialog_updates_the_spec() -> None: - """`p` opens the injected path prompt; its result becomes the next burst's path.""" +async def test_trace_screen_composer_updates_the_spec() -> None: + """`p` opens the injected composer flow; its result becomes the next burst's path.""" asked: list[str] = [] - async def edit(current: str): # noqa: ANN001 + async def compose(current: str): # noqa: ANN001 asked.append(current) return "3d,f2" - screen, _ = _trace_screen(edit_path=edit) + screen, _ = _trace_screen(compose_path=compose) screen.handle("text", "p") await asyncio.sleep(0) assert asked == [""] assert screen._path_spec == "3d,f2" - assert "3d,f2" in _plain(screen.render_body(100)) + body = _plain(screen.render_body(100)) + assert "3d,f2" in body + assert "auto return" in body # the planned route previews the outbound leg + + +async def test_trace_screen_explore_adopts_a_scenario_path() -> None: + """`x` runs the injected explore flow; adopting a path sets the spec, None keeps it.""" + + async def adopt(current: str): # noqa: ANN001 + return "3d63,f2c2" + + screen, _ = _trace_screen(explore=adopt) + screen.handle("text", "x") + await asyncio.sleep(0) + assert screen._path_spec == "3d63,f2c2" + + async def keep(current: str): # noqa: ANN001 + return None + + screen._explore = keep + screen.handle("text", "x") + await asyncio.sleep(0) + assert screen._path_spec == "3d63,f2c2" # None leaves the spec untouched + + +async def test_trace_screen_opens_idle_until_enter() -> None: + """Selecting a target must never transmit by itself: no burst until Enter.""" + screen, session = _trace_screen() + assert not screen._running and screen._worker is None + assert "press Enter to trace" in _plain(screen.render_body(100)) + screen.handle("enter") + assert screen._running + await screen._worker + assert session.stack == [] # the tracing dialog was popped with the burst + + +async def test_trace_screen_burst_floats_the_tracing_dialog() -> None: + """A burst pushes the abortable dialog for its duration and pops it however it ends.""" + release = asyncio.Event() + + async def burst(samples, path_spec, on_trace): # noqa: ANN001 + on_trace(_trace(5.0)) + await release.wait() + + screen, session = _trace_screen(burst=burst) + screen.start_burst() + await asyncio.sleep(0) + assert len(session.stack) == 1 + dialog = session.stack[0] + assert "2/3" in dialog.status # one reply landed; the second is in flight + body = _plain(dialog.render_body(60)) + assert "Abort" in body + release.set() + await screen._worker + assert session.stack == [] + + +async def test_tracing_dialog_abort_cancels_the_burst() -> None: + """Enter/Esc on the tracing dialog cancels the in-flight burst via the screen.""" + release = asyncio.Event() + + async def burst(samples, path_spec, on_trace): # noqa: ANN001 + await release.wait() + + screen, session = _trace_screen(burst=burst) + screen.start_burst() + await asyncio.sleep(0) + session.stack[0].handle("escape") + with pytest.raises(asyncio.CancelledError): + await screen._worker + assert session.stack == [] + assert not screen._running async def test_trace_screen_escape_cancels_the_inflight_burst() -> None: diff --git a/tests/test_monitor.py b/tests/test_monitor.py index f4821b0..afdba55 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -237,8 +237,13 @@ async def test_observations_round_trip_and_aggregate(tmp_path: Path) -> None: nodes = repo.heard_nodes() assert nodes - # Every node aggregated should have been heard at least once. - assert sum(n.count for n in nodes) == len(observations) + # Every aggregated reception should be counted — except packet-log rows, whose SNR + # belongs to the last relay rather than the node, so they feed topology instead. + receptions = [o for o in observations if o.kind != "packet"] + assert sum(n.count for n in nodes) == len(receptions) + # The simulator also overhears relayed packets, which persist with their path. + packets = repo.packet_paths() + assert packets and all(p.hops for p in packets) # Nodes are ordered most-recently-heard first. assert nodes == sorted(nodes, key=lambda n: n.last_seen, reverse=True) repo.close() diff --git a/tests/test_topology.py b/tests/test_topology.py new file mode 100644 index 0000000..58f7d8b --- /dev/null +++ b/tests/test_topology.py @@ -0,0 +1,246 @@ +"""Unit tests for the observed-topology graph, path scenarios, and the path composer. + +The graph is pure data-in/data-out, so these run headless: evidence rows are built by +hand (mirroring what the repository returns) and the assertions cover canonicalization, +bidirectional link folding, strength ordering, scenario ranking, and the composer's +step-by-step state machine. +""" + +from __future__ import annotations + +from datetime import timedelta + +from meshterm.core.models import Contact, Observation, utcnow +from meshterm.persistence.repository import PacketPath, Repository, TracedPath +from meshterm.services.path_probe import ProbeCandidate, ProbeOutcome, probe_paths +from meshterm.services.topology import build_topology, collapse_width +from meshterm.ui.path_composer import AUTO_SPEC, PathComposerScreen +from meshterm.ui.tui.screen import CANCEL + +US = "aaaaaaaaaaaa" +REPEATER = Contact(name="Hub", public_key="3d63c6429436" + "0" * 52, key_prefix="3d63c6429436") +FAR = Contact(name="Far", public_key="f2c24f54551e" + "0" * 52, key_prefix="f2c24f54551e") +LEAF = Contact(name="Leaf", public_key="27d4396a2967" + "0" * 52, key_prefix="27d4396a2967") + + +def _topo(trace_paths=(), packet_paths=(), contacts=None): # noqa: ANN001 + return build_topology( + self_id=US + "0" * 52, + contacts=list(contacts) if contacts is not None else [REPEATER, FAR, LEAF], + trace_paths=list(trace_paths), + packet_paths=list(packet_paths), + ) + + +def _traced(*hops, age_hours: float = 0.0) -> TracedPath: + """A trace walk from ``(node_hash, snr)`` pairs; the final hash-less hop is us.""" + return TracedPath(when=utcnow() - timedelta(hours=age_hours), hops=list(hops)) + + +# --- graph construction --------------------------------------------------------- + + +def test_trace_walk_yields_bidirectional_links_at_canonical_ids() -> None: + """A boomerang trace folds out+return readings onto the same undirected links.""" + topo = _topo( + trace_paths=[_traced(("3d", 12.5), ("f2", -5.5), ("3d", -6.5), (None, 11.75))] + ) + # us↔Hub crossed twice (first hop out, last hop home), Hub↔Far twice as well. + near = topo.link(topo.self_id, "3d63c6429436") + far = topo.link("3d63c6429436", "f2c24f54551e") + assert near is not None and near.samples == 2 + assert sorted(near.snrs) == [11.75, 12.5] + assert far is not None and far.samples == 2 + assert sorted(far.snrs) == [-6.5, -5.5] + + +def test_canonicalization_maps_prefixes_and_rejects_junk() -> None: + """Any-width hashes collapse onto contact ids; ambiguity and non-hex stay honest.""" + topo = _topo() + assert topo.canonical("3d") == "3d63c6429436" + assert topo.canonical("3d63c6429436" + "0" * 20) == "3d63c6429436" + assert topo.canonical("hop0") is None # legacy simulator artefact, not hex + ambiguous = _topo(contacts=[REPEATER, Contact(name="Twin", public_key="3d99" + "0" * 60)]) + assert ambiguous.canonical("3d") == "3d" # two contacts match: keep the short id + + +def test_contact_routes_and_packet_paths_feed_the_graph() -> None: + """Firmware-learned routes and RX-logged packet paths both count as evidence.""" + routed = Contact( + name="Far", public_key=FAR.public_key, key_prefix=FAR.key_prefix, + route_hops=("3d63c6429436",), last_seen=utcnow(), + ) + packet = PacketPath(when=utcnow(), origin="27d4396a2967", snr=8.0, hops=["3d63c6429436"]) + topo = _topo(packet_paths=[packet], contacts=[REPEATER, routed, LEAF]) + assert topo.link(topo.self_id, "3d63c6429436") is not None # both sources touch it + route_link = topo.link("3d63c6429436", "f2c24f54551e") + assert route_link is not None and route_link.sources == {"route"} + packet_link = topo.link("27d4396a2967", "3d63c6429436") + assert packet_link is not None and packet_link.sources == {"packet"} + # Only the final link (last relay → us) carries the reception SNR. + assert topo.link(topo.self_id, "3d63c6429436").snrs == [8.0] + assert packet_link.snrs == [] + + +# --- suggestions and scenarios ---------------------------------------------------- + + +def test_next_hops_sorts_by_link_strength_and_excludes_used_nodes() -> None: + """Suggestions rank the heavily-observed fresh link first and honour exclusions.""" + strong = [_traced(("3d", 12.0), (None, 12.0)) for _ in range(6)] + weak = [_traced(("27d4", -9.0), (None, -9.0), age_hours=24 * 21)] + topo = _topo(trace_paths=strong + weak) + nodes = [s.node for s in topo.next_hops(topo.self_id)] + assert nodes == ["3d63c6429436", "27d4396a2967"] + excluded = topo.next_hops(topo.self_id, exclude=frozenset({"3d63c6429436"})) + assert [s.node for s in excluded] == ["27d4396a2967"] + + +def test_scenarios_rank_observed_route_and_pin_device_route_first() -> None: + """The device route leads, then observed evidence, then the unobserved direct shot.""" + walks = [ + _traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0)) for _ in range(4) + ] + topo = _topo(trace_paths=walks) + scenarios = topo.scenarios("f2c24f54551e", device_route=("3d63c6429436",)) + assert scenarios[0].source == "device" + assert scenarios[0].hops == ("3d63c6429436",) + labels = [s.source for s in scenarios] + assert "direct" in labels # the baseline is always offered + direct = next(s for s in scenarios if s.source == "direct") + assert direct.score == 0.0 # never observed → ranked on measurement only + # The observed route (same hops as the device route) deduplicates away. + assert sum(1 for s in scenarios if s.hops == ("3d63c6429436",)) == 1 + + +def test_scenario_spec_ends_at_target_and_collapses_width() -> None: + """Specs are outbound-only, target-terminated, at a width every hash can honour.""" + walks = [_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0))] + topo = _topo(trace_paths=walks) + scenario = next( + s for s in topo.scenarios("f2c24f54551e") if s.hops == ("3d63c6429436",) + ) + assert scenario.spec("f2c24f54551e", 2) == "3d63,f2c2" + assert collapse_width("3d", "f2c24f54551e", ceiling=2) == 1 # narrowest hash rules + + +# --- repository round-trip --------------------------------------------------------- + + +def test_repository_round_trips_packet_paths_and_candidates(tmp_path) -> None: # noqa: ANN001 + """Packet observations persist their path; candidates land in path_candidates.""" + repo = Repository(tmp_path / "t.db") + run = repo.start_run("monitor", {}) + repo.record_observation( + run, Observation(node="27d4396a2967", kind="packet", snr=7.5, path="3d63,f2c2") + ) + repo.record_observation(run, Observation(node="27d4396a2967", kind="advert", snr=3.0)) + packets = repo.packet_paths() + assert len(packets) == 1 + assert packets[0].hops == ["3d63", "f2c2"] + assert packets[0].origin == "27d4396a2967" + # Packet rows never pollute per-node reception statistics. + heard = repo.heard_nodes() + assert len(heard) == 1 and heard[0].count == 1 and heard[0].median_snr == 3.0 + + probe_run = repo.start_run("trace", {"mode": "probe"}) + repo.record_path_candidate( + probe_run, "Far", "3d,f2", bottleneck_snr=-5.0, success_rate=1.0, median_rtt_ms=320.0 + ) + row = repo._conn.execute("SELECT * FROM path_candidates").fetchone() + assert row["target"] == "Far" and row["success_rate"] == 1.0 + repo.close() + + +# --- path probe ---------------------------------------------------------------------- + + +async def test_probe_paths_ranks_reliability_first() -> None: + """A path that always answers outranks a stronger-SNR one that drops traces.""" + from meshterm.core.models import TraceResult, Hop + + class _Device: + async def run_trace(self, target, *, path=None, timeout=10.0): # noqa: ANN001 + if path == "good": + return TraceResult( + target=target, success=True, + hops=[Hop(index=0, node="3d", snr=2.0)], round_trip_ms=300.0, + ) + return TraceResult(target=target, success=False) + + outcomes = await probe_paths( + _Device(), "Far", + [ProbeCandidate(label="flaky", spec="bad"), ProbeCandidate(label="solid", spec="good")], + samples=2, cooldown_s=0.0, + ) + assert [o.candidate.label for o in outcomes] == ["solid", "flaky"] + assert outcomes[0].stats.success_rate == 1.0 + + +# --- path composer --------------------------------------------------------------------- + + +def _composer(topo, hops=None): # noqa: ANN001 + return PathComposerScreen( + target_id="f2c24f54551e", + target_hash="f2c24f54551e" + "0" * 52, + target_label="Far", + device_label="Us", + topology=topo, + width_bytes=1, + hops=list(hops or []), + ) + + +def _rows_plain(screen: PathComposerScreen) -> str: + return "\n".join(screen.render_body(90)) + + +def test_composer_suggests_from_tail_and_appends_on_enter() -> None: + """The strongest neighbour of the path's tail is the first suggestion; Enter adds it.""" + walks = [_traced(("3d", 12.0), ("f2", -5.0), ("3d", -5.5), (None, 12.0))] + screen = _composer(_topo(trace_paths=walks)) + body = _rows_plain(screen) + assert "Hub" in body and "auto" in body.lower() # suggestion + symmetric-return note + screen.handle("enter") # top row: the Hub suggestion + assert screen._hops == ["3d63c6429436"] + # From the new tail the target is excluded, so Far never appears as a hop. + assert all(s.node != "f2c24f54551e" for s in screen._suggestions()) + + +def test_composer_typed_hex_adds_a_custom_hop_and_backspace_removes() -> None: + """Even-length hex typed into the filter becomes an addable custom hop.""" + screen = _composer(_topo()) + for ch in "beef": + screen.handle("text", ch) + screen.handle("enter") # the "+ add hop beef" row is first + assert screen._hops == ["beef"] + screen.handle("backspace") # entry is empty → removes the last hop + assert screen._hops == [] + + +async def test_composer_commits_spec_auto_and_cancel() -> None: + """Use resolves the target-terminated spec; Auto resolves the empty spec; Esc cancels.""" + import asyncio + + walks = [_traced(("3d", 12.0), (None, 12.0))] + + screen = _composer(_topo(trace_paths=walks), hops=["3d63c6429436"]) + screen.future = asyncio.get_running_loop().create_future() + screen.handle("end") # jump to the last action row (Cancel)… + screen.handle("up") + screen.handle("up") # …then back up to "Use this path" + screen.handle("enter") + assert screen.future.result() == "3d,f2" + + auto = _composer(_topo(trace_paths=walks)) + auto.future = asyncio.get_running_loop().create_future() + auto.handle("end") + auto.handle("up") # "Auto — let the device route" + auto.handle("enter") + assert auto.future.result() == AUTO_SPEC + + cancelled = _composer(_topo(trace_paths=walks)) + cancelled.future = asyncio.get_running_loop().create_future() + cancelled.handle("escape") + assert cancelled.future.result() is CANCEL