bacnet-network 0.12.0

BACnet network layer: routing, router tables, priority channels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! Router table — maps BACnet network numbers to transport ports.
//!
//! Per ASHRAE 135-2020 Clause 6.4, a BACnet router maintains a routing table
//! that records which directly-connected or learned networks can be reached
//! via which port.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use bacnet_types::MacAddr;

// Align with the existing 30s reject-busy deadline: at most one accepted
// reject-driven change per (ingress port, network) per window without fresh
// learning. A legitimate unreachable-after-busy signal may wait up to 30s.
const HOLD_DOWN: Duration = Duration::from_secs(30);

// Repeat-based local hardening, aligned with the existing flap window.
const CORROBORATION_WINDOW: Duration = Duration::from_secs(60);

/// Count-only outcomes for routing claims handled by one router table.
///
/// All totals saturate at `u64::MAX`, never affect routing decisions, and expose
/// no peer identities. Learning totals cover inspected I-Am-Router and
/// Initialize-Routing-Table-Ack entries, not manual table edits, management
/// Initialize-Routing-Table writes, or other message types. Existing cap-triggered early stops remain: their unexamined suffixes
/// are not classified or counted. Flap warnings are counted at their emission.
/// Pending replacements are not successful learning until corroborated. Disconnect
/// totals count each well-formed ignored removal request, even for absent/direct
/// routes; malformed messages are not counted.
/// Duplicate cross-port entries within one message supply no extra vote or count.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct RoutingClaimSnapshot {
    /// Rejects that changed a learned route's effective state or removed it.
    pub reject_applied: u64,
    /// Rejects ignored as no-ops or during hold-down (counted once each).
    pub reject_dampened: u64,
    /// No-op rejects, including missing routes and directly-connected immunity.
    /// Busy duplicates do not extend the existing busy deadline.
    pub reject_dampened_same_state: u64,
    /// State-changing rejects ignored within 30s of this key's last applied one.
    pub reject_dampened_hold_down: u64,
    /// Inspected learning claims that inserted or refreshed a learned route.
    pub learned_ok: u64,
    /// Inspected entries that triggered the existing route-cap early stop.
    pub learned_cap_ignored: u64,
    /// Flap warnings emitted at the existing port-change threshold.
    pub flap_warned: u64,
    /// Cross-port claims held pending, including new challengers and expiry restarts.
    pub pending_started: u64,
    /// Replacements applied on a second same-network/port claim within 60s inclusive.
    pub corroborated_applied: u64,
    /// Pending slots found older than 60s and discarded on the next learning claim.
    /// Non-expiry cleanup (removal, aging, manual edits or refresh) does not count.
    pub pending_expired: u64,
    /// Disconnect-Connection-To-Network removal requests ignored (PTP unsupported).
    pub disconnect_removal_ignored: u64,
}

#[derive(Debug, Clone)]
struct PendingReplacement {
    port_index: usize,
    first_seen: Instant,
}

/// Reachability status of a route entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReachabilityStatus {
    /// Route is available for traffic.
    Reachable,
    /// Route is temporarily unreachable due to congestion (Router-Busy).
    Busy,
    /// Route has permanently failed.
    Unreachable,
}

/// A route entry in the router table.
///
/// Freshness is split (RB-06): `last_seen` is control-plane confirmation
/// (learning claims and management applies only), while `last_used` is
/// data-plane forwarding use. Expiry keys off `last_seen` only so sustained
/// traffic cannot manufacture fresh route evidence. Busy/Available marks
/// touch neither timestamp.
#[derive(Debug, Clone)]
pub struct RouteEntry {
    /// Index of the port this network is reachable through.
    pub port_index: usize,
    /// Whether this is a directly-connected network (vs learned via another router).
    pub directly_connected: bool,
    /// MAC address of the next-hop router (empty for directly-connected networks).
    pub next_hop_mac: MacAddr,
    /// When this learned route was last confirmed. `None` for direct routes.
    pub last_seen: Option<Instant>,
    /// When this route was last used for forwarding. `None` until first use
    /// or after a port change installs an unused path. Never extends expiry.
    pub last_used: Option<Instant>,
    /// Recorded reachability state of this route.
    pub reachability: ReachabilityStatus,
    /// Deadline after which a `Busy` status auto-clears (spec 6.6.3.6).
    pub busy_until: Option<Instant>,
    /// Number of times this route changed ports within the flap detection window.
    pub flap_count: u8,
    /// When the route last changed ports.
    pub last_port_change: Option<Instant>,
}

