From 0c6a69edac0384098b07b05010a22ca6f3fd1e7a Mon Sep 17 00:00:00 2001 From: Igor Yamolov Date: Tue, 17 Nov 2026 20:12:07 +0100 Subject: [PATCH 1/3] Look for cheaper routes in the background --- crates/ziggurat-driver/src/zigbee_stack.rs | 14 + .../src/zigbee_stack/neighbor.rs | 6 + .../ziggurat-driver/src/zigbee_stack/nwk.rs | 6 + .../ziggurat-driver/src/zigbee_stack/route.rs | 17 +- .../src/zigbee_stack/route_refresh.rs | 240 +++++++++ crates/ziggurat-zigbee/src/constants.rs | 21 + crates/ziggurat-zigbee/src/nwk.rs | 1 + crates/ziggurat-zigbee/src/nwk/neighbors.rs | 89 +++- .../ziggurat-zigbee/src/nwk/route_refresh.rs | 324 ++++++++++++ .../src/nwk/route_refresh/tests.rs | 488 ++++++++++++++++++ crates/ziggurat-zigbee/src/nwk/routing.rs | 100 +++- .../ziggurat-zigbee/src/nwk/routing/tests.rs | 195 +++++++ 12 files changed, 1497 insertions(+), 4 deletions(-) create mode 100644 crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs create mode 100644 crates/ziggurat-zigbee/src/nwk/route_refresh.rs create mode 100644 crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs diff --git a/crates/ziggurat-driver/src/zigbee_stack.rs b/crates/ziggurat-driver/src/zigbee_stack.rs index 832cc811..fbed6e93 100644 --- a/crates/ziggurat-driver/src/zigbee_stack.rs +++ b/crates/ziggurat-driver/src/zigbee_stack.rs @@ -34,6 +34,7 @@ mod mac; mod neighbor; mod nwk; mod route; +mod route_refresh; mod send_handle; mod sends; mod tasklets; @@ -57,6 +58,7 @@ pub use ziggurat_zigbee::nwk::broadcast_budget::{ pub use ziggurat_zigbee::nwk::broadcasts::Broadcasts; pub use ziggurat_zigbee::nwk::neighbors::Neighbors; pub use ziggurat_zigbee::nwk::next_hop::{HostRoute, RouteDirective, SendMode}; +pub use ziggurat_zigbee::nwk::route_refresh::RouteRefresh; pub use ziggurat_zigbee::nwk::routing::Routing; pub use ziggurat_zigbee::nwk::security::NwkSecurity; pub use ziggurat_zigbee::nwk::{neighbors, routing}; @@ -358,6 +360,8 @@ pub struct Nib { pub mtorr_debouncer: Debouncer, /// NWK routing state and decision logic (route/discovery/record tables) pub routing: Routing, + /// The routes to look at again in the background, and when + pub route_refresh: RouteRefresh, /// Broadcast deduplication and passive acknowledgment accounting pub broadcasts: Broadcasts, /// The network key, its outgoing frame counter, and per-relayer replay protection @@ -517,6 +521,7 @@ impl State { link_status_debouncer: Debouncer::default(), mtorr_debouncer: Debouncer::default(), routing: Routing::default(), + route_refresh: RouteRefresh::default(), broadcasts: Broadcasts::default(), nwk_security: NwkSecurity::new( config.network_key.clone(), @@ -728,6 +733,9 @@ pub struct ZigbeeStack { /// earlier pub(crate) mtorr_wake: Notify, + /// Wakes the route refresh task when a trigger queued a destination + pub(crate) route_refresh_kick: Notify, + /// Signaled whenever a link status command is digested; the MTORR startup wait /// uses it to advertise as soon as a neighbor link is established pub(crate) link_status_received: Notify, @@ -880,6 +888,7 @@ impl ZigbeeStack { src_match_written: Mutex::new(SrcMatchTable::default()), parent_annce_received: Mutex::new(None), mtorr_wake: Notify::new(), + route_refresh_kick: Notify::new(), link_status_received: Notify::new(), link_status_wake: Notify::new(), address_conflict_wake: Notify::new(), @@ -1141,6 +1150,11 @@ impl ZigbeeStack { }); } + // Look again, in the background, at routes that may have become cheaper + self.spawn_tracked(|arc_self| async move { + arc_self.route_refresh_task().await; + }); + // Reprogram the radio whenever it resets out from under us self.spawn_tracked(|arc_self| async move { arc_self.radio_recovery_task().await; diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index a1b5d0c6..292692b0 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -148,6 +148,12 @@ impl ZigbeeStack { self.request_link_status_for_new_router(); } + // The link works again: the routes that failed through it may be cheaper + // through it than on their detour + if let Some(neighbor_nwk) = outcome.restored_link { + self.note_hop_recovered(neighbor_nwk); + } + self.link_status_received.notify_one(); } diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 078ee6cb..53d4712e 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -59,6 +59,7 @@ impl ZigbeeStack { self.core_now(), self.activity_params(), ); + core.nib.route_refresh.forget(nwk); core.sends.fail_unrouted(nwk); self.commit_sends(core); } @@ -405,6 +406,7 @@ impl ZigbeeStack { let mut core = self.core(); nwk_frame.nwk_header.sequence_number = core.nib.next_sequence_number(); + let hint_stands_in = self.hint_stands_in_for_a_route(&core.nib, destination, &mode); let resolved = next_hop::resolve( &core.nib.routing, &core.nib.neighbors, @@ -416,6 +418,10 @@ impl ZigbeeStack { let handle = match resolved { NextHop::Resolved(next_hop) => { + if hint_stands_in { + self.queue_hinted_refresh(&mut core.nib, destination); + } + let poll_address = Self::poll_address(&core.nib, next_hop); self.enqueue_unicast_in( &mut core, diff --git a/crates/ziggurat-driver/src/zigbee_stack/route.rs b/crates/ziggurat-driver/src/zigbee_stack/route.rs index a5e653a7..6746f155 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route.rs @@ -47,6 +47,12 @@ impl ZigbeeStack { self.activity_params(), ); + // A reply to our refresh counts as an answer even when it does not replace the + // route, so it is noted before the disposition can drop it + if route_reply_cmd.originator_nwk == self.state.network_address { + self.note_refresh_reply(route_reply_cmd.responder_nwk, outcome.update); + } + let (next_hop_nwk, path_cost) = match outcome.disposition { RouteReplyDisposition::Drop => return, RouteReplyDisposition::Established => { @@ -408,8 +414,17 @@ impl ZigbeeStack { } } + /// Every active route through `next_hop` fails. Their destinations are noted as + /// displaced from it, so route refresh tries them again when the hop recovers. pub(super) fn invalidate_routes_via(&self, next_hop: Nwk) { - self.core().nib.routing.invalidate_via(next_hop); + let now = self.core_now(); + let mut guard = self.core(); + let nib = &mut guard.nib; + + for destination in nib.routing.invalidate_via(next_hop) { + nib.route_refresh.note_displaced(destination, next_hop, now); + } + drop(guard); } /// Zigbee spec 3.6.4.8.1: another router could not deliver a frame we originated; diff --git a/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs b/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs new file mode 100644 index 00000000..96995a61 --- /dev/null +++ b/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs @@ -0,0 +1,240 @@ +//! Route refresh in the driver: the wait for the neighbors to settle after a start, +//! and the task that paces the refresh discoveries `RouteRefresh` decides on. + +use crate::runtime::Runtime; +use ziggurat_ieee_802154::types::Nwk; +use ziggurat_phy::RadioPhy; +use ziggurat_zigbee::nwk::route_refresh::{RefreshReason, RouteRefreshPolicy}; +use ziggurat_zigbee::nwk::routing::RouteUpdate; + +use super::{Nib, RouteDirective, SendMode, ZigbeeStack}; + +impl ZigbeeStack { + /// Wait for the neighbors to settle after a start, before route refresh looks at + /// any route. Receivers drop route requests from senders with a zero outgoing + /// cost, and the empty link status sent at startup has just zeroed it on every + /// neighbor. Wait one link status period, so every router neighbor gets to send its + /// link status, then tell them all their side with one of our own. A router that + /// answers at once is not enough: the others would still drop our requests. + async fn settle_after_start(&self) { + self.sleep_until_core(self.core_now() + self.tunables.link_status_period()) + .await; + + if let Ok(link_status) = self.send_link_status_broadcast(false) { + let _ = link_status.delivered().await; + } + } + + /// The route refresh tunables, read afresh so a change takes effect at once. + fn route_refresh_policy(&self) -> RouteRefreshPolicy { + RouteRefreshPolicy { + spacing: self.tunables.route_refresh_spacing(), + backoff: self.tunables.route_refresh_backoff(), + backoff_max: self.tunables.route_refresh_backoff_max(), + displaced_retention: self.tunables.displaced_route_retention(), + } + } + + /// Once the neighbors have settled after the start, look again, in the background, + /// at the routes found before, then at whatever the triggers queue. One refresh + /// discovery goes out per `route_refresh_spacing` at most, and none while a frame + /// waits for a discovery: frames come first. A refresh keeps the route in use until + /// a strictly cheaper reply arrives (`Routing::begin_refresh`). + /// + /// The `route_refresh` tunable is read on every pass: off, the task issues nothing + /// and the triggers queue nothing. The settle step, and the settle trigger, only + /// run if it is on at the start. + pub async fn route_refresh_task(&self) { + if self.tunables.route_refresh() { + self.settle_after_start().await; + + let settled = { + let mut guard = self.core(); + let nib = &mut guard.nib; + let policy = self.next_hop_policy(); + let destinations = nib + .routing + .refreshable_destinations(policy.is_concentrator, policy.max_source_route); + + for &destination in &destinations { + nib.route_refresh + .enqueue(destination, RefreshReason::Settled); + } + + drop(guard); + destinations.len() + }; + tracing::info!("Neighbors settled: refreshing {settled} routes found before"); + } + + loop { + let wake = if self.tunables.route_refresh() { + self.refresh_routes() + } else { + self.core_now() + self.tunables.route_discovery_time() + }; + + let _ = self + .timeout_at_core(wake, self.route_refresh_kick.notified()) + .await; + } + } + + /// One pass of the route refresh task: note the refreshes that went unanswered, + /// issue the next one that is due, and return when the next pass is due. + fn refresh_routes(&self) -> ziggurat_zigbee::Instant { + let policy = self.route_refresh_policy(); + let route_discovery_time = self.tunables.route_discovery_time(); + let own_address = self.state.network_address; + let now = self.core_now(); + + let mut guard = self.core(); + let core = &mut *guard; + + for missed in core.nib.route_refresh.tick(now, policy) { + let destination = missed.destination; + match missed.retry_in { + Some(backoff) => tracing::info!( + "Route refresh: no reply from {destination:?}, next try in {backoff:?}" + ), + None => { + tracing::info!("Route refresh: no reply from {destination:?}, giving up on it"); + } + } + } + + let frames_wait = core.nib.routing.frames_await_discovery(); + let mut issued = false; + + if !frames_wait + && let Some((destination, reason)) = core.nib.route_refresh.next_due(now, policy) + { + match core.nib.routing.begin_refresh( + own_address, + destination, + now, + route_discovery_time, + self.activity_params(), + ) { + Some(request_id) => { + tracing::info!("Route refresh: refreshing {destination:?} ({reason:?})"); + self.broadcast_discovery_request(core, destination, request_id); + core.nib.route_refresh.issued( + destination, + reason, + now, + now + route_discovery_time, + ); + issued = true; + } + None => { + tracing::debug!( + "Route refresh: {destination:?} is already under discovery, skipping" + ); + } + } + } + + // Nothing pending: check back at the discovery time. While frames wait for a + // discovery, check back no sooner than the spacing, or a due refresh would spin. + let next_wake = core + .nib + .route_refresh + .next_wake(now, policy) + .unwrap_or(now + route_discovery_time); + let next_wake = if frames_wait { + next_wake.max(now + policy.spacing) + } else { + next_wake + }; + + if issued { + self.commit_sends(guard); + } + + next_wake + } + + /// `hop` works again, as a link status shows or as the server learns another way + /// (a backbone peer that answers again). The routes that failed through it are + /// refreshed: they may be cheaper through it than on their detour. + pub fn note_hop_recovered(&self, hop: Nwk) { + if !self.tunables.route_refresh() { + return; + } + + let now = self.core_now(); + let policy = self.route_refresh_policy(); + let queued = self + .core() + .nib + .route_refresh + .hop_recovered(hop, now, policy); + + if queued > 0 { + tracing::info!("Next hop {hop:?} works again: refreshing {queued} routes"); + self.route_refresh_kick.notify_one(); + } + } + + /// A route reply to a discovery of ours from `responder`. If it answers a refresh, + /// the refresh ends and the destination's back-off with it; `update` is the route + /// it moved, if it did. + pub(super) fn note_refresh_reply(&self, responder: Nwk, update: Option) { + if !self.core().nib.route_refresh.note_reply(responder) { + return; + } + + if let Some(update) = update { + tracing::info!( + "Route refresh: {:?} now via {:?} at cost {}", + update.destination, + update.next_hop, + update.path_cost + ); + } + + // The next refresh may be due now that this one is no longer in flight + self.route_refresh_kick.notify_one(); + } + + /// Whether a send in `mode` to `destination` would go by a host route hint because + /// the stack has no route of its own. Checked beside `next_hop::resolve`, which + /// stays unaware of route refresh. End device children are reached directly and + /// need no route. + pub(super) fn hint_stands_in_for_a_route( + &self, + nib: &Nib, + destination: Nwk, + mode: &SendMode, + ) -> bool { + if !matches!(mode, SendMode::Route(RouteDirective::Hint(_))) + || nib.neighbors.end_device_child_eui64(destination).is_some() + { + return false; + } + + let policy = self.next_hop_policy(); + let stack_route = if policy.is_concentrator { + nib.routing + .route_to(destination, policy.max_source_route) + .is_some() + } else { + nib.routing.next_hop(destination).is_some() + }; + + !stack_route + } + + /// A host route hint stood in for a route to `destination`: refresh it, so a real + /// route takes over before the host stops hinting. + pub(super) fn queue_hinted_refresh(&self, nib: &mut Nib, destination: Nwk) { + if !self.tunables.route_refresh() { + return; + } + + nib.route_refresh + .enqueue(destination, RefreshReason::Hinted); + self.route_refresh_kick.notify_one(); + } +} diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 3f8aa143..179f881b 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -345,6 +345,27 @@ tunables! { /// together. pending_route_discovery_attempts: u8 = 1, + /// Route refresh: look again for cheaper routes in the background, without + /// dropping the route in use, after the neighbors settle following a start, for + /// destinations only a host route hint reached, and for routes that failed through + /// a hop that works again. + route_refresh: bool = true, + + /// The least time between two route refreshes. It bounds the broadcasts route + /// refresh adds to the network. + route_refresh_spacing: Duration = Duration::from_secs(2), + + /// How long a destination that did not answer a route refresh waits before the + /// next one. Each later miss doubles it, up to `route_refresh_backoff_max`. + route_refresh_backoff: Duration = Duration::from_secs(60), + + /// The longest wait between route refreshes of a destination that does not answer. + route_refresh_backoff_max: Duration = Duration::from_secs(30 * 60), + + /// How long after its route failed through a hop a destination is refreshed when + /// that hop works again. + displaced_route_retention: Duration = Duration::from_secs(10 * 60), + /// The default timeout for any end device child that does not negotiate a /// different value via the End Device Timeout Request command (spec 3.6.10.2). end_device_timeout_default: EndDeviceTimeout = EndDeviceTimeout::Minutes256, diff --git a/crates/ziggurat-zigbee/src/nwk.rs b/crates/ziggurat-zigbee/src/nwk.rs index 818c5d89..6ac5d192 100644 --- a/crates/ziggurat-zigbee/src/nwk.rs +++ b/crates/ziggurat-zigbee/src/nwk.rs @@ -7,6 +7,7 @@ pub mod commands; pub mod frame; pub mod neighbors; pub mod next_hop; +pub mod route_refresh; pub mod routing; pub mod security; diff --git a/crates/ziggurat-zigbee/src/nwk/neighbors.rs b/crates/ziggurat-zigbee/src/nwk/neighbors.rs index cc09af65..c22093d7 100644 --- a/crates/ziggurat-zigbee/src/nwk/neighbors.rs +++ b/crates/ziggurat-zigbee/src/nwk/neighbors.rs @@ -193,6 +193,10 @@ pub struct LinkStatusOutcome { /// The sender's address, if its outgoing cost collapsed to zero: the link is /// considered broken and routes through it must be invalidated (spec 3.6.4.4.2). pub lost_link: Option, + /// The sender's address, if its outgoing cost rose from zero: the link works again + /// (or for the first time), and routes that failed through it may be worth looking + /// at again. + pub restored_link: Option, /// The sender's previous network address, if the link status came from a new one. pub replaced_address: Option, /// Our link status lists the sender from now on and did not before, so the sender @@ -914,9 +918,11 @@ impl Neighbors { tracing::trace!("Updated neighbor table entry: {neighbor_entry:?}"); let lost_link = previous_outgoing_cost > 0 && neighbor_entry.outgoing_cost == 0; + let restored_link = previous_outgoing_cost == 0 && neighbor_entry.outgoing_cost > 0; LinkStatusOutcome { lost_link: lost_link.then_some(neighbor_entry.network_address), + restored_link: restored_link.then_some(neighbor_entry.network_address), replaced_address, link_status_due: !was_in_link_status && neighbor_entry.is_in_link_status(), link_status_answer_due: link_status_cmd.link_statuses.is_empty(), @@ -1017,7 +1023,9 @@ mod test { let link_status = link_status_listing(own); let mut neighbors = Neighbors::default(); - neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); + // A new router's first link status listing us is a link that works + let outcome = neighbors.on_link_status(own, router, old, 200, &link_status, now, ACTIVITY); + assert_eq!(outcome.restored_link, Some(old)); neighbors.record_lqa(old, 200); neighbors.record_lqa(old, 200); assert_eq!(neighbors.link(old).unwrap().eui64, router); @@ -1032,6 +1040,7 @@ mod test { outcome, LinkStatusOutcome { lost_link: None, + restored_link: None, replaced_address: Some(old), link_status_due: false, link_status_answer_due: false, @@ -1102,6 +1111,7 @@ mod test { outcome, LinkStatusOutcome { lost_link: None, + restored_link: None, replaced_address: None, link_status_due: true, link_status_answer_due: true, @@ -1114,6 +1124,7 @@ mod test { outcome, LinkStatusOutcome { lost_link: None, + restored_link: None, replaced_address: None, link_status_due: false, link_status_answer_due: true, @@ -1183,6 +1194,7 @@ mod test { outcome, LinkStatusOutcome { lost_link: Some(router_nwk), + restored_link: None, replaced_address: None, link_status_due: false, link_status_answer_due: false, @@ -1392,6 +1404,81 @@ mod test { assert_eq!(inbound_activity(&neighbors), 1); } + const OWN: Nwk = Nwk(0x0000); + const ROUTER_NWK: Nwk = Nwk(0x4965); + + fn link_status_from_router( + neighbors: &mut Neighbors, + listing: Nwk, + at: Instant, + ) -> LinkStatusOutcome { + let cmd = NwkLinkStatusCommand { + is_first_frame: true, + is_last_frame: true, + link_statuses: vec![NwkLinkStatus { + address: listing, + incoming_cost: 1, + outgoing_cost: 1, + }], + }; + neighbors.on_link_status( + OWN, + Eui64::from_hex("20:6e:f1:ff:fe:0a:d8:8c"), + ROUTER_NWK, + 255, + &cmd, + at, + ACTIVITY, + ) + } + + /// The router's link status, listing us (cost 1) or not (cost 0 toward us). + fn link_status_toward_us(neighbors: &mut Neighbors, listed: bool) -> LinkStatusOutcome { + let listing = if listed { OWN } else { Nwk(0x1111) }; + link_status_from_router(neighbors, listing, Instant::from_micros(0)) + } + + #[test] + fn test_link_status_restoring_the_cost_toward_us_reports_a_restored_link() { + let mut neighbors = Neighbors::default(); + link_status_toward_us(&mut neighbors, true); + link_status_toward_us(&mut neighbors, false); + + let outcome = link_status_toward_us(&mut neighbors, true); + + assert_eq!(outcome.restored_link, Some(ROUTER_NWK)); + } + + #[test] + fn test_link_status_keeping_the_cost_toward_us_reports_no_restored_link() { + let mut neighbors = Neighbors::default(); + link_status_toward_us(&mut neighbors, true); + + let outcome = link_status_toward_us(&mut neighbors, true); + + assert_eq!(outcome.restored_link, None); + } + + #[test] + fn test_link_status_dropping_the_cost_toward_us_reports_no_restored_link() { + let mut neighbors = Neighbors::default(); + link_status_toward_us(&mut neighbors, true); + + let outcome = link_status_toward_us(&mut neighbors, false); + + assert_eq!(outcome.restored_link, None); + } + + #[test] + fn test_link_status_dropping_the_cost_toward_us_reports_a_lost_link() { + let mut neighbors = Neighbors::default(); + link_status_toward_us(&mut neighbors, true); + + let outcome = link_status_toward_us(&mut neighbors, false); + + assert_eq!(outcome.lost_link, Some(ROUTER_NWK)); + } + #[test] fn test_only_end_device_children_time_out() { let mut neighbors = neighbors_with(NwkDeviceType::EndDevice); diff --git a/crates/ziggurat-zigbee/src/nwk/route_refresh.rs b/crates/ziggurat-zigbee/src/nwk/route_refresh.rs new file mode 100644 index 00000000..b23c6b5d --- /dev/null +++ b/crates/ziggurat-zigbee/src/nwk/route_refresh.rs @@ -0,0 +1,324 @@ +//! Route refresh: a paced queue of destinations whose working routes are worth +//! looking at again. +//! +//! Ziggurat changes a route only when something fails, so a route found while the +//! network was still settling stays expensive for good. Route refresh re-discovers +//! routes in three cases (see `RefreshReason`) and backs off for destinations that do +//! not answer. This is the pure decision logic: the driver paces it, issues the +//! discoveries through `Routing::begin_refresh`, and reports replies. +//! +//! Deviation from the proposal: the rate is bounded by a fixed spacing between +//! refreshes only, with no separate per-minute cap; the spacing already bounds it. + +use alloc::vec::Vec; +use core::time::Duration; + +use ziggurat_ieee_802154::types::Nwk; + +use crate::Instant; +use crate::flat_map::FlatMap; + +#[cfg(test)] +mod tests; + +/// At most this many destinations are remembered as displaced from one hop. When the +/// list is full, the oldest is dropped. +pub const MAX_DISPLACED_PER_HOP: usize = 32; + +/// How many tries at the longest back-off a destination that does not answer gets. +/// +/// The next miss gives up on it: a device that is gone for good, or an address it no +/// longer holds, would otherwise draw a network-wide route request every back-off for +/// ever. A later trigger queues it again from the start. +pub const MAX_RETRIES_AT_CAP: u8 = 3; + +/// Network addresses from here up are broadcast addresses: no route goes to them. +const FIRST_BROADCAST_ADDRESS: u16 = 0xFFF8; + +/// Why a destination is due for a refresh. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RefreshReason { + /// Its route was found before the neighbors settled after a start, while some of + /// them may still have dropped our route requests. + Settled, + /// Only a host route hint reached it: a real route lets the hint expire. + Hinted, + /// Its route failed through a hop that works again. + HopRecovered, +} + +/// The tunables route refresh runs by. Passed in, never stored, so a changed tunable +/// takes effect on the next call. +#[derive(Debug, Clone, Copy)] +pub struct RouteRefreshPolicy { + /// The least time between two refreshes. + pub spacing: Duration, + /// The wait before trying a destination again after its first unanswered refresh. + /// Each later miss doubles it. + pub backoff: Duration, + /// The longest back-off. + pub backoff_max: Duration, + /// How long a destination displaced from a hop is worth refreshing when the hop + /// recovers. + pub displaced_retention: Duration, +} + +/// An unanswered refresh. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Missed { + pub destination: Nwk, + /// The back-off before the next try, or `None` when route refresh gave up on the + /// destination. + pub retry_in: Option, +} + +/// The back-off a destination's last unanswered refresh got. +#[derive(Debug, Clone, Copy)] +struct Backoff { + duration: Duration, + /// How many misses in a row got the longest back-off. + at_cap: u8, +} + +#[derive(Debug)] +struct Queued { + destination: Nwk, + reason: RefreshReason, + /// Not due before this instant: the destination is in back-off. + not_before: Option, +} + +#[derive(Debug)] +struct InFlight { + reason: RefreshReason, + deadline: Instant, +} + +/// The queue of destinations to refresh, the destinations displaced from each hop, +/// the refreshes in flight, and a back-off per destination. +#[derive(Debug, Default)] +pub struct RouteRefresh { + /// Oldest first, one entry per destination. + queue: Vec, + /// Per hop, the destinations whose routes failed through it and when, oldest + /// first. + displaced: FlatMap>, + in_flight: FlatMap, + backoff: FlatMap, + /// When the last refresh went out, for the spacing. + last_issued: Option, +} + +impl RouteRefresh { + /// Queue `destination` for a refresh. A destination already queued keeps its + /// place and first reason; one with a refresh in flight and broadcast addresses + /// are not queued. + pub fn enqueue(&mut self, destination: Nwk, reason: RefreshReason) { + self.enqueue_new(destination, reason); + } + + /// `enqueue`, returning whether the destination was newly queued. + fn enqueue_new(&mut self, destination: Nwk, reason: RefreshReason) -> bool { + if destination.as_u16() >= FIRST_BROADCAST_ADDRESS + || self.in_flight.contains_key(&destination) + || self.is_queued(destination) + { + return false; + } + + self.queue.push(Queued { + destination, + reason, + not_before: None, + }); + true + } + + fn is_queued(&self, destination: Nwk) -> bool { + self.queue + .iter() + .any(|queued| queued.destination == destination) + } + + /// The route to `destination` through `failed_next_hop` failed. Remembered so the + /// destination is refreshed when the hop recovers. + pub fn note_displaced(&mut self, destination: Nwk, failed_next_hop: Nwk, now: Instant) { + let displaced = self.displaced.entry(failed_next_hop).or_default(); + + displaced.retain(|&(other, _)| other != destination); + displaced.push((destination, now)); + + if displaced.len() > MAX_DISPLACED_PER_HOP { + displaced.remove(0); + } + } + + /// `hop` works again: queue the destinations displaced from it within the + /// retention, and forget its list. One already queued in back-off is due at once, + /// with its back-off restarted: the hop recovering is news about its reachability. + /// Returns how many were newly queued or made due. + pub fn hop_recovered(&mut self, hop: Nwk, now: Instant, policy: RouteRefreshPolicy) -> usize { + let Some(displaced) = self.displaced.remove(&hop) else { + return 0; + }; + + displaced + .into_iter() + .filter(|&(_, at)| now.saturating_duration_since(at) <= policy.displaced_retention) + .filter(|&(destination, _)| { + if self.enqueue_new(destination, RefreshReason::HopRecovered) { + return true; + } + + let Some(queued) = self + .queue + .iter_mut() + .find(|queued| queued.destination == destination) + else { + return false; + }; + + self.backoff.remove(&destination); + queued.not_before.take().is_some() + }) + .count() + } + + /// Take the oldest queued destination that is not in back-off, or `None` within + /// `spacing` of the last refresh issued. Destinations in back-off stay queued. + pub fn next_due( + &mut self, + now: Instant, + policy: RouteRefreshPolicy, + ) -> Option<(Nwk, RefreshReason)> { + if self + .last_issued + .is_some_and(|last| now < last + policy.spacing) + { + return None; + } + + let index = self + .queue + .iter() + .position(|queued| queued.not_before.is_none_or(|not_before| not_before <= now))?; + let queued = self.queue.remove(index); + + Some((queued.destination, queued.reason)) + } + + /// A refresh of `destination` went out: it is in flight until `deadline`, and the + /// next one waits for the spacing. + pub fn issued( + &mut self, + destination: Nwk, + reason: RefreshReason, + now: Instant, + deadline: Instant, + ) { + self.in_flight + .insert(destination, InFlight { reason, deadline }); + self.last_issued = Some(now); + } + + /// A route reply from `responder` reached us. If it answers a refresh in flight, + /// the refresh ends and the destination's back-off is cleared: a reply that does + /// not replace the route still shows the destination answers. + pub fn note_reply(&mut self, responder: Nwk) -> bool { + if self.in_flight.remove(&responder).is_none() { + return false; + } + + self.backoff.remove(&responder); + true + } + + /// Refreshes past their deadline went unanswered. Each gets a back-off, the + /// initial one or double its last up to the cap, and is queued again with its + /// reason, not due before the back-off ends. After `MAX_RETRIES_AT_CAP` tries at + /// the cap, the next miss gives up on the destination instead. + pub fn tick(&mut self, now: Instant, policy: RouteRefreshPolicy) -> Vec { + self.in_flight + .extract_if(|_, in_flight| in_flight.deadline <= now) + .map(|(destination, in_flight)| { + let reason = in_flight.reason; + let duration = self + .backoff + .get(&destination) + .map_or(policy.backoff, |last| last.duration.saturating_mul(2)) + .min(policy.backoff_max); + let previous_at_cap = self.backoff.get(&destination).map_or(0, |b| b.at_cap); + let at_cap = if duration >= policy.backoff_max { + previous_at_cap.saturating_add(1) + } else { + 0 + }; + + self.queue + .retain(|queued| queued.destination != destination); + + if at_cap > MAX_RETRIES_AT_CAP { + self.backoff.remove(&destination); + return Missed { + destination, + retry_in: None, + }; + } + + self.backoff + .insert(destination, Backoff { duration, at_cap }); + self.queue.push(Queued { + destination, + reason, + not_before: Some(now + duration), + }); + + Missed { + destination, + retry_in: Some(duration), + } + }) + .collect() + } + + /// When there is next something to do: a queued destination may go (after the + /// spacing and its back-off), or a refresh in flight reaches its deadline. `None` + /// when nothing is queued or in flight. Displaced entries expiring is not counted: + /// they are only checked when their hop recovers. + pub fn next_wake(&self, now: Instant, policy: RouteRefreshPolicy) -> Option { + let spacing_end = self.last_issued.map_or(now, |last| last + policy.spacing); + + let next_queued = self + .queue + .iter() + .map(|queued| queued.not_before.unwrap_or(now).max(spacing_end)) + .min(); + + let next_deadline = self + .in_flight + .values() + .map(|in_flight| in_flight.deadline) + .min(); + + next_queued.into_iter().chain(next_deadline).min() + } + + /// The device at `nwk` left or joined again: no refresh goes to it and no hop + /// list names it as a destination. Its own list as a hop stays: a router that + /// rejoins at its address comes back, and the routes that failed through it are + /// worth refreshing when it works again. Deviation from the plan, which dropped it. + pub fn forget(&mut self, nwk: Nwk) { + self.queue.retain(|queued| queued.destination != nwk); + self.in_flight.remove(&nwk); + self.backoff.remove(&nwk); + self.displaced.retain(|_, displaced| { + displaced.retain(|&(destination, _)| destination != nwk); + !displaced.is_empty() + }); + } + + /// No refresh is queued or in flight. + pub const fn is_empty(&self) -> bool { + self.queue.is_empty() && self.in_flight.is_empty() + } +} diff --git a/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs b/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs new file mode 100644 index 00000000..0978d571 --- /dev/null +++ b/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs @@ -0,0 +1,488 @@ +use alloc::vec; +use alloc::vec::Vec; +use core::time::Duration; + +use ziggurat_ieee_802154::types::Nwk; + +use crate::Instant; + +use super::*; + +const DEVICE: Nwk = Nwk(0x1111); +const OTHER_DEVICE: Nwk = Nwk(0x2222); +const HOP: Nwk = Nwk(0x3333); +const OTHER_HOP: Nwk = Nwk(0x4444); + +const START: Instant = Instant::from_micros(0); +const ROUTE_DISCOVERY_TIME: Duration = Duration::from_secs(10); + +const POLICY: RouteRefreshPolicy = RouteRefreshPolicy { + spacing: Duration::from_secs(2), + backoff: Duration::from_secs(60), + backoff_max: Duration::from_secs(30 * 60), + displaced_retention: Duration::from_secs(10 * 60), +}; + +fn retry(backoff: Duration) -> Missed { + Missed { + destination: DEVICE, + retry_in: Some(backoff), + } +} + +fn at(seconds: u64) -> Instant { + START + Duration::from_secs(seconds) +} + +/// Take the next due refresh and issue it, as the driver does. +fn issue(refresh: &mut RouteRefresh, now: Instant) -> Option<(Nwk, RefreshReason)> { + let due = refresh.next_due(now, POLICY)?; + refresh.issued(due.0, due.1, now, now + ROUTE_DISCOVERY_TIME); + Some(due) +} + +/// Issue the refresh of `DEVICE` at `now` and let it go unanswered. Returns what the +/// timer pass at its deadline reports. +fn miss(refresh: &mut RouteRefresh, now: Instant) -> Vec { + assert_eq!(issue(refresh, now).map(|due| due.0), Some(DEVICE)); + refresh.tick(now + ROUTE_DISCOVERY_TIME, POLICY) +} + +// enqueue / next_due + +#[test] +fn test_next_due_returns_the_oldest_first() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Hinted); + + assert_eq!( + refresh.next_due(START, POLICY), + Some((DEVICE, RefreshReason::Settled)) + ); + assert_eq!( + refresh.next_due(START, POLICY), + Some((OTHER_DEVICE, RefreshReason::Hinted)) + ); +} + +#[test] +fn test_destination_queued_twice_is_due_once() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(DEVICE, RefreshReason::Hinted); + + assert!(refresh.next_due(START, POLICY).is_some()); + assert_eq!(refresh.next_due(START, POLICY), None); +} + +#[test] +fn test_destination_queued_twice_keeps_the_first_reason() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(DEVICE, RefreshReason::Hinted); + + assert_eq!( + refresh.next_due(START, POLICY), + Some((DEVICE, RefreshReason::Settled)) + ); +} + +#[test] +fn test_broadcast_address_is_not_queued() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(Nwk(0xFFFD), RefreshReason::Hinted); + + assert!(refresh.is_empty()); +} + +#[test] +fn test_destination_in_flight_is_not_queued_again() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + refresh.enqueue(DEVICE, RefreshReason::Hinted); + + assert_eq!(refresh.next_due(at(5), POLICY), None); +} + +#[test] +fn test_due_respects_spacing() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + assert_eq!( + refresh.next_due(START + Duration::from_millis(1999), POLICY), + None + ); +} + +#[test] +fn test_due_after_spacing_returns_the_next_destination() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + assert_eq!( + refresh.next_due(at(2), POLICY), + Some((OTHER_DEVICE, RefreshReason::Settled)) + ); +} + +// note_displaced / hop_recovered + +#[test] +fn test_hop_recovery_queues_its_displaced_destinations() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, HOP, START); + + assert_eq!(refresh.hop_recovered(HOP, at(30), POLICY), 1); + assert_eq!( + refresh.next_due(at(30), POLICY), + Some((DEVICE, RefreshReason::HopRecovered)) + ); +} + +#[test] +fn test_hop_recovery_empties_the_hops_displaced_list() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, HOP, START); + refresh.hop_recovered(HOP, at(30), POLICY); + + assert_eq!(refresh.hop_recovered(HOP, at(31), POLICY), 0); +} + +#[test] +fn test_displaced_entry_past_retention_is_not_queued() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, HOP, START); + + assert_eq!(refresh.hop_recovered(HOP, at(10 * 60 + 1), POLICY), 0); + assert!(refresh.is_empty()); +} + +#[test] +fn test_displaced_list_drops_the_oldest_past_its_limit() { + let mut refresh = RouteRefresh::default(); + for n in 0..=32 { + refresh.note_displaced(Nwk(0x1000 + n), HOP, START); + } + + assert_eq!(refresh.hop_recovered(HOP, START, POLICY), 32); + let mut due = Vec::new(); + let mut now = START; + while let Some((destination, _)) = issue(&mut refresh, now) { + due.push(destination); + now = now + POLICY.spacing; + } + assert!(!due.contains(&Nwk(0x1000))); +} + +#[test] +fn test_displaced_again_counts_as_newest() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, HOP, START); + for n in 0..31 { + refresh.note_displaced(Nwk(0x1000 + n), HOP, START); + } + refresh.note_displaced(DEVICE, HOP, START); + refresh.note_displaced(Nwk(0x2000), HOP, START); + + refresh.hop_recovered(HOP, START, POLICY); + + let mut due = Vec::new(); + let mut now = START; + while let Some((destination, _)) = issue(&mut refresh, now) { + due.push(destination); + now = now + POLICY.spacing; + } + assert!(due.contains(&DEVICE)); + assert!(!due.contains(&Nwk(0x1000))); +} + +#[test] +fn test_hop_recovery_makes_a_destination_in_back_off_due() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + refresh.note_displaced(DEVICE, HOP, at(10)); + + refresh.hop_recovered(HOP, at(20), POLICY); + + assert_eq!( + refresh.next_due(at(20), POLICY), + Some((DEVICE, RefreshReason::Settled)) + ); +} + +#[test] +fn test_hop_recovery_restarts_the_back_off_of_a_destination() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + refresh.note_displaced(DEVICE, HOP, at(10)); + refresh.hop_recovered(HOP, at(20), POLICY); + + assert_eq!(miss(&mut refresh, at(20)), vec![retry(POLICY.backoff)]); +} + +#[test] +fn test_hop_recovery_with_nothing_displaced_queues_nothing() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, OTHER_HOP, START); + + assert_eq!(refresh.hop_recovered(HOP, START, POLICY), 0); + assert!(refresh.is_empty()); +} + +// issued / note_reply / tick + +#[test] +fn test_reply_from_the_refreshed_destination_is_noted() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + assert!(refresh.note_reply(DEVICE)); +} + +#[test] +fn test_answered_refresh_is_not_reported_as_missed() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + refresh.note_reply(DEVICE); + + assert_eq!(refresh.tick(at(10), POLICY), Vec::new()); +} + +#[test] +fn test_reply_without_a_refresh_in_flight_is_not_noted() { + let mut refresh = RouteRefresh::default(); + + assert!(!refresh.note_reply(DEVICE)); +} + +#[test] +fn test_unanswered_refresh_gets_the_initial_back_off() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + + assert_eq!(miss(&mut refresh, START), vec![retry(POLICY.backoff)]); +} + +#[test] +fn test_refresh_in_flight_before_its_deadline_is_not_missed() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + assert_eq!(refresh.tick(at(9), POLICY), Vec::new()); +} + +#[test] +fn test_destination_in_back_off_is_not_due() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + + assert_eq!(refresh.next_due(at(10 + 59), POLICY), None); +} + +#[test] +fn test_destination_in_back_off_does_not_block_others() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Hinted); + + assert_eq!( + refresh.next_due(at(11), POLICY), + Some((OTHER_DEVICE, RefreshReason::Hinted)) + ); +} + +#[test] +fn test_destination_is_due_again_after_its_back_off() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::HopRecovered); + miss(&mut refresh, START); + + assert_eq!( + refresh.next_due(at(10 + 60), POLICY), + Some((DEVICE, RefreshReason::HopRecovered)) + ); +} + +#[test] +fn test_second_miss_doubles_the_back_off() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + + assert_eq!(miss(&mut refresh, at(70)), vec![retry(POLICY.backoff * 2)]); +} + +/// Let the refresh of `DEVICE` go unanswered until route refresh gives up on it. +/// Returns each miss's back-off, `None` for the miss it gave up at. +fn miss_until_given_up(refresh: &mut RouteRefresh) -> Vec> { + let mut now = START; + let mut retries = Vec::new(); + loop { + let missed = miss(refresh, now)[0]; + retries.push(missed.retry_in.map(|backoff| backoff.as_secs())); + let Some(backoff) = missed.retry_in else { + return retries; + }; + now = now + ROUTE_DISCOVERY_TIME + backoff; + } +} + +#[test] +fn test_back_off_doubles_up_to_the_cap() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + + let retries = miss_until_given_up(&mut refresh); + + assert_eq!( + &retries[..7], + &[ + Some(60), + Some(120), + Some(240), + Some(480), + Some(960), + Some(1800), + Some(1800) + ] + ); +} + +#[test] +fn test_misses_at_the_cap_end_in_giving_up() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + + let retries = miss_until_given_up(&mut refresh); + + assert_eq!( + retries.iter().filter(|retry| **retry == Some(1800)).count(), + usize::from(MAX_RETRIES_AT_CAP) + ); +} + +#[test] +fn test_destination_given_up_on_is_not_queued_again() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + + miss_until_given_up(&mut refresh); + + assert!(refresh.is_empty()); +} + +#[test] +fn test_reply_ends_the_back_off() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + miss(&mut refresh, at(70)); + issue(&mut refresh, at(200)); + refresh.note_reply(DEVICE); + refresh.enqueue(DEVICE, RefreshReason::HopRecovered); + + assert_eq!(miss(&mut refresh, at(300)), vec![retry(POLICY.backoff)]); +} + +// forget + +#[test] +fn test_forget_drops_the_destination_everywhere() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + issue(&mut refresh, at(11)); + refresh.note_displaced(DEVICE, HOP, at(11)); + refresh.note_displaced(OTHER_DEVICE, HOP, at(11)); + + refresh.forget(DEVICE); + refresh.forget(OTHER_DEVICE); + + assert!(refresh.is_empty()); + assert_eq!(refresh.tick(at(10_000), POLICY), Vec::new()); + assert_eq!(refresh.hop_recovered(HOP, at(12), POLICY), 0); +} + +// A router that rejoins at its address is forgotten and comes back: the routes that +// failed through it are still worth refreshing when it works again. +#[test] +fn test_forget_keeps_the_hops_own_displaced_list() { + let mut refresh = RouteRefresh::default(); + refresh.note_displaced(DEVICE, HOP, START); + + refresh.forget(HOP); + + assert_eq!(refresh.hop_recovered(HOP, at(30), POLICY), 1); +} + +#[test] +fn test_forget_leaves_other_destinations_alone() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + + refresh.forget(DEVICE); + + assert_eq!( + refresh.next_due(START, POLICY), + Some((OTHER_DEVICE, RefreshReason::Settled)) + ); +} + +// next_wake + +#[test] +fn test_next_wake_with_nothing_to_do_is_none() { + let refresh = RouteRefresh::default(); + + assert_eq!(refresh.next_wake(START, POLICY), None); +} + +#[test] +fn test_next_wake_within_spacing_is_when_spacing_ends() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + refresh.note_reply(DEVICE); + + assert_eq!(refresh.next_wake(START, POLICY), Some(at(2))); +} + +#[test] +fn test_next_wake_with_a_refresh_in_flight_is_no_later_than_its_deadline() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + issue(&mut refresh, START); + + assert!( + refresh + .next_wake(START, POLICY) + .is_some_and(|wake| wake <= at(10)) + ); +} + +#[test] +fn test_next_wake_in_back_off_is_when_the_back_off_ends() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + miss(&mut refresh, START); + + assert_eq!(refresh.next_wake(at(10), POLICY), Some(at(70))); +} diff --git a/crates/ziggurat-zigbee/src/nwk/routing.rs b/crates/ziggurat-zigbee/src/nwk/routing.rs index f0ce768e..c3fa270b 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing.rs @@ -456,8 +456,11 @@ impl Routing { } /// Mark every active route through the given next hop as inactive, forcing a fresh - /// discovery on next use. - pub fn invalidate_via(&mut self, next_hop: Nwk) { + /// discovery on next use. Returns the destinations whose routes it invalidated, so + /// route refresh can try them again once the hop recovers. + pub fn invalidate_via(&mut self, next_hop: Nwk) -> Vec { + let mut invalidated = Vec::new(); + for entry in self.route_table.values_mut() { if entry.status == Status::Active && entry.next_hop_address == next_hop { tracing::info!( @@ -465,8 +468,101 @@ impl Routing { entry.destination ); entry.status = Status::Inactive; + invalidated.push(entry.destination); } } + + invalidated + } + + /// The destinations with an active route. + pub fn active_destinations(&self) -> Vec { + self.route_table + .values() + .filter(|entry| entry.status == Status::Active) + .map(|entry| entry.destination) + .collect() + } + + /// The destinations whose active route a refresh could improve, for the settle + /// trigger. A route at path cost 1 cannot get strictly cheaper. A concentrator + /// sends by a usable route record rather than by the routing table, so a refresh + /// of its table route would change nothing it uses. + pub fn refreshable_destinations( + &self, + is_concentrator: bool, + max_source_route: u8, + ) -> Vec { + self.route_table + .values() + .filter(|entry| entry.status == Status::Active && entry.path_cost > 1) + .filter(|entry| { + !is_concentrator + || !self + .route_record_table + .get(&entry.destination) + .is_some_and(|relays| relays.len() < max_source_route as usize) + }) + .map(|entry| entry.destination) + .collect() + } + + /// Whether a frame of ours waits for a route discovery. Route refresh yields to + /// these: its discoveries hold no frame. + pub const fn frames_await_discovery(&self) -> bool { + !self.discoveries_left.is_empty() + } + + /// Start a route refresh: a discovery toward `destination` that no frame waits on, + /// so it never registers in `discoveries_left`. Returns the identifier to put in + /// the route request, or `None` when a discovery toward it is already underway. + /// + /// An active route stays `Active` and in use. Its discovery entry starts with the + /// route's path cost as the residual cost and `accept_route_reply` is unchanged: + /// seeding the residual cost is what lets only a strictly cheaper reply replace + /// the route. Without an active route this is an ordinary discovery. + pub fn begin_refresh( + &mut self, + own_address: Nwk, + destination: Nwk, + now: Instant, + route_discovery_time: Duration, + activity: ActivityParams, + ) -> Option { + self.expire_discoveries(now); + + let path_cost = match self.route_table.get(&destination) { + Some(entry) if entry.status == Status::DiscoveryUnderway => return None, + Some(entry) if entry.status == Status::Active => entry.path_cost, + _ => { + return Some(self.begin_discovery( + own_address, + destination, + now, + route_discovery_time, + activity, + )); + } + }; + + self.request_sequence_number = self.request_sequence_number.wrapping_add(1); + let request_id = self.request_sequence_number; + + self.discovery_table.insert( + (own_address, request_id), + DiscoveryEntry { + route_request_id: request_id, + source_address: own_address, + sender_address: UNKNOWN_NEXT_HOP, + forward_cost: 0, + residual_cost: Some(path_cost), + expiration_time: now + route_discovery_time, + destination_address: destination, + handled: true, + }, + ); + + Some(request_id) } /// Remove the route to a destination, returning whether an entry was removed. An diff --git a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs index 2fcc1c1a..2a0773dc 100644 --- a/crates/ziggurat-zigbee/src/nwk/routing/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/routing/tests.rs @@ -980,3 +980,198 @@ fn test_equal_cost_copy_is_fresh_after_an_unhandled_cheaper_copy() { routing.note_route_request_handled(DEVICE, 1); assert!(!receive_copy(&mut routing, 2).fresh); } + +// Route refresh: a discovery toward a destination whose route stays in use until a +// strictly cheaper reply arrives. + +fn refresh(routing: &mut Routing, now: Instant) -> Option { + routing.begin_refresh(OWN, DEVICE, now, ROUTE_DISCOVERY_TIME, ACTIVITY) +} + +fn refresh_reply(routing: &mut Routing, request_id: RouteRequestId, cost: u8) -> RouteReplyOutcome { + routing.accept_route_reply(OWN, OWN, request_id, DEVICE, ROUTER, cost, START, ACTIVITY) +} + +#[test] +fn test_refresh_of_an_active_route_returns_a_request_id() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 12, START, ACTIVITY); + + assert!(refresh(&mut routing, START).is_some()); +} + +#[test] +fn test_refresh_keeps_the_route_active_through_the_same_next_hop() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 12, START, ACTIVITY); + + let _ = refresh(&mut routing, START); + + assert_eq!(routing.route_status(DEVICE), Some(Status::Active)); + assert_eq!(routing.next_hop(DEVICE), Some(NEIGHBOR)); +} + +#[test] +fn test_refresh_reply_with_a_strictly_cheaper_path_moves_the_route() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 12, START, ACTIVITY); + let request_id = refresh(&mut routing, START).unwrap(); + + let _ = refresh_reply(&mut routing, request_id, 3); + + assert_eq!(routing.next_hop(DEVICE), Some(ROUTER)); +} + +#[test] +fn test_refresh_reply_with_an_equal_or_costlier_path_keeps_the_route() { + for cost in [12, 13] { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 12, START, ACTIVITY); + let request_id = refresh(&mut routing, START).unwrap(); + + let reply = refresh_reply(&mut routing, request_id, cost); + + assert_eq!(reply.disposition, RouteReplyDisposition::Drop); + assert_eq!(routing.next_hop(DEVICE), Some(NEIGHBOR)); + } +} + +#[test] +fn test_refresh_without_a_route_starts_a_discovery() { + let mut routing = Routing::default(); + + assert!(refresh(&mut routing, START).is_some()); + assert_eq!( + routing.route_status(DEVICE), + Some(Status::DiscoveryUnderway) + ); +} + +#[test] +fn test_refresh_of_an_inactive_route_starts_a_discovery() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 12, START, ACTIVITY); + let _ = routing.invalidate_via(NEIGHBOR); + + assert!(refresh(&mut routing, START).is_some()); + assert_eq!( + routing.route_status(DEVICE), + Some(Status::DiscoveryUnderway) + ); +} + +#[test] +fn test_refresh_without_a_route_holds_no_frame() { + let mut routing = Routing::default(); + + let _ = refresh(&mut routing, START); + + assert!(!routing.frames_await_discovery()); +} + +#[test] +fn test_refresh_skips_a_destination_under_discovery() { + let mut routing = Routing::default(); + assert!(want(&mut routing, START, 1)); + + assert_eq!(refresh(&mut routing, START), None); +} + +#[test] +fn test_active_destinations_lists_only_active_routes() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.restore_route(OTHER_DEVICE, ROUTER, 3, START, ACTIVITY); + let _ = routing.invalidate_via(ROUTER); + let _ = routing.begin_discovery(OWN, NEIGHBOR, START, ROUTE_DISCOVERY_TIME, ACTIVITY); + + assert_eq!(routing.active_destinations(), vec![DEVICE]); +} + +#[test] +fn test_invalidate_via_returns_the_destinations_through_the_hop() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.restore_route(ROUTER, ROUTER, 1, START, ACTIVITY); + + let mut invalidated = routing.invalidate_via(NEIGHBOR); + invalidated.sort_by_key(|nwk| nwk.0); + + assert_eq!(invalidated, vec![DEVICE, OTHER_DEVICE]); +} + +#[test] +fn test_invalidate_via_leaves_the_routes_through_the_hop_inactive() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 3, START, ACTIVITY); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 3, START, ACTIVITY); + + let _ = routing.invalidate_via(NEIGHBOR); + + assert_eq!(routing.route_status(DEVICE), Some(Status::Inactive)); + assert_eq!(routing.route_status(OTHER_DEVICE), Some(Status::Inactive)); +} + +#[test] +fn test_frames_await_discovery_while_a_frame_wants_a_route() { + let mut routing = Routing::default(); + let _ = want(&mut routing, START, 1); + + assert!(routing.frames_await_discovery()); +} + +#[test] +fn test_frames_await_no_discovery_when_none_waits() { + let routing = Routing::default(); + + assert!(!routing.frames_await_discovery()); +} + +#[test] +fn test_refreshable_destinations_skip_a_route_at_the_lowest_cost() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, DEVICE, 1, START, ACTIVITY); + routing.restore_route(OTHER_DEVICE, NEIGHBOR, 2, START, ACTIVITY); + + assert_eq!( + routing.refreshable_destinations(true, MAX_SOURCE_ROUTE), + vec![OTHER_DEVICE] + ); +} + +#[test] +fn test_refreshable_destinations_of_a_concentrator_skip_a_source_routed_destination() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 5, START, ACTIVITY); + routing.store_route_record(DEVICE, vec![ROUTER]); + + assert_eq!( + routing.refreshable_destinations(true, MAX_SOURCE_ROUTE), + Vec::new() + ); +} + +#[test] +fn test_refreshable_destinations_of_a_router_keep_a_destination_with_a_route_record() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 5, START, ACTIVITY); + routing.store_route_record(DEVICE, vec![ROUTER]); + + assert_eq!( + routing.refreshable_destinations(false, MAX_SOURCE_ROUTE), + vec![DEVICE] + ); +} + +#[test] +fn test_refreshable_destinations_skip_inactive_routes() { + let mut routing = Routing::default(); + routing.restore_route(DEVICE, NEIGHBOR, 5, START, ACTIVITY); + let _ = routing.invalidate_via(NEIGHBOR); + + assert_eq!( + routing.refreshable_destinations(false, MAX_SOURCE_ROUTE), + Vec::new() + ); +} From 352cff9007b6d38c201419eea57e79c2ff609461 Mon Sep 17 00:00:00 2001 From: Igor Yamolov Date: Tue, 17 Nov 2026 21:28:32 +0100 Subject: [PATCH 2/3] Hold route refreshes while the broadcast budget is low A refresh is a network-wide route request that every router repeats, so its cost grows with the mesh. Refreshes now draw from the broadcast budget as a new lowest class, `TrafficClass::Background`, which stops above the new `broadcast_host_reserve` (20 tokens). A refused refresh goes back to the queue with its reason, due again when the budget says a token frees; nothing went out, so neither the spacing nor its back-off moves. On a busy mesh, where relayed broadcasts drain the bucket, refreshes slow down by themselves; an idle one still runs at the spacing. Co-Authored-By: Claude Opus 5.5 --- .../ziggurat-driver/src/zigbee_stack/nwk.rs | 1 + .../src/zigbee_stack/route_refresh.rs | 67 ++++++---- crates/ziggurat-zigbee/src/constants.rs | 5 + .../src/nwk/broadcast_budget.rs | 115 +++++++++++++++++- .../ziggurat-zigbee/src/nwk/route_refresh.rs | 21 ++++ .../src/nwk/route_refresh/tests.rs | 67 ++++++++++ 6 files changed, 249 insertions(+), 27 deletions(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs index 53d4712e..62a8125c 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/nwk.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/nwk.rs @@ -714,6 +714,7 @@ impl ZigbeeStack { self.tunables.broadcast_token_refill(), self.tunables.broadcast_critical_reserve(), self.tunables.broadcast_forwarding_reserve(), + self.tunables.broadcast_host_reserve(), ); if let BroadcastAdmission::Defer { retry_in } = admission { diff --git a/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs b/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs index 96995a61..adb863ea 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/route_refresh.rs @@ -4,6 +4,7 @@ use crate::runtime::Runtime; use ziggurat_ieee_802154::types::Nwk; use ziggurat_phy::RadioPhy; +use ziggurat_zigbee::nwk::broadcast_budget::{BroadcastAdmission, TrafficClass}; use ziggurat_zigbee::nwk::route_refresh::{RefreshReason, RouteRefreshPolicy}; use ziggurat_zigbee::nwk::routing::RouteUpdate; @@ -37,8 +38,9 @@ impl ZigbeeStack { /// Once the neighbors have settled after the start, look again, in the background, /// at the routes found before, then at whatever the triggers queue. One refresh - /// discovery goes out per `route_refresh_spacing` at most, and none while a frame - /// waits for a discovery: frames come first. A refresh keeps the route in use until + /// discovery goes out per `route_refresh_spacing` at most, none while a frame waits + /// for a discovery, and none while the broadcast budget is low: a refresh is + /// `TrafficClass::Background`, the first class refused. Frames come first. A refresh keeps the route in use until /// a strictly cheaper reply arrives (`Routing::begin_refresh`). /// /// The `route_refresh` tunable is read on every pass: off, the task issues nothing @@ -109,28 +111,47 @@ impl ZigbeeStack { if !frames_wait && let Some((destination, reason)) = core.nib.route_refresh.next_due(now, policy) { - match core.nib.routing.begin_refresh( - own_address, - destination, + let admission = self.broadcast_budget.lock().take( + TrafficClass::Background, now, - route_discovery_time, - self.activity_params(), - ) { - Some(request_id) => { - tracing::info!("Route refresh: refreshing {destination:?} ({reason:?})"); - self.broadcast_discovery_request(core, destination, request_id); - core.nib.route_refresh.issued( - destination, - reason, - now, - now + route_discovery_time, - ); - issued = true; - } - None => { - tracing::debug!( - "Route refresh: {destination:?} is already under discovery, skipping" - ); + self.tunables.broadcast_budget_tokens(), + self.tunables.broadcast_token_refill(), + self.tunables.broadcast_critical_reserve(), + self.tunables.broadcast_forwarding_reserve(), + self.tunables.broadcast_host_reserve(), + ); + + if let BroadcastAdmission::Defer { retry_in } = admission { + tracing::debug!( + "Route refresh: broadcast budget low, {destination:?} waits {retry_in:?}" + ); + core.nib + .route_refresh + .defer(destination, reason, now + retry_in); + } else { + match core.nib.routing.begin_refresh( + own_address, + destination, + now, + route_discovery_time, + self.activity_params(), + ) { + Some(request_id) => { + tracing::info!("Route refresh: refreshing {destination:?} ({reason:?})"); + self.broadcast_discovery_request(core, destination, request_id); + core.nib.route_refresh.issued( + destination, + reason, + now, + now + route_discovery_time, + ); + issued = true; + } + None => { + tracing::debug!( + "Route refresh: {destination:?} is already under discovery, skipping" + ); + } } } } diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index 179f881b..d102d494 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -430,6 +430,11 @@ tunables! { /// so a host flood cannot stop us relaying the mesh's own broadcasts. broadcast_forwarding_reserve: u8 = 2, + /// Broadcast tokens reserved for host broadcasts above the forwarding floor, which + /// background broadcasts (route refresh) never draw: a refresh only goes out while + /// more than critical + forwarding + host reserve tokens are left. + broadcast_host_reserve: u8 = 20, + /// An intentional spec deviation: while permitting joins, spray a beacon every 5 ms /// for this long after each beacon request, to out-compete neighbouring networks /// that permanently permit joins. Zero disables it (a single beacon per request, diff --git a/crates/ziggurat-zigbee/src/nwk/broadcast_budget.rs b/crates/ziggurat-zigbee/src/nwk/broadcast_budget.rs index 6d662ed7..cfb1ee38 100644 --- a/crates/ziggurat-zigbee/src/nwk/broadcast_budget.rs +++ b/crates/ziggurat-zigbee/src/nwk/broadcast_budget.rs @@ -13,6 +13,9 @@ pub enum TrafficClass { /// A transit frame relayed for another device: dropping one degrades the mesh but /// the originator retries end-to-end. Forwarding, + /// Optional stack work, such as route refresh: refused first under pressure, and it + /// never draws the tokens kept for host traffic. The caller tries again later. + Background, /// Stack machinery the mesh cannot function without: joins, APS acks, NWK /// commands, indirect deliveries. Always admitted. Critical, @@ -24,7 +27,8 @@ pub enum BroadcastAdmission { /// Send now. Admit, /// Refused: a token for this class frees no sooner than `retry_in`. Only - /// [`TrafficClass::Forwarding`] and [`TrafficClass::Host`] are ever refused; + /// [`TrafficClass::Background`], [`TrafficClass::Forwarding`] and + /// [`TrafficClass::Host`] are ever refused; /// [`TrafficClass::Critical`] always admits. Defer { retry_in: Duration }, } @@ -34,7 +38,7 @@ pub enum BroadcastAdmission { pub struct BroadcastBudget { /// Available tokens. Critical broadcasts bypass the bucket and draw nothing; host /// and forwarding traffic only draws above its floor, so the count never dips below - /// zero. + /// zero. Background traffic stops higher still, above the host reserve. tokens: u32, /// When the last whole token was accrued. Advanced in whole-token steps so the /// sub-token remainder of elapsed time is never discarded. @@ -51,11 +55,21 @@ impl BroadcastBudget { } /// The token floor a class may not dip into. - fn floor(class: TrafficClass, critical_reserve: u8, forwarding_reserve: u8) -> u32 { + fn floor( + class: TrafficClass, + critical_reserve: u8, + forwarding_reserve: u8, + host_reserve: u8, + ) -> u32 { match class { TrafficClass::Critical => 0, TrafficClass::Forwarding => u32::from(critical_reserve), TrafficClass::Host => u32::from(critical_reserve) + u32::from(forwarding_reserve), + TrafficClass::Background => { + u32::from(critical_reserve) + + u32::from(forwarding_reserve) + + u32::from(host_reserve) + } } } @@ -107,6 +121,7 @@ impl BroadcastBudget { refill_interval: Duration, critical_reserve: u8, forwarding_reserve: u8, + host_reserve: u8, ) -> BroadcastAdmission { let capacity = u32::from(capacity); self.refill(now, capacity, refill_interval); @@ -117,7 +132,7 @@ impl BroadcastBudget { // refills. BroadcastAdmission::Admit } else { - let floor = Self::floor(class, critical_reserve, forwarding_reserve); + let floor = Self::floor(class, critical_reserve, forwarding_reserve, host_reserve); if self.tokens > floor { self.tokens -= 1; BroadcastAdmission::Admit @@ -130,3 +145,95 @@ impl BroadcastBudget { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const CAPACITY: u8 = 10; + const REFILL: Duration = Duration::from_secs(1); + const CRITICAL_RESERVE: u8 = 1; + const FORWARDING_RESERVE: u8 = 1; + const HOST_RESERVE: u8 = 3; + /// Background broadcasts may not draw the last five tokens. + const BACKGROUND_FLOOR: u8 = CRITICAL_RESERVE + FORWARDING_RESERVE + HOST_RESERVE; + + const START: Instant = Instant::from_micros(0); + + fn take(budget: &mut BroadcastBudget, class: TrafficClass) -> BroadcastAdmission { + budget.take( + class, + START, + CAPACITY, + REFILL, + CRITICAL_RESERVE, + FORWARDING_RESERVE, + HOST_RESERVE, + ) + } + + /// A budget, never refilled during the test, holding `tokens`. + fn budget_with(tokens: u8) -> BroadcastBudget { + let mut budget = BroadcastBudget::new(CAPACITY); + for _ in tokens..CAPACITY { + assert_eq!( + take(&mut budget, TrafficClass::Host), + BroadcastAdmission::Admit + ); + } + budget + } + + #[test] + fn test_background_above_its_floor_is_admitted() { + let mut budget = budget_with(BACKGROUND_FLOOR + 1); + + assert_eq!( + take(&mut budget, TrafficClass::Background), + BroadcastAdmission::Admit + ); + } + + #[test] + fn test_admitted_background_draws_a_token() { + let mut budget = budget_with(BACKGROUND_FLOOR + 1); + take(&mut budget, TrafficClass::Background); + + assert_eq!( + take(&mut budget, TrafficClass::Background), + BroadcastAdmission::Defer { retry_in: REFILL } + ); + } + + #[test] + fn test_background_at_its_floor_is_deferred() { + let mut budget = budget_with(BACKGROUND_FLOOR); + + assert!(matches!( + take(&mut budget, TrafficClass::Background), + BroadcastAdmission::Defer { .. } + )); + } + + #[test] + fn test_host_is_admitted_where_background_is_deferred() { + let mut budget = budget_with(BACKGROUND_FLOOR); + + assert_eq!( + take(&mut budget, TrafficClass::Host), + BroadcastAdmission::Admit + ); + } + + #[test] + fn test_deferred_background_waits_for_the_tokens_it_lacks() { + let mut budget = budget_with(BACKGROUND_FLOOR - 2); + + assert_eq!( + take(&mut budget, TrafficClass::Background), + BroadcastAdmission::Defer { + retry_in: REFILL * 3 + } + ); + } +} diff --git a/crates/ziggurat-zigbee/src/nwk/route_refresh.rs b/crates/ziggurat-zigbee/src/nwk/route_refresh.rs index b23c6b5d..dffd563c 100644 --- a/crates/ziggurat-zigbee/src/nwk/route_refresh.rs +++ b/crates/ziggurat-zigbee/src/nwk/route_refresh.rs @@ -207,6 +207,27 @@ impl RouteRefresh { Some((queued.destination, queued.reason)) } + /// The refresh of `destination` that `next_due` returned could not go out yet (the + /// broadcast budget refused it). It goes back with its reason, not due before + /// `until`, ahead of the queued destinations that are not waiting. + /// Nothing went out, so the spacing does not start and its back-off is unchanged. + pub fn defer(&mut self, destination: Nwk, reason: RefreshReason, until: Instant) { + let index = self + .queue + .iter() + .position(|queued| queued.not_before.is_none()) + .unwrap_or(self.queue.len()); + + self.queue.insert( + index, + Queued { + destination, + reason, + not_before: Some(until), + }, + ); + } + /// A refresh of `destination` went out: it is in flight until `deadline`, and the /// next one waits for the spacing. pub fn issued( diff --git a/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs b/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs index 0978d571..9920e80e 100644 --- a/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs +++ b/crates/ziggurat-zigbee/src/nwk/route_refresh/tests.rs @@ -486,3 +486,70 @@ fn test_next_wake_in_back_off_is_when_the_back_off_ends() { assert_eq!(refresh.next_wake(at(10), POLICY), Some(at(70))); } + +// defer + +/// Take the next due refresh and put it back until `until`, as the driver does when +/// the broadcast budget refuses it. +fn defer(refresh: &mut RouteRefresh, now: Instant, until: Instant) -> Option { + let (destination, reason) = refresh.next_due(now, POLICY)?; + refresh.defer(destination, reason, until); + Some(destination) +} + +#[test] +fn test_deferred_destination_is_not_due_before_the_deferral_ends() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + defer(&mut refresh, START, at(5)); + + assert_eq!(refresh.next_due(at(4), POLICY), None); +} + +#[test] +fn test_deferred_destination_is_due_first_when_the_deferral_ends() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + defer(&mut refresh, START, at(5)); + defer(&mut refresh, START, at(5)); + + assert_eq!( + refresh.next_due(at(5), POLICY).map(|due| due.0), + Some(DEVICE) + ); +} + +#[test] +fn test_deferred_destination_keeps_its_reason() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::HopRecovered); + defer(&mut refresh, START, at(5)); + + assert_eq!( + refresh.next_due(at(5), POLICY), + Some((DEVICE, RefreshReason::HopRecovered)) + ); +} + +#[test] +fn test_deferral_does_not_start_the_spacing() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + refresh.enqueue(OTHER_DEVICE, RefreshReason::Settled); + defer(&mut refresh, START, at(30)); + + assert_eq!( + refresh.next_due(START, POLICY).map(|due| due.0), + Some(OTHER_DEVICE) + ); +} + +#[test] +fn test_next_wake_with_a_deferral_is_when_it_ends() { + let mut refresh = RouteRefresh::default(); + refresh.enqueue(DEVICE, RefreshReason::Settled); + defer(&mut refresh, START, at(5)); + + assert_eq!(refresh.next_wake(START, POLICY), Some(at(5))); +} From 315d7b6cedaac437e59867f45ee62604d7e8603d Mon Sep 17 00:00:00 2001 From: Igor Yamolov Date: Wed, 18 Nov 2026 03:13:22 +0100 Subject: [PATCH 3/3] Hold early link statuses until one link status period after the start The stack starts with an empty sibling table, so an early link status sent within the first period lists only the routers heard so far. A router that has not spoken yet (it waits for its own 15 s period) reads that list as "I do not hear you" and, with #144, zeroes its cost toward us: it then drops our route requests and cannot carry route replies back to us until our next link status. On the bench this kept 0x0391 on a cost-4 detour after every restart. Debouncer::hold keeps requests from moving a firing before a given time. The periodic link status task holds its debouncer for the first period when the new hold_early_link_status_after_start tunable is on (default). Co-Authored-By: Claude Opus 5.5 --- .../src/zigbee_stack/neighbor.rs | 7 ++++ crates/ziggurat-zigbee/src/constants.rs | 8 +++++ crates/ziggurat-zigbee/src/debouncer.rs | 36 ++++++++++++++++++- 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs index 292692b0..966e8aaa 100644 --- a/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs +++ b/crates/ziggurat-driver/src/zigbee_stack/neighbor.rs @@ -239,6 +239,13 @@ impl ZigbeeStack { // The network start has just sent one self.restart_link_status_period(); + // Early link statuses wait for the first periodic one, which lists every + // router heard for a whole period + if self.tunables.hold_early_link_status_after_start() { + let first_period_end = self.core_now() + self.tunables.link_status_period(); + self.core().nib.link_status_debouncer.hold(first_period_end); + } + loop { self.wait_for_debouncer(|nib| &nib.link_status_debouncer, &self.link_status_wake) .await; diff --git a/crates/ziggurat-zigbee/src/constants.rs b/crates/ziggurat-zigbee/src/constants.rs index d102d494..f03d356a 100644 --- a/crates/ziggurat-zigbee/src/constants.rs +++ b/crates/ziggurat-zigbee/src/constants.rs @@ -447,6 +447,14 @@ tunables! { /// router is unknown, which means a burst of link statuses. When false, such a /// router waits for the periodic link status. hack_early_link_status_for_unknown_routers: bool = true, + + /// Hold every early link status until one link status period after the start. + /// The stack starts with no sibling routers, so an early link status lists only + /// the routers heard so far. A router that has not spoken yet takes that list as + /// "I do not hear you" and zeroes its cost toward us, which makes it drop our + /// route requests and replies until our next link status. When false, early link + /// statuses go out as soon as they are asked for. + hold_early_link_status_after_start: bool = true, } #[cfg(test)] diff --git a/crates/ziggurat-zigbee/src/debouncer.rs b/crates/ziggurat-zigbee/src/debouncer.rs index b9e6bc75..4c974978 100644 --- a/crates/ziggurat-zigbee/src/debouncer.rs +++ b/crates/ziggurat-zigbee/src/debouncer.rs @@ -9,6 +9,7 @@ use crate::Instant; pub struct Debouncer { next: Instant, last_fired: Instant, + held_until: Instant, } impl Debouncer { @@ -20,7 +21,7 @@ impl Debouncer { /// Returns whether the next firing moved earlier: it stays where it is if it is /// already due sooner. pub fn request(&mut self, at: Instant, min_interval: Duration) -> bool { - let at = at.max(self.last_fired + min_interval); + let at = at.max(self.last_fired + min_interval).max(self.held_until); let earlier = at < self.next; if earlier { @@ -30,6 +31,11 @@ impl Debouncer { earlier } + /// Requests move the next firing no earlier than `until`. + pub fn hold(&mut self, until: Instant) { + self.held_until = until; + } + /// It fires at `now`: the next firing is due an `interval` later. pub fn fired(&mut self, now: Instant, interval: Duration) { self.last_fired = now; @@ -95,4 +101,32 @@ mod test { assert!(debouncer.request(at(21_000), min_interval)); assert_eq!(debouncer.next(), at(21_000)); } + + #[test] + fn test_held_request_waits_for_the_hold_to_end() { + let mut debouncer = started(); + debouncer.hold(at(15_000)); + + assert!(!debouncer.request(at(1_400), Duration::ZERO)); + assert_eq!(debouncer.next(), at(15_000)); + } + + #[test] + fn test_hold_shorter_than_the_interval_moves_a_request_to_its_end() { + let mut debouncer = started(); + debouncer.hold(at(5_000)); + + assert!(debouncer.request(at(1_400), Duration::ZERO)); + assert_eq!(debouncer.next(), at(5_000)); + } + + #[test] + fn test_request_after_the_hold_is_taken_as_it_is() { + let mut debouncer = started(); + debouncer.hold(at(15_000)); + debouncer.fired(at(15_000), INTERVAL); + + assert!(debouncer.request(at(16_000), Duration::ZERO)); + assert_eq!(debouncer.next(), at(16_000)); + } }