One trace per action: retire bursts so repeaters never see us flood

Repeaters penalize (and can blacklist) nodes that burst traffic, so
every trace-transmitting surface now sends exactly one transmission
per human action: Enter on the live screen runs a single trace (the
screen still aggregates the session's medians), the scenario probe
measures each candidate path once, and the CLI drops --samples to
become a true one-shot. trace_runner.measure and the s-key sample
cycle go with it.

Also de-pollute the target picker's "Recently traced" section: the
repository now returns a short recency-ordered list instead of the
ever-growing all-time tally, and stored hex prefixes fold back to
their contact names so a node shows once.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Fable 5 committed 2026-07-10 21:51:04 -04:00
1 parent f1e1896918
commit ce133a321e
10 files changed
+321 -299

No files matched your search

+3 -2
View File
@@ -39,8 +39,9 @@ meshterm
# Connect over Bluetooth instead of USB (address from `meshterm devices`)
meshterm --ble AA:BB:CC:DD:EE:FF info
# Scripted: every menu option is also a subcommand
meshterm trace --target Alice --samples 10 --profile yagi
# Scripted: every menu option is also a subcommand. A trace transmits exactly once —
# repeaters can blacklist nodes that burst traffic — so run it again to sample more.
meshterm trace --target Alice --profile yagi
# Force a route through specific repeaters (MeshCore-app style): comma-separated
# contact names and/or hex key prefixes, mixed freely. Blank lets the device route.
+13 -4
View File
@@ -348,14 +348,23 @@ class Repository:
timestamp=datetime.fromisoformat(row["created_at"]),
)
def traced_targets(self) -> list[str]:
"""Return the distinct trace destinations recorded, most-traced first.
def traced_targets(self, *, limit: int = 5) -> list[str]:
"""Return recent trace destinations, most recently traced first.
This feeds the target picker's *Recently traced* section, so the list is
deliberately short and recency-ordered: an all-time tally only ever grows,
burying current work under stale names (``--mock`` targets included).
Args:
limit: Maximum number of distinct targets to return.
Returns:
Target names ordered by descending trace count.
Distinct target names, most recently traced first.
"""
rows = self._conn.execute(
"SELECT target, COUNT(*) AS n FROM traces GROUP BY target ORDER BY n DESC"
"SELECT target, MAX(id) AS latest FROM traces "
"GROUP BY target ORDER BY latest DESC LIMIT ?",
(limit,),
).fetchall()
return [row["target"] for row in rows]
+15 -12
View File
@@ -1,10 +1,11 @@
"""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
evidence; this module puts them to the test. Each candidate outbound path is traced once
(by default — repeaters penalize, and can blacklist, nodes that burst traffic), every
trace is persisted exactly like a normal trace run, 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.
"""
@@ -42,7 +43,7 @@ class ProbeOutcome:
Attributes:
candidate: The route that was measured.
stats: The aggregated trace statistics over its burst.
stats: The aggregated trace statistics over its traces.
"""
candidate: ProbeCandidate
@@ -66,7 +67,7 @@ async def probe_paths(
target: str,
candidates: list[ProbeCandidate],
*,
samples: int = 3,
samples: int = 1,
cooldown_s: float = 1.0,
on_result: Optional[ProbeProgress] = None,
persist_trace: Optional[Callable[[TraceResult], Awaitable[None] | None]] = None,
@@ -74,17 +75,19 @@ async def probe_paths(
) -> 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.
Runs the candidates sequentially (one radio, duty cycle applies), a single trace
each by default. 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.
samples: Traces per candidate. The default of one is deliberate — repeaters
can blacklist nodes that burst traffic; raise it only when the airtime
budget clearly allows.
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.
+8 -41
View File
@@ -1,8 +1,11 @@
"""Repeated-trace execution with robust aggregation and duty-cycle pacing.
"""Repeated-trace execution with duty-cycle pacing, plus trace parsing helpers.
This is the measurement primitive both the trace tool and the TX/path optimizers build
on: run a trace N times, optionally reporting progress, and aggregate into robust
statistics while persisting every individual trace.
:func:`run_traces` is the measurement primitive the TX optimizer and the path probe
build on: run a trace N times with pacing, optionally reporting progress, persisting
every individual trace. The ``trace`` tool itself deliberately does *not* loop — it
transmits exactly one trace per invocation, because repeaters penalize (and can
blacklist) nodes that burst traffic — but it shares this module's path parsing and
node-name resolution.
"""
from __future__ import annotations
@@ -11,7 +14,7 @@ import asyncio
from typing import Awaitable, Callable, Optional
from ..core.connection import Device
from ..core.models import Contact, TraceResult, TraceStats
from ..core.models import Contact, TraceResult
ProgressCallback = Callable[[int, int, TraceResult], None]
@@ -186,39 +189,3 @@ async def run_traces(
if i < samples - 1 and cooldown_s > 0:
await asyncio.sleep(cooldown_s)
return results
async def measure(
device: Device,
target: str,
*,
samples: int = 5,
path: Optional[str] = None,
cooldown_s: float = 1.0,
on_result: Optional[ProgressCallback] = None,
persist: Optional[Callable[[TraceResult], Awaitable[None] | None]] = None,
) -> TraceStats:
"""Run traces and return their robust aggregate statistics.
Args:
device: The connected device to trace through.
target: Destination node name or key prefix.
samples: Number of traces to run.
path: Optional explicit path to force.
cooldown_s: Delay between traces.
on_result: Optional per-trace progress callback.
persist: Optional per-trace persistence callback.
Returns:
A :class:`TraceStats` summarizing the run.
"""
results = await run_traces(
device,
target,
samples=samples,
path=path,
cooldown_s=cooldown_s,
on_result=on_result,
persist=persist,
)
return TraceStats.from_traces(target, results)
+97 -73
View File
@@ -1,17 +1,20 @@
"""The ``trace`` tool: path traces to a target, live in the menu, one-shot on the CLI.
Every invocation transmits exactly *one* trace — repeaters penalize (and can blacklist)
nodes that burst traffic, so repeat sampling is always a human decision, never a loop.
In the interactive menu this opens the live trace screen
(: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,
standing on a repeater with stored admin credentials, can fetch that repeater's live
neighbour table for suggestions our own radio never heard), 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.
screen opens armed but idle — Enter runs one trace under an abortable tracing dialog
(press again to sample more; the screen aggregates the session), ``p`` composes a forced
path hop by hop from the topology observed in received traffic (and, standing on a
repeater with stored admin credentials, can fetch that repeater's live neighbour table
for suggestions our own radio never heard), and ``x`` explores ranked path scenarios
(with an optional probe that measures each candidate once and offers the winner). On the
CLI it stays a scriptable one-shot: run one trace, print the route and per-hop SNR, 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.
Both front ends persist identically: one ``runs`` row per trace, recorded under it, so
stored history reads the same no matter where it came from.
"""
from __future__ import annotations
@@ -22,17 +25,17 @@ import typer
from rich.text import Text
from ..context import AppContext
from ..core.models import LOCAL_DEVICE_LABEL, Contact
from ..core.models import LOCAL_DEVICE_LABEL, Contact, TraceStats
from ..services import trace_runner
from ..ui.widgets import stats_panel, traces_table
from ..ui.widgets import stats_panel
from .base import Tool, ToolResult, register
#: Upper bound on traces per scripted run — the per-trace table renders one column each,
#: so this keeps the output readable and the radio's duty cycle in check.
MAX_TRACES = 9
_BACK = "__back__"
#: The characters a stored trace target must consist of to be treated as a hex key
#: prefix when folding it back to a contact name in the target picker.
_HEX_DIGITS = frozenset("0123456789abcdef")
@register
class TraceTool(Tool):
@@ -61,7 +64,7 @@ class TraceTool(Tool):
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Run — without the outer run row on the live path.
The live screen opens one ``runs`` row *per burst* (matching what a scripted
The live screen opens one ``runs`` row *per trace* (matching what a scripted
invocation records), so wrapping the whole screen session in another row would
double-log it. Scripted runs keep the base class's logging.
@@ -77,16 +80,15 @@ class TraceTool(Tool):
return await super().execute(ctx, params)
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Open the live screen (menu) or run a persisted one-shot burst (CLI).
"""Open the live screen (menu) or run one persisted trace (CLI).
Args:
ctx: Shared application context.
params: ``live`` + ``target`` from the menu picker; or ``target`` (str),
``samples`` (int), optional ``path``, and the injected ``_run_id`` from
the CLI.
optional ``path``, and the injected ``_run_id`` from the CLI.
Returns:
A :class:`ToolResult` with the aggregated statistics.
A :class:`ToolResult` with the trace's outcome.
"""
if params.get("live"):
return await self._run_live(ctx, str(params["target"]))
@@ -138,7 +140,7 @@ class TraceTool(Tool):
device = await ctx.device()
contacts = await device.get_contacts()
recent = ctx.repo.traced_targets()
recent = _recent_targets(ctx.repo.traced_targets(), contacts)
if not contacts and not recent:
entered = await ctx.ui.text("Target node (name or key prefix):")
@@ -182,20 +184,19 @@ class TraceTool(Tool):
# -- scripted (CLI) -------------------------------------------------------------
async def _run_cli(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
"""Run the traces, persist each one, and print the summary tables.
"""Run one trace, persist it, and print the route and per-hop summary.
One transmission per invocation is a hard rule — repeaters penalize (and can
blacklist) nodes that burst traffic — so sampling means invoking again.
Args:
ctx: Shared application context.
params: ``target`` (str), ``samples`` (int), optional ``path``, and the
injected ``_run_id``.
params: ``target`` (str), optional ``path``, and the injected ``_run_id``.
Returns:
A :class:`ToolResult` with the aggregated statistics.
A :class:`ToolResult` with the trace's outcome.
"""
target = params["target"]
samples = max(1, min(MAX_TRACES, int(params.get("samples", 3))))
if int(params.get("samples", 3)) > MAX_TRACES:
ctx.ui.note(f"[warn]capping at {MAX_TRACES} traces[/warn]")
run_id = params["_run_id"]
device = await ctx.device()
@@ -223,56 +224,40 @@ class TraceTool(Tool):
else:
ctx.ui.note("[muted]path: auto (device-routed)[/muted]")
traces: list = []
with ctx.ui.progress("trace") as progress:
task = progress.add_task(f"tracing {target}", total=samples)
task = progress.add_task(f"tracing {target}", total=1)
result = await device.run_trace(target, path=path)
ctx.repo.record_trace(run_id, result)
progress.advance(task)
def on_result(done: int, total: int, result) -> None: # noqa: ANN001
traces.append(result)
progress.advance(task)
stats = await trace_runner.measure(
device,
target,
samples=samples,
path=path,
cooldown_s=ctx.settings.trace_cooldown_s,
on_result=on_result,
persist=lambda t: ctx.repo.record_trace(run_id, t),
)
# Use the first reply we got as the representative route shown in the summary
# (forced path, or the route the device resolved when auto-routing).
current = next((t for t in traces if t.success), None)
if traces:
ctx.ui.show(traces_table(traces, device_label, resolve, device_hash))
# The stats panel renders route + per-hop readings for the single trace (its
# medians collapse to the readings themselves).
stats = TraceStats.from_traces(target, [result])
ctx.ui.show(
stats_panel(stats, device_label, resolve, route=current, device_hash=device_hash)
stats_panel(
stats,
device_label,
resolve,
route=result if result.success else None,
device_hash=device_hash,
)
)
summary: dict[str, Any] = {
"target": stats.target,
"samples": stats.samples,
"success_rate": round(stats.success_rate, 3),
"median_min_snr": stats.median_min_snr,
"median_rtt_ms": stats.median_rtt_ms,
"median_hop_snrs": [
{
"hop": agg.index,
"from": agg.origin or device_label,
"to": agg.destination or device_label,
"median_snr": agg.median_snr,
}
for agg in stats.hop_snrs
],
"target": target,
"success": result.success,
"hops": result.hop_count if result.success else None,
"min_snr": result.min_snr,
"rtt_ms": result.round_trip_ms,
}
if path:
summary["path"] = path
via = f" via [brand]{path}[/brand]" if path else ""
return ToolResult(
summary=summary,
message=f"[ok]✓[/ok] traced [brand]{target}[/brand] x{samples}{via}",
)
if result.success:
message = f"[ok]✓[/ok] traced [brand]{target}[/brand]{via}"
else:
message = f"[err]✗[/err] no reply from [brand]{target}[/brand]{via}"
return ToolResult(summary=summary, message=message)
def register_cli(self, app: typer.Typer) -> None:
"""Register the ``trace`` subcommand.
@@ -282,12 +267,9 @@ class TraceTool(Tool):
"""
from ..cli import run_tool_command
@app.command(name=self.name, help="Run repeated path traces to a target and aggregate SNR")
@app.command(name=self.name, help="Run a single path trace to a target and show per-hop SNR")
def _trace(
target: str = typer.Option(..., "--target", "-t", help="Target node name/prefix"),
samples: int = typer.Option(
3, "--samples", "-n", help=f"Number of traces (max {MAX_TRACES})"
),
path: Optional[str] = typer.Option(
None,
"--path",
@@ -295,12 +277,54 @@ class TraceTool(Tool):
help="Force a route: comma-separated contact names/hex prefixes (e.g. 3d,f2,3d)",
),
) -> None:
tool_params: dict[str, Any] = {"target": target, "samples": samples}
tool_params: dict[str, Any] = {"target": target}
if path:
tool_params["path"] = path
run_tool_command(self, tool_params)
def _recent_targets(stored: list[str], contacts: list[Contact]) -> list[str]:
"""Clean the stored recent-target names for the picker's *Recently traced* section.
Targets are recorded exactly as the user addressed them, so the same node can
appear once as a contact name and again as a raw hex prefix typed some other day.
Each stored target is folded back to its contact's current name when it matches one
(by name, case-insensitively, or as a prefix of a contact's public key), then
deduplicated with order preserved — so every node shows once, under the name the
rest of the picker uses.
Args:
stored: Recent trace destinations, most recent first, as recorded.
contacts: The device's current contacts to fold names against.
Returns:
The display names, most recently traced first, one per node.
"""
by_fold = {c.name.casefold(): c.name for c in contacts}
def fold(target: str) -> str:
named = by_fold.get(target.casefold())
if named is not None:
return named
needle = target.lower().removeprefix("0x")
# Only fold plausible key prefixes (≥2 bytes of hex) — a short hex-looking
# *name* like "ace" must not be mistaken for an address.
if len(needle) >= 4 and all(ch in _HEX_DIGITS for ch in needle):
for c in contacts:
if (c.public_key or "").lower().startswith(needle):
return c.name
return target
names: list[str] = []
seen: set[str] = set()
for target in stored:
name = fold(target)
if name.casefold() not in seen:
seen.add(name.casefold())
names.append(name)
return names
def _by_recency(contacts: list[Contact]) -> list[Contact]:
"""Order contacts most-recently-heard first (never-heard last, alphabetically).
+80 -105
View File
@@ -5,9 +5,12 @@ table output). Where the old flow started tracing the instant a target was picke
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:
* **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.
* **Enter** runs a *single* trace. While it flies, a floating *tracing* dialog (spinner,
Abort) sits over the screen — the reply streams into the log behind it, and Esc in the
dialog cancels the trace without leaving the screen. One transmission per keypress is
deliberate: repeaters penalize chatty nodes (flood detection can blacklist us), so
sampling is left human-paced — press Enter again and the screen keeps aggregating
every trace of the session into its medians.
* **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,
@@ -18,16 +21,17 @@ whatever you make it, and nothing transmits until you say so. Three verbs drive
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.
observed alternatives). Adopt one directly — or probe them all, one measured trace per
candidate (the same single-transmission rule), 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
Every trace is persisted exactly like a scripted run: one ``runs`` row per trace,
recorded under it, so the stored history reads the same no matter which front end
produced it.
"""
@@ -52,17 +56,9 @@ from .widgets import NodeResolver, _link_text, _route_text
if TYPE_CHECKING:
from ..context import AppContext
#: Seconds between spinner frames while a burst or probe is in flight.
#: Seconds between spinner frames while a trace 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
@@ -71,10 +67,11 @@ _BAR_WIDTH = 16
_BAR_SNR_MIN = -15.0
_BAR_SNR_MAX = 10.0
#: A burst runner: ``(samples, path_spec, on_trace)`` → runs the traces, streaming each
#: result to ``on_trace`` as it lands. Provided by :func:`open_trace`, which closes over
#: the device, repository, and settings so the screen stays free of persistence concerns.
BurstRunner = Callable[[int, str, Callable[[TraceResult], None]], Awaitable[None]]
#: A single-trace runner: ``(path_spec, on_trace)`` → runs exactly one trace, handing
#: the result to ``on_trace`` when it lands. Provided by :func:`open_trace`, which closes
#: over the device, repository, and settings so the screen stays free of persistence
#: concerns.
TraceOnce = Callable[[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.
@@ -105,7 +102,7 @@ def snr_bar(snr: Optional[float], width: int = _BAR_WIDTH) -> Text:
class TracingDialog(Screen):
"""The floating in-flight dialog: a spinner chip, live progress, and Abort.
Pushed over the trace screen while a burst (or scenario probe) transmits, so the
Pushed over the trace screen while a trace (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.
@@ -180,11 +177,12 @@ class TracingDialog(Screen):
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).
Keys: Enter runs one trace (a floating dialog with Abort rides on top while it
flies — one transmission per keypress, because repeaters can blacklist nodes that
burst traffic), ``p`` composes the forced path hop by hop from observed topology,
``x`` explores and probes ranked path scenarios, the usual scroll keys move the
view, and Esc backs out (cancelling any in-flight trace; already-recorded traces
are kept).
"""
floating = False
@@ -197,11 +195,10 @@ class TraceScreen(Screen):
device_hash: Optional[str],
resolve: NodeResolver,
session: Any,
burst: BurstRunner,
trace: TraceOnce,
compose_path: PathFlow,
explore: PathFlow,
previous: Optional[TraceResult] = None,
samples: int = 3,
) -> None:
"""Create the screen (nothing transmits until the user presses Enter).
@@ -211,14 +208,14 @@ class TraceScreen(Screen):
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 and the floating dialog).
burst: Runs one burst of traces, streaming results (see :data:`BurstRunner`).
trace: Runs exactly one trace, handing back the result (see
:data:`TraceOnce`).
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.
"""
super().__init__()
self.title = f"trace · {target}"
@@ -227,17 +224,15 @@ class TraceScreen(Screen):
self._device_hash = device_hash
self._resolve = resolve
self._session = session
self._burst = burst
self._trace_once = trace
self._compose_path = compose_path
self._explore = explore
self._previous = previous
self._samples = samples if samples in _SAMPLE_CYCLE else 3
self._path_spec = ""
self._traces: list[TraceResult] = []
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
@@ -246,42 +241,37 @@ class TraceScreen(Screen):
@property
def footer_hint(self) -> str: # type: ignore[override]
"""The footer keys, tracking whether a burst is in flight."""
"""The footer keys, tracking whether a trace is in flight."""
if self._running:
return "tracing… · ↑↓ PgUp/PgDn scroll · Esc back"
return (
"Enter trace · p compose path · x explore paths · s samples · "
"↑↓ scroll · Esc back"
)
return "Enter trace · p compose path · x explore paths · ↑↓ scroll · Esc back"
def start_burst(self) -> None:
"""Kick off one burst of traces in the background (no-op while one is running)."""
def start_trace(self) -> None:
"""Kick off one trace in the background (no-op while one is already flying)."""
if self._running:
return
self._running = True
self._status = ""
self._burst_done = 0
self._spinner.reset()
self._worker = asyncio.ensure_future(self._run_burst())
self._worker = asyncio.ensure_future(self._run_trace())
self._session.invalidate()
async def _run_burst(self) -> None:
"""Drive one burst to completion under the floating tracing dialog.
async def _run_trace(self) -> None:
"""Drive one trace to completion under the floating tracing dialog.
The dialog is pushed for the duration and popped however the burst ends —
The dialog is pushed for the duration and popped however the trace 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.
so the 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)
await self._trace_once(self._path_spec, self._on_trace)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001 - report inline, keep the screen alive
@@ -292,18 +282,13 @@ class TraceScreen(Screen):
await ticker
except asyncio.CancelledError:
pass
except Exception: # noqa: BLE001 - a spinner hiccup must never break a burst
except Exception: # noqa: BLE001 - a spinner hiccup must never break a trace
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:
@@ -312,29 +297,23 @@ class TraceScreen(Screen):
self._session.invalidate()
def _on_trace(self, result: TraceResult) -> None:
"""Append one landed trace, advance the dialog, and repaint."""
"""Append the landed trace, echo it on 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:
"""Cancel any in-flight burst (already-recorded traces are kept)."""
"""Cancel any in-flight trace (already-recorded traces are kept)."""
if self._worker is not None and not self._worker.done():
self._worker.cancel()
# --- input -------------------------------------------------------------------
def handle(self, action: str, data: str = "") -> None:
"""Run bursts, compose/explore paths, tweak samples, scroll, or dismiss."""
"""Run a trace, compose/explore paths, scroll, or dismiss."""
if action == "enter":
self.start_burst()
elif action == "text" and data.lower() == "s":
if not self._running:
idx = _SAMPLE_CYCLE.index(self._samples)
self._samples = _SAMPLE_CYCLE[(idx + 1) % len(_SAMPLE_CYCLE)]
self.start_trace()
elif action == "text" and data.lower() == "p":
self._open_flow(self._compose_path)
elif action == "text" and data.lower() == "x":
@@ -356,7 +335,7 @@ class TraceScreen(Screen):
self.resolve(None)
def _open_flow(self, flow: PathFlow) -> None:
"""Float a path-picking flow over the screen (one at a time, not mid-burst).
"""Float a path-picking flow over the screen (one at a time, not mid-trace).
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
@@ -451,7 +430,7 @@ class TraceScreen(Screen):
return text
def _summary(self, stats: TraceStats) -> Text:
"""The run's aggregates plus the current burst configuration, label-aligned."""
"""The session's aggregates plus the current path, label-aligned."""
snr = stats.median_min_snr
snr_text = (
Text(f"{snr:+.1f} dB", style=snr_style(snr)) if snr is not None else Text("—")
@@ -462,9 +441,7 @@ class TraceScreen(Screen):
("success rate ", "muted"), (rate if stats.samples else "—", ""), ("\n", ""),
("median min SNR ", "muted"), snr_text, ("\n", ""),
("median RTT ", "muted"), (rtt, ""), ("\n", ""),
("burst ", "muted"),
(f"{self._samples} trace{'s' if self._samples != 1 else ''}", ""),
(" · path ", "muted"),
("path ", "muted"),
)
if self._path_spec:
summary.append(self._path_spec, style="brand")
@@ -544,7 +521,7 @@ 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, the database, and the observed-topology services:
each burst opens its own ``runs`` row and records every trace under it (same shape a
each trace opens its own ``runs`` row and is recorded 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
@@ -810,11 +787,13 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
return text
def outcome_title(rank: int, outcome: ProbeOutcome) -> Text:
"""One probed candidate as a ranked select row: measured, not guessed."""
"""One probed candidate as a ranked select row: one measured trace, not a guess."""
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)
if stats.successes:
text.append("✓ replied", style="ok")
else:
text.append("✗ no reply", style="err")
snr = stats.median_min_snr
if snr is not None:
text.append(" min ", style="muted")
@@ -827,30 +806,30 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
return text
async def run_probe(
candidates: list[ProbeCandidate], samples: int
candidates: list[ProbeCandidate],
) -> Optional[list[ProbeOutcome]]:
"""Measure every candidate under an abortable dialog; ``None`` when aborted.
"""Measure every candidate — one trace each — under an abortable dialog.
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.
Each candidate gets exactly one transmission (the screen-wide rule: repeaters
can blacklist nodes that burst traffic); ``None`` when aborted.
"""
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}"
dialog.status = f"path 1/{len(candidates)} · one trace each"
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.status = f"path {index + 1}/{len(candidates)} · one trace each"
dialog.last = result
session.invalidate()
@@ -859,7 +838,6 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
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),
@@ -957,7 +935,7 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
items.append(Separator(" "))
items.append(
Choice(
title=Text.assemble(("⚡ ", "warn"), "Probe all — trace each path and rank"),
title=Text.assemble(("⚡ ", "warn"), "Probe all — trace each path once and rank"),
value=("probe", None),
)
)
@@ -983,7 +961,7 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
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)
outcomes = await run_probe(candidates)
if not outcomes:
return None
result_items: list = [
@@ -1005,38 +983,35 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
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."""
async def trace_once(path_spec: str, on_trace: Callable[[TraceResult], None]) -> None:
"""Run one persisted trace: one transmission, its own ``runs`` row.
A single transmission per keypress is deliberate — repeaters penalize (and
can blacklist) nodes that burst traffic — so repeat sampling is left to the
human, and the screen aggregates whatever lands.
"""
path = trace_runner.parse_trace_path(path_spec, contacts) if path_spec.strip() else None
params: dict[str, Any] = {"target": target, "samples": samples}
params: dict[str, Any] = {"target": target}
if path:
params["path"] = path
run_id = ctx.repo.start_run("trace", params, ctx.profile_name)
try:
results = await trace_runner.run_traces(
device,
target,
samples=samples,
path=path,
cooldown_s=ctx.settings.trace_cooldown_s,
on_result=lambda _done, _total, result: on_trace(result),
persist=lambda t: ctx.repo.record_trace(run_id, t),
)
result = await device.run_trace(target, path=path)
except BaseException as exc:
# A cancelled or failed burst still closes its run row, so no ``running``
# orphan is left behind; the traces already recorded stay.
# A cancelled or failed trace still closes its run row, so no ``running``
# orphan is left behind.
ctx.repo.finish_run(run_id, "error", {"error": str(exc) or type(exc).__name__})
raise
stats = TraceStats.from_traces(target, results)
ctx.repo.record_trace(run_id, result)
on_trace(result)
ctx.repo.finish_run(
run_id,
"ok",
{
"target": stats.target,
"samples": stats.samples,
"success_rate": round(stats.success_rate, 3),
"median_min_snr": stats.median_min_snr,
"median_rtt_ms": stats.median_rtt_ms,
"target": target,
"success": result.success,
"min_snr": result.min_snr,
"rtt_ms": result.round_trip_ms,
},
)
@@ -1046,7 +1021,7 @@ async def open_trace(ctx: "AppContext", target: str) -> int:
device_hash=device_hash,
resolve=resolve,
session=session,
burst=burst,
trace=trace_once,
compose_path=compose,
explore=explore,
previous=ctx.repo.latest_trace(target),
+44 -51
View File
@@ -1,6 +1,6 @@
"""Unit tests for the live Trace and TX-optimize screens.
These drive the two full-screen tools' pure logic — burst/sweep state machines, key
These drive the two full-screen tools' pure logic — trace/sweep state machines, key
handling, and rendering — against fake sessions and injected runners, so they run fast
and headless (the same approach as ``test_tui``).
"""
@@ -72,13 +72,12 @@ def test_snr_bar_clamps_out_of_range_readings() -> None:
def _trace_screen(
burst=None, compose_path=None, explore=None, previous=None
trace=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_trace(path_spec, on_trace): # noqa: ANN001
on_trace(_trace(5.0, 2.0))
async def default_flow(current): # noqa: ANN001
return current
@@ -89,7 +88,7 @@ def _trace_screen(
device_hash="aabb" + "00" * 30,
resolve=lambda label: label,
session=session,
burst=burst or default_burst,
trace=trace or default_trace,
compose_path=compose_path or default_flow,
explore=explore or default_flow,
previous=previous,
@@ -97,16 +96,21 @@ def _trace_screen(
return screen, session
async def test_trace_screen_burst_streams_results_into_the_log() -> None:
"""A burst appends each landed trace; the log and aggregates render them."""
async def test_trace_screen_one_trace_per_enter_accumulates() -> None:
"""Each Enter transmits exactly one trace; the session aggregates what landed.
Single-transmission is the screen's blacklist-avoidance rule: repeat sampling is
the human's call, so three keypresses mean three traces and a three-sample median.
"""
screen, _ = _trace_screen()
screen.start_burst()
await asyncio.sleep(0) # let the worker run
await screen._worker
for _ in range(3):
screen.start_trace()
await screen._worker
body = _plain(screen.render_body(100))
assert "success rate" in body and "3/3" in body
assert "#3" in body # newest-first numbering
assert "Per-hop medians" in body
assert "burst" not in body.lower() # no burst configuration is offered anywhere
async def test_trace_screen_seeds_route_from_previous_trace() -> None:
@@ -122,18 +126,18 @@ async def test_trace_screen_seeds_route_from_previous_trace() -> None:
assert "(previous" not in body
async def test_trace_screen_only_one_burst_at_a_time() -> None:
"""Enter during a burst is a no-op; the running flag gates re-entry."""
async def test_trace_screen_only_one_trace_at_a_time() -> None:
"""Enter during an in-flight trace is a no-op; the running flag gates re-entry."""
started = 0
release = asyncio.Event()
async def burst(samples, path_spec, on_trace): # noqa: ANN001
async def trace(path_spec, on_trace): # noqa: ANN001
nonlocal started
started += 1
await release.wait()
screen, _ = _trace_screen(burst=burst)
screen.start_burst()
screen, _ = _trace_screen(trace=trace)
screen.start_trace()
assert screen._running
screen.handle("enter") # ignored while running
release.set()
@@ -142,31 +146,20 @@ async def test_trace_screen_only_one_burst_at_a_time() -> None:
assert not screen._running
async def test_trace_screen_burst_failure_reads_inline() -> None:
"""A failed burst reports its error in the log area instead of crashing the screen."""
async def test_trace_screen_failure_reads_inline() -> None:
"""A failed trace reports its error in the log area instead of crashing the screen."""
async def burst(samples, path_spec, on_trace): # noqa: ANN001
async def trace(path_spec, on_trace): # noqa: ANN001
raise RuntimeError("no route")
screen, _ = _trace_screen(burst=burst)
screen.start_burst()
screen, _ = _trace_screen(trace=trace)
screen.start_trace()
await screen._worker
assert "trace failed: no route" in _plain(screen.render_body(100))
async def test_trace_screen_samples_cycle_only_when_idle() -> None:
"""`s` cycles the burst size through the odd sample counts, but never mid-burst."""
screen, _ = _trace_screen()
assert screen._samples == 3
screen.handle("text", "s")
assert screen._samples == 5
screen._running = True
screen.handle("text", "s")
assert screen._samples == 5 # locked while a burst is in flight
async def test_trace_screen_composer_updates_the_spec() -> None:
"""`p` opens the injected composer flow; its result becomes the next burst's path."""
"""`p` opens the injected composer flow; its result becomes the next trace's path."""
asked: list[str] = []
async def compose(current: str): # noqa: ANN001
@@ -204,30 +197,30 @@ async def test_trace_screen_explore_adopts_a_scenario_path() -> None:
async def test_trace_screen_opens_idle_until_enter() -> None:
"""Selecting a target must never transmit by itself: no burst until Enter."""
"""Selecting a target must never transmit by itself: nothing flies 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
assert session.stack == [] # the tracing dialog was popped with the trace
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."""
async def test_trace_screen_floats_the_tracing_dialog() -> None:
"""A trace 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
async def trace(path_spec, on_trace): # noqa: ANN001
on_trace(_trace(5.0))
await release.wait()
screen, session = _trace_screen(burst=burst)
screen.start_burst()
screen, session = _trace_screen(trace=trace)
screen.start_trace()
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
assert dialog.last is not None # the landed reply echoes on the dialog
body = _plain(dialog.render_body(60))
assert "Abort" in body
release.set()
@@ -235,15 +228,15 @@ async def test_trace_screen_burst_floats_the_tracing_dialog() -> None:
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."""
async def test_tracing_dialog_abort_cancels_the_trace() -> None:
"""Enter/Esc on the tracing dialog cancels the in-flight trace via the screen."""
release = asyncio.Event()
async def burst(samples, path_spec, on_trace): # noqa: ANN001
async def trace(path_spec, on_trace): # noqa: ANN001
await release.wait()
screen, session = _trace_screen(burst=burst)
screen.start_burst()
screen, session = _trace_screen(trace=trace)
screen.start_trace()
await asyncio.sleep(0)
session.stack[0].handle("escape")
with pytest.raises(asyncio.CancelledError):
@@ -252,15 +245,15 @@ async def test_tracing_dialog_abort_cancels_the_burst() -> None:
assert not screen._running
async def test_trace_screen_escape_cancels_the_inflight_burst() -> None:
"""Esc resolves the screen and cancels a burst that is still measuring."""
async def test_trace_screen_escape_cancels_the_inflight_trace() -> None:
"""Esc resolves the screen and cancels a trace that is still measuring."""
release = asyncio.Event()
async def burst(samples, path_spec, on_trace): # noqa: ANN001
async def trace(path_spec, on_trace): # noqa: ANN001
await release.wait()
screen, _ = _trace_screen(burst=burst)
screen.start_burst()
screen, _ = _trace_screen(trace=trace)
screen.start_trace()
screen.future = asyncio.get_running_loop().create_future()
screen.handle("escape")
assert screen.future.result() is None
+15 -10
View File
@@ -129,17 +129,22 @@ def test_recent_traces_empty_target(repo: Repository) -> None:
# -- traced_targets --------------------------------------------------------
def test_traced_targets_ordered_by_count(repo: Repository) -> None:
"""Targets are returned most-traced first."""
run = repo.start_run("trace", {})
for _ in range(5):
repo.record_trace(run, _make_trace("Alice", ("r", 1.0)))
for _ in range(2):
repo.record_trace(run, _make_trace("Bob", ("r", 1.0)))
for _ in range(8):
repo.record_trace(run, _make_trace("Carol", ("r", 1.0)))
def test_traced_targets_recency_ordered_and_capped(repo: Repository) -> None:
"""Targets come back most recently traced first, deduplicated, and capped.
assert repo.traced_targets() == ["Carol", "Alice", "Bob"]
The all-time trace count must not matter: a heavily-traced old target (Alice here)
ranks by its *latest* trace, so stale favourites and leftover mock names age out of
the picker's short "Recently traced" list instead of squatting on top forever.
"""
run = repo.start_run("trace", {})
for _ in range(8):
repo.record_trace(run, _make_trace("Alice", ("r", 1.0)))
for name in ["Bob", "Carol", "Dave", "Erin", "Frank"]:
repo.record_trace(run, _make_trace(name, ("r", 1.0)))
repo.record_trace(run, _make_trace("Bob", ("r", 1.0))) # Bob traced again just now
assert repo.traced_targets() == ["Bob", "Frank", "Erin", "Dave", "Carol"]
assert repo.traced_targets(limit=2) == ["Bob", "Frank"]
def test_traced_targets_empty_db(repo: Repository) -> None:
+19 -1
View File
@@ -62,6 +62,23 @@ def test_parse_trace_path_rejects_mixed_widths() -> None:
trace_runner.parse_trace_path("3d,a1b2c3", contacts=[])
def test_recent_targets_folds_hex_to_names_and_dedupes() -> None:
"""Stored targets collapse to contact names so a node shows once in the picker.
The same node traced as "alice" one day and by its key prefix another must appear
a single time under its contact name; a hex-looking *name* stays a name, and
unknown prefixes pass through untouched.
"""
from meshterm.tools.trace import _recent_targets
contacts = [
Contact(name="Alice", public_key="d4e5f6a7" + "00" * 28, key_prefix="d4e5f6a7"),
Contact(name="cafe", public_key="12ab34cd" + "00" * 28, key_prefix="12ab34cd"),
]
stored = ["d4e5f6", "alice", "Alice", "cafe", "beefbeef", "d4e5f6a7"]
assert _recent_targets(stored, contacts) == ["Alice", "cafe", "beefbeef"]
def test_path_hash_flags_power_of_two_only() -> None:
"""Trace flags encode the hash width as 1 << s, so only 1/2/4/8 bytes map."""
assert trace_runner.path_hash_flags(1) == 0
@@ -270,7 +287,8 @@ async def test_mock_device_trace_is_unimodal_in_tx() -> None:
async def avg_snr(tx: int) -> float:
await device.set_tx_power(tx)
stats = await trace_runner.measure(device, "Alice", samples=15, cooldown_s=0)
results = await trace_runner.run_traces(device, "Alice", samples=15, cooldown_s=0)
stats = TraceStats.from_traces("Alice", results)
return stats.median_min_snr or -99.0
low, peak, high = await avg_snr(2), await avg_snr(14), await avg_snr(22)
+27
View File
@@ -251,6 +251,33 @@ async def test_probe_paths_ranks_reliability_first() -> None:
assert outcomes[0].stats.success_rate == 1.0
async def test_probe_paths_defaults_to_one_trace_per_candidate() -> None:
"""By default each candidate is measured with a single transmission.
This is the blacklist-avoidance rule: repeaters penalize nodes that burst traffic,
so probing N paths must cost exactly N traces unless the caller opts into more.
"""
from meshterm.core.models import Hop, TraceResult
transmitted: list[str] = []
class _Device:
async def run_trace(self, target, *, path=None, timeout=10.0): # noqa: ANN001
transmitted.append(path)
return TraceResult(
target=target, success=True,
hops=[Hop(index=0, node="3d", snr=2.0)], round_trip_ms=300.0,
)
outcomes = await probe_paths(
_Device(), "Far",
[ProbeCandidate(label="a", spec="3d"), ProbeCandidate(label="b", spec="f2")],
cooldown_s=0.0,
)
assert transmitted == ["3d", "f2"] # one trace per candidate, in order
assert all(o.stats.samples == 1 for o in outcomes)
# --- path composer ---------------------------------------------------------------------