/// Convergence mode for learned cross-port moves (RB-06).
///
/// Standard (default) applies the 135-2020 6.6.3.2 last-wins rule immediately:
/// the router takes every fresh advertisement as a topology change and adopts
/// it on arrival. Hardened is an explicit opt-in local restriction that
/// holds cross-port moves pending for a second same-(network, port) claim
/// within 60s; it does not authenticate the claim and can delay legitimate
/// convergence (alternation resets the slot, single-shot advertisers wait for
/// the 60s reaper plus a fresh claim).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConvergenceMode {
    /// Immediate single-claim convergence (spec default).
    #[default]
    Standard,
    /// K=2/60s corroboration gate (explicit opt-in hardening).
    Hardened,
}

/// BACnet routing table.
///
/// Maps network numbers to the port through which they can be reached.
/// Standard convergence ([`ConvergenceMode::Standard`]) is the default;
/// hardened corroboration is an explicit opt-in via [`Self::new_hardened`]
/// or [`Self::set_convergence`].
#[derive(Debug, Clone)]
pub struct RouterTable {
    /// Network number → route entry.
    routes: HashMap<u16, RouteEntry>,
    // Network → (ingress port → last APPLIED reject). Grouping by network makes
    // re-arming on learning/removal local. Only live learned routes retain
    // records, at most one per router ingress port; absent/direct spam allocates
    // nothing. Neither peer MACs nor advertised source addresses are keys.
    reject_transitions: HashMap<u16, HashMap<usize, Instant>>,
    // One challenger per live learned network, never keyed by peer identity.
    // Thus pending entries <= live learned routes. Every route replacement,
    // removal and mutable-entry handoff clears its slot; expiry is checked
    // lazily on the next claim for that network plus the periodic reaper
    // (`expire_pending_at`, driven by the router aging task).
    pending_replacements: HashMap<u16, PendingReplacement>,
    claim_counters: RoutingClaimSnapshot,
    convergence: ConvergenceMode,
}

impl RouterTable {
    /// Create an empty routing table with standard single-claim convergence.
    pub fn new() -> Self {
        Self {
            routes: HashMap::new(),
            reject_transitions: HashMap::new(),
            pending_replacements: HashMap::new(),
            claim_counters: RoutingClaimSnapshot::default(),
            convergence: ConvergenceMode::Standard,
        }
    }

    /// Create an empty routing table with the hardened K=2/60s gate enabled.
    ///
    /// Explicit opt-in only: cross-port learned moves wait for a second
    /// same-(network, port) claim within 60s, with flap warnings retained.
    /// Alternating challengers reset the slot and single-shot advertisers
    /// need the reaper plus a fresh claim to converge.
    pub fn new_hardened() -> Self {
        let mut table = Self::new();
        table.convergence = ConvergenceMode::Hardened;
        table
    }

    /// Select the convergence mode. Switching to standard clears no routes
    /// but leaves any hardened pending slots to lazy/reaper expiry; switching
    /// to hardened keeps installed routes and applies the gate to later claims.
    pub fn set_convergence(&mut self, mode: ConvergenceMode) {
        self.convergence = mode;
    }

    /// Current convergence mode.
    pub fn convergence(&self) -> ConvergenceMode {
        self.convergence
    }

    /// Number of pending hardened challengers (bounded by live learned routes).
    pub fn pending_count(&self) -> usize {
        self.pending_replacements.len()
    }

    /// Read a consistent, non-resetting copy of this table's routing-claim totals.
    ///
    /// For a live router, call `router.table().lock().await.claim_snapshot()`.
    /// The snapshot owns only counts and remains readable after table drop;
    /// cloning the table copies, rather than shares, its counters and records.
    pub fn claim_snapshot(&self) -> RoutingClaimSnapshot {
        self.claim_counters
    }

    pub(crate) fn record_learned(&mut self) {
        self.claim_counters.learned_ok = self.claim_counters.learned_ok.saturating_add(1);
    }

