Skip to main content

ant_node/replication/
bootstrap.rs

1//! New-node bootstrap logic (Section 16).
2//!
3//! A joining node performs active sync to discover and verify keys it should
4//! hold, then transitions to normal operation once all bootstrap work drains.
5
6use std::collections::HashSet;
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use crate::logging::{debug, info, warn};
11use tokio::sync::RwLock;
12use tokio_util::sync::CancellationToken;
13
14use saorsa_core::DhtNetworkEvent;
15
16use crate::ant_protocol::XorName;
17use crate::replication::scheduling::ReplicationQueues;
18use crate::replication::types::BootstrapState;
19
20// ---------------------------------------------------------------------------
21// DHT bootstrap gate
22// ---------------------------------------------------------------------------
23
24/// Outcome of waiting for the `DhtNetworkEvent::BootstrapComplete` event.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum BootstrapGateResult {
27    /// The event was received — routing table is populated.
28    Received,
29    /// Timed out or channel error — proceed anyway (bootstrap node scenario).
30    TimedOut,
31    /// Shutdown was requested while waiting.
32    Shutdown,
33}
34
35/// Wait for saorsa-core's `DhtNetworkEvent::BootstrapComplete` before
36/// returning.
37///
38/// The caller must supply a pre-subscribed `dht_events` receiver. This is
39/// critical: the subscription must be created **before**
40/// `P2PNode::start()` so the `BootstrapComplete` event is not missed.
41///
42/// Returns [`BootstrapGateResult::Received`] on success,
43/// [`BootstrapGateResult::TimedOut`] if the timeout elapses (e.g. a
44/// bootstrap node with no peers), or [`BootstrapGateResult::Shutdown`] if
45/// cancellation is signalled.
46pub async fn wait_for_bootstrap_complete(
47    mut dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
48    timeout_secs: u64,
49    shutdown: &CancellationToken,
50) -> BootstrapGateResult {
51    let timeout = Duration::from_secs(timeout_secs);
52
53    let result = tokio::select! {
54        () = shutdown.cancelled() => {
55            debug!("Bootstrap sync: shutdown during BootstrapComplete wait");
56            BootstrapGateResult::Shutdown
57        }
58        () = tokio::time::sleep(timeout) => {
59            warn!(
60                "Bootstrap sync: timed out after {timeout_secs}s waiting for \
61                 BootstrapComplete — proceeding (likely a bootstrap node with no peers)",
62            );
63            BootstrapGateResult::TimedOut
64        }
65        gate = async {
66            loop {
67                match dht_events.recv().await {
68                    Ok(DhtNetworkEvent::BootstrapComplete { num_peers }) => {
69                        info!(
70                            "Bootstrap sync: DHT bootstrap complete \
71                             with {num_peers} peers in routing table"
72                        );
73                        break BootstrapGateResult::Received;
74                    }
75                    Ok(_) => {}
76                    Err(e) => {
77                        warn!(
78                            "Bootstrap sync: DHT event channel error: {e}, \
79                             proceeding without gate"
80                        );
81                        break BootstrapGateResult::TimedOut;
82                    }
83                }
84            }
85        } => gate,
86    };
87    drop(dht_events);
88    result
89}
90
91// ---------------------------------------------------------------------------
92// Bootstrap sync
93// ---------------------------------------------------------------------------
94
95// `snapshot_close_neighbors` is defined in `neighbor_sync` and re-used here.
96
97/// Mark bootstrap as complete, updating the shared state.
98pub async fn mark_bootstrap_drained(bootstrap_state: &Arc<RwLock<BootstrapState>>) {
99    let mut state = bootstrap_state.write().await;
100    state.drained = true;
101    info!("Bootstrap explicitly marked as drained");
102}
103
104/// Check if bootstrap is drained and update state if so.
105///
106/// Bootstrap is drained when:
107/// 1. All bootstrap peer requests have completed.
108/// 2. All bootstrap-discovered keys have left the pipeline (no longer in
109///    `PendingVerify`, `FetchQueue`, or `InFlightFetch`).
110///
111/// Returns `true` if bootstrap is (now) drained.
112pub async fn check_bootstrap_drained(
113    bootstrap_state: &Arc<RwLock<BootstrapState>>,
114    queues: &ReplicationQueues,
115) -> bool {
116    let mut state = bootstrap_state.write().await;
117    if state.drained {
118        return true;
119    }
120
121    if state.pending_peer_requests > 0 {
122        return false;
123    }
124
125    // Hints rejected at capacity, or displaced when another sender reclaims a
126    // borrowed slot, must be re-delivered by the originating source before
127    // drain can be claimed; otherwise we'd silently mark ourselves complete
128    // with outstanding work the source still owes us.
129    // Entries retire per-source as each source's next admission cycle
130    // completes with zero rejections — see `clear_capacity_rejected` — or
131    // expire once the source has been silent past the re-delivery TTL — see
132    // `expire_capacity_rejected`.
133    if !state.capacity_rejected_sources.is_empty() {
134        let n = state.capacity_rejected_sources.len();
135        debug!("Bootstrap NOT drained: {n} source(s) have outstanding capacity-rejected hints");
136        return false;
137    }
138
139    if queues.is_bootstrap_work_empty(&state.pending_keys) {
140        state.drained = true;
141        info!("Bootstrap drained: all peer requests completed and work queues empty");
142        true
143    } else {
144        false
145    }
146}
147
148/// Record that `source` had one or more hints rejected at capacity this cycle.
149///
150/// Tracks each source's **first** rejection time, not a counter and not the
151/// most recent time: a repeat rejection re-asserts the debt but does not
152/// restart the expiry clock (see
153/// [`BootstrapState::capacity_rejected_sources`]). Bootstrap cannot drain
154/// while this source has an entry; cleared by [`clear_capacity_rejected`] when
155/// the same source's next admission cycle completes with zero rejections (i.e.
156/// the source successfully re-delivered everything that previously
157/// overflowed), or expired by [`expire_capacity_rejected`] once the debt has
158/// stood past the re-delivery TTL.
159pub async fn note_capacity_rejected(
160    bootstrap_state: &Arc<RwLock<BootstrapState>>,
161    source: saorsa_core::identity::PeerId,
162) {
163    let mut state = bootstrap_state.write().await;
164    if state.note_capacity_rejected(source, Instant::now()) {
165        let n = state.capacity_rejected_sources.len();
166        debug!(
167            "Bootstrap: source {source} now has outstanding capacity-rejected hints \
168             ({n} sources outstanding)"
169        );
170    }
171}
172
173/// Mark `source`'s outstanding capacity rejections as cleared.
174///
175/// Called whenever `source` completes an admission cycle with zero
176/// capacity rejections: the source successfully re-delivered any hints
177/// that previously overflowed, so its contribution to "bootstrap not
178/// drained" is retired. Returns whether an outstanding entry was removed.
179pub async fn clear_capacity_rejected(
180    bootstrap_state: &Arc<RwLock<BootstrapState>>,
181    source: &saorsa_core::identity::PeerId,
182) -> bool {
183    let mut state = bootstrap_state.write().await;
184    if state.capacity_rejected_sources.remove(source).is_some() {
185        let n = state.capacity_rejected_sources.len();
186        debug!(
187            "Bootstrap: cleared outstanding capacity rejections for {source} \
188             ({n} sources still outstanding)"
189        );
190        true
191    } else {
192        false
193    }
194}
195
196/// Expire capacity-rejection records whose most recent rejection is older
197/// than `max_age`, returning how many sources were expired.
198///
199/// A source that has not re-delivered within `max_age` has abandoned its
200/// owed re-hints — or departed in a race with its own `PeerRemoved` cleanup,
201/// leaving a record that no admission cycle or removal event can ever clear.
202/// Expiry forfeits the keys that source still owed so bootstrap can drain;
203/// the post-bootstrap neighbor-sync and audit/repair pipeline recover them
204/// (see `BootstrapState::capacity_rejected_sources`).
205pub async fn expire_capacity_rejected(
206    bootstrap_state: &Arc<RwLock<BootstrapState>>,
207    max_age: Duration,
208) -> usize {
209    let now = Instant::now();
210    let mut state = bootstrap_state.write().await;
211    let before = state.capacity_rejected_sources.len();
212    state
213        .capacity_rejected_sources
214        .retain(|source, rejected_at| {
215            let expired = now.duration_since(*rejected_at) >= max_age;
216            if expired {
217                warn!(
218                    "Bootstrap: expiring capacity-rejection record for {source} — the source \
219                 abandoned re-delivery (or departed mid-admission) and the hints it still \
220                 owed are forfeited"
221                );
222            }
223            !expired
224        });
225    before - state.capacity_rejected_sources.len()
226}
227
228/// Record a set of discovered keys into the bootstrap state for drain tracking.
229#[allow(clippy::implicit_hasher)]
230pub async fn track_discovered_keys(
231    bootstrap_state: &Arc<RwLock<BootstrapState>>,
232    keys: &HashSet<XorName>,
233) {
234    let mut state = bootstrap_state.write().await;
235    state.pending_keys.extend(keys);
236    debug!(
237        "Bootstrap tracking {} total discovered keys",
238        state.pending_keys.len()
239    );
240}
241
242/// Increment the pending peer request counter.
243pub async fn increment_pending_requests(
244    bootstrap_state: &Arc<RwLock<BootstrapState>>,
245    count: usize,
246) {
247    let mut state = bootstrap_state.write().await;
248    state.pending_peer_requests += count;
249}
250
251/// Decrement the pending peer request counter (saturating).
252pub async fn decrement_pending_requests(
253    bootstrap_state: &Arc<RwLock<BootstrapState>>,
254    count: usize,
255) {
256    let mut state = bootstrap_state.write().await;
257    state.pending_peer_requests = state.pending_peer_requests.saturating_sub(count);
258}
259
260// ---------------------------------------------------------------------------
261// Tests
262// ---------------------------------------------------------------------------
263
264#[cfg(test)]
265#[allow(clippy::unwrap_used, clippy::expect_used)]
266mod tests {
267    use super::*;
268
269    fn xor_name_from_byte(b: u8) -> XorName {
270        [b; 32]
271    }
272
273    #[tokio::test]
274    async fn check_drained_when_already_drained() {
275        let state = Arc::new(RwLock::new(BootstrapState {
276            drained: true,
277            pending_peer_requests: 5,
278            pending_keys: HashSet::new(),
279            capacity_rejected_sources: std::collections::HashMap::new(),
280        }));
281        let queues = ReplicationQueues::new();
282
283        assert!(
284            check_bootstrap_drained(&state, &queues).await,
285            "should be drained when flag is already set"
286        );
287    }
288
289    #[tokio::test]
290    async fn check_drained_blocked_by_pending_requests() {
291        let state = Arc::new(RwLock::new(BootstrapState {
292            drained: false,
293            pending_peer_requests: 2,
294            pending_keys: HashSet::new(),
295            capacity_rejected_sources: std::collections::HashMap::new(),
296        }));
297        let queues = ReplicationQueues::new();
298
299        assert!(
300            !check_bootstrap_drained(&state, &queues).await,
301            "should not drain with pending requests"
302        );
303    }
304
305    #[tokio::test]
306    async fn check_drained_transitions_when_all_work_done() {
307        let state = Arc::new(RwLock::new(BootstrapState {
308            drained: false,
309            pending_peer_requests: 0,
310            pending_keys: std::iter::once(xor_name_from_byte(0x01)).collect(),
311            capacity_rejected_sources: std::collections::HashMap::new(),
312        }));
313        let queues = ReplicationQueues::new();
314
315        // Key 0x01 is not in any queue, so bootstrap should drain.
316        assert!(check_bootstrap_drained(&state, &queues).await);
317        assert!(state.read().await.drained, "drained flag should be set");
318    }
319
320    #[tokio::test]
321    async fn check_drained_blocked_by_queued_key() {
322        let state = Arc::new(RwLock::new(BootstrapState {
323            drained: false,
324            pending_peer_requests: 0,
325            pending_keys: std::iter::once(xor_name_from_byte(0x01)).collect(),
326            capacity_rejected_sources: std::collections::HashMap::new(),
327        }));
328        let mut queues = ReplicationQueues::new();
329
330        // Put the bootstrap key into the pending-verify queue.
331        let now = Instant::now();
332        let entry = crate::replication::types::VerificationEntry {
333            state: crate::replication::types::VerificationState::PendingVerify,
334            verified_sources: Vec::new(),
335            tried_sources: HashSet::new(),
336            created_at: now,
337            next_verify_at: now,
338            hint_sources: HashSet::from([saorsa_core::identity::PeerId::from_bytes([0u8; 32])]),
339            replica_hint_sources: HashSet::from([saorsa_core::identity::PeerId::from_bytes(
340                [0u8; 32],
341            )]),
342        };
343        queues.add_pending_verify(xor_name_from_byte(0x01), entry);
344
345        assert!(
346            !check_bootstrap_drained(&state, &queues).await,
347            "should not drain while bootstrap key is still in pipeline"
348        );
349    }
350
351    #[tokio::test]
352    async fn mark_bootstrap_drained_sets_flag() {
353        let state = Arc::new(RwLock::new(BootstrapState::new()));
354        mark_bootstrap_drained(&state).await;
355        assert!(state.read().await.drained);
356    }
357
358    #[tokio::test]
359    async fn track_discovered_keys_accumulates() {
360        let state = Arc::new(RwLock::new(BootstrapState::new()));
361        let set_a: HashSet<XorName> = [xor_name_from_byte(0x01), xor_name_from_byte(0x02)]
362            .into_iter()
363            .collect();
364        let set_b: HashSet<XorName> = [xor_name_from_byte(0x02), xor_name_from_byte(0x03)]
365            .into_iter()
366            .collect();
367
368        track_discovered_keys(&state, &set_a).await;
369        track_discovered_keys(&state, &set_b).await;
370
371        let s = state.read().await;
372        assert_eq!(s.pending_keys.len(), 3, "should deduplicate across calls");
373    }
374
375    #[tokio::test]
376    async fn increment_and_decrement_pending_requests() {
377        let state = Arc::new(RwLock::new(BootstrapState::new()));
378
379        increment_pending_requests(&state, 5).await;
380        assert_eq!(state.read().await.pending_peer_requests, 5);
381
382        decrement_pending_requests(&state, 3).await;
383        assert_eq!(state.read().await.pending_peer_requests, 2);
384
385        // Saturating subtraction.
386        decrement_pending_requests(&state, 10).await;
387        assert_eq!(
388            state.read().await.pending_peer_requests,
389            0,
390            "should saturate at zero"
391        );
392    }
393
394    /// Round-3 regression: a source that previously had capacity-rejected
395    /// hints must be retired from the "not yet drained" list when it
396    /// completes a later admission cycle with zero rejections, otherwise
397    /// `check_bootstrap_drained` is permanently wedged after a single
398    /// rejection.
399    #[tokio::test]
400    async fn capacity_rejected_clears_on_clean_cycle() {
401        let state = Arc::new(RwLock::new(BootstrapState::new()));
402        let queues = ReplicationQueues::new();
403        let source = saorsa_core::identity::PeerId::from_bytes([7u8; 32]);
404
405        // First cycle: this source overflowed, drain blocked.
406        note_capacity_rejected(&state, source).await;
407        assert!(
408            !check_bootstrap_drained(&state, &queues).await,
409            "drain must be blocked while a source has outstanding capacity rejections"
410        );
411
412        // Second cycle from the SAME source: zero rejections → clear it.
413        clear_capacity_rejected(&state, &source).await;
414        assert!(
415            check_bootstrap_drained(&state, &queues).await,
416            "drain must complete once the source's outstanding rejections are cleared"
417        );
418    }
419
420    /// Per-source granularity: one source's clean cycle must NOT clear a
421    /// different source's outstanding rejections.
422    #[tokio::test]
423    async fn capacity_rejected_is_per_source() {
424        let state = Arc::new(RwLock::new(BootstrapState::new()));
425        let queues = ReplicationQueues::new();
426        let source_a = saorsa_core::identity::PeerId::from_bytes([0xAA; 32]);
427        let source_b = saorsa_core::identity::PeerId::from_bytes([0xBB; 32]);
428
429        note_capacity_rejected(&state, source_a).await;
430        note_capacity_rejected(&state, source_b).await;
431        assert!(!check_bootstrap_drained(&state, &queues).await);
432
433        // Only A clears; B still owes us re-hints.
434        clear_capacity_rejected(&state, &source_a).await;
435        assert!(
436            !check_bootstrap_drained(&state, &queues).await,
437            "B's outstanding rejections must keep drain blocked"
438        );
439
440        clear_capacity_rejected(&state, &source_b).await;
441        assert!(check_bootstrap_drained(&state, &queues).await);
442    }
443
444    /// A source rejected within the TTL still blocks drain: expiry must not
445    /// forfeit re-delivery the source may legitimately still perform.
446    #[tokio::test]
447    async fn capacity_rejected_within_ttl_still_blocks_drain() {
448        let state = Arc::new(RwLock::new(BootstrapState::new()));
449        let queues = ReplicationQueues::new();
450        let source = saorsa_core::identity::PeerId::from_bytes([0xC1; 32]);
451
452        note_capacity_rejected(&state, source).await;
453        assert_eq!(
454            expire_capacity_rejected(&state, Duration::from_secs(3600)).await,
455            0,
456            "a fresh rejection must survive expiry with a generous max_age"
457        );
458        assert!(
459            !check_bootstrap_drained(&state, &queues).await,
460            "a within-TTL rejection must keep drain blocked"
461        );
462    }
463
464    /// The orphaned-entry escape hatch: once a source's rejection record
465    /// expires, drain is no longer blocked by it.
466    #[tokio::test]
467    async fn capacity_rejected_expiry_unblocks_drain() {
468        let state = Arc::new(RwLock::new(BootstrapState::new()));
469        let queues = ReplicationQueues::new();
470        let source = saorsa_core::identity::PeerId::from_bytes([0xC2; 32]);
471
472        note_capacity_rejected(&state, source).await;
473        assert!(!check_bootstrap_drained(&state, &queues).await);
474
475        assert_eq!(expire_capacity_rejected(&state, Duration::ZERO).await, 1);
476        assert!(
477            check_bootstrap_drained(&state, &queues).await,
478            "drain must complete once the abandoned rejection expires"
479        );
480    }
481
482    /// Expiry is per-source: dropping a stale source must not forfeit a
483    /// fresh source's owed re-delivery.
484    #[tokio::test]
485    async fn capacity_rejected_expiry_is_per_source() {
486        let state = Arc::new(RwLock::new(BootstrapState::new()));
487        let queues = ReplicationQueues::new();
488        let stale_source = saorsa_core::identity::PeerId::from_bytes([0xC3; 32]);
489        let fresh_source = saorsa_core::identity::PeerId::from_bytes([0xC4; 32]);
490        let max_age = Duration::from_secs(60);
491        let stale_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
492
493        state
494            .write()
495            .await
496            .capacity_rejected_sources
497            .insert(stale_source, stale_rejected_at);
498        note_capacity_rejected(&state, fresh_source).await;
499
500        assert_eq!(expire_capacity_rejected(&state, max_age).await, 1);
501        assert!(
502            state
503                .read()
504                .await
505                .capacity_rejected_sources
506                .contains_key(&fresh_source),
507            "the fresh source must survive another source's expiry"
508        );
509        assert!(
510            !check_bootstrap_drained(&state, &queues).await,
511            "the fresh source must still block drain"
512        );
513    }
514
515    /// A repeat rejection re-asserts the debt but must NOT restart the expiry
516    /// clock.
517    ///
518    /// Refreshing on every rejection is what wedged bootstrap open: a source
519    /// that keeps overflowing the queue keeps its own record permanently
520    /// fresh, `check_bootstrap_drained` never returns true, and auditing stays
521    /// off for the lifetime of the pressure (Invariant 19).
522    #[tokio::test]
523    async fn repeat_capacity_rejection_does_not_refresh_timestamp() {
524        let state = Arc::new(RwLock::new(BootstrapState::new()));
525        let source = saorsa_core::identity::PeerId::from_bytes([0xC5; 32]);
526        let max_age = Duration::from_secs(60);
527        let first_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
528
529        state
530            .write()
531            .await
532            .capacity_rejected_sources
533            .insert(source, first_rejected_at);
534        note_capacity_rejected(&state, source).await;
535
536        let recorded_at = state
537            .read()
538            .await
539            .capacity_rejected_sources
540            .get(&source)
541            .copied()
542            .unwrap();
543        assert_eq!(
544            recorded_at, first_rejected_at,
545            "a repeat rejection must leave the first-seen time alone"
546        );
547        assert_eq!(
548            expire_capacity_rejected(&state, max_age).await,
549            1,
550            "an aged debt must still expire even though the source keeps \
551             re-overflowing the queue"
552        );
553    }
554
555    /// Sustained pressure cannot hold bootstrap open past the TTL.
556    ///
557    /// Drives the production accounting shape — repeated rejections arriving
558    /// faster than the TTL — and asserts the node still drains.
559    #[tokio::test]
560    async fn sustained_capacity_rejection_still_drains_after_ttl() {
561        const REJECTION_ROUNDS: usize = 8;
562
563        let state = Arc::new(RwLock::new(BootstrapState::new()));
564        let queues = ReplicationQueues::new();
565        let source = saorsa_core::identity::PeerId::from_bytes([0xC6; 32]);
566        let max_age = Duration::from_secs(60);
567
568        for _ in 0..REJECTION_ROUNDS {
569            note_capacity_rejected(&state, source).await;
570            assert!(
571                !check_bootstrap_drained(&state, &queues).await,
572                "an outstanding debt must block drain while it is inside the TTL"
573            );
574        }
575
576        // Age the (unrefreshed) first-seen stamp past the TTL.
577        let aged = Instant::now().checked_sub(max_age * 2).unwrap();
578        state
579            .write()
580            .await
581            .capacity_rejected_sources
582            .insert(source, aged);
583
584        assert_eq!(
585            expire_capacity_rejected(&state, max_age).await,
586            1,
587            "the debt must expire once the FIRST rejection is older than the TTL"
588        );
589        assert!(
590            check_bootstrap_drained(&state, &queues).await,
591            "bootstrap must drain once the expired debt is forfeited"
592        );
593    }
594}