Skip to main content

agentmux_srv_core/backend/lan/
mdns_health.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Is our mDNS service really announced on an IPv4 interface?
5//!
6//! `mdns-sd` builds one socket per interface when its daemon is created. For
7//! IPv4 that is a bind to `0.0.0.0:5353`, a multicast-group join and a test
8//! packet; if any step fails the crate logs at `debug!` and **skips that
9//! interface** (mdns-sd's service daemon, "bind a socket to {}: {}. Skipped."). The
10//! daemon still starts and `LAN discovery started (mDNS)` is still logged, so a
11//! host can hear its peers (over IPv6) and never be heard. That is exactly what
12//! happened on Area54 on 2026-10-01 (SPEC_LAN_FIREWALL_SETUP_2026_10_01.md 8.1).
13//!
14//! The daemon already says which interfaces it announced on: its monitor
15//! channel emits `DaemonEvent::Announce(fullname, addresses)` only for
16//! interfaces that have a working socket. This module turns that into a health
17//! verdict. It opens **no socket of its own**: a second receiver on UDP 5353
18//! would compete with the daemon it is checking (Codex P1 on #4133), and
19//! `mdns-sd` always answers by multicast, so a legacy-unicast probe from an
20//! ephemeral port would never get an answer.
21
22use std::collections::{BTreeMap, BTreeSet};
23use std::net::{IpAddr, Ipv4Addr};
24use std::str::FromStr;
25
26/// How long after start the daemon gets to announce before "nothing announced"
27/// counts as a verdict. Probing plus the first announcement takes well under a
28/// second on a healthy host.
29pub const GRACE: std::time::Duration = std::time::Duration::from_secs(5);
30
31/// Consecutive undiscoverable verdicts, one per watchdog tick, required before
32/// the daemon is rebuilt. One miss can be a slow start, not a fault.
33pub const STRIKES_BEFORE_REBUILD: u32 = 2;
34
35/// Ticks to wait after rebuild attempt k (1-based) before attempt k+1; the last
36/// value repeats for ever. At the 15 s tick that is 30 s, 1 min, 2 min, 5 min, then
37/// every 10 min. There is NO cap on the number of attempts.
38///
39/// A cap of three, 30 s apart, was the first version and it failed on Area54
40/// (0.59.4, 2026-10-02): the holder of UDP 5353 was a long-lived program (Chrome had
41/// started 14 s before srv), all three attempts landed inside the same 90 s of
42/// contention, the watchdog gave up, and by 06:32 the port was free again with
43/// nothing left to retry. A rebuild costs milliseconds, so retrying slowly for ever
44/// is the right trade; each attempt names the cause (`lan::mdns_diag`).
45pub const RETRY_AFTER_TICKS: &[u32] = &[2, 4, 8, 20, 40];
46
47/// Ticks the watchdog will keep trying to bring the daemon back when LAN is
48/// wanted but no daemon is running (a rebuild whose new daemon failed to start).
49/// Without this a transient failure inside a rebuild would leave LAN dead until
50/// the user toggled it (ReAgent P2 on #4148).
51pub const MAX_DOWN_RETRIES: u32 = 6;
52
53/// Whether this verdict should be sent to the windows on this tick.
54///
55/// The frontend learns the verdict only from `laninstances:health` events, and
56/// a window opened (or a WebSocket reconnected) after the event has no way to
57/// ask. So a standing problem is **re-sent every tick**; sending it only on
58/// change left a late window showing `peers` for as long as the fault lasted
59/// (ReAgent P1 on #4148). `Healthy` is sent only on change: no news is the
60/// frontend's default for a window with nothing recorded. `Pending` is a gap
61/// between verdicts, never news.
62pub fn should_publish(health: &MdnsHealth, changed: bool) -> bool {
63    match health {
64        MdnsHealth::Pending => false,
65        MdnsHealth::Healthy => changed,
66        MdnsHealth::Degraded { .. } | MdnsHealth::Undiscoverable { .. } => true,
67    }
68}
69
70/// How long a peer's request keeps proving that other machines can reach this one.
71pub const PEER_PROOF_WINDOW_MS: u64 = 15 * 60 * 1000;
72
73/// When another machine last made an authenticated request of this one over the
74/// LAN (Unix ms; 0 for never).
75static LAST_INBOUND_PEER_MS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
76
77/// Whether a request from `peer` is another machine reaching us: not this host talking to itself,
78/// over loopback or at one of its own interface addresses (another AgentMux instance on this host is
79/// listed as a LAN peer at the host's own address, and shows nothing about other machines).
80pub fn is_remote_peer(peer: IpAddr, own: &std::collections::HashSet<IpAddr>) -> bool {
81    !peer.is_loopback() && !peer.is_unspecified() && !own.contains(&peer)
82}
83
84/// Record a request that came in over the LAN with the LAN key. The self-check
85/// below can't see through a shared UDP 5353 (Chrome, Windows' own mDNS, others
86/// bind it too), but a peer that got through has shown it can find us.
87pub fn note_inbound_peer(peer: IpAddr) {
88    if is_remote_peer(peer, &crate::backend::lan::listeners::cached_local_addresses()) {
89        LAST_INBOUND_PEER_MS.store(agentmux_common::time::now_ms_u64(), std::sync::atomic::Ordering::Relaxed);
90    }
91}
92
93/// When a peer last reached us, if one has.
94pub fn last_inbound_peer_ms() -> Option<u64> {
95    match LAST_INBOUND_PEER_MS.load(std::sync::atomic::Ordering::Relaxed) {
96        0 => None,
97        ms => Some(ms),
98    }
99}
100
101/// The self-check's verdict, corrected by what actually happened: while a peer
102/// has reached us within the window, other machines can see this one, so an
103/// `Undiscoverable` verdict is not true. `Healthy` also stops the watchdog's
104/// rebuild count from climbing, and clears the warning.
105pub fn with_peer_proof(health: MdnsHealth, last_inbound_peer_ms: Option<u64>, now_ms: u64) -> MdnsHealth {
106    let proven = last_inbound_peer_ms.is_some_and(|t| now_ms.saturating_sub(t) <= PEER_PROOF_WINDOW_MS);
107    match health {
108        MdnsHealth::Undiscoverable { .. } if proven => MdnsHealth::Healthy,
109        other => other,
110    }
111}
112
113/// [`with_peer_proof`] with the clock and the recorded contact.
114pub fn corrected(health: MdnsHealth) -> MdnsHealth {
115    with_peer_proof(health, last_inbound_peer_ms(), agentmux_common::time::now_ms_u64())
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, Default)]
119pub enum MdnsHealth {
120    /// Too soon after start to say.
121    #[default]
122    Pending,
123    /// Announced on every IPv4 address we expect to be reachable on, or there
124    /// is no usable IPv4 address to announce on.
125    Healthy,
126    /// Announced on some expected IPv4 addresses but not all (usually a virtual
127    /// adapter). Worth a warning, not a flagged indicator.
128    Degraded { missing: Vec<Ipv4Addr> },
129    /// Announced on none of them: other machines cannot find this one.
130    Undiscoverable { missing: Vec<Ipv4Addr> },
131}
132
133impl MdnsHealth {
134    #[cfg(test)]
135    pub fn is_undiscoverable(&self) -> bool {
136        matches!(self, MdnsHealth::Undiscoverable { .. })
137    }
138
139    /// The value sent to the frontend as `state`.
140    pub fn wire_state(&self) -> &'static str {
141        match self {
142            MdnsHealth::Pending => "pending",
143            MdnsHealth::Healthy => "healthy",
144            MdnsHealth::Degraded { .. } => "degraded",
145            MdnsHealth::Undiscoverable { .. } => "undiscoverable",
146        }
147    }
148
149    pub fn missing(&self) -> &[Ipv4Addr] {
150        match self {
151            MdnsHealth::Degraded { missing } | MdnsHealth::Undiscoverable { missing } => missing,
152            _ => &[],
153        }
154    }
155}
156
157/// Every IPv4 address written in `payload`. `mdns-sd` 0.12 formats the address
158/// part of `DaemonEvent::Announce` two ways (a debug-formatted list at
159/// registration, `host:addr` on later announcements), so this scans for
160/// dotted quads and does not depend on either shape. IPv6 is ignored: only the
161/// IPv4 socket was ever missing.
162pub fn ipv4_in(payload: &str) -> Vec<Ipv4Addr> {
163    payload
164        .split(|c: char| !(c.is_ascii_digit() || c == '.'))
165        .filter(|t| !t.is_empty())
166        .filter_map(|t| Ipv4Addr::from_str(t).ok())
167        .collect()
168}
169
170/// The IPv4 addresses a LAN peer could reach us on, **grouped by interface**:
171/// not loopback, unspecified, link-local (169.254/16), multicast or broadcast.
172///
173/// Grouped because `mdns-sd` announces on ONE address per interface and IP
174/// version (`send_unsolicited_response`), so an interface with two IPv4
175/// addresses never announces its second. Counting each address would leave such
176/// a host `Degraded` for good. An interface is covered when any one of its
177/// addresses was announced.
178pub fn expected_by_interface(
179    local: impl IntoIterator<Item = (String, IpAddr)>,
180) -> Vec<BTreeSet<Ipv4Addr>> {
181    let mut by_name: BTreeMap<String, BTreeSet<Ipv4Addr>> = BTreeMap::new();
182    for (name, addr) in local {
183        let IpAddr::V4(v4) = addr else { continue };
184        if v4.is_loopback()
185            || v4.is_unspecified()
186            || v4.is_link_local()
187            || v4.is_multicast()
188            || v4.is_broadcast()
189        {
190            continue;
191        }
192        by_name.entry(name).or_default().insert(v4);
193    }
194    by_name.into_values().collect()
195}
196
197/// The verdict. Only addresses we expected count: an announcement on an address
198/// we do not listen on proves nothing about the ones we do. `missing` names one
199/// address (the lowest) per uncovered interface.
200pub fn evaluate(expected: &[BTreeSet<Ipv4Addr>], announced: &BTreeSet<Ipv4Addr>) -> MdnsHealth {
201    if expected.is_empty() {
202        return MdnsHealth::Healthy;
203    }
204    let missing: Vec<Ipv4Addr> = expected
205        .iter()
206        .filter(|iface| iface.is_disjoint(announced))
207        .filter_map(|iface| iface.iter().next().copied())
208        .collect();
209    if missing.is_empty() {
210        MdnsHealth::Healthy
211    } else if missing.len() == expected.len() {
212        MdnsHealth::Undiscoverable { missing }
213    } else {
214        MdnsHealth::Degraded { missing }
215    }
216}
217
218/// The verdict for a daemon of a given age.
219///
220/// `Pending` unless we are actually watching the daemon (`monitored`) and it has
221/// had its start-up grace. Without a monitor nothing ever fills `announced`, so
222/// evaluating would report a false `Undiscoverable` on any host with an IPv4
223/// address, rebuild three times for nothing and flag the indicator (ReAgent P1
224/// on #4148). "We cannot tell" is `Pending`, never a fault.
225pub fn verdict(
226    monitored: bool,
227    since_start: std::time::Duration,
228    expected: &[BTreeSet<Ipv4Addr>],
229    announced: &BTreeSet<Ipv4Addr>,
230) -> MdnsHealth {
231    if !monitored || since_start < GRACE {
232        return MdnsHealth::Pending;
233    }
234    evaluate(expected, announced)
235}
236
237#[derive(Debug, PartialEq, Eq)]
238pub enum Action {
239    Nothing,
240    /// Rebuild the daemon (turn LAN off and on).
241    Rebuild,
242}
243
244/// Decides, tick by tick, when an undiscoverable verdict justifies a rebuild.
245#[derive(Debug, Default)]
246pub struct Watchdog {
247    strikes: u32,
248    rebuilds: u32,
249    /// Ticks left before the next rebuild attempt is allowed.
250    cooldown: u32,
251    down_retries: u32,
252}
253
254impl Watchdog {
255    pub fn rebuilds(&self) -> u32 {
256        self.rebuilds
257    }
258
259    /// Ticks until the next attempt, right after a `Rebuild` (for the log line).
260    pub fn retry_in_ticks(&self) -> u32 {
261        self.cooldown
262    }
263
264    /// Forget everything, for when LAN is switched off.
265    pub fn reset(&mut self) {
266        *self = Watchdog::default();
267    }
268
269    /// LAN is wanted but no daemon is running. Returns whether to try starting
270    /// one again this tick. Deliberately does not touch the rebuild budget: a
271    /// failed rebuild must not wipe the count of rebuilds already spent.
272    pub fn observe_down(&mut self) -> bool {
273        if self.down_retries < MAX_DOWN_RETRIES {
274            self.down_retries += 1;
275            true
276        } else {
277            false
278        }
279    }
280
281    pub fn observe(&mut self, health: &MdnsHealth) -> Action {
282        // A daemon exists again, so the "down" retries start over.
283        self.down_retries = 0;
284        // Time passes on every tick, whatever the verdict.
285        self.cooldown = self.cooldown.saturating_sub(1);
286        match health {
287            // No verdict yet: neither a strike nor a recovery.
288            MdnsHealth::Pending => Action::Nothing,
289            MdnsHealth::Healthy => {
290                *self = Watchdog { down_retries: 0, ..Watchdog::default() };
291                Action::Nothing
292            }
293            MdnsHealth::Degraded { .. } => {
294                self.strikes = 0;
295                Action::Nothing
296            }
297            MdnsHealth::Undiscoverable { .. } => {
298                if self.rebuilds == 0 {
299                    // One miss can be a slow start; the first rebuild needs two in a row.
300                    self.strikes += 1;
301                    if self.strikes < STRIKES_BEFORE_REBUILD {
302                        return Action::Nothing;
303                    }
304                } else if self.cooldown > 0 {
305                    // Backing off between attempts.
306                    return Action::Nothing;
307                }
308                self.strikes = 0;
309                self.rebuilds += 1;
310                let step = (self.rebuilds as usize - 1).min(RETRY_AFTER_TICKS.len() - 1);
311                self.cooldown = RETRY_AFTER_TICKS[step];
312                Action::Rebuild
313            }
314        }
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    fn ip(s: &str) -> Ipv4Addr {
323        s.parse().unwrap()
324    }
325    fn set(v: &[&str]) -> BTreeSet<Ipv4Addr> {
326        v.iter().map(|s| ip(s)).collect()
327    }
328    /// One entry per interface, one address each.
329    fn ifaces(v: &[&str]) -> Vec<BTreeSet<Ipv4Addr>> {
330        v.iter().map(|s| set(&[s])).collect()
331    }
332    fn undiscoverable() -> MdnsHealth {
333        MdnsHealth::Undiscoverable { missing: vec![ip("192.168.1.26")] }
334    }
335
336    #[test]
337    fn a_peer_that_reached_us_overrides_an_undiscoverable_verdict() {
338        let now = 10_000_000;
339        let recent = Some(now - 60_000);
340        assert_eq!(with_peer_proof(undiscoverable(), recent, now), MdnsHealth::Healthy);
341        // Contact at the edge of the window still counts; past it, the verdict stands.
342        assert_eq!(with_peer_proof(undiscoverable(), Some(now - PEER_PROOF_WINDOW_MS), now), MdnsHealth::Healthy);
343        assert!(with_peer_proof(undiscoverable(), Some(now - PEER_PROOF_WINDOW_MS - 1), now).is_undiscoverable());
344        // No peer has ever reached us: the self-check stands.
345        assert!(with_peer_proof(undiscoverable(), None, now).is_undiscoverable());
346        // Other verdicts are left alone.
347        let degraded = MdnsHealth::Degraded { missing: vec![ip("198.51.100.9")] };
348        assert_eq!(with_peer_proof(degraded.clone(), recent, now), degraded);
349        assert_eq!(with_peer_proof(MdnsHealth::Pending, recent, now), MdnsHealth::Pending);
350    }
351
352    #[test]
353    fn proof_keeps_the_rebuild_count_from_climbing() {
354        let mut w = Watchdog::default();
355        assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
356        assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
357        assert_eq!(w.rebuilds(), 1);
358        // From here every tick has a peer's proof: Healthy resets the budget and nothing rebuilds.
359        for _ in 0..40 {
360            let h = with_peer_proof(undiscoverable(), Some(1), 2);
361            assert_eq!(w.observe(&h), Action::Nothing);
362        }
363        assert_eq!(w.rebuilds(), 0);
364    }
365
366    #[test]
367    fn this_host_talking_to_itself_is_not_a_peer() {
368        let own: std::collections::HashSet<IpAddr> = ["198.51.100.20".parse().unwrap()].into_iter().collect();
369        assert!(!is_remote_peer("127.0.0.1".parse().unwrap(), &own));
370        assert!(!is_remote_peer("::1".parse().unwrap(), &own));
371        assert!(!is_remote_peer("0.0.0.0".parse().unwrap(), &own));
372        // A sibling instance on this host reaches us from the host's own LAN address.
373        assert!(!is_remote_peer("198.51.100.20".parse().unwrap(), &own));
374        assert!(is_remote_peer("198.51.100.30".parse().unwrap(), &own));
375    }
376
377    #[test]
378    fn parses_the_registration_payload_shape() {
379        // `format!("{:?}", Vec<IpAddr>)`
380        let got = ipv4_in("[192.168.1.26, 172.17.16.1, fe80::1]");
381        assert_eq!(got, vec![ip("192.168.1.26"), ip("172.17.16.1")]);
382    }
383
384    #[test]
385    fn parses_the_host_colon_addr_payload_shape() {
386        assert_eq!(ipv4_in("Area54.local.:192.168.1.26"), vec![ip("192.168.1.26")]);
387        // A host label with digits must not be mistaken for an address.
388        assert!(ipv4_in("Area54.local.").is_empty());
389        assert!(ipv4_in("").is_empty());
390    }
391
392    #[test]
393    fn expected_drops_everything_a_peer_could_not_use() {
394        let local = [
395            ("lo", "127.0.0.1"),
396            ("any", "0.0.0.0"),
397            ("apipa", "169.254.21.81"),
398            ("mc", "224.0.0.251"),
399            ("bc", "255.255.255.255"),
400            ("Ethernet", "192.168.1.26"),
401            ("vEthernet", "172.17.16.1"),
402            ("v6only", "fe80::1"),
403        ]
404        .map(|(n, a)| (n.to_string(), a.parse::<IpAddr>().unwrap()));
405        assert_eq!(expected_by_interface(local), vec![set(&["192.168.1.26"]), set(&["172.17.16.1"])]);
406    }
407
408    #[test]
409    fn two_addresses_on_one_interface_are_one_group() {
410        let local = [("Ethernet", "192.168.1.26"), ("Ethernet", "192.168.1.27"), ("Wi-Fi", "10.0.0.5")]
411            .map(|(n, a)| (n.to_string(), a.parse::<IpAddr>().unwrap()));
412        assert_eq!(
413            expected_by_interface(local),
414            vec![set(&["192.168.1.26", "192.168.1.27"]), set(&["10.0.0.5"])]
415        );
416    }
417
418    #[test]
419    fn nothing_to_announce_on_is_not_a_fault() {
420        assert_eq!(evaluate(&[], &set(&[])), MdnsHealth::Healthy);
421    }
422
423    #[test]
424    fn announced_on_all_expected_is_healthy() {
425        let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
426        assert_eq!(evaluate(&e, &set(&["192.168.1.26", "172.17.16.1"])), MdnsHealth::Healthy);
427    }
428
429    // ReAgent P2 on #4148: mdns-sd announces one address per interface, so the
430    // second address of a NIC is never announced and must not count as missing.
431    #[test]
432    fn an_interface_is_covered_by_any_one_of_its_addresses() {
433        let e = vec![set(&["192.168.1.26", "192.168.1.27"])];
434        assert_eq!(evaluate(&e, &set(&["192.168.1.26"])), MdnsHealth::Healthy);
435        assert_eq!(evaluate(&e, &set(&["192.168.1.27"])), MdnsHealth::Healthy);
436    }
437
438    #[test]
439    fn announcements_outside_the_expected_set_prove_nothing() {
440        let e = ifaces(&["192.168.1.26"]);
441        assert!(evaluate(&e, &set(&["10.9.9.9"])).is_undiscoverable());
442    }
443
444    #[test]
445    fn the_area54_case_is_undiscoverable() {
446        // Both IPv4 interfaces expected; the daemon announced on neither.
447        let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
448        let h = evaluate(&e, &set(&[]));
449        assert_eq!(h.wire_state(), "undiscoverable");
450        assert_eq!(h.missing(), &[ip("192.168.1.26"), ip("172.17.16.1")]);
451    }
452
453    #[test]
454    fn a_missing_virtual_adapter_alone_is_only_degraded() {
455        let e = ifaces(&["192.168.1.26", "172.17.16.1"]);
456        let h = evaluate(&e, &set(&["192.168.1.26"]));
457        assert_eq!(h, MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] });
458        assert!(!h.is_undiscoverable());
459    }
460
461    #[test]
462    fn a_standing_problem_is_resent_every_tick_so_a_late_window_learns_of_it() {
463        // ReAgent P1 on #4148.
464        let bad = undiscoverable();
465        for _ in 0..3 {
466            assert!(should_publish(&bad, false), "unchanged but still broken: resend");
467        }
468        let degraded = MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] };
469        assert!(should_publish(&degraded, false));
470    }
471
472    #[test]
473    fn healthy_is_only_sent_on_change_and_pending_never() {
474        assert!(should_publish(&MdnsHealth::Healthy, true), "recovery must clear a warning");
475        assert!(!should_publish(&MdnsHealth::Healthy, false));
476        assert!(!should_publish(&MdnsHealth::Pending, true));
477        assert!(!should_publish(&MdnsHealth::Pending, false));
478    }
479
480    #[test]
481    fn a_down_daemon_is_retried_a_bounded_number_of_times() {
482        let mut w = Watchdog::default();
483        let tries = (0..20).filter(|_| w.observe_down()).count() as u32;
484        assert_eq!(tries, MAX_DOWN_RETRIES);
485    }
486
487    #[test]
488    fn a_failed_rebuild_does_not_wipe_the_rebuild_budget() {
489        // ReAgent P2 on #4148: rebuild, the new daemon fails to start, the watchdog
490        // sees "down" and retries. The spent rebuild must still be counted.
491        let mut w = Watchdog::default();
492        w.observe(&undiscoverable());
493        assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
494        assert_eq!(w.rebuilds(), 1);
495        assert!(w.observe_down());
496        assert!(w.observe_down());
497        assert_eq!(w.rebuilds(), 1, "still counted while the daemon is down");
498    }
499
500    #[test]
501    fn a_daemon_coming_back_restores_the_retries() {
502        let mut w = Watchdog::default();
503        while w.observe_down() {}
504        assert!(!w.observe_down(), "exhausted");
505        w.observe(&MdnsHealth::Pending); // a daemon exists again
506        assert!(w.observe_down(), "retries start over");
507    }
508
509    #[test]
510    fn no_monitor_means_no_verdict_however_long_it_has_been() {
511        // ReAgent P1 on #4148: nothing would ever fill `announced`.
512        let e = ifaces(&["192.168.1.26"]);
513        let long_ago = GRACE * 100;
514        assert_eq!(verdict(false, long_ago, &e, &set(&[])), MdnsHealth::Pending);
515        assert_eq!(verdict(false, long_ago, &e, &set(&["192.168.1.26"])), MdnsHealth::Pending);
516    }
517
518    #[test]
519    fn a_monitored_daemon_gets_its_start_up_grace_then_a_verdict() {
520        let e = ifaces(&["192.168.1.26"]);
521        assert_eq!(verdict(true, GRACE / 2, &e, &set(&[])), MdnsHealth::Pending);
522        assert!(verdict(true, GRACE, &e, &set(&[])).is_undiscoverable());
523        assert_eq!(verdict(true, GRACE, &e, &set(&["192.168.1.26"])), MdnsHealth::Healthy);
524    }
525
526    #[test]
527    fn one_miss_is_not_enough_to_rebuild() {
528        let mut w = Watchdog::default();
529        assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
530        assert_eq!(w.rebuilds(), 0);
531    }
532
533    #[test]
534    fn two_consecutive_misses_rebuild_and_a_pending_verdict_does_not_count() {
535        let mut w = Watchdog::default();
536        assert_eq!(w.observe(&undiscoverable()), Action::Nothing);
537        // The rebuilt daemon reports Pending: not a strike, not a recovery.
538        assert_eq!(w.observe(&MdnsHealth::Pending), Action::Nothing);
539        assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
540        assert_eq!(w.rebuilds(), 1);
541    }
542
543    #[test]
544    fn a_healthy_tick_resets_the_strikes() {
545        let mut w = Watchdog::default();
546        w.observe(&undiscoverable());
547        w.observe(&MdnsHealth::Healthy);
548        assert_eq!(w.observe(&undiscoverable()), Action::Nothing, "strikes restarted");
549    }
550
551    /// Never gives up, and backs off: the gaps between attempts are 2, 4, 8, 20 then 40
552    /// ticks, for ever. (The first version stopped after three, 30 s apart, and failed on
553    /// Area54: the port was free again minutes later and nothing was left to retry.)
554    #[test]
555    fn rebuilds_back_off_and_never_stop() {
556        let mut w = Watchdog::default();
557        let mut at = Vec::new();
558        for tick in 1..=400u32 {
559            if w.observe(&undiscoverable()) == Action::Rebuild {
560                at.push(tick);
561            }
562        }
563        let gaps: Vec<u32> = at.windows(2).map(|p| p[1] - p[0]).collect();
564        assert_eq!(at[0], 2, "the first rebuild needs two misses in a row");
565        assert_eq!(&gaps[..5], &[2, 4, 8, 20, 40], "{at:?}");
566        assert!(gaps[5..].iter().all(|g| *g == 40), "settles at one attempt per 40 ticks: {gaps:?}");
567        assert!(400 - at.last().unwrap() < 40, "still retrying at the end: {at:?}");
568        assert!(at.len() > 10, "far more than the old cap of 3: {}", at.len());
569    }
570
571    /// The Area54 timeline: a long-lived program holds the port for minutes, then lets
572    /// go. Every attempt while it holds fails; the first one after it lets go succeeds.
573    /// Under the old cap this never recovered.
574    #[test]
575    fn a_holder_that_lets_go_minutes_later_is_still_recovered() {
576        const HOLDER_LEAVES_AT_TICK: u32 = 28; // 7 minutes at the 15 s tick
577        let mut w = Watchdog::default();
578        let mut recovered_ok = false;
579        let mut recovered_at = None;
580        for tick in 1..=200u32 {
581            let health = if recovered_ok { MdnsHealth::Healthy } else { undiscoverable() };
582            if w.observe(&health) == Action::Rebuild {
583                // A rebuilt daemon announces only if the port is free by then.
584                recovered_ok = tick >= HOLDER_LEAVES_AT_TICK;
585            }
586            if recovered_ok && recovered_at.is_none() {
587                recovered_at = Some(tick);
588            }
589        }
590        let at = recovered_at.expect("it must recover once the holder lets go");
591        assert!((HOLDER_LEAVES_AT_TICK..HOLDER_LEAVES_AT_TICK + 40).contains(&at), "recovered at tick {at}");
592        assert_eq!(w.rebuilds(), 0, "full health restores the budget");
593    }
594
595    #[test]
596    fn the_next_attempt_time_is_exposed_for_the_log_line() {
597        let mut w = Watchdog::default();
598        w.observe(&undiscoverable());
599        assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
600        assert_eq!(w.retry_in_ticks(), RETRY_AFTER_TICKS[0]);
601    }
602
603    #[test]
604    fn recovery_restores_the_rebuild_budget() {
605        let mut w = Watchdog::default();
606        for _ in 0..40 {
607            w.observe(&undiscoverable());
608        }
609        w.observe(&MdnsHealth::Healthy);
610        assert_eq!(w.rebuilds(), 0);
611        w.observe(&undiscoverable());
612        assert_eq!(w.observe(&undiscoverable()), Action::Rebuild);
613    }
614
615    #[test]
616    fn degraded_does_not_clear_the_rebuild_count_but_does_clear_strikes() {
617        let mut w = Watchdog::default();
618        w.observe(&undiscoverable());
619        w.observe(&undiscoverable()); // rebuild #1
620        assert_eq!(w.rebuilds(), 1);
621        w.observe(&MdnsHealth::Degraded { missing: vec![ip("172.17.16.1")] });
622        assert_eq!(w.rebuilds(), 1, "only full health restores the budget");
623    }
624}