    pub(crate) fn record_learning_cap(&mut self) {
        self.claim_counters.learned_cap_ignored =
            self.claim_counters.learned_cap_ignored.saturating_add(1);
    }

    pub(crate) fn record_disconnect_removal_ignored(&mut self) {
        self.claim_counters.disconnect_removal_ignored = self
            .claim_counters
            .disconnect_removal_ignored
            .saturating_add(1);
    }

    /// Apply an I-Am-Router / Init-ACK learning claim.
    ///
    /// Standard mode applies immediately (135-2020 6.6.3.2 last-wins) with
    /// flap warnings retained. Hardened mode gates cross-port learned moves
    /// only: they need two claims for the same (network, new port) within
    /// 60s inclusive. The caller holds the table lock across this synchronous
    /// gate and update. Absent learning and current-port refreshes are
    /// immediate in both modes. `now` makes the inclusive 60s boundary
    /// testable without sleeping. Standard clears any stale challenger for
    /// the network without counting it; hardened counts starts/applies/expiry.
    pub(crate) fn apply_learning_claim(
        &mut self,
        network: u16,
        port_index: usize,
        next_hop_mac: MacAddr,
        now: Instant,
    ) -> bool {
        if self.convergence == ConvergenceMode::Standard {
            self.pending_replacements.remove(&network);
            return self.add_learned_with_flap_detection_at(network, port_index, next_hop_mac, now);
        }
        let pending = self
            .pending_replacements
            .remove(&network)
            .filter(|pending| {
                if now.duration_since(pending.first_seen) > CORROBORATION_WINDOW {
                    self.claim_counters.pending_expired =
                        self.claim_counters.pending_expired.saturating_add(1);
                    false
                } else {
                    true
                }
            });
        if self
            .routes
            .get(&network)
            .is_some_and(|entry| !entry.directly_connected && entry.port_index != port_index)
        {
            if pending.is_some_and(|pending| pending.port_index == port_index) {
                // K=2: the second claim supplies the next hop, even if its MAC
                // differs. Neither source identity nor message type is a key.
                self.claim_counters.corroborated_applied =
                    self.claim_counters.corroborated_applied.saturating_add(1);
            } else {
                self.pending_replacements.insert(
                    network,
                    PendingReplacement {
                        port_index,
                        first_seen: now,
                    },
                );
                self.claim_counters.pending_started =
                    self.claim_counters.pending_started.saturating_add(1);
                debug_assert!(self.pending_replacements.keys().all(|net| self
                    .routes
                    .get(net)
                    .is_some_and(|entry| !entry.directly_connected)));
                return false; // Keep all old route state, including forwarding and age.
            }
        }
        self.add_learned_with_flap_detection_at(network, port_index, next_hop_mac, now)
    }

    /// Discard hardened pending slots older than 60s at `now`.
    ///
    /// Periodic reaper for idle routes: lazy expiry alone cannot clear a slot
    /// with no further claims. Counts one `pending_expired` per discarded
    /// slot; other cleanup (removal, aging, manual edits, refresh) does not
    /// count. Returns the discarded network numbers in ascending order.
    pub fn expire_pending_at(&mut self, now: Instant) -> Vec<u16> {
        let mut expired: Vec<u16> = self
            .pending_replacements
            .iter()
            .filter(|(_, pending)| now.duration_since(pending.first_seen) > CORROBORATION_WINDOW)
            .map(|(net, _)| *net)
            .collect();
        expired.sort_unstable();
        for net in &expired {
            self.pending_replacements.remove(net);
            self.claim_counters.pending_expired =
                self.claim_counters.pending_expired.saturating_add(1);
        }
        expired
    }

