From 8afa592e9a65aba27f8d1fce97c2762a7b08bf0d Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 28 Jul 2026 00:33:58 -0400 Subject: [PATCH] Route graph: a hop heard twice is drawn twice, and said so MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merging a repeated hop into one marker is right across paths and wrong within one. A via chain that names the same hop twice closes a cycle, and the left-to-right flow has nowhere to seat it: the balanced-x relaxation iterates a cyclic edge set, never reaches its fixed point, and returns wherever the sweep budget stopped. The loop's relays then land in one column — markers piled a cell apart, labels colliding or dropped, the back edge falling as a bare vertical — while the hops outside it are crushed against the ends. Worse, the residue depends on set iteration order, so the pile's column swung with the hash seed: the very frame-to-frame jump the first-appearance node order exists to prevent. render_path_graph grows allow_duplicate_nodes, which hands each revisit its own marker (occurrence-qualified ids the caller's callbacks never see, so both markers draw as the same node). The walk is acyclic again, spreads evenly, and reads in the order it was heard. Relays shared *between* paths still merge — that fan is what the widget is for. Opt-in, because the two situations want opposite things. The Trophy case scores a path we composed, so collapsing a revisit is deliberate there — re-walking a node must not make the shape look bigger than the ground it covered. An overheard chain has no such duty: nothing in it is ours to inflate, and a repeat is evidence. Evidence we cannot read, though — hops are addressed by a one-byte hash, so a repeat is as likely two colliding nodes as a genuine loop. The packet card and the Message paths dialog now say exactly that under the via row and the graph, naming the repeated hops through the shared path widget. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/ui/message_paths_screen.py | 22 +++++- meshterm/ui/packet_viewer.py | 20 ++++- meshterm/ui/pathgraph.py | 101 ++++++++++++++++++++++++ meshterm/ui/records_screen.py | 12 ++- meshterm/ui/widgets.py | 50 ++++++++++++ tests/test_message_paths_screen.py | 25 ++++++ tests/test_packet_viewer.py | 26 +++++++ tests/test_pathgraph.py | 115 ++++++++++++++++++++++++++++ tests/test_widgets.py | 26 ++++++- 9 files changed, 391 insertions(+), 6 deletions(-) diff --git a/meshterm/ui/message_paths_screen.py b/meshterm/ui/message_paths_screen.py index ca4d5f6..2e3e5b6 100644 --- a/meshterm/ui/message_paths_screen.py +++ b/meshterm/ui/message_paths_screen.py @@ -39,7 +39,7 @@ from rich.text import Text from ..core.models import ChatMessage from ..services.message_paths import Arrival -from .pathgraph import PathLayer, render_path_graph +from .pathgraph import PathLayer, render_path_graph, revisited_hops from .pathline import path_line from .theme import snr_style from .tui.render import crop_cells, render_to_ansi @@ -49,6 +49,7 @@ from .widgets import ( NodeResolver, TypeOf, node_type_legend, + revisit_note, route_graph_style, ) @@ -199,6 +200,7 @@ class MessagePathsScreen(Screen): style="faint") lines.append(render_to_ansi(caption, width, no_wrap=True)) lines.append(render_to_ansi(node_type_legend(), width, no_wrap=True)) + lines.extend(self._revisit_line(width)) lines.append("") for i, arrival in enumerate(self._arrivals): if i == self._index: @@ -320,4 +322,22 @@ class MessagePathsScreen(Screen): return render_path_graph( layers, width, glyph_of=glyph_of, label_of=label_of, label_rgb_of=label_rgb_of, + allow_duplicate_nodes=True, ) + + def _revisit_line(self, width: int) -> list[str]: + """The ⚠ note when any drawn path touches one hop twice, else no line at all. + + These paths are *overheard*, not composed: a repeated hop is real evidence, so the graph + draws each visit its own marker (``allow_duplicate_nodes``) rather than folding the walk + into a cycle it cannot seat. That leaves one name on two markers, which this explains — + once for the whole fan, naming every hop repeated anywhere in it, since the note belongs + to the picture rather than to whichever arrival ↑↓ happen to be resting on. + """ + repeated: list[str] = [] + for path in self._paths(): + for hop in revisited_hops(path): + if hop not in repeated: + repeated.append(hop) + note = revisit_note(repeated, self._resolve, self_name=self._self_name) + return [] if note is None else [render_to_ansi(note, width, no_wrap=True)] diff --git a/meshterm/ui/packet_viewer.py b/meshterm/ui/packet_viewer.py index a882762..a261725 100644 --- a/meshterm/ui/packet_viewer.py +++ b/meshterm/ui/packet_viewer.py @@ -40,7 +40,7 @@ from ..core.channels import decrypt_channel_text from ..core.models import NODE_TYPE_LABELS, Observation from ..services.trace_runner import NodeResolver from .map_render import _SELF, _UNKNOWN -from .pathgraph import PathLayer, render_path_graph +from .pathgraph import PathLayer, render_path_graph, revisited_hops from .pathline import PathLine, path_line from .theme import name_style, snr_style from .trace_screen import snr_bar @@ -55,6 +55,7 @@ from .widgets import ( format_ago, highlighted_hash, node_type_legend, + revisit_note, route_graph_style, ) @@ -573,6 +574,14 @@ class PacketViewer(Screen): (an advert's ``adv_key``; other classes arrive origin-less, drawn ``?``), the right endpoint always us — the same layered route-graph widget the Message paths dialog and the Trophy case draw, in a single white path. + + Drawn with ``allow_duplicate_nodes``, because this chain is *observed*: we did not + compose it, its hops are named by a one-byte hash, and a repeat among them is as likely + two colliding nodes as a genuine loop. Folding such a repeat into one marker would make + a cycle the left-to-right flow cannot seat — the walk collapses into a pile of markers + one column wide — so each visit takes its own marker and the chain draws in the order it + was heard. The ``via`` row's :func:`~meshterm.ui.widgets.revisit_note` says why a name + appears twice. """ if entry.kind != "packet": return [] @@ -587,6 +596,7 @@ class PacketViewer(Screen): return render_path_graph( [PathLayer(hops=hops, color=_ROUTE_EDGE, priority=3)], width, glyph_of=glyph_of, label_of=label_of, label_rgb_of=label_rgb_of, + allow_duplicate_nodes=True, ) def _graph_source(self, entry: PacketEntry) -> Optional[str]: @@ -646,6 +656,14 @@ class PacketViewer(Screen): "", Text("reception describes the last relay, not the origin", style="faint"), )) + # A chain that names one hop twice reads as a mistake until it is explained; the graph + # below draws that hop twice too (see ``_graph_lines``), so the note covers both. + revisits = revisit_note( + revisited_hops([hop for hop in (entry.path or "").split(",") if hop]), + self._resolve, prefix_bytes=self._prefix_bytes, self_name=self._self_name, + ) + if revisits is not None: + rows.append(("", revisits)) if typename == "GRP_TXT": rows.extend(self._decrypt_rows(raw)) return rows diff --git a/meshterm/ui/pathgraph.py b/meshterm/ui/pathgraph.py index bfecb4d..775fc2f 100644 --- a/meshterm/ui/pathgraph.py +++ b/meshterm/ui/pathgraph.py @@ -47,6 +47,19 @@ over and then settles. Concretely: marker sits on its highest-priority path's lane, and a lower path that also rides it leans off its lane to meet the marker and back — which reads as the alternative *branching through the shared node*, exactly the story the evidence tells; +* **revisits** — that merge is right *across* paths (two routes rode one relay) and wrong + *within* one: a single walk that touches the same hop twice is not a node two routes share, + it is a **cycle**, and a left-to-right flow has nowhere to seat one. Ranked over the cyclic + edge set the balanced-x relaxation never settles, so the loop's members land in near-identical + columns — markers piled a cell apart, labels colliding, the back-edge dropping as a bare + vertical — while the relays outside it are squashed against the ends. ``allow_duplicate_nodes`` + hands each revisit its own marker instead (see :func:`_split_revisits`), which keeps the flow + acyclic and draws the walk in its true order; the cost is that one node *may* appear twice, + so a caller that turns it on should say so on the surface (:func:`~meshterm.ui.widgets. + revisit_note`). It is opt-in because the choice is a caller's to make: a path we *composed* + (the Trophy case's scored walk) collapses a revisit deliberately, while an **observed** via + chain — hops named by a one-byte hash, where a repeat is as likely two colliding nodes as a + genuine loop — must be drawn as heard; * **detours** — a route heard as a sibling route *plus* an inserted relay is that sibling with a detour, and the whole fan is measured against the row budget *before* its shape is committed: while the rows allow, the detour **nests** — its inserted relay takes the lane @@ -93,6 +106,12 @@ from .mapcanvas import RGB, MapCanvas, parse_hex SRC_NODE = "\x00src" DST_NODE = "\x00dst" +#: Joins a hop id to its occurrence index when ``allow_duplicate_nodes`` splits a path's +#: revisits into their own markers. Leans on the same guarantee the endpoint sentinels do — +#: NUL never appears in a hex hop id — so a qualified id can never collide with a real one, +#: and :func:`_base_node` maps it back before any caller callback ever sees it. +_OCCURRENCE_SEP = "\x00#" + #: Text rows between adjacent lane markers — the pitch one lane maps to. At the default there #: are two blank rows padding each gap (room for a lane's label and its neighbour's), and an #: *even* lane count opens one extra row between the two central lanes so the endpoints land on @@ -326,6 +345,73 @@ def _is_hex(value: str) -> bool: return bool(value) and all(char in _HEX_DIGITS for char in value) +def revisited_hops(hops: Sequence[str]) -> tuple[str, ...]: + """The hops one path touches more than once, in first-appearance order. + + The test a caller applies before deciding to draw with ``allow_duplicate_nodes`` — and the + hops it then names in its warning (:func:`~meshterm.ui.widgets.revisit_note`), since a + graph drawing one node twice owes the reader that much. Judged on the ids as given: at the + one-byte width an observed via chain addresses its hops by, a repeat is as likely two + different nodes colliding on a hash byte as a packet genuinely walking a loop, and neither + the path nor this widget can tell them apart — which is exactly what the warning says. + """ + counts: dict[str, int] = {} + for hop in hops: + if hop: + counts[hop] = counts.get(hop, 0) + 1 + return tuple(hop for hop, seen in counts.items() if seen > 1) + + +def _split_revisits(layers: Sequence[PathLayer]) -> list[PathLayer]: + """Give every revisit *within* a path its own node id, so no walk folds into a cycle. + + The k-th occurrence of a hop in one layer becomes ``hop\\x00#k`` (the first keeps the bare + id), which leaves the flow acyclic and lets the balanced rank spread the walk evenly again. + Counting runs per layer but the qualifier is positional, so occurrence *k* of a hop means the + same id in every layer that reaches that far: two routes riding one relay once still merge on + the bare id — the diverge/converge story the widget exists to tell survives untouched, and + only a genuine within-path repeat splits. + """ + split: list[PathLayer] = [] + for layer in layers: + seen: dict[str, int] = {} + hops: list[str] = [] + for hop in layer.hops: + nth = seen.get(hop, 0) + seen[hop] = nth + 1 + hops.append(hop if nth == 0 else f"{hop}{_OCCURRENCE_SEP}{nth}") + split.append(PathLayer(tuple(hops), layer.color, layer.priority, layer.emphasis)) + return split + + +def _base_node(node: str) -> str: + """An occurrence-qualified internal id back to the caller's own node id (else unchanged).""" + return node.split(_OCCURRENCE_SEP, 1)[0] + + +def _unqualified( + glyph_of: GlyphOf, label_of: LabelOf, label_rgb_of: LabelRgbOf +) -> tuple[GlyphOf, LabelOf, LabelRgbOf]: + """Wrap the per-node callbacks so a split revisit reaches them as the node it really is. + + Occurrence qualifiers are the widget's private bookkeeping: a caller supplies callbacks keyed + on its own hop ids and gets back a marker, a label and a hue per *node*, so both markers of a + revisited hop draw identically — the same glyph, the same name, the same colour — and the + picture says "here twice" rather than inventing a second identity. + """ + + def glyph(node: str) -> tuple[str, str]: + return glyph_of(_base_node(node)) + + def label(node: str) -> Optional[str]: + return label_of(_base_node(node)) + + def label_rgb(node: str) -> RGB: + return label_rgb_of(_base_node(node)) + + return glyph, label, label_rgb + + def _draw_rank(layer: PathLayer) -> int: """A layer's edge draw rank: emphasis dominates, layout priority breaks ties. @@ -347,6 +433,7 @@ def render_path_graph( min_rows: int = 5, max_rows: int = 15, lane_pitch: int = _LANE_PITCH_ROWS, + allow_duplicate_nodes: bool = False, ) -> list[str]: """Draw the diverge/converge route-flow graph and return its ANSI lines. @@ -370,6 +457,14 @@ def render_path_graph( so the endpoints land on an exact centred row. The row budget compresses the pitch when there are many lanes, and never stretches it when there are few. Defaults to :data:`_LANE_PITCH_ROWS`. + allow_duplicate_nodes: Draw a hop a path touches *twice* as two markers rather than + folding it into one. Off by default, because folding is right for a path the caller + composed. Turn it on for an **observed** walk, where the fold would make a cycle the + left-to-right flow cannot seat and the layout collapses (see the module docstring): + the walk then draws in its true order, at the cost of one node possibly appearing + twice — which the caller should flag on the surface (:func:`~meshterm.ui.widgets. + revisit_note`, over :func:`revisited_hops`). Relays shared *between* paths merge + either way. Returns: One ANSI string per canvas row (empty when there are no layers to draw). @@ -378,6 +473,12 @@ def render_path_graph( return [] drawn = _collapse(_coalesce_prefixes(layers)) + if allow_duplicate_nodes: + # After the prefix/identical folds, so a revisit is counted over the ids actually drawn: + # a hop that only *looks* repeated at two hash widths coalesces to one id first, and is + # then correctly seen as the single visit it is. + drawn = _split_revisits(drawn) + glyph_of, label_of, label_rgb_of = _unqualified(glyph_of, label_of, label_rgb_of) seqs = [(SRC_NODE, *layer.hops, DST_NODE) for layer in drawn] # First-appearance order for every node, so the layout is identical on every repaint: a diff --git a/meshterm/ui/records_screen.py b/meshterm/ui/records_screen.py index b3be13e..447f8be 100644 --- a/meshterm/ui/records_screen.py +++ b/meshterm/ui/records_screen.py @@ -226,9 +226,15 @@ class RecordDialog(Screen): (:func:`~meshterm.ui.pathgraph.render_path_graph`), the same shape the Message paths dialog draws a delivery over. Relays wear their own map marker (``▲`` repeater, …) where the type is known. Nodes the walk passed through more than once - — a boomerang's mirrored return leg — collapse to their first appearance: the - layered graph can only seat a node once, and the route line below still - carries every hop, revisits and all. + — a boomerang's mirrored return leg — collapse to their first appearance, and the + route line below still carries every hop, revisits and all. + + That collapse is a *deliberate* choice here, not the widget's limit: a graph can draw + each visit its own marker (``allow_duplicate_nodes``, which the observed-packet surfaces + turn on), and this one declines. A trophy record scores a path **we composed**, so + re-walking one node must never make the shape look bigger than the ground it covered — + one node, one marker, whatever the spec asked for. An overheard via chain has the + opposite duty: nothing there is ours to inflate, and a repeat is evidence. """ seen: set[str] = set() hops: list[str] = [] diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index 2840981..bccdcee 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -317,6 +317,56 @@ def path_text( return text +def revisit_note( + repeats: Sequence[str], + resolve: NodeResolver = _identity, + *, + prefix_bytes: int = 0, + self_name: Optional[str] = None, +) -> Optional[Text]: + """The warning a path that touches one hop twice owes its reader, or ``None`` for none. + + A route graph drawn with ``allow_duplicate_nodes`` + (:func:`~meshterm.ui.pathgraph.render_path_graph`) plants two markers carrying the same + name, and the ``via`` row above it names the same node twice — both honest, both confusing + left unexplained. This is the one line that explains them, and it refuses to pick between the + two readings, because nothing in the packet can: an observed chain addresses its hops by a + hash a single byte wide, so a repeat is as easily two different nodes colliding on that byte + as one node the packet genuinely passed twice. It names the repeated hops through THE path + widget (:func:`path_text`), so each reads in its own name hue exactly as it does in the + ``via`` row the reader is comparing against. + + Takes the repeated hops rather than the path itself, so the caller decides what "repeated" + means for its surface: one path asks :func:`~meshterm.ui.pathgraph.revisited_hops`, while a + surface drawing a *fan* of paths must union each path's own revisits — a hop two different + routes share is not a revisit at all, and pooling their hops would libel it as one. + + Args: + repeats: The hops to warn about, already known repeated (empty = no warning). + resolve: Maps a hop hash to a friendly name when known. + prefix_bytes: Path-hash width to light in an unnamed hop's hash (0 = none). + self_name: Our own node's name, so a repeat of *us* draws in the white ``you`` style. + + Returns: + A one-line :class:`Text` fitting 72 cells for the paths a radio really carries, or + ``None`` when ``repeats`` is empty and there is nothing to warn about. + """ + if not repeats: + return None + # The mark carries its own span rather than riding the Text's base style, so nothing that + # follows can inherit ``warn`` — the names keep their node hues and the prose stays muted. + note = Text() + note.append("⚠ ", style="warn") + for i, hop in enumerate(repeats): + if i: + note.append(", ", style="muted") + note.append_text( + path_text([hop], resolve, prefix_bytes=prefix_bytes, self_name=self_name) + ) + note.append(" repeats — a loop, or two nodes sharing one hash", style="muted") + return note + + def _path_node( hop: Optional[str], resolve: NodeResolver, diff --git a/tests/test_message_paths_screen.py b/tests/test_message_paths_screen.py index c5d6ab1..24ea09d 100644 --- a/tests/test_message_paths_screen.py +++ b/tests/test_message_paths_screen.py @@ -60,6 +60,31 @@ def test_paths_screen_renders_graph_rows_and_cursor() -> None: assert screen.cursor_line() is not None +def test_paths_screen_warns_once_for_a_path_that_revisits_a_hop() -> None: + """A path touching one hop twice draws it twice, warned about once for the whole fan. + + The note belongs to the picture, not to the arrival ↑↓ rest on, so it names every hop + repeated anywhere in the fan and says so a single time under the legend. + """ + now = utcnow() + screen = _screen([ + Arrival(when=now, hops=("3d63", "a1b2", "77aa", "3d63"), snr=4.0), + Arrival(when=now + timedelta(seconds=2), hops=("a1b2",), snr=-2.0), + ]) + body = _plain(screen.render_body(76)) + assert body.count("⚠") == 1 + assert "YUL-Cartierville repeats — a loop, or two nodes sharing one hash" in body + graph = body.split("origin →")[0] + assert graph.count("3d") == 2 # both visits marked + assert graph.count("a1") == 1 # the relay the two paths *share* stays one marker + + +def test_paths_screen_stays_quiet_when_no_path_revisits() -> None: + """Two paths crossing the same relay is sharing, not revisiting — nothing to warn about.""" + body = _plain(_screen(_arrivals()).render_body(76)) + assert "⚠" not in body + + def test_paths_screen_labels_every_relay_with_its_hash_byte() -> None: """Graph relays carry their first hash byte, both paths at once; the rows carry the names alone — no hash repeated after one, the two tied together by the node's hue.""" diff --git a/tests/test_packet_viewer.py b/tests/test_packet_viewer.py index ce50311..d7debee 100644 --- a/tests/test_packet_viewer.py +++ b/tests/test_packet_viewer.py @@ -176,6 +176,32 @@ def test_packet_viewer_draws_a_relayed_packets_route_graph() -> None: assert "3d" in body and "a1" in body # each relay labelled by its hash byte +def test_packet_viewer_draws_a_revisited_hop_twice_and_warns() -> None: + """An overheard chain naming one hop twice draws it twice, and says why it did. + + Folded to a single marker the walk would close a cycle the left-to-right flow cannot seat, + and the whole graph collapses into a pile one column wide. So the packet card splits the + revisit — and owes the reader the warning, because nothing in a one-byte hash can say + whether the repeat is a genuine loop or two different nodes colliding on that byte. + """ + names = {"c1": "C14903", "8e": "MileEnd", "da": "Relais", "ee": "ParcEx"} + entry = PacketEntry(when=utcnow(), kind="packet", path="7f,c1,8e,da,ee,c1,27") + body = _plain( + PacketViewer([entry], 0, resolve=lambda h: names.get(h, "")).render_body(80) + ) + assert "⚠" in body and "repeats" in body + assert "a loop, or two nodes sharing one hash" in body + assert body.count("C14903") == 3 # twice in the via row, once named in the warning + assert body.count("c1") == 2 # and both visits carry a marker label in the graph + + +def test_packet_viewer_stays_quiet_when_every_hop_is_distinct() -> None: + """The revisit warning is not chrome: a normal relayed packet never shows it.""" + entry = PacketEntry(when=utcnow(), kind="packet", path="3d63,a1b2") + body = _plain(_viewer(entry).render_body(80)) + assert "⚠" not in body and "repeats" not in body + + def test_packet_viewer_skips_the_graph_for_a_direct_packet() -> None: """A packet with no relays says so in the via row and draws no (pointless) two-node graph.""" entry = PacketEntry(when=utcnow(), kind="packet", path="") diff --git a/tests/test_pathgraph.py b/tests/test_pathgraph.py index b2e08e9..3340edf 100644 --- a/tests/test_pathgraph.py +++ b/tests/test_pathgraph.py @@ -11,15 +11,19 @@ from meshterm.ui.pathgraph import ( SRC_NODE, _GRAPH_PAD_DOTS, _LANE_PITCH_ROWS, + _OCCURRENCE_SEP, PathLayer, _assign_lanes, _balanced_x, + _base_node, _bypass_vias, _coalesce_prefixes, _collapse, _layout_lanes, _route, + _split_revisits, render_path_graph, + revisited_hops, ) _ANSI = re.compile(r"\x1b\[[0-9;]*m") @@ -160,6 +164,117 @@ def test_endpoint_labels_may_leave_the_marker_row() -> None: assert "…" not in plain +def test_revisited_hops_names_only_within_path_repeats() -> None: + """The detector reports a hop touched twice by *one* path, in first-appearance order.""" + assert revisited_hops(("7f", "c1", "8e", "da", "ee", "c1", "27")) == ("c1",) + assert revisited_hops(("aa", "bb", "aa", "cc", "bb")) == ("aa", "bb") + assert revisited_hops(("aa", "bb", "cc")) == () + assert revisited_hops(()) == () + + +def test_revisited_path_folds_into_a_cycle_that_piles_its_relays() -> None: + """Why the flag exists: folded, a revisit makes a cycle the balanced rank cannot settle. + + ``c1`` twice closes a loop over ``8e``/``da``/``ee``. Ranked over that cyclic edge set the + longest-path relaxation never reaches a fixed point, so the loop's members land within a + hair of each other — one column of piled markers — while the relays outside it are squashed + against the two ends. This pins the broken behaviour the flag is the escape from. + + Thresholds are loose because the folded numbers are not even *stable*: the relaxation + iterates an edge **set**, which on an acyclic graph reaches the same fixed point whatever + the order and on this cycle simply stops wherever the sweep budget ran out. So the pile's + column swings with the interpreter's hash seed — the very frame-to-frame jumping the + first-appearance node order exists to prevent. What every seed agrees on is the shape + asserted here, and splitting the revisit is what restores the fixed point (see + :func:`test_allow_duplicate_nodes_keeps_x_strictly_rising_along_the_walk`). + """ + hops = ("7f", "c1", "8e", "da", "ee", "c1", "27") + seq = (SRC_NODE, *hops, DST_NODE) + ordered = list(dict.fromkeys(seq)) + x = _balanced_x(ordered, set(zip(seq, seq[1:]))) + # Evenly spread, these eight nodes would sit 1/7 apart and the four loop members would + # span three of those gaps; folded, the whole loop fits inside a single one. + loop = [x[node] for node in ("c1", "8e", "da", "ee")] + assert max(loop) - min(loop) < 1 / 7 + assert x["7f"] < 0.15 and x["27"] > 0.85 # its neighbours crushed against the ends + + +def test_allow_duplicate_nodes_keeps_x_strictly_rising_along_the_walk() -> None: + """Split, the rank regains the fixed point — and with it the widget's ordering invariant. + + ``_balanced_x`` promises the fraction rises strictly along every path, so edges only ever + run left to right. A folded revisit breaks that (the cycle leaves the relaxation short of + convergence, and even puts us at a lower rank than the hop before us); splitting restores + it, which is also what makes the layout reproducible between repaints. + """ + hops = ("7f", "c1", "8e", "da", "ee", "c1", "27") + [layer] = _split_revisits([PathLayer(hops, WHITE, 3)]) + seq = (SRC_NODE, *layer.hops, DST_NODE) + ordered = list(dict.fromkeys(seq)) + x = _balanced_x(ordered, set(zip(seq, seq[1:]))) + walked = [x[node] for node in seq] + assert walked == sorted(walked) and len(set(walked)) == len(walked) + assert x[SRC_NODE] == 0.0 and x[DST_NODE] == 1.0 + # A single walk with nothing else to balance against spreads dead evenly end to end. + gaps = [b - a for a, b in zip(walked, walked[1:])] + assert max(gaps) - min(gaps) < 1e-9 + + +def test_allow_duplicate_nodes_spreads_a_revisited_path_evenly() -> None: + """Split, the same walk is an acyclic run again: every hop its own evenly-spaced column.""" + hops = ("7f", "c1", "8e", "da", "ee", "c1", "27") + layers = [PathLayer(hops, WHITE, 3)] + plain = _ANSI.sub("", "\n".join(_render(layers))) + split = _ANSI.sub( + "", + "\n".join( + render_path_graph( + layers, 60, glyph_of=_glyph, + label_of=lambda node: "you" if node in (SRC_NODE, DST_NODE) else node[:2], + label_rgb_of=lambda _node: WHITE, + allow_duplicate_nodes=True, + ) + ), + ) + # Both visits of c1 draw their own marker, labelled identically — the node, twice. + assert split.count("c1") == 2 + # Every other hop keeps exactly one marker: only the genuine revisit split. + for hop in ("7f", "8e", "da", "ee", "27"): + assert split.count(hop) == 1 + # Folded, that second marker does not exist — and the pile is tight enough that the label + # placer sometimes cannot seat even the first one, so this is an at-most, not an exactly. + assert plain.count("c1") <= 1 + + +def test_allow_duplicate_nodes_still_merges_a_relay_two_paths_share() -> None: + """Splitting is *within* a path only: the diverge/converge story survives untouched. + + Two routes riding one relay is the merge the widget exists for, and the flag must not + break it — ``zz`` stays a single marker both lanes pass through. + """ + layers = [PathLayer(("aa", "zz"), WHITE, 4), PathLayer(("bb", "zz"), GREY, 2)] + plain = _ANSI.sub( + "", + "\n".join( + render_path_graph( + layers, 60, glyph_of=_glyph, label_of=lambda node: node[:2], + label_rgb_of=lambda _node: WHITE, allow_duplicate_nodes=True, + ) + ), + ) + assert plain.count("zz") == 1 + + +def test_split_revisits_qualifies_only_the_later_visits() -> None: + """The first visit keeps the caller's bare id; later ones take a private qualifier.""" + [layer] = _split_revisits([PathLayer(("aa", "bb", "aa", "bb", "aa"), WHITE, 3)]) + assert layer.hops == ("aa", "bb", f"aa{_OCCURRENCE_SEP}1", f"bb{_OCCURRENCE_SEP}1", + f"aa{_OCCURRENCE_SEP}2") + assert layer.color == WHITE and layer.priority == 3 + # Every qualified id maps back to the node the caller named it by. + assert [_base_node(hop) for hop in layer.hops] == ["aa", "bb", "aa", "bb", "aa"] + + def test_prefix_dupe_relay_folds_onto_its_only_wide_match() -> None: """A 1-byte hop beside the same node's wide id, across layers, becomes one node.""" layers = [ diff --git a/tests/test_widgets.py b/tests/test_widgets.py index 5d6560e..fbeeaf3 100644 --- a/tests/test_widgets.py +++ b/tests/test_widgets.py @@ -7,7 +7,7 @@ and every caller inherits it. from __future__ import annotations -from meshterm.ui.widgets import _format_age, format_ago, path_text +from meshterm.ui.widgets import _format_age, format_ago, path_text, revisit_note def test_format_age_is_the_bare_column_form() -> None: @@ -162,3 +162,27 @@ def test_route_graph_source_label_takes_its_resolved_keys_hue() -> None: resolve=lambda h: h, self_name="us", source="Alice", ) assert rgb_unknown(SRC_NODE) == (148, 163, 184) # unresolvable origin stays muted + + +def test_revisit_note_names_the_repeats_and_refuses_to_guess_why() -> None: + """The one line a graph drawing a node twice owes its reader — both readings, neither picked.""" + note = revisit_note(["aa"], _resolve) + assert note is not None + assert note.plain == "⚠ Alice repeats — a loop, or two nodes sharing one hash" + styles = {note.plain[s.start : s.end]: str(s.style) for s in note.spans} + assert styles.get("⚠ ") == "warn" # the app's warn mark, themed + assert styles.get("Alice") not in (None, "warn") # the name keeps its own node hue + + +def test_revisit_note_lists_every_repeated_hop() -> None: + """More than one hop repeated names them all, comma-joined, still one sentence.""" + note = revisit_note(["aa", "3d"], _resolve) + assert note is not None + assert note.plain.startswith("⚠ Alice, YUL repeats — ") + assert len(note.plain) <= 72 # the footer/row budget every surface renders it inside + + +def test_revisit_note_is_absent_when_nothing_repeats() -> None: + """No repeats, no line — the warning is evidence, never chrome.""" + assert revisit_note([], _resolve) is None + assert revisit_note(()) is None