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            unresolved_retries: 0,
343            no_holder_reported: false,
344        };
345        queues.add_pending_verify(xor_name_from_byte(0x01), entry);
346
347        assert!(
348            !check_bootstrap_drained(&state, &queues).await,
349            "should not drain while bootstrap key is still in pipeline"
350        );
351    }
352
353    #[tokio::test]
354    async fn mark_bootstrap_drained_sets_flag() {
355        let state = Arc::new(RwLock::new(BootstrapState::new()));
356        mark_bootstrap_drained(&state).await;
357        assert!(state.read().await.drained);
358    }
359
360    #[tokio::test]
361    async fn track_discovered_keys_accumulates() {
362        let state = Arc::new(RwLock::new(BootstrapState::new()));
363        let set_a: HashSet<XorName> = [xor_name_from_byte(0x01), xor_name_from_byte(0x02)]
364            .into_iter()
365            .collect();
366        let set_b: HashSet<XorName> = [xor_name_from_byte(0x02), xor_name_from_byte(0x03)]
367            .into_iter()
368            .collect();
369
370        track_discovered_keys(&state, &set_a).await;
371        track_discovered_keys(&state, &set_b).await;
372
373        let s = state.read().await;
374        assert_eq!(s.pending_keys.len(), 3, "should deduplicate across calls");
375    }
376
377    #[tokio::test]
378    async fn increment_and_decrement_pending_requests() {
379        let state = Arc::new(RwLock::new(BootstrapState::new()));
380
381        increment_pending_requests(&state, 5).await;
382        assert_eq!(state.read().await.pending_peer_requests, 5);
383
384        decrement_pending_requests(&state, 3).await;
385        assert_eq!(state.read().await.pending_peer_requests, 2);
386
387        // Saturating subtraction.
388        decrement_pending_requests(&state, 10).await;
389        assert_eq!(
390            state.read().await.pending_peer_requests,
391            0,
392            "should saturate at zero"
393        );
394    }
395
396    /// Round-3 regression: a source that previously had capacity-rejected
397    /// hints must be retired from the "not yet drained" list when it
398    /// completes a later admission cycle with zero rejections, otherwise
399    /// `check_bootstrap_drained` is permanently wedged after a single
400    /// rejection.
401    #[tokio::test]
402    async fn capacity_rejected_clears_on_clean_cycle() {
403        let state = Arc::new(RwLock::new(BootstrapState::new()));
404        let queues = ReplicationQueues::new();
405        let source = saorsa_core::identity::PeerId::from_bytes([7u8; 32]);
406
407        // First cycle: this source overflowed, drain blocked.
408        note_capacity_rejected(&state, source).await;
409        assert!(
410            !check_bootstrap_drained(&state, &queues).await,
411            "drain must be blocked while a source has outstanding capacity rejections"
412        );
413
414        // Second cycle from the SAME source: zero rejections → clear it.
415        clear_capacity_rejected(&state, &source).await;
416        assert!(
417            check_bootstrap_drained(&state, &queues).await,
418            "drain must complete once the source's outstanding rejections are cleared"
419        );
420    }
421
422    /// Per-source granularity: one source's clean cycle must NOT clear a
423    /// different source's outstanding rejections.
424    #[tokio::test]
425    async fn capacity_rejected_is_per_source() {
426        let state = Arc::new(RwLock::new(BootstrapState::new()));
427        let queues = ReplicationQueues::new();
428        let source_a = saorsa_core::identity::PeerId::from_bytes([0xAA; 32]);
429        let source_b = saorsa_core::identity::PeerId::from_bytes([0xBB; 32]);
430
431        note_capacity_rejected(&state, source_a).await;
432        note_capacity_rejected(&state, source_b).await;
433        assert!(!check_bootstrap_drained(&state, &queues).await);
434
435        // Only A clears; B still owes us re-hints.
436        clear_capacity_rejected(&state, &source_a).await;
437        assert!(
438            !check_bootstrap_drained(&state, &queues).await,
439            "B's outstanding rejections must keep drain blocked"
440        );
441
442        clear_capacity_rejected(&state, &source_b).await;
443        assert!(check_bootstrap_drained(&state, &queues).await);
444    }
445
446    /// A source rejected within the TTL still blocks drain: expiry must not
447    /// forfeit re-delivery the source may legitimately still perform.
448    #[tokio::test]
449    async fn capacity_rejected_within_ttl_still_blocks_drain() {
450        let state = Arc::new(RwLock::new(BootstrapState::new()));
451        let queues = ReplicationQueues::new();
452        let source = saorsa_core::identity::PeerId::from_bytes([0xC1; 32]);
453
454        note_capacity_rejected(&state, source).await;
455        assert_eq!(
456            expire_capacity_rejected(&state, Duration::from_hours(1)).await,
457            0,
458            "a fresh rejection must survive expiry with a generous max_age"
459        );
460        assert!(
461            !check_bootstrap_drained(&state, &queues).await,
462            "a within-TTL rejection must keep drain blocked"
463        );
464    }
465
466    /// The orphaned-entry escape hatch: once a source's rejection record
467    /// expires, drain is no longer blocked by it.
468    #[tokio::test]
469    async fn capacity_rejected_expiry_unblocks_drain() {
470        let state = Arc::new(RwLock::new(BootstrapState::new()));
471        let queues = ReplicationQueues::new();
472        let source = saorsa_core::identity::PeerId::from_bytes([0xC2; 32]);
473
474        note_capacity_rejected(&state, source).await;
475        assert!(!check_bootstrap_drained(&state, &queues).await);
476
477        assert_eq!(expire_capacity_rejected(&state, Duration::ZERO).await, 1);
478        assert!(
479            check_bootstrap_drained(&state, &queues).await,
480            "drain must complete once the abandoned rejection expires"
481        );
482    }
483
484    /// Expiry is per-source: dropping a stale source must not forfeit a
485    /// fresh source's owed re-delivery.
486    #[tokio::test]
487    async fn capacity_rejected_expiry_is_per_source() {
488        let state = Arc::new(RwLock::new(BootstrapState::new()));
489        let queues = ReplicationQueues::new();
490        let stale_source = saorsa_core::identity::PeerId::from_bytes([0xC3; 32]);
491        let fresh_source = saorsa_core::identity::PeerId::from_bytes([0xC4; 32]);
492        let max_age = Duration::from_mins(1);
493        let stale_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
494
495        state
496            .write()
497            .await
498            .capacity_rejected_sources
499            .insert(stale_source, stale_rejected_at);
500        note_capacity_rejected(&state, fresh_source).await;
501
502        assert_eq!(expire_capacity_rejected(&state, max_age).await, 1);
503        assert!(
504            state
505                .read()
506                .await
507                .capacity_rejected_sources
508                .contains_key(&fresh_source),
509            "the fresh source must survive another source's expiry"
510        );
511        assert!(
512            !check_bootstrap_drained(&state, &queues).await,
513            "the fresh source must still block drain"
514        );
515    }
516
517    /// A repeat rejection re-asserts the debt but must NOT restart the expiry
518    /// clock.
519    ///
520    /// Refreshing on every rejection is what wedged bootstrap open: a source
521    /// that keeps overflowing the queue keeps its own record permanently
522    /// fresh, `check_bootstrap_drained` never returns true, and auditing stays
523    /// off for the lifetime of the pressure (Invariant 19).
524    #[tokio::test]
525    async fn repeat_capacity_rejection_does_not_refresh_timestamp() {
526        let state = Arc::new(RwLock::new(BootstrapState::new()));
527        let source = saorsa_core::identity::PeerId::from_bytes([0xC5; 32]);
528        let max_age = Duration::from_mins(1);
529        let first_rejected_at = Instant::now().checked_sub(max_age * 2).unwrap();
530
531        state
532            .write()
533            .await
534            .capacity_rejected_sources
535            .insert(source, first_rejected_at);
536        note_capacity_rejected(&state, source).await;
537
538        let recorded_at = state
539            .read()
540            .await
541            .capacity_rejected_sources
542            .get(&source)
543            .copied()
544            .unwrap();
545        assert_eq!(
546            recorded_at, first_rejected_at,
547            "a repeat rejection must leave the first-seen time alone"
548        );
549        assert_eq!(
550            expire_capacity_rejected(&state, max_age).await,
551            1,
552            "an aged debt must still expire even though the source keeps \
553             re-overflowing the queue"
554        );
555    }
556
557    /// Sustained pressure cannot hold bootstrap open past the TTL.
558    ///
559    /// Drives the production accounting shape — repeated rejections arriving
560    /// faster than the TTL — and asserts the node still drains.
561    #[tokio::test]
562    async fn sustained_capacity_rejection_still_drains_after_ttl() {
563        const REJECTION_ROUNDS: usize = 8;
564
565        let state = Arc::new(RwLock::new(BootstrapState::new()));
566        let queues = ReplicationQueues::new();
567        let source = saorsa_core::identity::PeerId::from_bytes([0xC6; 32]);
568        let max_age = Duration::from_mins(1);
569
570        for _ in 0..REJECTION_ROUNDS {
571            note_capacity_rejected(&state, source).await;
572            assert!(
573                !check_bootstrap_drained(&state, &queues).await,
574                "an outstanding debt must block drain while it is inside the TTL"
575            );
576        }
577
578        // Age the (unrefreshed) first-seen stamp past the TTL.
579        let aged = Instant::now().checked_sub(max_age * 2).unwrap();
580        state
581            .write()
582            .await
583            .capacity_rejected_sources
584            .insert(source, aged);
585
586        assert_eq!(
587            expire_capacity_rejected(&state, max_age).await,
588            1,
589            "the debt must expire once the FIRST rejection is older than the TTL"
590        );
591        assert!(
592            check_bootstrap_drained(&state, &queues).await,
593            "bootstrap must drain once the expired debt is forfeited"
594        );
595    }
596}