    /// Apply only the reject-driven table transition, never its relay.
    /// The caller holds the table lock across this synchronous gate and update.
    /// `now` is supplied so deadline boundaries can be tested without sleeping.
    pub(crate) fn apply_reject(
        &mut self,
        network: u16,
        ingress_port: usize,
        reason: u8,
        now: Instant,
    ) {
        let changes_state = self.routes.get(&network).is_some_and(|entry| {
            if entry.directly_connected {
                return false;
            }
            // Compare effective state, not the stored Busy marker: a busy
            // deadline may have elapsed before the next aging sweep.
            match reason {
                1 => entry.reachability != ReachabilityStatus::Unreachable,
                2 => {
                    // A Busy (flow-control) claim never lifts permanent
                    // Unreachable: the route is already beyond reachable, so
                    // there is no change to apply, dampen, or record — only
                    // Available or fresh learning exits Unreachable. An
                    // unexpired Busy is likewise already in effect.
                    entry.reachability != ReachabilityStatus::Unreachable
                        && (entry.reachability != ReachabilityStatus::Busy
                            || entry.busy_until.is_some_and(|deadline| now >= deadline))
                }
                _ => true,
            }
        });
        let held_down = self
            .reject_transitions
            .get(&network)
            .and_then(|ports| ports.get(&ingress_port))
            .is_some_and(|last| now.duration_since(*last) < HOLD_DOWN);
        if !changes_state || held_down {
            let counters = &mut self.claim_counters;
            counters.reject_dampened = counters.reject_dampened.saturating_add(1);
            if !changes_state {
                counters.reject_dampened_same_state =
                    counters.reject_dampened_same_state.saturating_add(1);
            } else {
                counters.reject_dampened_hold_down =
                    counters.reject_dampened_hold_down.saturating_add(1);
            }
            return; // Ignored claims never slide the window or busy deadline.
        }

        match reason {
            1 => self.mark_unreachable(network),
            2 => self.mark_busy(network, now + Duration::from_secs(30)),
            _ => {
                self.remove(network); // Removal also discards every port's record.
            }
        }
        if self.routes.contains_key(&network) {
            self.reject_transitions
                .entry(network)
                .or_default()
                .insert(ingress_port, now);
        }
        self.claim_counters.reject_applied = self.claim_counters.reject_applied.saturating_add(1);
    }

    /// Add a directly-connected network on the given port.
    /// Network 0 and 0xFFFF are reserved and will be silently ignored.
    pub fn add_direct(&mut self, network: u16, port_index: usize) {
        if network == 0 || network == 0xFFFF {
            return;
        }
        self.reject_transitions.remove(&network);
        self.pending_replacements.remove(&network);
        self.routes.insert(
            network,
            RouteEntry {
                port_index,
                directly_connected: true,
                next_hop_mac: MacAddr::new(),
                last_seen: None,
                last_used: None,
                reachability: ReachabilityStatus::Reachable,
                busy_until: None,
                flap_count: 0,
                last_port_change: None,
            },
        );
    }

    /// Add a learned route (network reachable via a next-hop router on the given port).
    /// Network 0 and 0xFFFF are reserved and will be silently ignored.
    /// Does not overwrite direct routes. Control-plane confirmation: sets
    /// `last_seen`; preserves `last_used` on a same-port refresh, resets it
    /// on a new or moved path.
    pub fn add_learned(&mut self, network: u16, port_index: usize, next_hop_mac: MacAddr) {
        self.add_learned_at(network, port_index, next_hop_mac, Instant::now());
    }

    /// Injectable-time variant of [`Self::add_learned`] for deterministic tests.
    pub fn add_learned_at(
        &mut self,
        network: u16,
        port_index: usize,
        next_hop_mac: MacAddr,
        now: Instant,
    ) {
        if network == 0 || network == 0xFFFF {
            return;
        }
        let preserved_used = self.routes.get(&network).and_then(|existing| {
            if existing.directly_connected {
                None
            } else if existing.port_index == port_index {
                existing.last_used
            } else {
                None
            }
        });
        if self
            .routes
            .get(&network)
            .is_some_and(|existing| existing.directly_connected)
        {
            return; // never overwrite direct routes
        }
        self.reject_transitions.remove(&network);
        self.pending_replacements.remove(&network);
        self.routes.insert(
            network,
            RouteEntry {
                port_index,
                directly_connected: false,
                next_hop_mac,
                last_seen: Some(now),
                last_used: preserved_used,
                reachability: ReachabilityStatus::Reachable,
                busy_until: None,
                flap_count: 0,
                last_port_change: None,
            },
        );
    }

