From 5dc62cdc5b39a271a2c3a799464fe8e1797328ce Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 20 Nov 2026 21:21:11 -0500 Subject: [PATCH] Relay marks count every repeater; near relays are gone The first build counted only the relays past the first hops of the outbound paths. On JP's Public channel, 23 of 23 sent messages came back only through the two home repeaters: each repeater relays one time, and the next hop (8 km away) is too far for the companion to hear. So every message showed the warning mark, and nothing was ever confirmed. Now each repeater that sends a copy back counts, the same as a DM ack: spinner, then a check with the number of repeaters, or a cross. The warning state, the near-relay snapshot of each send, the ^P atom, and heard_via are removed. heard_relays keeps only the paths; a database with the first build of the table gets it made again (derived data only). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 25 ++--- docs/cli/README.md | 20 ++-- docs/development/writing-style.md | 1 - docs/guide/features.md | 2 +- meshterm/core/preferences.py | 8 +- meshterm/persistence/db.py | 22 ++-- meshterm/persistence/repository.py | 54 +++------- meshterm/services/chat_service.py | 11 -- meshterm/services/heard_by.py | 156 ++++++++--------------------- meshterm/tools/chat.py | 25 ++--- meshterm/ui/chat.py | 64 +++--------- tests/test_gallery.py | 32 ++---- tests/test_heard_by.py | 123 ++++++++--------------- 13 files changed, 164 insertions(+), 379 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 943e790..0a4ee7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,22 +11,15 @@ can change how things behave. It does not only add new things. ### Added -- **A channel message that you send shows whether it went past your own repeaters.** A - channel has no acknowledgement, but your radio hears each repeater that relays your - message, and each copy names the relays that it went through. The end of your message - shows a spinner, then `✓` and the number of relays that heard it past your **near - relays**. Your near relays are the first hops of the outbound paths of your active site. - At home, a relay by the repeater next to you proves only that the message left your - radio. `⚠` means that only your near relays sent it back, and `✗` means that no relay - sent it back. A copy that comes late changes the mark. Select the message to see the - names of the relays, and which of your near relays carried it out. The wait is the new - *Relay wait* preference (`heard_wait_s`, 30 s). With no outbound paths, each relay - counts. MeshTerm sees only the relays that your radio hears, and only while it is - connected. `meshterm chat history --channel` shows the same verdict in a `HEARD` column, - and `--json` gives `heard`, `heard_by`, and `heard_via` (#38). -- **^P on your own channel message counts the relays past your near relays.** The line - under the quote of the message adds `3 past your near relays` to the copies and paths - that it already counted. +- **A channel message that you send shows whether a repeater relayed it.** A channel has + no acknowledgement, but your radio hears each repeater that relays your message. The + end of your message shows a spinner, then `✓` and the number of repeaters that sent a + copy back, or `✗` when none did. A copy that comes late changes the mark, the same as a + late acknowledgement of a direct message. Select the message to see the names of the + repeaters. The wait is the new *Relay wait* preference (`heard_wait_s`, 30 s). MeshTerm + sees only the repeaters that your radio hears, and only while it is connected. + `meshterm chat history --channel` shows the same count in a `HEARD` column, and + `--json` gives `heard` and `heard_by` (#38). ### Fixed diff --git a/docs/cli/README.md b/docs/cli/README.md index a71a705..832913e 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -1153,18 +1153,15 @@ channel has a `HEARD` column for each of your own messages: $ meshterm chat history --channel 0 TIME DIR PEER SNR_DB HEARD TEXT 12m in Public +6.5 - Alice: anyone on the ridge? - 10m out Public - 3 heading up now - 4m out Public - near at the top + 10m out Public - 2 heading up now + 4m out Public - none at the top now out Public - wait coming down ``` -A number is the count of relays past your **near relays**: the first hop of each outbound -path of the active site, or of the fixed device (refer to `meshterm outbound`). These -relays heard your message, so it went farther than the repeaters next to you. `near` -means that only your near relays sent it back. `none` means that no relay sent it back. -`wait` means that the message is still in its wait (the `heard_wait_s` preference). With -no outbound paths, each relay counts. MeshTerm sees only the relays that your radio hears, -and only while it is connected. A received message has no value (`-`). +A number is the count of repeaters that sent a copy back. `none` means that no repeater +sent it back. `wait` means that the message is still in its wait (the `heard_wait_s` +preference). MeshTerm sees only the relays that your radio hears, and only while it is +connected. A received message has no value (`-`). **Rooms.** A room server is a message board that lives on a radio. First, join the room with [`meshterm rooms join`](#meshterm-rooms). After that, post with `send --to`, in the @@ -1244,9 +1241,8 @@ the purpose of the one absence token. It is also the reason why the plain face p nothing there: it has no way to say it. `history` is an array, with the oldest message first. Each record also has `heard` -(`"waiting"`, `"beyond"`, `"nearby"`, `"unheard"`, or `null` when the message is not -your own channel message), `heard_by` (the hashes of the relays past your near relays), -and `heard_via` (the near relays that carried the message out): +(`"waiting"`, `"heard"`, `"unheard"`, or `null` when the message is not your own channel +message) and `heard_by` (the hashes of the repeaters that sent a copy back): ```json {"created_at":"2026-09-08T08:27:37Z","direction":"out","node":{"name":"Alice","key":null,"hash":"d4e5f6a7","type":null,"self":false},"channel":null,"author":null,"snr_db":null,"text":"on my way","acked":true} diff --git a/docs/development/writing-style.md b/docs/development/writing-style.md index 0f83d9f..54db11b 100644 --- a/docs/development/writing-style.md +++ b/docs/development/writing-style.md @@ -183,7 +183,6 @@ and in quoted text. | path | An ordered list of hops that you write or force (`a1,3d,…`) | | | route | The sequence of nodes that a trace went through or will go through | | | hop | One node in a path or a route | | -| near relay | The first hop of an outbound path that applies now. A copy of our channel message that only near relays sent back proves that the message left our radio, not that it went farther | own repeater, home repeater, local relay | | outbound path | A path that starts at our node and goes out into the mesh, one or more hops long. The user trusts it for the first hops of a route, because the user knows which way out works | outbound leg (for this: an outbound leg is the outbound half of a trace) | | site | A name for where the user takes the computer (`Home`, `Foulab`), with its outbound paths in order. One site is active | profile (for this: a profile is a connection alias in `config.toml`) | | fixed device | A companion that never moves. It keeps its own outbound paths, and the active site does not apply to it | | diff --git a/docs/guide/features.md b/docs/guide/features.md index 6bda522..e95275b 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -15,7 +15,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **💬 Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Your own channel message shows whether it went past your near relays (the first hops of your outbound paths): a spinner, then `✓` and the number of relays that heard it, `⚠` when only your near relays sent it back, or `✗` when no relay did. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` | +| **💬 Chat** | Live full-screen messages on channels and to contacts. The transcript scrolls, the input line stays at the bottom, and sent and received messages appear together. The rooms that you joined are also here. Each post shows under the name of its author. MeshTerm stores each message. Unread counts show in the menu header. To see each path on which a message reached your node, select the message and press ^P. Your own channel message shows whether a repeater relayed it: a spinner, then `✓` and the number of repeaters that sent a copy back, or `✗` when none did. Enter on a path opens a trace of that route: back to the sender of a received message, or out to the contact of a sent direct message. When the trace comes home, the Device route row can make that route the radio's route to the contact. | `meshterm chat send / history / list / listen` | | **📻 Channels** | Create, join, reorder, mute, and share mesh channels. You can share a channel with a QR code or a `meshcore://` link. If you give a channel a **send scope**, its messages are flooded into one region. Only the repeaters that carry that region relay them. When you change to a new device, export all the channels to a file, then import the file on the new device. The **channel guide** lists the public channels that MeshTerm heard, also the channels that are not on your device, and adds one with Enter. | `meshterm channels list / add / join / import / share / clear / scope / export / guide` | | **📌 Rooms** | Each room server that your radio knows. A room server is a message board on a radio. It keeps the latest posts and sends you the posts that you missed. Join a room with its password. If a room does not answer, MeshTerm tells you what it knows and offers the next step to try. For example, it can send again by flood when the route that your radio learned is no longer good. When the clock of a room goes back (often after a reboot), the room sends you no new post, because each new post looks older than the ones that you have. The node page of the room then says so and offers to ask for all its posts again. | `meshterm rooms list / join / forget` | | **📨 Courier** | A store-and-forward outbox for contacts that you cannot reach yet. Queue a message. MeshTerm sends it when the contact is next heard, or at a time that you set. It tracks the acks, and it waits longer between each try (exponential backoff). | `meshterm courier queue / list / send / cancel / clear` | diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 0c61c23..b8436ac 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -332,10 +332,10 @@ PREFERENCES: tuple[PrefSpec, ...] = ( help="Wait this long for a relay of a channel message", group="Sending", value_type="int", - # A channel message that we sent shows a spinner until a relay that is not a near - # relay sends a copy back, or until this wait is over. Then it shows ⚠ (only near - # relays) or ✗ (no copy). A flood goes out through the mesh in seconds, and 30 s - # also covers a busy channel (refer to meshterm.services.heard_by). + # A channel message that we sent shows a spinner until a repeater sends a copy + # back, or until this wait is over. Then it shows ✗ (no copy). A repeater relays + # in seconds, and 30 s also covers a busy channel (refer to + # meshterm.services.heard_by). default=30, minimum=5, maximum=600, diff --git a/meshterm/persistence/db.py b/meshterm/persistence/db.py index afc5cc4..3e139f2 100644 --- a/meshterm/persistence/db.py +++ b/meshterm/persistence/db.py @@ -189,15 +189,12 @@ CREATE TABLE IF NOT EXISTS node_places ( found_at TEXT NOT NULL -- UTC ISO-8601 ); --- Our own channel messages: whether a relay that is not one of our near relays heard them --- (refer to meshterm.services.heard_by). near_hops is a JSON list of the near relays at the --- time of the send. paths is a JSON list of the relay paths of the copies that came back, --- written one time when the message is out of the match window of the packet log. NULL: --- not settled yet. +-- Our own channel messages: the relays that sent a copy back (refer to +-- meshterm.services.heard_by). paths is a JSON list of the relay paths of the copies, +-- written one time when the message is out of the match window of the packet log. CREATE TABLE IF NOT EXISTS heard_relays ( message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE, - near_hops TEXT, - paths TEXT + paths TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_traces_run ON traces(run_id); @@ -456,6 +453,17 @@ def _migrate(conn: sqlite3.Connection) -> None: "WHERE sent_at IS NOT NULL" ) + heard_cols = {row["name"] for row in conn.execute("PRAGMA table_info(heard_relays)")} + if "near_hops" in heard_cols: + # The first build of schema 24 kept the near relays of each send. They are gone + # (refer to meshterm.services.heard_by), and the table holds only derived data, + # so it is made again. The chat fills it again from the packet log. + conn.execute("DROP TABLE heard_relays") + conn.execute( + "CREATE TABLE heard_relays (message_id INTEGER PRIMARY KEY " + "REFERENCES messages(id) ON DELETE CASCADE, paths TEXT NOT NULL)" + ) + stored = conn.execute("SELECT value FROM schema_meta WHERE key = 'version'").fetchone() if stored is not None and int(stored["value"]) < 19: # v18 -> v19: no private key in the run log. `config import-key` stored its key as diff --git a/meshterm/persistence/repository.py b/meshterm/persistence/repository.py index 140badb..ac1c221 100644 --- a/meshterm/persistence/repository.py +++ b/meshterm/persistence/repository.py @@ -2254,72 +2254,44 @@ class Repository: # -- relays that heard our channel messages --------------------------------------- - def set_near_hops(self, message_id: int, near: tuple[str, ...]) -> None: - """Keep the near relays at the time that one of our channel messages went out. - - Thus a change of site later does not change the verdict of the message (refer to - :mod:`~meshterm.services.heard_by`). - - Args: - message_id: The ``messages`` row of the sent message. - near: The near relays, as lowercase hex. - """ - self._conn.execute( - "INSERT INTO heard_relays (message_id, near_hops) VALUES (?, ?) " - "ON CONFLICT(message_id) DO UPDATE SET near_hops = excluded.near_hops", - (message_id, json.dumps(list(near))), - ) - self._conn.commit() - - def settle_heard( - self, message_id: int, near: tuple[str, ...], paths: list[tuple[str, ...]] - ) -> None: + def settle_heard(self, message_id: int, paths: list[tuple[str, ...]]) -> None: """Store the relay paths of the copies of one message, when no more can come. + Refer to :mod:`~meshterm.services.heard_by`. + Args: message_id: The ``messages`` row of the sent message. - near: The near relays that the verdict used. paths: The relay paths of the copies that came back. An empty list is a stored "no copy came back". """ self._conn.execute( - "INSERT INTO heard_relays (message_id, near_hops, paths) VALUES (?, ?, ?) " - "ON CONFLICT(message_id) DO UPDATE SET near_hops = excluded.near_hops, " - "paths = excluded.paths", - (message_id, json.dumps(list(near)), json.dumps([list(p) for p in paths])), + "INSERT INTO heard_relays (message_id, paths) VALUES (?, ?) " + "ON CONFLICT(message_id) DO UPDATE SET paths = excluded.paths", + (message_id, json.dumps([list(p) for p in paths])), ) self._conn.commit() - def heard_records( - self, message_ids: list[int] - ) -> dict[int, tuple[tuple[str, ...] | None, list[tuple[str, ...]] | None]]: - """The stored near relays and relay paths of some of our channel messages. + def heard_records(self, message_ids: list[int]) -> dict[int, list[tuple[str, ...]]]: + """The stored relay paths of some of our channel messages. Args: message_ids: The ``messages`` rows to read. Returns: - For each row that has a record: the near relays (``None`` when they were not - kept), and the relay paths (``None`` when the message is not settled yet). + The relay paths of each row that is settled. A row that is not settled yet is + absent. """ - out: dict[int, tuple[tuple[str, ...] | None, list[tuple[str, ...]] | None]] = {} + out: dict[int, list[tuple[str, ...]]] = {} ids = [int(i) for i in message_ids if i is not None] for start in range(0, len(ids), 500): part = ids[start : start + 500] marks = ",".join("?" * len(part)) rows = self._conn.execute( - f"SELECT message_id, near_hops, paths FROM heard_relays " - f"WHERE message_id IN ({marks})", + f"SELECT message_id, paths FROM heard_relays WHERE message_id IN ({marks})", part, ).fetchall() for row in rows: - near = tuple(json.loads(row["near_hops"])) if row["near_hops"] else None - paths = ( - [tuple(p) for p in json.loads(row["paths"])] - if row["paths"] is not None - else None - ) - out[int(row["message_id"])] = (near, paths) + out[int(row["message_id"])] = [tuple(p) for p in json.loads(row["paths"])] return out def delete_chat_history(self, peer: str | None) -> int: diff --git a/meshterm/services/chat_service.py b/meshterm/services/chat_service.py index 678c4d9..be5423a 100644 --- a/meshterm/services/chat_service.py +++ b/meshterm/services/chat_service.py @@ -834,17 +834,6 @@ class ChatService: scope=await self._sent_under(asked), ) chat.row_id = self._ctx.repo.record_chat_message(chat, run_id=self._run_id) - # The near relays of this send, so that a later change of site does not change - # whether the message went past them (refer to meshterm.services.heard_by). - if getattr(self._ctx, "outbound_store", None) is not None: - try: - from .heard_by import near_relays - from .outbound import current_choice - - choice = await current_choice(self._ctx) - self._ctx.repo.set_near_hops(chat.row_id, near_relays(choice.paths)) - except Exception as exc: # noqa: BLE001 - the message went out. Only the mark is less exact - self._ctx.log.debug("couldn't keep the near relays of a send: %s", exc) return chat async def _sent_under(self, asked: str | None) -> str | None: diff --git a/meshterm/services/heard_by.py b/meshterm/services/heard_by.py index fa23a7c..ef5be9e 100644 --- a/meshterm/services/heard_by.py +++ b/meshterm/services/heard_by.py @@ -1,30 +1,23 @@ # SPDX-License-Identifier: Apache-2.0 -"""Tell whether a channel message that we sent went past our own repeaters (issue #38). +"""Tell whether a repeater relayed a channel message that we sent (issue #38). A channel broadcast has no acknowledgement. But the device hears the relay of our broadcast by each repeater in range, and its RX log records each copy with the path that the copy went through (refer to :mod:`~meshterm.services.message_paths`). Each hop in that -path heard the message. Thus the copies that come back are the proof that somebody heard -it. +path heard the message. Thus a copy that comes back is the proof that a repeater heard the +message and sent it on. -A copy from a repeater next to us proves little: it shows that the message left our -radio. The user names these repeaters already, as the first hops of the **outbound -paths** of the active site or of a fixed device (refer to -:mod:`~meshterm.core.outbound_store`). This module calls them the **near relays**. Each -other hop in a copy is a relay that is not near, and it proves that the message went -farther. A near relay is near by its identity, not by its place in a path: the path -``UpperSalaberry → Cartierville`` has two near relays at home, and no other relay. +Each relay counts, the repeater next to us too. A first version counted only the relays +past the first hops of the outbound paths. In practice, nothing past them ever came back: +each repeater relays a packet one time, and the relays farther out are too far for our +radio to hear (JP, 2026-11-20, from 23 of 23 messages on his Public channel). -A managed node is not a near relay. The user can manage a repeater on the other side of -the city, and a relay by that repeater is good proof that the message went out. +The verdict of a message has three states, the same as the delivery of a direct message: -The verdict of a message has four states: - -* :data:`WAITING`: no relay that is not near was heard yet, and the wait - (``heard_wait_s``) is not over. The chat shows a spinner. -* :data:`BEYOND`: one or more relays that are not near heard it. The chat shows ``✓`` and - the number of these relays. -* :data:`NEARBY`: after the wait, only near relays sent a copy back. The chat shows ``⚠``. +* :data:`WAITING`: no copy came back yet, and the wait (``heard_wait_s``) is not over. The + chat shows a spinner. +* :data:`HEARD`: one or more relays sent a copy back. The chat shows ``✓`` and the number + of the relays. * :data:`UNHEARD`: after the wait, no copy came back. The chat shows ``✗``. A copy that comes back late changes the verdict, as a late acknowledgement does for a @@ -32,8 +25,8 @@ direct message. After the match window of the packet log (:data:`~meshterm.services.message_paths.CHANNEL_WINDOW`), nothing can change it, and MeshTerm stores the paths, so that the next visit does not decrypt the log again. -Two limits stay. MeshTerm sees only the relays that our radio hears, so a relay farther -away than that never shows. And MeshTerm must be connected while the copies come back. +Two limits stay. MeshTerm sees only the relays that our radio hears. And MeshTerm must be +connected while the copies come back. Nothing in this module transmits. It is a read-model over the repository. """ @@ -55,8 +48,7 @@ if TYPE_CHECKING: #: The verdict states (refer to the module docstring). WAITING = "waiting" -BEYOND = "beyond" -NEARBY = "nearby" +HEARD = "heard" UNHEARD = "unheard" #: The number of messages that :meth:`HeardTracker.fill` examines before each yield to the @@ -72,52 +64,17 @@ class HeardBy: """The verdict on one channel message that we sent. Attributes: - state: :data:`WAITING`, :data:`BEYOND`, :data:`NEARBY`, or :data:`UNHEARD`. - beyond: The hashes of the relays that are not near, in the order first heard. - Each one heard the message. - via: The near relays that started the copies that went farther, in the order first - heard. Thus the user sees which of the repeaters at home carried the message - out. + state: :data:`WAITING`, :data:`HEARD`, or :data:`UNHEARD`. + relays: The hashes of the relays in the copies, in the order first heard. Each one + heard the message. copies: The number of copies that came back. """ state: str - beyond: tuple[str, ...] = () - via: tuple[str, ...] = () + relays: tuple[str, ...] = () copies: int = 0 -def near_relays(paths: Iterable[Sequence[str]]) -> tuple[str, ...]: - """The first hop of each outbound path, without duplicates, in order. - - Args: - paths: The outbound paths that apply - (:attr:`~meshterm.core.outbound_store.OutboundChoice.paths`). - - Returns: - The near relays, as lowercase hex. - """ - out: list[str] = [] - for path in paths: - if path: - hop = str(path[0]).lower() - if hop not in out: - out.append(hop) - return tuple(out) - - -def is_near(hop: str, near: Sequence[str]) -> bool: - """Whether a hop of a path is one of the near relays. - - A hop in a packet path is a hash: one to three bytes of the key. A near relay is a - longer key prefix. The hop matches when one starts with the other. When two - repeaters share a one-byte hash, a relay that is not near can match a near relay. Then - the count is too low, but it never claims a relay that did not occur. - """ - hop = hop.lower() - return bool(hop) and any(n.startswith(hop) or hop.startswith(n) for n in near) - - def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]: """The paths of the copies that tell which relays heard the message. @@ -128,49 +85,35 @@ def relay_paths(arrivals: Iterable[Arrival]) -> list[RelayPath]: return [a.hops for a in arrivals if a.hops and a.route_known] -def judge( - paths: Sequence[RelayPath], near: Sequence[str], *, age_s: float, wait_s: float -) -> HeardBy: +def judge(paths: Sequence[RelayPath], *, age_s: float, wait_s: float) -> HeardBy: """The verdict on a message from the paths of its copies. Args: paths: The relay paths of the copies that came back, in the order heard. - near: The near relays at the time of the send. age_s: The time since the send, in seconds. wait_s: The wait before "no relay" becomes the verdict (``heard_wait_s``). Returns: The verdict. """ - beyond: list[str] = [] - via: list[str] = [] + relays: list[str] = [] for path in paths: - far = [hop.lower() for hop in path if not is_near(hop, near)] - for hop in far: - if hop not in beyond: - beyond.append(hop) - if far: - for hop in path: - if hop.lower() == far[0]: - break - if hop.lower() not in via: - via.append(hop.lower()) - if beyond: - state = BEYOND + for hop in path: + if hop.lower() not in relays: + relays.append(hop.lower()) + if relays: + state = HEARD elif age_s < wait_s: state = WAITING - elif paths: - state = NEARBY else: state = UNHEARD - return HeardBy(state, tuple(beyond), tuple(via), len(paths)) + return HeardBy(state, tuple(relays), len(paths)) @dataclass(slots=True) class _Record: - """What the tracker knows about one message: its near relays, and the copies so far.""" + """What the tracker knows about one message: the copies so far, and if more can come.""" - near: tuple[str, ...] paths: list[RelayPath] = field(default_factory=list) settled: bool = False @@ -191,7 +134,6 @@ class HeardTracker: *, channel_name: str, secret: bytes | None, - near_now: tuple[str, ...], wait_s: Callable[[], float], clock: Callable[[], datetime] = utcnow, ) -> None: @@ -202,15 +144,12 @@ class HeardTracker: channel_name: The name of the channel (for the decryption). secret: The key of the channel. With no key, nothing can be matched, and each verdict is ``None``. - near_now: The near relays that apply now. A message sent before MeshTerm kept - the near relays of each send uses these. wait_s: Gives the ``heard_wait_s`` preference, read at each verdict. clock: Gives the current time (a fixed clock in the tests). """ self._repo = repo self._channel_name = channel_name self._secret = secret - self._near_now = near_now self._wait_s = wait_s self._clock = clock self._records: dict[int, _Record] = {} @@ -238,12 +177,12 @@ class HeardTracker: record = self._records.get(message.row_id) # type: ignore[arg-type] if record is None: return None - return judge(record.paths, record.near, age_s=self._age_s(message), wait_s=self._wait_s()) + return judge(record.paths, age_s=self._age_s(message), wait_s=self._wait_s()) def note_sent(self, message: ChatMessage) -> None: """Start the verdict of a message that was sent while the screen is open.""" if self._ours(message): - self._records[message.row_id] = _Record(near=self._near_now) # type: ignore[index] + self._records[message.row_id] = _Record() # type: ignore[index] self._revision += 1 async def fill(self, messages: Sequence[ChatMessage]) -> None: @@ -258,19 +197,14 @@ class HeardTracker: ours = [m for m in messages if self._ours(m)] stored = self._repo.heard_records([m.row_id for m in ours]) # type: ignore[misc] for message in ours: - near, paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type] + paths = stored.get(message.row_id) # type: ignore[arg-type] if paths is not None: - self._records[message.row_id] = _Record( # type: ignore[index] - near=near if near is not None else self._near_now, - paths=list(paths), - settled=True, - ) + self._records[message.row_id] = _Record(paths=list(paths), settled=True) # type: ignore[index] self._revision += 1 todo = [m for m in reversed(ours) if m.row_id not in self._records] for start in range(0, len(todo), _CHUNK): for message in todo[start : start + _CHUNK]: - near, _paths = stored.get(message.row_id, (None, None)) # type: ignore[arg-type] - self._examine(message, near if near is not None else self._near_now) + self._examine(message) self._revision += 1 await asyncio.sleep(0) @@ -291,7 +225,7 @@ class HeardTracker: if record is None or record.settled: continue before = list(record.paths) - self._examine(message, record.near) + self._examine(message) changed = changed or self._records[message.row_id].paths != before # type: ignore[index] if changed: self._revision += 1 @@ -301,7 +235,7 @@ class HeardTracker: """Whether one of the messages shows the spinner now.""" return any((v := self.verdict(m)) is not None and v.state == WAITING for m in messages) - def _examine(self, message: ChatMessage, near: tuple[str, ...]) -> None: + def _examine(self, message: ChatMessage) -> None: """Match the copies of one message in the packet log, and settle it if it is old.""" assert self._secret is not None and message.row_id is not None arrivals = channel_arrivals( @@ -309,19 +243,18 @@ class HeardTracker: ) paths = relay_paths(arrivals) settled = self._age_s(message) > CHANNEL_WINDOW.total_seconds() - self._records[message.row_id] = _Record(near=near, paths=paths, settled=settled) + self._records[message.row_id] = _Record(paths=paths, settled=settled) if settled: - self._repo.settle_heard(message.row_id, near, paths) + self._repo.settle_heard(message.row_id, paths) -async def make_tracker( +def make_tracker( ctx: AppContext, *, channel_name: str, secret: bytes | None ) -> HeardTracker | None: - """A tracker for one channel, with the near relays that apply now. + """A tracker for one channel. Args: - ctx: The shared application context (the repository, the outbound paths, and the - preferences). + ctx: The shared application context (the repository and the preferences). channel_name: The name of the channel. secret: The key of the channel. With no key, there is no tracker. @@ -330,18 +263,9 @@ async def make_tracker( """ if not secret: return None - from .outbound import current_choice - - near: tuple[str, ...] = () - if getattr(ctx, "outbound_store", None) is not None: - try: - near = near_relays((await current_choice(ctx)).paths) - except Exception: # noqa: BLE001 - with no outbound paths, each relay counts - near = () return HeardTracker( ctx.repo, channel_name=channel_name, secret=secret, - near_now=near, wait_s=lambda: float(ctx.preferences.heard_wait_s), ) diff --git a/meshterm/tools/chat.py b/meshterm/tools/chat.py index d5ade71..0ff0bfa 100644 --- a/meshterm/tools/chat.py +++ b/meshterm/tools/chat.py @@ -1324,7 +1324,6 @@ def _message_columns(*, author_lane: bool = False, heard_lane: bool = False) -> fields.hidden("acked"), fields.hidden("heard"), fields.hidden("heard_by"), - fields.hidden("heard_via"), ) @@ -1373,7 +1372,7 @@ def _author_ref(author: str, name_of: NodeResolver | None) -> NodeRef: async def _channel_verdicts( ctx: AppContext, channel: int, messages: list[ChatMessage] ) -> Callable[[ChatMessage], HeardBy | None] | None: - """The verdicts on our messages in a channel: did a relay past the near relays hear them? + """The verdicts on our messages in a channel: did a repeater send a copy back? Refer to :mod:`~meshterm.services.heard_by`. With no key for the slot, there is no verdict, and the column is absent on each row. @@ -1388,7 +1387,7 @@ async def _channel_verdicts( name = str((payload or {}).get("channel_name") or f"#{channel}") except Exception: # noqa: BLE001 - no key, no verdict. The history still prints return None - tracker = await make_tracker(ctx, channel_name=name, secret=secret) + tracker = make_tracker(ctx, channel_name=name, secret=secret) if tracker is None: return None await tracker.fill(messages) @@ -1414,7 +1413,7 @@ def _transcript( me: Our node, the author of our own posts in a room. heard: Gives the verdict on each of our channel messages (refer to :mod:`~meshterm.services.heard_by`). With it, the plain face has a ``HEARD`` - lane. The document always has ``heard``, ``heard_by``, and ``heard_via``. + lane. The document always has ``heard`` and ``heard_by``. """ from ..ui.report import Listing @@ -1449,8 +1448,7 @@ def _transcript( "text": message.text, "acked": message.acked, "heard": verdict.state if verdict is not None else None, - "heard_by": list(verdict.beyond) if verdict is not None else None, - "heard_via": list(verdict.via) if verdict is not None else None, + "heard_by": list(verdict.relays) if verdict is not None else None, "heard_cell": _heard_cell(verdict), } ) @@ -1464,20 +1462,19 @@ def _transcript( def _heard_cell(verdict: HeardBy | None) -> str: - """The plain ``HEARD`` cell: the number of relays past the near relays, or a word. + """The plain ``HEARD`` cell: the number of relays that sent a copy back, or a word. - ``near`` is a message that only the near relays sent back, ``none`` is one that no - relay sent back, and ``wait`` is one that is still in its wait. A message that is not - ours has no verdict (``-``). + ``none`` is a message that no repeater sent back, and ``wait`` is one that is still in + its wait. A message that is not ours has no verdict (``-``). """ - from ..services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING + from ..services.heard_by import HEARD, UNHEARD, WAITING from ..ui import script if verdict is None: return script.NONE - if verdict.state == BEYOND: - return str(len(verdict.beyond)) - return {NEARBY: "near", UNHEARD: "none", WAITING: "wait"}.get(verdict.state, script.NONE) + if verdict.state == HEARD: + return str(len(verdict.relays)) + return {UNHEARD: "none", WAITING: "wait"}.get(verdict.state, script.NONE) def _live_messages() -> Listing: diff --git a/meshterm/ui/chat.py b/meshterm/ui/chat.py index 2b585b2..ce3e158 100644 --- a/meshterm/ui/chat.py +++ b/meshterm/ui/chat.py @@ -40,7 +40,7 @@ from ..core.models import ( ) from ..core.regions import WILDCARD from ..platforms import Platform, on_platform -from ..services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING, HeardBy, HeardTracker +from ..services.heard_by import HEARD, UNHEARD, WAITING, HeardBy, HeardTracker from . import pixelart from .compose import MentionEditor from .pathline import PATH_INK, PathHop @@ -88,9 +88,6 @@ _CORRECTED = ("?", "warn") #: animated spinner instead (refer to :meth:`ChatScreen._delivery_glyph`). _DELIVERED = ("✓", "ok") _FAILED = ("✗", "err") -#: The mark of our channel message that only the near relays sent back: it left our radio, -#: and nothing proves that it went farther (refer to :mod:`~meshterm.services.heard_by`). -_NEAR_ONLY = ("⚠", "warn") #: The time that the chat waits after a channel packet before it looks for copies of our #: messages in the packet log. The recorder stores each packet in the background. _HEARD_SETTLE_S = 1.0 @@ -337,8 +334,8 @@ class ChatScreen(Screen): resend_flood: Like ``resend``, but it first forgets the route that the device learned to the contact, so that the retry floods (direct chats only). With ``None``, ^R always retries on the route, as it did before. - heard: The verdicts on our own channel messages: whether a relay that is not a - near relay sent a copy back (refer to :mod:`~meshterm.services.heard_by`). + heard: The verdicts on our own channel messages: whether a repeater sent a copy + back (refer to :mod:`~meshterm.services.heard_by`). With ``None`` (a direct chat, or a channel with no key), our channel messages show no mark. hop_name: Gives the name of a relay from its hash, for the note under a @@ -1132,42 +1129,33 @@ class ChatScreen(Screen): heard = self._heard(message) return ( message.acked, - None if heard is None else (heard.state, heard.beyond, heard.via), + None if heard is None else (heard.state, heard.relays), ) def _heard_mark(self, heard: HeardBy) -> Text: """The mark at the end of our channel message: the marks of a direct message. - The spinner turns while no relay that is not near sent a copy back, until the - ``heard_wait_s`` wait is over. Then ``✓`` and the number of these relays, ``⚠`` for - a message that only the near relays sent back, or ``✗`` for no copy at all. + The spinner turns while no repeater sent a copy back, until the ``heard_wait_s`` + wait is over. Then ``✓`` and the number of the relays, or ``✗`` for no copy at all. """ if heard.state == WAITING: return self._spinner.text() - if heard.state == BEYOND: + if heard.state == HEARD: glyph, style = _DELIVERED - return Text(f"{glyph} {len(heard.beyond)}", style=style) - if heard.state == NEARBY: - return Text(_NEAR_ONLY[0], style=_NEAR_ONLY[1]) + return Text(f"{glyph} {len(heard.relays)}", style=style) glyph, style = _FAILED return Text(glyph, style=style) def _heard_note(self, heard: HeardBy) -> Text | None: """The line under a selected channel message of ours: which relays heard it.""" note = Text() - if heard.state == BEYOND: - names = ", ".join(self._hop_name(hop) for hop in heard.beyond) + if heard.state == HEARD: + names = ", ".join(self._hop_name(hop) for hop in heard.relays) note.append(f"{_DELIVERED[0]} ", style=_DELIVERED[1]) - note.append(f"heard by {names}", style="muted") - if heard.via: - via = ", ".join(self._hop_name(hop) for hop in heard.via) - note.append(f" · via {via}", style="muted") - elif heard.state == NEARBY: - note.append(f"{_NEAR_ONLY[0]} ", style=_NEAR_ONLY[1]) - note.append("only your near relays sent it back", style="muted") + note.append(f"relayed by {names}", style="muted") elif heard.state == UNHEARD: note.append(f"{_FAILED[0]} ", style=_FAILED[1]) - note.append("no relay sent it back", style="muted") + note.append("no repeater sent it back", style="muted") else: return None return note @@ -2227,7 +2215,7 @@ async def _make_heard_tracker( from ..services.heard_by import make_tracker secret = await _channel_secret(conversation, device) - tracker = await make_tracker(ctx, channel_name=conversation.label, secret=secret) + tracker = make_tracker(ctx, channel_name=conversation.label, secret=secret) if tracker is None: return None, None stored_names, _named_at = ctx.repo.node_names_with_times() @@ -2235,30 +2223,6 @@ async def _make_heard_tracker( return tracker, lambda hop: resolve(hop) or hop -async def _past_near_atom(ctx: AppContext, message: ChatMessage, arrivals: list) -> str: - """The atom of the paths dialog that counts the relays past our near relays. - - The near relays are the ones kept with the send, or the ones that apply now for a - message sent before MeshTerm kept them (refer to :mod:`~meshterm.services.heard_by`). - """ - from ..services.heard_by import judge, near_relays, relay_paths - from ..services.outbound import current_choice - - near: tuple[str, ...] | None = None - if message.row_id is not None: - near, _paths = ctx.repo.heard_records([message.row_id]).get(message.row_id, (None, None)) - if near is None and getattr(ctx, "outbound_store", None) is not None: - try: - near = near_relays((await current_choice(ctx)).paths) - except Exception: # noqa: BLE001 - with no outbound paths, each relay counts - near = None - heard = judge(relay_paths(arrivals), near or (), age_s=float("inf"), wait_s=0.0) - count = len(heard.beyond) - if not near: - return f" · {count} relay{'s' if count != 1 else ''}" - return f" · {count} past your near relay{'s' if len(near) != 1 else ''}" - - async def _with_restore(ctx: AppContext, attempt: Callable[[], Awaitable[Any]]) -> Any: """Run a direct send. If the device forgot the contact, offer to restore it, then retry. @@ -2552,8 +2516,6 @@ async def _make_paths_presenter( if arrivals else "no copies in the packet log" ) - if arrivals and message.outbound: - summary += await _past_near_atom(ctx, message, arrivals) elif conversation.is_channel: await session.scroll( Text( diff --git a/tests/test_gallery.py b/tests/test_gallery.py index 192a3bc..8dc24ae 100644 --- a/tests/test_gallery.py +++ b/tests/test_gallery.py @@ -68,7 +68,7 @@ from meshterm.platforms import ( set_platform, ) from meshterm.services.courier import CourierService -from meshterm.services.heard_by import BEYOND, NEARBY, UNHEARD, WAITING, HeardBy +from meshterm.services.heard_by import HEARD, UNHEARD, WAITING, HeardBy from meshterm.services.message_paths import Arrival from meshterm.services.monitor_service import ACTIVITY_BUCKETS from meshterm.services.records import CATEGORY_BY_ID @@ -826,37 +826,27 @@ class _GalleryHeard: def _chat_heard(cols: int, rows: int) -> Screen: - """Our channel messages with the four relay marks, and the note of the picked one. + """Our channel messages with the three relay marks, and the note of the picked one. - The marks are the spinner, ``⚠`` (only the near relays sent it back), ``✗`` (no copy), - and ``✓ 3`` (three relays past the near relays). The newest message is picked, so its - note names the relays and the near relay that carried it out. The names are long, so - the note wraps under the body on the PicoCalc. + The marks are ``✗`` (no repeater sent a copy back), the spinner, and ``✓ 3`` (three + relays sent a copy back). The newest message is picked, so its note names the relays. + The names are long, so the note wraps under the body on the PicoCalc. """ conv = Conversation(label="Lakeside", is_channel=True, channel_idx=1) messages = [ ChatMessage(text="Alice: anyone on the ridge tonight?", is_channel=True), - ChatMessage(text="testing the new antenna", outbound=True, is_channel=True, row_id=1), - ChatMessage(text="anyone hear this?", outbound=True, is_channel=True, row_id=2), - ChatMessage(text="one more try", outbound=True, is_channel=True, row_id=3), - ChatMessage(text="heading up the ridge now", outbound=True, is_channel=True, row_id=4), + ChatMessage(text="anyone hear this?", outbound=True, is_channel=True, row_id=1), + ChatMessage(text="one more try", outbound=True, is_channel=True, row_id=2), + ChatMessage(text="heading up the ridge now", outbound=True, is_channel=True, row_id=3), ] heard = _GalleryHeard( { - "testing the new antenna": HeardBy(UNHEARD), - "anyone hear this?": HeardBy(NEARBY, copies=2), + "anyone hear this?": HeardBy(UNHEARD), "one more try": HeardBy(WAITING), - "heading up the ridge now": HeardBy( - BEYOND, beyond=("a1", "b2", "c3"), via=("3d",), copies=4 - ), + "heading up the ridge now": HeardBy(HEARD, relays=("a1", "b2", "c3"), copies=3), } ) - names = { - "a1": "Lakeside-North-Shore", - "b2": "Marina-Tower", - "c3": "Ridge-Top-Solar", - "3d": "Home-Yagi", - } + names = {"a1": "Lakeside-North-Shore", "b2": "Marina-Tower", "c3": "Ridge-Top-Solar"} screen = ChatScreen( conv, messages, diff --git a/tests/test_heard_by.py b/tests/test_heard_by.py index 3b47b10..96503b9 100644 --- a/tests/test_heard_by.py +++ b/tests/test_heard_by.py @@ -1,5 +1,5 @@ # SPDX-License-Identifier: Apache-2.0 -"""Tests for the verdict on our channel messages: did a relay past our near relays hear it? +"""Tests for the verdict on our channel messages: did a repeater send a copy back? The pure part (:func:`judge` and its helpers) is tested with plain paths. The tracker runs against a real temporary repository, with GRP_TXT packets in the firmware form, so the @@ -9,6 +9,7 @@ tests also use the window query, the decryption, and the stored verdicts. from __future__ import annotations import asyncio +import sqlite3 from datetime import datetime, timedelta, timezone from pathlib import Path @@ -19,25 +20,17 @@ from meshterm.core.channels import channel_hash, derive_secret from meshterm.core.models import ChatMessage, Observation, utcnow from meshterm.persistence.repository import Repository from meshterm.services.heard_by import ( - BEYOND, - NEARBY, + HEARD, UNHEARD, WAITING, HeardTracker, - is_near, judge, - near_relays, relay_paths, ) from meshterm.services.message_paths import Arrival, channel_arrivals SECRET = derive_secret("#general") -# Invented repeaters: two near relays at home (one of them on a yagi), and two far ones. -HOME_OMNI = "3d00aa000001" -HOME_YAGI = "27d4bb000002" -NEAR = (HOME_OMNI, HOME_YAGI) - def _grp_txt_raw(secret: bytes, text: str, *, sent: datetime | None = None) -> dict: """A GRP_TXT packet payload in the firmware form, with ``sent`` as its sender time.""" @@ -85,57 +78,19 @@ def _sent(repo: Repository, text: str, at: datetime) -> ChatMessage: # --- the pure verdict ------------------------------------------------------------------ -def test_near_relays_are_the_first_hops_of_the_outbound_paths() -> None: - """Each outbound path gives its first hop one time, in order, in lowercase.""" - paths = [("3D00AA000001", "51548cda57ae"), ("27d4bb000002", "3d00aa000001"), ()] - assert near_relays(paths) == (HOME_OMNI, HOME_YAGI) - - -def test_a_hash_matches_a_near_relay_by_its_prefix() -> None: - """A one-byte hash matches the longer key prefix of a near relay, in either case.""" - assert is_near("3D", NEAR) - assert is_near("27d4", NEAR) - assert not is_near("51", NEAR) - assert not is_near("", NEAR) - - -def test_a_relay_past_the_near_relays_makes_the_verdict_beyond() -> None: - """A copy through a far relay proves that the message went farther, at once.""" - heard = judge([("3d", "51"), ("27", "3d")], NEAR, age_s=1, wait_s=30) - assert heard.state == BEYOND - assert heard.beyond == ("51",) - assert heard.via == ("3d",) +def test_each_relay_in_the_copies_counts_one_time() -> None: + """The repeater next to us counts, and a relay in two copies counts one time.""" + heard = judge([("3D",), ("27", "3d")], age_s=1, wait_s=30) + assert heard.state == HEARD + assert heard.relays == ("3d", "27") assert heard.copies == 2 -def test_near_relays_are_near_at_any_place_in_the_path() -> None: - """The yagi relay after the omni relay is still a near relay, so nothing went farther.""" - heard = judge([("27", "3d")], NEAR, age_s=60, wait_s=30) - assert heard.state == NEARBY - assert heard.beyond == () - - -def test_the_verdict_waits_before_it_says_nearby_or_unheard() -> None: - """Inside the wait, no copy and near copies both wait. After it, they differ.""" - assert judge([], NEAR, age_s=5, wait_s=30).state == WAITING - assert judge([("3d",)], NEAR, age_s=5, wait_s=30).state == WAITING - assert judge([("3d",)], NEAR, age_s=31, wait_s=30).state == NEARBY - assert judge([], NEAR, age_s=31, wait_s=30).state == UNHEARD - - -def test_with_no_near_relays_each_relay_counts() -> None: - """With no outbound paths, a relay next to us is proof too.""" - heard = judge([("3d",), ("27", "51")], (), age_s=1, wait_s=30) - assert heard.state == BEYOND - assert heard.beyond == ("3d", "27", "51") - assert heard.via == () - - -def test_the_via_names_each_near_relay_that_started_a_far_copy() -> None: - """Both repeaters at home show when each of them carried the message out.""" - heard = judge([("3d", "51"), ("27", "a9", "51")], NEAR, age_s=1, wait_s=30) - assert heard.beyond == ("51", "a9") - assert heard.via == ("3d", "27") +def test_the_verdict_waits_before_it_says_unheard() -> None: + """With no copy, the verdict waits, then it is unheard. A copy ends the wait at once.""" + assert judge([], age_s=5, wait_s=30).state == WAITING + assert judge([], age_s=31, wait_s=30).state == UNHEARD + assert judge([("3d",)], age_s=5, wait_s=30).state == HEARD def test_relay_paths_skip_the_copies_that_tell_nothing() -> None: @@ -171,12 +126,11 @@ def test_two_sends_of_the_same_text_keep_their_own_copies(tmp_path: Path) -> Non # --- the tracker ----------------------------------------------------------------------- -def _tracker(repo: Repository, now: datetime, *, near=NEAR) -> HeardTracker: +def _tracker(repo: Repository, now: datetime) -> HeardTracker: return HeardTracker( repo, channel_name="#general", secret=SECRET, - near_now=near, wait_s=lambda: 30.0, clock=lambda: now, ) @@ -209,18 +163,17 @@ def test_the_tracker_ignores_other_messages(tmp_path: Path) -> None: def test_a_late_copy_changes_the_verdict(tmp_path: Path) -> None: - """A copy through a far relay after the wait turns the verdict from nearby to beyond.""" + """A copy after the wait turns the verdict from unheard to heard.""" repo, run = _repo(tmp_path) sent_at = utcnow().replace(microsecond=0) - timedelta(seconds=40) message = _sent(repo, "hello", sent_at) - _copy(repo, run, when=sent_at + timedelta(seconds=1), path="3d", text="hello", sent=sent_at) tracker = _tracker(repo, sent_at + timedelta(seconds=40)) asyncio.run(tracker.fill([message])) - assert tracker.verdict(message).state == NEARBY # type: ignore[union-attr] - _copy(repo, run, when=sent_at + timedelta(seconds=35), path="3d,51", text="hello", sent=sent_at) + assert tracker.verdict(message).state == UNHEARD # type: ignore[union-attr] + _copy(repo, run, when=sent_at + timedelta(seconds=35), path="3d", text="hello", sent=sent_at) assert tracker.refresh([message]) is True verdict = tracker.verdict(message) - assert verdict is not None and verdict.state == BEYOND and verdict.beyond == ("51",) + assert verdict is not None and verdict.state == HEARD and verdict.relays == ("3d",) repo.close() @@ -233,32 +186,17 @@ def test_an_old_message_is_stored_and_read_back(tmp_path: Path) -> None: repo, run, when=sent_at + timedelta(seconds=3), path="27,9f", text="old one", sent=sent_at ) asyncio.run(_tracker(repo, utcnow()).fill([message])) - stored = repo.heard_records([message.row_id]) # type: ignore[list-item] - assert stored[message.row_id] == (NEAR, [("27", "9f")]) # type: ignore[index] + assert repo.heard_records([message.row_id]) == {message.row_id: [("27", "9f")]} # type: ignore[list-item,dict-item] - # A second visit with other near relays keeps the ones that the verdict used. - again = _tracker(repo, utcnow(), near=()) + again = _tracker(repo, utcnow()) asyncio.run(again.fill([message])) verdict = again.verdict(message) - assert verdict is not None and verdict.beyond == ("9f",) and verdict.via == ("27",) - repo.close() - - -def test_the_near_relays_of_the_send_win_over_the_ones_of_today(tmp_path: Path) -> None: - """A message keeps the near relays of its send, also after a change of site.""" - repo, run = _repo(tmp_path) - sent_at = utcnow().replace(microsecond=0) - timedelta(seconds=60) - message = _sent(repo, "from home", sent_at) - repo.set_near_hops(message.row_id, NEAR) # type: ignore[arg-type] - _copy(repo, run, when=sent_at + timedelta(seconds=2), path="3d", text="from home", sent=sent_at) - tracker = _tracker(repo, sent_at + timedelta(seconds=60), near=("51000000",)) - asyncio.run(tracker.fill([message])) - assert tracker.verdict(message).state == NEARBY # type: ignore[union-attr] + assert verdict is not None and verdict.relays == ("27", "9f") repo.close() def test_a_message_sent_while_the_screen_is_open_waits(tmp_path: Path) -> None: - """A new send starts in the wait, with the near relays that apply now.""" + """A new send starts in the wait.""" repo, _run = _repo(tmp_path) now = datetime.now(timezone.utc).replace(microsecond=0) message = _sent(repo, "new", now) @@ -268,3 +206,20 @@ def test_a_message_sent_while_the_screen_is_open_waits(tmp_path: Path) -> None: assert tracker.revision != before assert tracker.waiting([message]) repo.close() + + +def test_the_first_build_of_the_table_is_made_again(tmp_path: Path) -> None: + """A database with the near relays column of the first build gets the table again.""" + path = tmp_path / "old.db" + Repository(path).close() + conn = sqlite3.connect(path) + conn.execute("DROP TABLE heard_relays") + conn.execute( + "CREATE TABLE heard_relays (message_id INTEGER PRIMARY KEY, near_hops TEXT, paths TEXT)" + ) + conn.commit() + conn.close() + repo = Repository(path) + cols = {row["name"] for row in repo._conn.execute("PRAGMA table_info(heard_relays)")} + assert cols == {"message_id", "paths"} + repo.close()