diff --git a/FLEET.md b/FLEET.md index 7bbb8735..6778abe2 100644 --- a/FLEET.md +++ b/FLEET.md @@ -245,6 +245,21 @@ RAM-only: a reboot wipes them, so a re-sent `!ack` job after a reboot re-runs *and* re-replies. A full reply store drops and counts the reply (`refused`); no reply cooldown in v1 — per-key dedupe already bounds each script to one reply. +**Repeat confirmation and retry:** after a reply floods, the repeater listens +for a neighbour repeating it. If none is heard within ~5 s, the reply is +re-sent **once, byte-identically** — same frozen timestamp, so the same on-air +packet — and then the repeater stops. Because the copy is byte-identical, every +node that already relayed the first attempt has it in its seen table and +suppresses the copy at the mesh layer *before* any app or companion sees it: a +retry can never appear as a duplicate message, and a healthy fleet still shows +exactly one reply per node. "Heard a repeat" proves a repeater relayed the +reply; it does **not** prove the operator's companion received it — there is no +end-to-end ack for flood group text. Each such miss is counted as `rtx` on the +status line; a climbing `rtx` means replies are not being repeated — likely no +neighbouring repeater in range, or heavy loss. The retry is build-time tunable +(`FLEET_ACK_RETRY`, `FLEET_ACK_REPEAT_WINDOW_MS`), never persisted; build with +`FLEET_ACK_RETRY=0` to restore the single fire-and-forget send. + ## Inline pauses (`!delay `) ```text @@ -331,7 +346,7 @@ All commands begin with `fleet`. | Command | Effect | |---|---| -| `fleet` | Status: `on, chan h=XX, tags 2/8; scripts ran:3 dup:1 noid:0 refused:0; pending 0/2; sched 0/2; seen 2/32; ackq 0/2; badline 0` | +| `fleet` | Status: `on, chan h=XX, tags 2/8; scripts ran:3 dup:1 noid:0 refused:0; pending 0/2; sched 0/2; seen 2/32; ackq 0/2 await 0 rtx 0; badline 0` | | `fleet on` / `fleet off` | Arm / idle the hooks (config preserved either way) | | `fleet chan set ` | Set/replace the one fleet channel (16 or 32 bytes hex) — `OK - fleet channel set h=XX (PSK holder = admin)` | | `fleet chan clear` | `OK - fleet channel cleared` — receipt stops, queued and armed scripts are cancelled, seen keys and counters kept | @@ -356,6 +371,8 @@ Counter meanings: | `badline` | Command lines skipped at run time for being over-long | | `sched` | Armed `!at` scripts (`0/2`) | | `ackq` | Pending acknowledgements (`0/2`) | +| `await` | Sent acknowledgements still awaiting a heard repeat (`0/2`) | +| `rtx` | Replies re-sent because the first attempt was not heard repeated | ## Two-phase fleet changes (radio presets and other cutovers) @@ -531,6 +548,7 @@ cli[2026-06-12-preset2-cfg] set radio 869.650,62.5,9,5 | Some nodes ran it, some didn't | `refused` counter on the stragglers | Their pending queue was full (a third job arrived before the first drained); re-send the job | | Script targets nobody | `fleet tag list` on the nodes | Tag typo (exact matching: `xiao ` ≠ `xiao`); or all nodes lack the tag and `!tags` was present | | No `!ack` reply arrived | `ackq` on the node; window too long? | Reply still jittering (up to `reply window` s); store was full (`refused`); or the channel changed between receipt and send | +| `rtx` climbing | Neighbouring repeaters in range? | Replies are not being heard repeated — likely no neighbouring repeater, or heavy loss; each miss is one extra byte-identical resend (never a duplicate, since nodes that already relayed suppress the copy) | | `dup` climbing, nothing changed | — | Normal: re-sends and duplicate flood deliveries | | Job ran twice | seen-ring wrap | 33+ distinct jobs this boot evicted the key; re-send deliberately via `forget` semantics | | Lines missing from a run | `badline` counter | Lines over the CLI's length limit were skipped — split the job | @@ -542,7 +560,8 @@ cli[2026-06-12-preset2-cfg] set radio 869.650,62.5,9,5 `fleet off` and `fleet chan clear` stop the fleet at once: receipt stops, and every queued, sleeping and armed script is cancelled (its key stays consumed, -see [Idempotency](#idempotency-at-most-once-per-key-per-boot)). A script that +see [Idempotency](#idempotency-at-most-once-per-key-per-boot)), as are queued +and awaiting acknowledgements. A script that switches the fleet off runs its remaining lines up to its next `!delay`, and nothing after that. `fleet forget ` re-arms one job. `filter off` does not stop fleet; the [battery gate does not stop fleet either](#battery-supersession). @@ -602,6 +621,7 @@ so it can't be orphaned from a fleet cutover by its own battery state. | Armed `!at` scripts | 2 (RAM-only; a reboot wipes them) | | Pending acknowledgements | 2 (RAM-only; a full store drops and counts) | | `!ack` reply window | 1–600 s; default 15 s (~5 s per repeater) | +| `!ack` repeat confirmation | one byte-identical resend after ~5 s with no repeat heard; RAM-only, build-time tunable (`FLEET_ACK_*`) | | Seen job keys | last 32 per boot (RAM-only; a 33rd evicts the oldest and re-arms it) | | `!id` key | 1–32 chars of `[A-Za-z0-9._-]` | | Tags | up to 8 on a repeater; up to 8 per `!tags` list; 1–16 chars each | diff --git a/examples/simple_repeater/FleetConfig.h b/examples/simple_repeater/FleetConfig.h index a102dd90..3a69dff2 100644 --- a/examples/simple_repeater/FleetConfig.h +++ b/examples/simple_repeater/FleetConfig.h @@ -89,6 +89,34 @@ #define FLEET_SCHED_STORE 2 // armed !at scripts (RAM-only) #endif +// --- acknowledgement repeat confirmation --- +// +// A reply is re-sent once, byte-identically, when no repeater is heard +// repeating it within FLEET_ACK_REPEAT_WINDOW_MS. Same frozen timestamp => +// same packet hash, so every node that already relayed the first attempt +// suppresses the copy at the mesh layer: the retry can never duplicate on air. +// RAM-only, so no FLEET_CFG_VERSION interaction. + +#ifndef FLEET_ACK_RETRY + #define FLEET_ACK_RETRY 1 // resend an !ack reply once, + // byte-identically, if no repeater + // is heard repeating it; + // 0 = today's fire-and-forget +#endif + +#ifndef FLEET_ACK_REPEAT_WINDOW_MS + #define FLEET_ACK_REPEAT_WINDOW_MS 5000UL // wait this long for a repeater to + // repeat the reply before resending. + // Covers a relay's calcRxDelay, not + // just a good-link echo +#endif + +#ifndef FLEET_ACK_RETRY_BACKOFF_MS + #define FLEET_ACK_RETRY_BACKOFF_MS 1000UL // re-try delay when the packet pool + // refused the first send (it used + // no attempt) +#endif + // Summary budget for one acknowledgement: the repeater name (max 31, CommonCLI // prefs) + ": " + the job key (FLEET_CLI_KEY_LEN) + " " must share the // createGroupDatagram data limit (184 B payload - 1 B hash - 15 B cipher pad = diff --git a/examples/simple_repeater/FleetManager.cpp b/examples/simple_repeater/FleetManager.cpp index 69dce17e..0fdc8f2e 100644 --- a/examples/simple_repeater/FleetManager.cpp +++ b/examples/simple_repeater/FleetManager.cpp @@ -27,6 +27,7 @@ void FleetManager::resetToDefaults() { reply_count = 0; offered = 0; matched = 0; + reply_retries = 0; // device services are deliberately NOT reset here: they are wiring (set by // MyMesh::begin() before load()), not config state — they have in-class // initializers and survive every resetToDefaults()/load() call @@ -246,6 +247,10 @@ void FleetManager::runScripts(CliExecFn fn, void* exec_ctx) { runner.abortPending(); memset(sched, 0, sizeof(sched)); sched_count = 0; + // queued + awaiting acknowledgements die with the fleet too (today a due + // ack survived `fleet off`; that inconsistency is closed here) + memset(replies, 0, sizeof(replies)); + reply_count = 0; } // scheduled scripts that have come due move to the run queue; one that @@ -273,30 +278,92 @@ void FleetManager::runScripts(CliExecFn fn, void* exec_ctx) { scheduleAckIfNeeded(res); } - sendDueReplies(); + serviceReplies(); } -void FleetManager::sendDueReplies() { +int FleetManager::getAwaitingCount() const { + int n = 0; + for (int i = 0; i < reply_count; i++) { + if (replies[i].awaiting) n++; + } + return n; +} + +void FleetManager::removeReply(int idx) { + memmove(&replies[idx], &replies[idx + 1], (reply_count - idx - 1) * sizeof(replies[0])); + memset(&replies[reply_count - 1], 0, sizeof(replies[0])); + reply_count--; +} + +void FleetManager::serviceReplies() { for (int i = 0; i < reply_count;) { - // signed difference: the deadline is at most one jitter window away, so - // the subtraction only wraps when millis() itself does - if ((int32_t)(millis() - replies[i].deadline_ms) < 0) { i++; continue; } - if (send_fn != NULL) { - char body[FLEET_CLI_KEY_LEN + 1 + FLEET_REPLY_SUMMARY_LEN]; // "\n" - snprintf(body, sizeof(body), "%s\n%s", replies[i].key, replies[i].summary); - // the captured channel goes back out as-is; if the send cannot happen - // (packet pool empty), the reply is skipped silently - send_fn(send_ctx, replies[i].chan_secret, replies[i].chan_hash, body); + FleetReply& r = replies[i]; + // signed difference: the deadline is at most one jitter window (or retry + // window/backoff) away, so it only wraps when millis() itself does + if ((int32_t)(millis() - r.deadline_ms) < 0) { i++; continue; } + + char body[FLEET_CLI_KEY_LEN + 1 + FLEET_REPLY_SUMMARY_LEN]; // "\n" + snprintf(body, sizeof(body), "%s\n%s", r.key, r.summary); + + if (r.awaiting) { + // window elapsed with no repeater heard repeating the reply: one + // byte-identical resend. Same ts => same packet hash, so every node that + // already relayed attempt 1 suppresses this copy — no duplicate on air. + if (send_fn != NULL) { + send_fn(send_ctx, r.chan_secret, r.chan_hash, r.tx_ts, body, NULL); + } + reply_retries++; // the miss count: the first attempt drew no repeat + removeReply(i); + continue; + } + + // first attempt: stamp it now, remember the ts and hash for a possible retry + uint32_t ts = time_fn ? time_fn(time_ctx) : 0; + uint8_t hash[MAX_HASH_SIZE]; + bool sent = send_fn != NULL && + send_fn(send_ctx, r.chan_secret, r.chan_hash, ts, body, hash); + if (!sent) { + // packet pool refused the send: no attempt used, try again shortly + r.deadline_ms = millis() + FLEET_ACK_RETRY_BACKOFF_MS; + i++; + continue; + } + if (!FLEET_ACK_RETRY) { // off switch: today's fire-and-forget + removeReply(i); + continue; + } + r.tx_ts = ts; + memcpy(r.pkt_hash, hash, MAX_HASH_SIZE); + r.awaiting = 1; + r.deadline_ms = millis() + FLEET_ACK_REPEAT_WINDOW_MS; + i++; + } +} + +void FleetManager::onHeardPacket(const mesh::Packet* packet) { + if (!enabled || reply_count == 0) return; // cheap gate: no SHA in the common case + // a repeat can only arrive via a repeater's relay, which appends a path hash; + // a zero-hop mirror/bridge echo of the raw bytes is not a repeat + if (packet->getPathHashCount() == 0) return; + + // calculatePacketHash() covers payload type + payload (path excluded), so the + // origin's outbound copy and any hop's rebroadcast hash identically; a + // foreign reply differs in payload. The 8-byte SHA-256 prefix makes a false + // positive negligible. + uint8_t hash[MAX_HASH_SIZE]; + packet->calculatePacketHash(hash); + for (int i = 0; i < reply_count; i++) { + if (replies[i].awaiting && memcmp(replies[i].pkt_hash, hash, MAX_HASH_SIZE) == 0) { + removeReply(i); // confirmed: a repeater relayed our reply + return; } - memmove(&replies[i], &replies[i + 1], (reply_count - i - 1) * sizeof(replies[0])); - memset(&replies[reply_count - 1], 0, sizeof(replies[0])); - reply_count--; } } bool FleetManager::sendAlert(const char* body) { if (!enabled || psk_len == 0 || send_fn == NULL) return false; - send_fn(send_ctx, psk, chan_hash, body); + uint32_t ts = time_fn ? time_fn(time_ctx) : 0; + send_fn(send_ctx, psk, chan_hash, ts, body, NULL); // one-shot: no retry return true; } @@ -471,7 +538,9 @@ static void fleetStatus(FleetManager& fleet, char* reply) { radd(&out, &remain, "; pending %d/%d", s.getPendingCount(), FLEET_CLI_QUEUE_DEPTH); radd(&out, &remain, "; sched %d/%d", fleet.getSchedCount(), FLEET_SCHED_STORE); radd(&out, &remain, "; seen %d/%d", s.getSeenCount(), FLEET_CLI_SEEN_SIZE); - radd(&out, &remain, "; ackq %d/%d", fleet.getReplyCount(), FLEET_REPLY_STORE); + radd(&out, &remain, "; ackq %d/%d await %d rtx %lu", + fleet.getReplyCount(), FLEET_REPLY_STORE, fleet.getAwaitingCount(), + (unsigned long)fleet.getReplyRetries()); radd(&out, &remain, "; badline %lu", (unsigned long)s.getBadLines()); } diff --git a/examples/simple_repeater/FleetManager.h b/examples/simple_repeater/FleetManager.h index c164999d..31c63790 100644 --- a/examples/simple_repeater/FleetManager.h +++ b/examples/simple_repeater/FleetManager.h @@ -34,12 +34,16 @@ // them in begin(); the native tests stub them. // clock: unix epoch seconds (the node RTC) // jitter: a uniform random value in [0, window) for ack reply scheduling -// sender: sends `body` as a plain group text (txt_type 0x00) on the captured -// channel, with the repeater's own name as the sender +// sender: composes `body` as a plain group text (txt_type 0x00) on the +// captured channel with the repeater's own name as sender and `ts` +// as the group timestamp, then floods it. Writes the resulting +// packet's MAX_HASH_SIZE-byte hash to `out_pkt_hash` when non-NULL. +// Returns true iff a packet was created and queued. `ts` is +// caller-supplied so a retry can reproduce the exact same packet. typedef uint32_t (*FleetTimeFn)(void* ctx); typedef uint32_t (*FleetJitterFn)(void* ctx, uint32_t window); -typedef void (*FleetSendFn)(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash, - const char* body); +typedef bool (*FleetSendFn)(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash, + uint32_t ts, const char* body, uint8_t* out_pkt_hash); // ---------------------------------------------------------------- /fleet_cfg @@ -110,13 +114,20 @@ class FleetManager { // pending acknowledgements (RAM-only, FLEET_REPLY_STORE entries): summary + // captured channel move here when a script finishes, and the reply is sent - // once its jitter deadline passes + // once its jitter deadline passes. A sent reply stays in the store until a + // repeater is heard repeating it (confirmed) or the repeat window elapses + // (then a single byte-identical resend, or nothing when FLEET_ACK_RETRY is 0) struct FleetReply { char key[FLEET_CLI_KEY_LEN + 1]; char summary[FLEET_REPLY_SUMMARY_LEN]; uint8_t chan_secret[PUB_KEY_SIZE]; uint8_t chan_hash; - uint32_t deadline_ms; // absolute millis(); wrap-safe compare + uint32_t deadline_ms; // awaiting==0: jitter deadline; + // awaiting==1: retry deadline + uint32_t tx_ts; // frozen group-text timestamp, so the + // retry is byte-identical + uint8_t pkt_hash[MAX_HASH_SIZE]; // hash of the sent packet (repeat identity) + uint8_t awaiting; // 0 = queued (pre-jitter); 1 = sent }; FleetReply replies[FLEET_REPLY_STORE]; int reply_count; @@ -124,6 +135,9 @@ class FleetManager { // RAM-only telemetry: scripts offered/matched on the fleet channel uint32_t offered; uint32_t matched; + // byte-identical resends issued: a reply whose first attempt was not heard + // repeated in time (the "not propagating" signal) + uint32_t reply_retries; LazySave save_flag; // needs save, written back by loop() @@ -182,7 +196,11 @@ public: uint32_t getOffered() const { return offered; } uint32_t getMatched() const { return matched; } int getSchedCount() const { return sched_count; } - int getReplyCount() const { return reply_count; } + // replies queued, waiting to be sent (unsent); sent ones awaiting a repeat + // occupy a store slot but are counted by getAwaitingCount() + int getReplyCount() const { return reply_count - getAwaitingCount(); } + int getAwaitingCount() const; // sent, awaiting a repeat + uint32_t getReplyRetries() const { return reply_retries; } // device service wiring (MyMesh::begin); see the typedefs above void setClock(FleetTimeFn fn, void* ctx) { time_fn = fn; time_ctx = ctx; } @@ -198,6 +216,12 @@ public: void onGroupData(const mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel, const uint8_t* data, size_t len); + // Receive-side repeat detector: called from MyMesh::logRx() for every RX + // packet, before the core's dedup gate. A packet whose hash matches an + // outstanding reply's sent packet, and which travelled at least one hop, + // confirms (drops) that reply — a neighbour repeater relayed it. + void onHeardPacket(const mesh::Packet* packet); + // Relay-side hook (MyMesh::allowPacketForward): returns true — meaning "let // the battery gate decide", not "allow" — except for the GRP_TXT/GRP_DATA // packet onGroupData() just recorded as MAC-verified under the fleet key. @@ -237,7 +261,11 @@ private: void scheduleAckIfNeeded(const CliRunResult& res); // a script with this key is armed or queued: a re-send must not run it twice bool inFlight(const char* key) const; - void sendDueReplies(); + // send every due acknowledgement, and issue a repeat-confirmation retry when + // a sent reply's window elapses without its repeat being heard + void serviceReplies(); + // shared detach: drop replies[idx], shifting the tail down + void removeReply(int idx); }; // CLI command handler: invoke with the command after "fleet" (prefix removed). diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 372da083..b0a0e4be 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -516,6 +516,8 @@ void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) { } void MyMesh::logRx(mesh::Packet *pkt, int len, float score) { + fleet.onHeardPacket(pkt); // ack repeat confirmation (pre-dedup receive hook) + #ifdef WITH_BRIDGE if (_prefs.bridge_pkt_src == 1) { bridge.sendPacket(pkt); @@ -1010,9 +1012,12 @@ static uint32_t fleetJitter(void* ctx, uint32_t window) { // captured channel, with the repeater's own name as the sender — companions // and other fleet members see an ordinary ": " message. The body // starts with the job key (charset [A-Za-z0-9._-], never '!'), so no fleet -// member can ever parse a reply as a script. -static void fleetReplySend(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash, - const char* body) { +// member can ever parse a reply as a script. Returns true iff a packet was +// created and queued, and reports its hash so FleetManager can recognise a +// neighbour's relay of it. `ts` is caller-supplied so a retry reproduces the +// exact same packet (hash). +static bool fleetReplySend(void* ctx, const uint8_t* chan_secret, uint8_t chan_hash, + uint32_t ts, const char* body, uint8_t* out_pkt_hash) { MyMesh* m = (MyMesh*)ctx; mesh::GroupChannel chan; memset(&chan, 0, sizeof(chan)); @@ -1024,16 +1029,18 @@ static void fleetReplySend(void* ctx, const uint8_t* chan_secret, uint8_t chan_h // ": " + body must fit one packet's data limit (168 B): bound the // composition so a long name truncates the tail rather than refusing the send uint8_t msg[FLEET_REPLY_DATA_MAX + 1]; - uint32_t ts = m->getRTCClock()->getCurrentTime(); memcpy(msg, &ts, 4); msg[4] = 0; // TXT_TYPE_PLAIN snprintf((char*)&msg[5], sizeof(msg) - 5, "%s: %s", m->getNodeName(), body); mesh::Packet* pkt = m->createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, chan, msg, 5 + strlen((char*)&msg[5])); + if (!pkt) return false; // pool empty: FleetManager retries later + if (out_pkt_hash) pkt->calculatePacketHash(out_pkt_hash); // flood is the only reply route (group texts carry no pubkey); the hook // method applies the repeater's configured path-hash size and its default // flood scope when set (unscoped otherwise) - if (pkt) m->sendFleetReply(pkt); + m->sendFleetReply(pkt); + return true; } // Announce battery-gate transitions on the fleet channel: one packet per diff --git a/test/test_fleet/test_fleet.cpp b/test/test_fleet/test_fleet.cpp index 56976aaa..4850aecf 100644 --- a/test/test_fleet/test_fleet.cpp +++ b/test/test_fleet/test_fleet.cpp @@ -751,10 +751,9 @@ struct GroupTextPayload { size_t len; }; -static GroupTextPayload makeGroupText(const char* sender, const char* text) { +static GroupTextPayload makeGroupTextTs(const char* sender, const char* text, uint32_t ts) { GroupTextPayload p; memset(&p, 0, sizeof(p)); - uint32_t ts = 12345; memcpy(p.data, &ts, 4); p.data[4] = TXT_TYPE_PLAIN; size_t off = 5; @@ -770,6 +769,10 @@ static GroupTextPayload makeGroupText(const char* sender, const char* text) { return p; } +static GroupTextPayload makeGroupText(const char* sender, const char* text) { + return makeGroupTextTs(sender, text, 12345); +} + // The packet the core hands onGroupDataRecv(): the payload is the channel hash // followed by the bytes (the native crypto mocks cannot MAC, so the plaintext // stands in for ciphertext; the hook only sees it through the packet hash). @@ -791,11 +794,21 @@ static void groupRecv(FleetManager& f, uint8_t type, const mesh::GroupChannel& c f.onGroupData(&pkt, type, c, p.data, p.len); } +// replay a neighbour repeater's rebroadcast of a sent packet, arriving at +// `hops` hops (the relay appends a path hash; the hash comparison ignores it) +static void hearRepeat(FleetManager& f, const mesh::Packet& sent, uint8_t hops = 1) { + mesh::Packet copy = sent; + copy.setPathHashCount(hops); + f.onHeardPacket(©); +} + // what the send callback saw struct SentReply { uint8_t secret[PUB_KEY_SIZE]; - uint8_t hash; + uint8_t hash; // channel hash + uint32_t ts = 0; // group-text timestamp std::string body; + mesh::Packet pkt; // the packet the callback claimed to send }; // injected device services, recording what they were given @@ -804,6 +817,7 @@ struct HookEnv { uint32_t clock_now = 1800000000UL; // a fixed epoch above the clock floor uint32_t jitter = 12345; uint32_t last_window = 0; + bool next_send_fails = false; // make the sender refuse the next packet ExecRecorder rec; static uint32_t timeFn(void* ctx) { return ((HookEnv*)ctx)->clock_now; } @@ -812,13 +826,22 @@ struct HookEnv { e->last_window = window; return e->jitter; } - static void sendFn(void* ctx, const uint8_t* secret, uint8_t hash, const char* body) { + static bool sendFn(void* ctx, const uint8_t* secret, uint8_t hash, uint32_t ts, + const char* body, uint8_t* out_pkt_hash) { auto* e = (HookEnv*)ctx; + if (e->next_send_fails) { e->next_send_fails = false; return false; } SentReply r; r.hash = hash; + r.ts = ts; r.body = body; memcpy(r.secret, secret, PUB_KEY_SIZE); + // compose the same packet MyMesh would, so a replayed rebroadcast of it has + // an identical calculatePacketHash() + GroupTextPayload p = makeGroupTextTs("xiao", body, ts); + r.pkt = makeGroupPacket(PAYLOAD_TYPE_GRP_TXT, hash, p); + if (out_pkt_hash) r.pkt.calculatePacketHash(out_pkt_hash); e->sent.push_back(r); + return true; } }; @@ -940,6 +963,178 @@ TEST_F(FleetHooksTest, AckAlwaysRepliesJitteredInChannel) { EXPECT_EQ(env.last_window, (uint32_t)FLEET_REPLY_WINDOW_MS); } +// --- ack repeat confirmation --------------------------------------------- + +#if FLEET_ACK_RETRY + +// A heard repeat of the reply cancels the retry: the reply is confirmed and +// dropped, and no second send is issued. +TEST_F(FleetHooksTest, AckConfirmedByRepeatCancelsRetry) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); // runs, schedules the ack + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + ASSERT_EQ(fleet.getAwaitingCount(), 1); + EXPECT_EQ(fleet.getReplyCount(), 0); // a sent reply is no longer "queued" + + hearRepeat(fleet, env.sent[0].pkt); // a neighbour relayed it + EXPECT_EQ(fleet.getAwaitingCount(), 0); + + // the window passes with no further repeat: already confirmed, nothing sent + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)1); + EXPECT_EQ(fleet.getReplyRetries(), (uint32_t)0); +} + +// No repeat within the window: exactly one byte-identical resend, then stop. +TEST_F(FleetHooksTest, AckNotRepeatedRetriesExactlyOnce) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + ASSERT_EQ(fleet.getAwaitingCount(), 1); + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)2); + EXPECT_EQ(fleet.getReplyRetries(), (uint32_t)1); + EXPECT_EQ(fleet.getAwaitingCount(), 0); // the retry is the last event + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)2); // no third send +} + +// The retry is byte-identical: same timestamp, same body, same packet hash, so +// every node that already relayed attempt 1 suppresses the copy. +TEST_F(FleetHooksTest, AckRetryIsByteIdentical) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)2); + + EXPECT_EQ(env.sent[0].ts, env.sent[1].ts); + EXPECT_EQ(env.sent[0].body, env.sent[1].body); + ASSERT_EQ(env.sent[0].pkt.payload_len, env.sent[1].pkt.payload_len); + EXPECT_EQ(memcmp(env.sent[0].pkt.payload, env.sent[1].pkt.payload, + env.sent[0].pkt.payload_len), 0); + uint8_t h0[MAX_HASH_SIZE], h1[MAX_HASH_SIZE]; + env.sent[0].pkt.calculatePacketHash(h0); + env.sent[1].pkt.calculatePacketHash(h1); + EXPECT_EQ(memcmp(h0, h1, MAX_HASH_SIZE), 0); +} + +// A zero-hop echo (bridge/mirror of the raw bytes) is not a relay: it must not +// confirm, so the retry still fires. +TEST_F(FleetHooksTest, AckZeroHopEchoDoesNotConfirm) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + + hearRepeat(fleet, env.sent[0].pkt, /*hops=*/0); + EXPECT_EQ(fleet.getAwaitingCount(), 1); // still awaiting + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)2); // retry issued + EXPECT_EQ(fleet.getReplyRetries(), (uint32_t)1); +} + +// A packet whose content differs (different hash) is not our reply. +TEST_F(FleetHooksTest, AckWrongHashDoesNotConfirm) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + + mesh::Packet other = env.sent[0].pkt; + other.setPathHashCount(1); // a real relay... + other.payload[other.payload_len - 1] ^= 0xFF; // ...of different content + fleet.onHeardPacket(&other); + EXPECT_EQ(fleet.getAwaitingCount(), 1); // not confirmed + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)2); +} + +// A refused first send used no attempt: the deadline slides by the backoff and +// the retry schedule is measured from the eventual successful send. +TEST_F(FleetHooksTest, AckSendRefusalUsesNoAttempt) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + env.next_send_fails = true; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)0); + EXPECT_EQ(fleet.getAwaitingCount(), 0); // no attempt used + + g_mock_millis += FLEET_ACK_RETRY_BACKOFF_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + EXPECT_EQ(fleet.getAwaitingCount(), 1); + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)2); // exactly one retry + EXPECT_EQ(fleet.getReplyRetries(), (uint32_t)1); +} + +#else + +// Off switch: the reply is dropped the instant the first send succeeds — +// today's fire-and-forget behavior, byte-for-byte. +TEST_F(FleetHooksTest, AckRetryOffDropsOnSend) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + ASSERT_EQ(env.sent.size(), (size_t)1); + EXPECT_EQ(fleet.getAwaitingCount(), 0); + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)1); + EXPECT_EQ(fleet.getReplyRetries(), (uint32_t)0); +} + +#endif // FLEET_ACK_RETRY + +// The kill switch clears queued and awaiting acknowledgements alike. +TEST_F(FleetHooksTest, FleetOffCancelsQueuedAndAwaitingAcks) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); // k1 sent, awaiting a repeat +#if FLEET_ACK_RETRY + ASSERT_EQ(fleet.getAwaitingCount(), 1); +#else + ASSERT_EQ(fleet.getAwaitingCount(), 0); // opt-out: dropped on send +#endif + + deliver("!id k2\n!ack\nset a"); + ASSERT_TRUE(pass()); // k2 queued, not yet due + EXPECT_EQ(fleet.getReplyCount(), 1); + + fleet.setEnabled(false); // kill switch + fleet.runScripts(ExecRecorder::fn, &env.rec); // applied + EXPECT_EQ(fleet.getReplyCount(), 0); + EXPECT_EQ(fleet.getAwaitingCount(), 0); + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); + EXPECT_EQ(env.sent.size(), (size_t)1); // nothing further sent +} + TEST_F(FleetHooksTest, AckErrSilentOnSuccessRepliesOnError) { deliver("!id k1\n!ack err\nset a"); ASSERT_TRUE(pass()); // all OK: silence means success @@ -1246,12 +1441,43 @@ TEST_F(FleetHooksTest, StatusLine) { EXPECT_NE(r.find("pending 0/2"), std::string::npos); EXPECT_NE(r.find("sched 0/2"), std::string::npos); EXPECT_NE(r.find("seen 0/32"), std::string::npos); - EXPECT_NE(r.find("ackq 0/2"), std::string::npos); + EXPECT_NE(r.find("ackq 0/2 await 0 rtx 0"), std::string::npos); EXPECT_NE(r.find("badline 0"), std::string::npos); // the psk is never echoed EXPECT_EQ(r.find("00010203"), std::string::npos); } +// onHeardPacket is inert while the fleet is off. +TEST_F(FleetHooksTest, HeardPacketInertWhileDisabled) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); + + fleet.setEnabled(false); + int awaiting = fleet.getAwaitingCount(); // whatever the retry config leaves + mesh::Packet p; + memset(&p, 0, sizeof(p)); + p.setPathHashCount(2); + fleet.onHeardPacket(&p); // inert while off: touches nothing, must not crash + EXPECT_EQ(fleet.getAwaitingCount(), awaiting); +} + +#if FLEET_ACK_RETRY +// The status line reports sent-awaiting and retried counts. +TEST_F(FleetHooksTest, StatusShowsAwaitAndRetries) { + deliver("!id k1\n!ack\nset a"); + ASSERT_TRUE(pass()); + g_mock_millis += env.jitter; + fleet.runScripts(ExecRecorder::fn, &env.rec); // sent, awaiting a repeat + EXPECT_NE(cli(fleet, "").find("await 1 rtx 0"), std::string::npos); + + g_mock_millis += FLEET_ACK_REPEAT_WINDOW_MS; + fleet.runScripts(ExecRecorder::fn, &env.rec); // missed: one retry + EXPECT_NE(cli(fleet, "").find("await 0 rtx 1"), std::string::npos); +} +#endif + TEST_F(FleetHooksTest, StatusCountsSkippedLines) { // an over-long command line is skipped at run time and shows in the status. // The whole message must fit one packet (5 B header + "alice: " + text).