    /// Wire Port ID for a dispatch port index (135-2020 6.4.7, Fig. 6-11).
    ///
    /// A zero Port ID instructs the receiver to delete every row it holds for
    /// that DNET, so 0 is a removal trigger, never a real port. The stable
    /// mapping is `port_index + 1`; `None` when the index cannot fit the
    /// 1-octet field (unreachable for a bounded port vector, handled by
    /// skipping the entry on encode).
    pub fn wire_port_id(port_index: usize) -> Option<u8> {
        u8::try_from(port_index.checked_add(1)?).ok()
    }

    /// Dispatch port index for a wire Port ID, given the local port count.
    ///
    /// Inverse of [`Self::wire_port_id`]: Port ID 0 (the purge trigger) and
    /// IDs past the local port count map to `None`; the caller applies purge
    /// versus unknown-port skip semantics.
    pub fn port_index_for_wire_id(port_id: u8, port_count: usize) -> Option<usize> {
        usize::from(port_id)
            .checked_sub(1)
            .filter(|index| *index < port_count)
    }

    /// Network numbers in ascending order for deterministic query replies.
    pub fn sorted_networks(&self) -> Vec<u16> {
        let mut networks = self.networks();
        networks.sort_unstable();
        networks
    }

    /// Apply one Initialize-Routing-Table update entry (135-2020 6.6.3.8).
    ///
    /// Each entry is an upsert keyed by DNET (see also 6.4.7): the supplied
    /// route takes the place of whatever row the table holds for that
    /// network, and a network the table lacks gets a fresh row. Management
    /// writes install learned routes and never direct ones — direct
    /// attachments stay locally configured until RB-09 authorization — so an
    /// existing direct entry is left untouched and reports `false`. Reserved
    /// networks are skipped. Replacement clears pending/reject records exactly
    /// like fresh learning.
    pub(crate) fn apply_management_update(
        &mut self,
        network: u16,
        port_index: usize,
        next_hop_mac: MacAddr,
    ) -> bool {
        if network == 0 || network == 0xFFFF {
            return false;
        }
        if self
            .routes
            .get(&network)
            .is_some_and(|entry| entry.directly_connected)
        {
            return false;
        }
        self.add_learned(network, port_index, next_hop_mac);
        true
    }

    /// Apply one Initialize-Routing-Table purge entry (Port ID 0, 6.4.7).
    ///
    /// Port ID 0 asks for every row naming that DNET to be deleted; here that
    /// is scoped to learned entries only, for the same direct-safety
    /// reason as [`Self::apply_management_update`]. Returns `true` only when
    /// a learned entry was actually removed.
    pub(crate) fn apply_management_removal(&mut self, network: u16) -> bool {
        if network == 0 || network == 0xFFFF {
            return false;
        }
        if self
            .routes
            .get(&network)
            .is_some_and(|entry| entry.directly_connected)
        {
            return false;
        }
        self.remove(network).is_some()
    }

    /// Add a learned route immediately (manual table update, without corroboration).
    /// Detects rapid port changes for operator visibility but never suppresses updates.
    ///
    /// Returns `true` if the route was inserted/updated.
    pub fn add_learned_with_flap_detection(
        &mut self,
        network: u16,
        port_index: usize,
        next_hop_mac: MacAddr,
    ) -> bool {
        self.add_learned_with_flap_detection_at(network, port_index, next_hop_mac, Instant::now())
    }

    /// Injectable-time variant of [`Self::add_learned_with_flap_detection`].
    ///
    /// A port change installs `last_seen = now` with `last_used = None` (the
    /// new path has not forwarded yet); a same-port refresh preserves
    /// `last_used` via [`Self::add_learned_at`].
    pub fn add_learned_with_flap_detection_at(
        &mut self,
        network: u16,
        port_index: usize,
        next_hop_mac: MacAddr,
        now: Instant,
    ) -> bool {
        if network == 0 || network == 0xFFFF {
            return false;
        }
        if let Some(existing) = self.routes.get(&network) {
            if existing.directly_connected {
                return false;
            }
            if existing.port_index != port_index {
                let flap_count = match existing.last_port_change {
                    Some(changed) if now.duration_since(changed) < Duration::from_secs(60) => {
                        existing.flap_count.saturating_add(1)
                    }
                    _ => 1,
                };
                if flap_count >= 3 {
                    self.claim_counters.flap_warned =
                        self.claim_counters.flap_warned.saturating_add(1);
                    tracing::warn!(
                        network,
                        old_port = existing.port_index,
                        new_port = port_index,
                        flap_count,
                        "Route flapping detected — network changed ports {} times in 60s",
                        flap_count
                    );
                }
                self.reject_transitions.remove(&network);
                self.pending_replacements.remove(&network);
                self.routes.insert(
                    network,
                    RouteEntry {
                        port_index,
                        directly_connected: false,
                        next_hop_mac,
                        last_seen: Some(now),
                        last_used: None,
                        reachability: ReachabilityStatus::Reachable,
                        busy_until: None,
                        flap_count,
                        last_port_change: Some(now),
                    },
                );
                return true;
            }
        }
        self.add_learned_at(network, port_index, next_hop_mac, now);
        true
    }

    /// Mark a network as busy with a deadline for auto-clear (spec 6.6.3.6).
    /// Directly-connected paths are never overridden by Busy: they are served
    /// locally, not via the announcing peer. A permanently Unreachable entry
    /// is likewise left untouched: a temporary congestion claim must never
    /// resurrect a failed route via the 30s auto-clear — only Available or
    /// fresh learning lifts Unreachable. Touches neither `last_seen` nor
    /// `last_used` (RB-06 freshness split).
    pub fn mark_busy(&mut self, network: u16, deadline: Instant) {
        if let Some(entry) = self.routes.get_mut(&network) {
            if !entry.directly_connected && entry.reachability != ReachabilityStatus::Unreachable {
                entry.reachability = ReachabilityStatus::Busy;
                entry.busy_until = Some(deadline);
            }
        }
    }

    /// Mark a network as available, clearing any busy state (spec 6.6.3.7).
    /// Directly-connected paths are never touched: Busy/Available only covers
    /// routes served via the announcing peer. Touches neither `last_seen` nor
    /// `last_used` (RB-06 freshness split).
    pub fn mark_available(&mut self, network: u16) {
        if let Some(entry) = self.routes.get_mut(&network) {
            if !entry.directly_connected {
                entry.reachability = ReachabilityStatus::Reachable;
                entry.busy_until = None;
            }
        }
    }

    /// Whether `network` is served via the announcing peer on this ingress
    /// path: a learned (never directly-connected) route whose egress port and
    /// next-hop MAC match the immediate link peer — not the routed SNET/SADR.
    /// RB-04 locks this predicate to 135-2020 Clauses 6.6.3.6/6.6.3.7: a Busy
    /// that omits its network list asks that traffic be held back for every
    /// network the router normally serves, and an Available without a list
    /// lifts that hold for all of them. Explicit lists intersect with the
    /// same set: listed nets outside the announcing path are not marked.
    pub fn is_served_via_peer(&self, network: u16, port_index: usize, next_hop: &MacAddr) -> bool {
        self.routes.get(&network).is_some_and(|entry| {
            !entry.directly_connected
                && entry.port_index == port_index
                && entry.next_hop_mac == *next_hop
        })
    }

    /// All networks served via the announcing peer: the omitted-list scope
    /// for Router-Busy/Router-Available-To-Network (Clauses 6.6.3.6/6.6.3.7).
    pub fn routes_served_via_peer(&self, port_index: usize, next_hop: &MacAddr) -> Vec<u16> {
        self.routes
            .iter()
            .filter(|(_, entry)| {
                !entry.directly_connected
                    && entry.port_index == port_index
                    && entry.next_hop_mac == *next_hop
            })
            .map(|(net, _)| *net)
            .collect()
    }

    /// Mark a network as permanently unreachable (spec 6.6.3.5, reject reason 1).
    /// Keeps the entry in the table (unlike `remove`).
    pub fn mark_unreachable(&mut self, network: u16) {
        if let Some(entry) = self.routes.get_mut(&network) {
            if !entry.directly_connected {
                entry.reachability = ReachabilityStatus::Unreachable;
                entry.busy_until = None;
            }
        }
    }

    /// Clear busy state for entries whose `busy_until` deadline has elapsed.
    pub fn clear_expired_busy(&mut self) {
        let now = Instant::now();
        for entry in self.routes.values_mut() {
            if let Some(deadline) = entry.busy_until {
                if now >= deadline {
                    entry.reachability = ReachabilityStatus::Reachable;
                    entry.busy_until = None;
                }
            }
        }
    }

    /// Get effective reachability, checking busy_until inline for immediate accuracy.
    /// This avoids up to 90s worst-case from the 60s aging sweep granularity.
    pub fn effective_reachability(&self, network: u16) -> Option<ReachabilityStatus> {
        self.routes.get(&network).map(|entry| {
            if entry.reachability == ReachabilityStatus::Busy {
                if let Some(deadline) = entry.busy_until {
                    if Instant::now() >= deadline {
                        return ReachabilityStatus::Reachable;
                    }
                }
            }
            entry.reachability
        })
    }

    /// Look up the route for a network number.
    pub fn lookup(&self, network: u16) -> Option<&RouteEntry> {
        self.routes.get(&network)
    }

    /// Lookup a mutable route entry by network number.
    /// Clears any pending challenger since the caller can replace the route state.
    pub fn lookup_mut(&mut self, network: u16) -> Option<&mut RouteEntry> {
        self.pending_replacements.remove(&network);
        self.routes.get_mut(&network)
    }

    /// Remove a route.
    pub fn remove(&mut self, network: u16) -> Option<RouteEntry> {
        self.reject_transitions.remove(&network);
        self.pending_replacements.remove(&network);
        self.routes.remove(&network)
    }

    /// List all known network numbers.
    pub fn networks(&self) -> Vec<u16> {
        self.routes.keys().copied().collect()
    }

    /// List networks reachable via ports OTHER than `exclude_port`.
    pub fn networks_not_on_port(&self, exclude_port: usize) -> Vec<u16> {
        self.routes
            .iter()
            .filter(|(_, entry)| entry.port_index != exclude_port)
            .map(|(net, _)| *net)
            .collect()
    }

    /// List networks reachable on a given port.
    pub fn networks_on_port(&self, port_index: usize) -> Vec<u16> {
        self.routes
            .iter()
            .filter(|(_, entry)| entry.port_index == port_index)
            .map(|(net, _)| *net)
            .collect()
    }

    /// Number of routes.
    pub fn len(&self) -> usize {
        self.routes.len()
    }

    /// Whether the table is empty.
    pub fn is_empty(&self) -> bool {
        self.routes.is_empty()
    }

    /// Record data-plane forwarding use for a learned route.
    ///
    /// Sets `last_used` only; `last_seen` (control-plane confirmation) is
    /// untouched so traffic cannot extend expiry. Direct routes are unaffected
    /// since they never expire.
    pub fn touch(&mut self, network: u16) {
        self.touch_used_at(network, Instant::now());
    }

    /// Injectable-time variant of [`Self::touch`] for deterministic tests.
    pub fn touch_used_at(&mut self, network: u16, now: Instant) {
        if let Some(entry) = self.routes.get_mut(&network) {
            if !entry.directly_connected {
                entry.last_used = Some(now);
            }
        }
    }

    /// Remove learned routes not confirmed within `max_age`.
    ///
    /// Keys off `last_seen` only; `last_used` never extends lifetime.
    /// Direct routes (`last_seen == None`) never expire.
    /// Returns the network numbers that were purged.
    pub fn purge_stale(&mut self, max_age: Duration) -> Vec<u16> {
        self.purge_stale_at(Instant::now(), max_age)
    }

    /// Injectable-time variant of [`Self::purge_stale`] for deterministic tests.
    pub fn purge_stale_at(&mut self, now: Instant, max_age: Duration) -> Vec<u16> {
        let stale: Vec<u16> = self
            .routes
            .iter()
            .filter(|(_, entry)| {
                if let Some(seen) = entry.last_seen {
                    !entry.directly_connected && now.duration_since(seen) > max_age
                } else {
                    false
                }
            })
            .map(|(net, _)| *net)
            .collect();
        for net in &stale {
            self.remove(*net);
        }
        stale
    }
}

impl Default for RouterTable {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
#[path = "router_table_reject_tests.rs"]
mod reject_tests;

#[cfg(test)]
#[path = "router_table_corroboration_tests.rs"]
mod corroboration_tests;

#[cfg(test)]
#[path = "router_table_tests.rs"]
mod tests;