Skip to main content

ant_node/replication/
neighbor_sync.rs

1//! Neighbor replication sync (Section 6.2).
2//!
3//! Round-robin cycle management: snapshot close neighbors, iterate through
4//! them in batches of `NEIGHBOR_SYNC_PEER_COUNT`, exchanging hint sets.
5
6use std::collections::{HashMap, HashSet};
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use crate::logging::{debug, info, warn};
11use rand::Rng;
12use saorsa_core::identity::PeerId;
13use saorsa_core::P2PNode;
14
15use crate::ant_protocol::XorName;
16use crate::client::xor_distance;
17use crate::error::Result;
18use crate::replication::config::{
19    ReplicationConfig, PAID_HINT_FULL_SCAN_ENTRIES, REPLICATION_PROTOCOL_ID,
20};
21use crate::replication::paid_list::{near_bits_for_radius, PaidList, XORNAME_BITS};
22use crate::replication::protocol::{
23    NeighborSyncRequest, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
24};
25use crate::replication::types::NeighborSyncState;
26use crate::storage::ChunkStore;
27
28/// Hint-build duration that is worth surfacing at info level.
29const HINT_BUILD_SLOW_LOG_MS: u128 = 250;
30
31/// Replica hint sent to a peer, with the close-group snapshot used to decide
32/// that hint.
33#[derive(Debug)]
34pub(crate) struct SentReplicaHint {
35    /// Key included in the replica hint set.
36    pub(crate) key: XorName,
37    /// Self-inclusive close group observed during hint construction.
38    pub(crate) close_peers: HashSet<PeerId>,
39}
40
41/// Result of an outbound neighbor-sync exchange.
42#[derive(Debug)]
43pub(crate) struct NeighborSyncOutcome {
44    /// The peer's sync response.
45    pub(crate) response: NeighborSyncResponse,
46    /// Replica hints sent to the peer in our request.
47    pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
48}
49
50/// Prebuilt hint sets for one outbound neighbor-sync exchange.
51#[derive(Debug, Default)]
52pub(crate) struct PeerSyncHints {
53    /// Replica hints, including the close-group snapshot needed for repair
54    /// proof recording after the request is successfully sent.
55    pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
56    /// Paid-list-only hints for this peer.
57    paid_hints: Vec<XorName>,
58}
59
60/// Build replica hints for a specific peer.
61///
62/// Returns keys that we believe the peer should hold (peer is among the
63/// `CLOSE_GROUP_SIZE` nearest to `K` in our `SelfInclusiveRT`).
64///
65/// This intentionally scans all locally stored records, not only records for
66/// which this node is still responsible. Out-of-range records retained by
67/// prune hysteresis therefore continue to repair their new close group before
68/// this node is allowed to delete them.
69pub async fn build_replica_hints_for_peer(
70    peer: &PeerId,
71    storage: &Arc<ChunkStore>,
72    p2p_node: &Arc<P2PNode>,
73    close_group_size: usize,
74) -> Vec<XorName> {
75    build_replica_hints_for_peer_with_close_groups(peer, storage, p2p_node, close_group_size)
76        .await
77        .into_iter()
78        .map(|hint| hint.key)
79        .collect()
80}
81
82pub(crate) async fn build_replica_hints_for_peer_with_close_groups(
83    peer: &PeerId,
84    storage: &Arc<ChunkStore>,
85    p2p_node: &Arc<P2PNode>,
86    close_group_size: usize,
87) -> Vec<SentReplicaHint> {
88    let all_keys = match storage.all_keys().await {
89        Ok(keys) => keys,
90        Err(e) => {
91            warn!("Failed to read stored keys for hint construction: {e}");
92            return Vec::new();
93        }
94    };
95
96    let dht = p2p_node.dht_manager();
97    let mut hints = Vec::new();
98    for key in all_keys {
99        let closest = dht
100            .find_closest_nodes_local_with_self(&key, close_group_size)
101            .await;
102        let close_peers = closest.iter().map(|n| n.peer_id).collect::<HashSet<_>>();
103        if close_peers.contains(peer) {
104            hints.push(SentReplicaHint { key, close_peers });
105        }
106    }
107    hints
108}
109
110/// How many low bits of a key may differ from this node's for the key to count
111/// as near it, from the distance to its farthest paid-close-group peer. Every
112/// key counts as near until this node knows a full paid close group.
113///
114/// With evenly spread IDs, entries beyond this carry no vote and need no hint.
115/// Where few peers are known near a key, this node or a neighbour can still be in
116/// its paid close group.
117pub(crate) async fn paid_near_bits(p2p_node: &Arc<P2PNode>, group_size: usize) -> usize {
118    let self_xor: XorName = *p2p_node.peer_id().as_bytes();
119    let closest = p2p_node
120        .dht_manager()
121        .find_closest_nodes_local(&self_xor, group_size)
122        .await;
123    if closest.len() < group_size {
124        return XORNAME_BITS;
125    }
126    closest
127        .iter()
128        .map(|node| xor_distance(&self_xor, node.peer_id.as_bytes()))
129        .max()
130        .map_or(XORNAME_BITS, |radius| near_bits_for_radius(&radius))
131}
132
133/// How many low bits of a key may differ from this node's for a hint build to read
134/// it: all of them while the list is small enough to read whole.
135fn paid_hint_scan_bits(entries: u64, near_bits: usize) -> usize {
136    if entries <= PAID_HINT_FULL_SCAN_ENTRIES {
137        XORNAME_BITS
138    } else {
139        near_bits
140    }
141}
142
143/// The paid-list keys a hint build considers.
144async fn paid_hint_candidates(
145    paid_list: &PaidList,
146    p2p_node: &Arc<P2PNode>,
147    group_size: usize,
148) -> Result<Vec<XorName>> {
149    let self_xor: XorName = *p2p_node.peer_id().as_bytes();
150    let near_bits = paid_near_bits(p2p_node, group_size).await;
151    let scan_bits = paid_hint_scan_bits(paid_list.count()?, near_bits);
152    paid_list.keys_near(&self_xor, scan_bits)
153}
154
155/// Build outbound hint sets for a batch of peers with one scan over local
156/// storage and one scan over the paid-list entries it can afford to read.
157pub(crate) async fn build_sync_hints_for_peers(
158    peers: &[PeerId],
159    storage: &Arc<ChunkStore>,
160    paid_list: &Arc<PaidList>,
161    p2p_node: &Arc<P2PNode>,
162    close_group_size: usize,
163    paid_list_close_group_size: usize,
164) -> HashMap<PeerId, PeerSyncHints> {
165    let started = Instant::now();
166    let target_peers = peers.iter().copied().collect::<HashSet<_>>();
167    let mut hints_by_peer = peers
168        .iter()
169        .copied()
170        .map(|peer| (peer, PeerSyncHints::default()))
171        .collect::<HashMap<_, _>>();
172
173    if peers.is_empty() {
174        return hints_by_peer;
175    }
176
177    let all_keys = match storage.all_keys().await {
178        Ok(keys) => keys,
179        Err(e) => {
180            warn!("Failed to read stored keys for batch hint construction: {e}");
181            Vec::new()
182        }
183    };
184    let stored_key_count = all_keys.len();
185
186    let dht = p2p_node.dht_manager();
187    for key in all_keys {
188        let closest = dht
189            .find_closest_nodes_local_with_self(&key, close_group_size)
190            .await;
191        let close_peers = closest.iter().map(|n| n.peer_id).collect::<HashSet<_>>();
192        for peer in close_peers.intersection(&target_peers) {
193            if let Some(peer_hints) = hints_by_peer.get_mut(peer) {
194                peer_hints.sent_replica_hints.push(SentReplicaHint {
195                    key,
196                    close_peers: close_peers.clone(),
197                });
198            }
199        }
200    }
201
202    let paid_keys =
203        match paid_hint_candidates(paid_list, p2p_node, paid_list_close_group_size).await {
204            Ok(keys) => keys,
205            Err(e) => {
206                warn!("Failed to read PaidForList for batch hint construction: {e}");
207                Vec::new()
208            }
209        };
210    let paid_key_count = paid_keys.len();
211
212    for key in paid_keys {
213        let closest = dht
214            .find_closest_nodes_local_with_self(&key, paid_list_close_group_size)
215            .await;
216        for node in closest {
217            if target_peers.contains(&node.peer_id) {
218                if let Some(peer_hints) = hints_by_peer.get_mut(&node.peer_id) {
219                    peer_hints.paid_hints.push(key);
220                }
221            }
222        }
223    }
224
225    let replica_hint_count = hints_by_peer
226        .values()
227        .map(|hints| hints.sent_replica_hints.len())
228        .sum::<usize>();
229    let paid_hint_count = hints_by_peer
230        .values()
231        .map(|hints| hints.paid_hints.len())
232        .sum::<usize>();
233    let elapsed_ms = started.elapsed().as_millis();
234
235    if elapsed_ms >= HINT_BUILD_SLOW_LOG_MS {
236        info!(
237            target: "ant_node::replication::neighbor_sync",
238            "Slow neighbor-sync hint build: peers={}, stored_keys={}, paid_keys={}, replica_hints={}, paid_hints={}, elapsed_ms={elapsed_ms}",
239            peers.len(),
240            stored_key_count,
241            paid_key_count,
242            replica_hint_count,
243            paid_hint_count,
244        );
245    } else {
246        debug!(
247            target: "ant_node::replication::neighbor_sync",
248            "Neighbor-sync hint build: peers={}, stored_keys={}, paid_keys={}, replica_hints={}, paid_hints={}, elapsed_ms={elapsed_ms}",
249            peers.len(),
250            stored_key_count,
251            paid_key_count,
252            replica_hint_count,
253            paid_hint_count,
254        );
255    }
256
257    hints_by_peer
258}
259
260/// Build paid hints for a specific peer.
261///
262/// Returns keys from our `PaidForList` that we believe the peer should
263/// track (peer is among `PAID_LIST_CLOSE_GROUP_SIZE` nearest to `K`).
264pub async fn build_paid_hints_for_peer(
265    peer: &PeerId,
266    paid_list: &Arc<PaidList>,
267    p2p_node: &Arc<P2PNode>,
268    paid_list_close_group_size: usize,
269) -> Vec<XorName> {
270    let paid_keys =
271        match paid_hint_candidates(paid_list, p2p_node, paid_list_close_group_size).await {
272            Ok(keys) => keys,
273            Err(e) => {
274                warn!("Failed to read PaidForList for hint construction: {e}");
275                return Vec::new();
276            }
277        };
278
279    let dht = p2p_node.dht_manager();
280    let mut hints = Vec::new();
281    for key in paid_keys {
282        let closest = dht
283            .find_closest_nodes_local_with_self(&key, paid_list_close_group_size)
284            .await;
285        if closest.iter().any(|n| n.peer_id == *peer) {
286            hints.push(key);
287        }
288    }
289    hints
290}
291
292/// Take a fresh snapshot of close neighbors for a new round-robin cycle.
293///
294/// Rule 1: Compute `CloseNeighbors(self)` as `NEIGHBOR_SYNC_SCOPE` nearest
295/// peers.
296pub async fn snapshot_close_neighbors(
297    p2p_node: &Arc<P2PNode>,
298    self_id: &PeerId,
299    scope: usize,
300) -> Vec<PeerId> {
301    let self_xor: XorName = *self_id.as_bytes();
302    let closest = p2p_node
303        .dht_manager()
304        .find_closest_nodes_local(&self_xor, scope)
305        .await;
306    closest.iter().map(|n| n.peer_id).collect()
307}
308
309/// Select the next batch of peers for sync from the current cycle.
310///
311/// Priority peers from routing-table churn are drained before the round-robin
312/// cursor. Rules 2-3 then scan forward from cursor, skip peers still under
313/// cooldown, and fill up to `peer_count` slots.
314pub fn select_sync_batch(
315    state: &mut NeighborSyncState,
316    peer_count: usize,
317    cooldown: Duration,
318) -> Vec<PeerId> {
319    let mut batch = Vec::new();
320    let now = Instant::now();
321
322    while batch.len() < peer_count {
323        let Some(peer) = select_next_sync_peer(state, now, cooldown) else {
324            break;
325        };
326        batch.push(peer);
327    }
328
329    batch
330}
331
332fn select_next_sync_peer(
333    state: &mut NeighborSyncState,
334    now: Instant,
335    cooldown: Duration,
336) -> Option<PeerId> {
337    while let Some(peer) = state.priority_order.pop_front() {
338        if peer_on_cooldown(state, &peer, now, cooldown) {
339            state.remove_peer(&peer);
340            continue;
341        }
342
343        state.remove_peer(&peer);
344        return Some(peer);
345    }
346
347    while state.cursor < state.order.len() {
348        let peer = state.order[state.cursor];
349
350        // Check cooldown (Rule 2a): if the peer was synced recently, remove
351        // from the snapshot and continue without advancing the cursor (the
352        // next element slides into the current cursor position).
353        if peer_on_cooldown(state, &peer, now, cooldown) {
354            state.order.remove(state.cursor);
355            continue;
356        }
357
358        state.cursor += 1;
359        return Some(peer);
360    }
361
362    None
363}
364
365fn peer_on_cooldown(
366    state: &NeighborSyncState,
367    peer: &PeerId,
368    now: Instant,
369    cooldown: Duration,
370) -> bool {
371    state
372        .last_sync_times
373        .get(peer)
374        .is_some_and(|last_sync| now.duration_since(*last_sync) < cooldown)
375}
376
377/// Execute a sync session with a single peer.
378///
379/// Returns the response hints if sync succeeded, or `None` if the peer
380/// was unreachable or the response could not be decoded.
381pub async fn sync_with_peer(
382    peer: &PeerId,
383    p2p_node: &Arc<P2PNode>,
384    storage: &Arc<ChunkStore>,
385    paid_list: &Arc<PaidList>,
386    config: &ReplicationConfig,
387    is_bootstrapping: bool,
388) -> Option<NeighborSyncResponse> {
389    sync_with_peer_with_outcome(
390        peer,
391        p2p_node,
392        storage,
393        paid_list,
394        config,
395        is_bootstrapping,
396        None,
397    )
398    .await
399    .map(|outcome| outcome.response)
400}
401
402/// `commitment`: sender's current commitment to piggyback on the request.
403/// `None` if the responder hasn't rotated one yet (e.g. fresh boot,
404/// empty storage) — receiver falls back to legacy path.
405#[allow(clippy::too_many_arguments)]
406pub(crate) async fn sync_with_peer_with_outcome(
407    peer: &PeerId,
408    p2p_node: &Arc<P2PNode>,
409    storage: &Arc<ChunkStore>,
410    paid_list: &Arc<PaidList>,
411    config: &ReplicationConfig,
412    is_bootstrapping: bool,
413    commitment: Option<crate::replication::commitment::StorageCommitment>,
414) -> Option<NeighborSyncOutcome> {
415    // Build peer-targeted hint sets (Rule 7).
416    let mut hints_by_peer = build_sync_hints_for_peers(
417        std::slice::from_ref(peer),
418        storage,
419        paid_list,
420        p2p_node,
421        config.close_group_size,
422        config.paid_list_close_group_size,
423    )
424    .await;
425    let hints = hints_by_peer.remove(peer).unwrap_or_default();
426    sync_with_peer_with_hints(peer, p2p_node, config, is_bootstrapping, hints, commitment).await
427}
428
429#[allow(clippy::too_many_arguments)]
430pub(crate) async fn sync_with_peer_with_hints(
431    peer: &PeerId,
432    p2p_node: &Arc<P2PNode>,
433    config: &ReplicationConfig,
434    is_bootstrapping: bool,
435    hints: PeerSyncHints,
436    // ADR-0002: sender's current commitment, piggybacked on the sync request so
437    // the receiver can ingest it (commitment gossip travels on neighbor sync) —
438    // see `NeighborSyncRequest::commitment` and `ingest_peer_commitment`.
439    commitment: Option<crate::replication::commitment::StorageCommitment>,
440) -> Option<NeighborSyncOutcome> {
441    let replica_hints = hints
442        .sent_replica_hints
443        .iter()
444        .map(|hint| hint.key)
445        .collect::<Vec<_>>();
446    let sent_replica_hints = hints.sent_replica_hints;
447
448    let request = NeighborSyncRequest {
449        replica_hints,
450        paid_hints: hints.paid_hints,
451        bootstrapping: is_bootstrapping,
452        commitment,
453    };
454    let request_id = rand::thread_rng().gen::<u64>();
455    let msg = ReplicationMessage {
456        request_id,
457        body: ReplicationMessageBody::NeighborSyncRequest(request),
458    };
459
460    let encoded = match msg.encode() {
461        Ok(data) => data,
462        Err(e) => {
463            warn!("Failed to encode sync request for {peer}: {e}");
464            return None;
465        }
466    };
467
468    let response = match p2p_node
469        .send_request(
470            peer,
471            REPLICATION_PROTOCOL_ID,
472            encoded,
473            config.verification_request_timeout,
474        )
475        .await
476    {
477        Ok(resp) => resp,
478        Err(e) => {
479            debug!("Sync with {peer} failed: {e}");
480            return None;
481        }
482    };
483
484    match ReplicationMessage::decode(&response.data) {
485        Ok(decoded) => {
486            if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
487                Some(NeighborSyncOutcome {
488                    response: resp,
489                    sent_replica_hints,
490                })
491            } else {
492                warn!("Unexpected response type from {peer} during sync");
493                None
494            }
495        }
496        Err(e) => {
497            warn!("Failed to decode sync response from {peer}: {e}");
498            None
499        }
500    }
501}
502
503/// Handle a failed sync attempt: remove peer from snapshot and try to fill
504/// the vacated slot.
505///
506/// Rule 3: Remove unreachable peer from pending sync state, attempt to fill
507/// by using the same priority-first scan as [`select_sync_batch`]. Applies the
508/// same cooldown filtering to avoid selecting a peer that was recently synced.
509pub fn handle_sync_failure(
510    state: &mut NeighborSyncState,
511    failed_peer: &PeerId,
512    cooldown: Duration,
513) -> Option<PeerId> {
514    // Find and remove the failed peer from the ordering.
515    state.remove_peer(failed_peer);
516
517    // Try to fill the vacated slot, applying the same priority and cooldown
518    // filtering used by select_sync_batch.
519    let now = Instant::now();
520    select_next_sync_peer(state, now, cooldown)
521}
522
523/// Record a successful sync with a peer.
524pub fn record_successful_sync(state: &mut NeighborSyncState, peer: &PeerId) {
525    state.last_sync_times.insert(*peer, Instant::now());
526}
527
528/// Handle incoming sync request from a peer.
529///
530/// Rules 4-6: Validate peer is in `LocalRT`. If yes, bidirectional sync.
531/// If not, outbound-only (send hints but don't accept inbound).
532///
533/// Returns `(response, sender_in_routing_table)` where the second element
534/// indicates whether the caller should process the sender's inbound hints.
535pub async fn handle_sync_request(
536    sender: &PeerId,
537    request: &NeighborSyncRequest,
538    p2p_node: &Arc<P2PNode>,
539    storage: &Arc<ChunkStore>,
540    paid_list: &Arc<PaidList>,
541    config: &ReplicationConfig,
542    is_bootstrapping: bool,
543) -> (NeighborSyncResponse, bool) {
544    let (response, _, sender_in_rt) = handle_sync_request_with_proofs(
545        sender,
546        request,
547        p2p_node,
548        storage,
549        paid_list,
550        config,
551        is_bootstrapping,
552        None,
553    )
554    .await;
555    (response, sender_in_rt)
556}
557
558#[allow(clippy::too_many_arguments)]
559pub(crate) async fn handle_sync_request_with_proofs(
560    sender: &PeerId,
561    _request: &NeighborSyncRequest,
562    p2p_node: &Arc<P2PNode>,
563    storage: &Arc<ChunkStore>,
564    paid_list: &Arc<PaidList>,
565    config: &ReplicationConfig,
566    is_bootstrapping: bool,
567    my_commitment: Option<crate::replication::commitment::StorageCommitment>,
568) -> (NeighborSyncResponse, Vec<SentReplicaHint>, bool) {
569    let sender_in_rt = p2p_node.dht_manager().is_in_routing_table(sender).await;
570
571    // Build outbound hints (always sent, even to non-RT peers).
572    let sent_replica_hints = build_replica_hints_for_peer_with_close_groups(
573        sender,
574        storage,
575        p2p_node,
576        config.close_group_size,
577    )
578    .await;
579    let replica_hints = sent_replica_hints
580        .iter()
581        .map(|hint| hint.key)
582        .collect::<Vec<_>>();
583    let paid_hints = build_paid_hints_for_peer(
584        sender,
585        paid_list,
586        p2p_node,
587        config.paid_list_close_group_size,
588    )
589    .await;
590
591    let response = NeighborSyncResponse {
592        replica_hints,
593        paid_hints,
594        bootstrapping: is_bootstrapping,
595        rejected_keys: Vec::new(),
596        commitment: my_commitment,
597    };
598
599    // Rule 4-6: accept inbound hints only if sender is in LocalRT.
600    (response, sent_replica_hints, sender_in_rt)
601}
602
603// ---------------------------------------------------------------------------
604// Tests
605// ---------------------------------------------------------------------------
606
607#[cfg(test)]
608#[allow(clippy::unwrap_used, clippy::expect_used)]
609mod tests {
610    use super::*;
611    use crate::replication::types::PeerSyncRecord;
612    use std::collections::HashMap;
613
614    /// Build a `PeerId` from a single byte (zero-padded to 32 bytes).
615    fn peer_id_from_byte(b: u8) -> PeerId {
616        let mut bytes = [0u8; 32];
617        bytes[0] = b;
618        PeerId::from_bytes(bytes)
619    }
620
621    /// A key whose last byte is `b`, the rest zero.
622    fn key_ending_in(b: u8) -> XorName {
623        let mut key = [0u8; 32];
624        key[31] = b;
625        key
626    }
627
628    // -- paid hint candidates ------------------------------------------------
629
630    #[tokio::test]
631    async fn a_far_key_is_read_for_hints_until_the_list_is_too_large_to_read_whole() {
632        // This node is 0, its neighbours are 1 and 2, and a group is two, so its
633        // group reaches distance 2. Key 129 is far from all three, yet its two
634        // closest are neighbour 1 (distance 128) and this node (129).
635        const THIS_NODE: u8 = 0;
636        const GROUP_RADIUS: u8 = 2;
637        const FAR_KEY: u8 = 129;
638        let dir = tempfile::tempdir().expect("tempdir");
639        let paid_list = PaidList::new(dir.path()).await.expect("paid list");
640        paid_list
641            .insert(&key_ending_in(FAR_KEY))
642            .await
643            .expect("insert");
644        let near_bits = near_bits_for_radius(&key_ending_in(GROUP_RADIUS));
645        let read = |entries| {
646            paid_list
647                .keys_near(
648                    &key_ending_in(THIS_NODE),
649                    paid_hint_scan_bits(entries, near_bits),
650                )
651                .expect("keys")
652        };
653
654        assert_eq!(
655            read(PAID_HINT_FULL_SCAN_ENTRIES),
656            vec![key_ending_in(FAR_KEY)]
657        );
658        assert!(
659            read(PAID_HINT_FULL_SCAN_ENTRIES + 1).is_empty(),
660            "above the limit only near keys are read"
661        );
662    }
663
664    // -- select_sync_batch ---------------------------------------------------
665
666    #[test]
667    fn select_sync_batch_returns_up_to_peer_count() {
668        let peers = vec![
669            peer_id_from_byte(1),
670            peer_id_from_byte(2),
671            peer_id_from_byte(3),
672            peer_id_from_byte(4),
673            peer_id_from_byte(5),
674        ];
675        let mut state = NeighborSyncState::new_cycle(peers);
676        let batch_size = 3;
677
678        let batch = select_sync_batch(&mut state, batch_size, Duration::from_secs(0));
679
680        assert_eq!(batch.len(), batch_size);
681        assert_eq!(batch[0], peer_id_from_byte(1));
682        assert_eq!(batch[1], peer_id_from_byte(2));
683        assert_eq!(batch[2], peer_id_from_byte(3));
684        assert_eq!(state.cursor, 3);
685    }
686
687    #[test]
688    fn select_sync_batch_skips_cooldown_peers() {
689        let peers = vec![
690            peer_id_from_byte(1),
691            peer_id_from_byte(2),
692            peer_id_from_byte(3),
693            peer_id_from_byte(4),
694        ];
695        let mut state = NeighborSyncState::new_cycle(peers);
696
697        // Mark peer 1 and peer 3 as recently synced.
698        state
699            .last_sync_times
700            .insert(peer_id_from_byte(1), Instant::now());
701        state
702            .last_sync_times
703            .insert(peer_id_from_byte(3), Instant::now());
704
705        let cooldown = Duration::from_hours(1); // 1 hour
706        let batch = select_sync_batch(&mut state, 2, cooldown);
707
708        // Peer 1 and peer 3 should be skipped (removed from order).
709        assert_eq!(batch.len(), 2);
710        assert_eq!(batch[0], peer_id_from_byte(2));
711        assert_eq!(batch[1], peer_id_from_byte(4));
712
713        // Cooldown peers should have been removed from the order.
714        assert!(!state.order.contains(&peer_id_from_byte(1)));
715        assert!(!state.order.contains(&peer_id_from_byte(3)));
716    }
717
718    #[test]
719    fn select_sync_batch_expired_cooldown_not_skipped() {
720        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
721        let mut state = NeighborSyncState::new_cycle(peers);
722
723        // Mark peer 1 as synced a long time ago (simulate expired cooldown).
724        // Use a small subtraction (2s) and a smaller cooldown (1s) to avoid
725        // `checked_sub` returning `None` on freshly-booted CI runners where
726        // `Instant::now()` (system uptime) may be very small.
727        state.last_sync_times.insert(
728            peer_id_from_byte(1),
729            Instant::now()
730                .checked_sub(Duration::from_secs(2))
731                .unwrap_or_else(Instant::now),
732        );
733
734        let cooldown = Duration::from_secs(1);
735        let batch = select_sync_batch(&mut state, 2, cooldown);
736
737        // Peer 1's cooldown expired so it should be included.
738        assert_eq!(batch.len(), 2);
739        assert_eq!(batch[0], peer_id_from_byte(1));
740        assert_eq!(batch[1], peer_id_from_byte(2));
741    }
742
743    #[test]
744    fn select_sync_batch_empty_order() {
745        let mut state = NeighborSyncState::new_cycle(vec![]);
746
747        let batch = select_sync_batch(&mut state, 4, Duration::from_secs(0));
748
749        assert!(batch.is_empty(), "expected an empty batch, got {batch:?}");
750        assert_eq!(state.cursor, 0);
751    }
752
753    #[test]
754    fn select_sync_batch_all_on_cooldown() {
755        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
756        let mut state = NeighborSyncState::new_cycle(peers);
757
758        state
759            .last_sync_times
760            .insert(peer_id_from_byte(1), Instant::now());
761        state
762            .last_sync_times
763            .insert(peer_id_from_byte(2), Instant::now());
764
765        let cooldown = Duration::from_hours(1);
766        let batch = select_sync_batch(&mut state, 4, cooldown);
767
768        assert!(
769            batch.is_empty(),
770            "expected an empty batch while every peer is in cooldown, got {batch:?}"
771        );
772        assert!(
773            state.order.is_empty(),
774            "expected an empty order, got {:?}",
775            state.order
776        );
777    }
778
779    // -- handle_sync_failure -------------------------------------------------
780
781    #[test]
782    fn handle_sync_failure_removes_peer_and_adjusts_cursor() {
783        let peers = vec![
784            peer_id_from_byte(1),
785            peer_id_from_byte(2),
786            peer_id_from_byte(3),
787            peer_id_from_byte(4),
788        ];
789        let mut state = NeighborSyncState::new_cycle(peers);
790        // Simulate having already processed peers at indices 0 and 1.
791        state.cursor = 2;
792
793        // Peer 2 (index 1, before cursor) fails.
794        let replacement =
795            handle_sync_failure(&mut state, &peer_id_from_byte(2), Duration::from_secs(0));
796
797        // Cursor should be adjusted down by 1 (was 2, now 1).
798        assert_eq!(state.cursor, 2); // was 2, removed at pos 1, adjusted to 1, then replacement advances to 2
799        assert!(!state.order.contains(&peer_id_from_byte(2)));
800
801        // Should get peer 4 as replacement (index 1 after removal = peer 3,
802        // but cursor was adjusted to 1 so peer 3 is at index 1; it returns
803        // the peer at the new cursor and advances).
804        assert!(replacement.is_some());
805    }
806
807    #[test]
808    fn handle_sync_failure_removes_peer_after_cursor() {
809        let peers = vec![
810            peer_id_from_byte(1),
811            peer_id_from_byte(2),
812            peer_id_from_byte(3),
813            peer_id_from_byte(4),
814        ];
815        let mut state = NeighborSyncState::new_cycle(peers);
816        state.cursor = 1;
817
818        // Peer 3 (index 2, after cursor) fails.
819        let replacement =
820            handle_sync_failure(&mut state, &peer_id_from_byte(3), Duration::from_secs(0));
821
822        // Cursor should stay at 1 (removal was after cursor).
823        assert_eq!(state.cursor, 2); // cursor was 1, replacement advances to 2
824        assert!(!state.order.contains(&peer_id_from_byte(3)));
825
826        // Replacement should be peer 2 (now at cursor position 1).
827        assert_eq!(replacement, Some(peer_id_from_byte(2)));
828    }
829
830    #[test]
831    fn handle_sync_failure_no_replacement_when_exhausted() {
832        let peers = vec![peer_id_from_byte(1)];
833        let mut state = NeighborSyncState::new_cycle(peers);
834        state.cursor = 1; // Already past the only peer.
835
836        let replacement =
837            handle_sync_failure(&mut state, &peer_id_from_byte(1), Duration::from_secs(0));
838
839        assert!(
840            state.order.is_empty(),
841            "expected the order to be exhausted, got {:?}",
842            state.order
843        );
844        assert!(replacement.is_none());
845    }
846
847    #[test]
848    fn handle_sync_failure_unknown_peer_is_noop() {
849        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
850        let mut state = NeighborSyncState::new_cycle(peers);
851        state.cursor = 1;
852
853        let replacement =
854            handle_sync_failure(&mut state, &peer_id_from_byte(99), Duration::from_secs(0));
855
856        // Order should be unchanged.
857        assert_eq!(state.order.len(), 2);
858        // Still tries to fill from cursor.
859        assert_eq!(replacement, Some(peer_id_from_byte(2)));
860        assert_eq!(state.cursor, 2);
861    }
862
863    // -- record_successful_sync ----------------------------------------------
864
865    #[test]
866    fn record_successful_sync_updates_last_sync_time() {
867        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
868        let mut state = NeighborSyncState::new_cycle(peers);
869        let peer = peer_id_from_byte(1);
870
871        assert!(!state.last_sync_times.contains_key(&peer));
872
873        let before = Instant::now();
874        record_successful_sync(&mut state, &peer);
875        let after = Instant::now();
876
877        let ts = state.last_sync_times.get(&peer).expect("timestamp exists");
878        assert!(*ts >= before);
879        assert!(*ts <= after);
880    }
881
882    #[test]
883    fn record_successful_sync_overwrites_previous() {
884        let peers = vec![peer_id_from_byte(1)];
885        let mut state = NeighborSyncState::new_cycle(peers);
886        let peer = peer_id_from_byte(1);
887
888        // Record a sync at an old time. Use a small subtraction to avoid
889        // `checked_sub` returning `None` on freshly-booted CI runners.
890        let old_time = Instant::now()
891            .checked_sub(Duration::from_secs(2))
892            .unwrap_or_else(Instant::now);
893        state.last_sync_times.insert(peer, old_time);
894
895        record_successful_sync(&mut state, &peer);
896
897        let ts = state.last_sync_times.get(&peer).expect("timestamp exists");
898        assert!(*ts > old_time, "sync time should be updated");
899    }
900
901    // -- Section 18: Neighbor sync scenarios --------------------------------
902
903    #[test]
904    fn scenario_35_round_robin_with_cooldown_skip() {
905        // With >PEER_COUNT eligible peers, consecutive rounds scan forward
906        // from cursor, skip cooldown peers, sync next batch.
907        // Create 8 peers, mark peers 2,4 on cooldown.
908        // First batch of 4: peers 1,3,5,6 (2,4 skipped and removed).
909        // Second batch of 4: peers 7,8 (only 2 remain).
910        // Cycle should complete after second batch.
911        let peers: Vec<PeerId> = (1..=8).map(peer_id_from_byte).collect();
912        let mut state = NeighborSyncState::new_cycle(peers);
913        let batch_size = 4;
914        let cooldown = Duration::from_hours(1);
915
916        // Mark peers 2 and 4 as recently synced (on cooldown).
917        state
918            .last_sync_times
919            .insert(peer_id_from_byte(2), Instant::now());
920        state
921            .last_sync_times
922            .insert(peer_id_from_byte(4), Instant::now());
923
924        // First batch: scan from cursor 0. Peers 2 and 4 are removed,
925        // leaving [1,3,5,6,7,8]. We pick the first 4: [1,3,5,6].
926        let batch1 = select_sync_batch(&mut state, batch_size, cooldown);
927        assert_eq!(batch1.len(), 4);
928        assert_eq!(batch1[0], peer_id_from_byte(1));
929        assert_eq!(batch1[1], peer_id_from_byte(3));
930        assert_eq!(batch1[2], peer_id_from_byte(5));
931        assert_eq!(batch1[3], peer_id_from_byte(6));
932
933        // Cooldown peers should have been removed from the order.
934        assert!(!state.order.contains(&peer_id_from_byte(2)));
935        assert!(!state.order.contains(&peer_id_from_byte(4)));
936
937        // Second batch: only peers 7,8 remain after cursor.
938        let batch2 = select_sync_batch(&mut state, batch_size, cooldown);
939        assert_eq!(batch2.len(), 2);
940        assert_eq!(batch2[0], peer_id_from_byte(7));
941        assert_eq!(batch2[1], peer_id_from_byte(8));
942
943        // Cycle should be complete after second batch.
944        assert!(state.is_cycle_complete());
945    }
946
947    #[test]
948    fn cycle_complete_when_cursor_past_order() {
949        // is_cycle_complete() returns true when cursor >= order.len().
950        let peers: Vec<PeerId> = (1..=3).map(peer_id_from_byte).collect();
951        let mut state = NeighborSyncState::new_cycle(peers);
952
953        // Not complete at the start.
954        assert!(!state.is_cycle_complete());
955
956        // Advance cursor to exactly order.len().
957        state.cursor = 3;
958        assert!(state.is_cycle_complete());
959
960        // Also complete when cursor exceeds order.len().
961        state.cursor = 10;
962        assert!(state.is_cycle_complete());
963
964        // Edge case: order is emptied (peers removed) with cursor at 0.
965        state.order.clear();
966        state.cursor = 0;
967        assert!(state.is_cycle_complete());
968    }
969
970    /// Scenario 36: Post-cycle responsibility pruning with time-based
971    /// hysteresis.
972    ///
973    /// When a full round-robin cycle completes, node runs one prune pass
974    /// over BOTH stored records and `PaidForList` entries using current
975    /// `SelfInclusiveRT`. Out-of-range items have timestamps recorded but
976    /// are deleted only after `PRUNE_HYSTERESIS_DURATION`. In-range items
977    /// have their timestamps cleared.
978    ///
979    /// Full `run_prune_pass` requires a live `P2PNode`. This test verifies
980    /// the deterministic trigger condition (cycle completion) and the
981    /// record-pruning contract:
982    ///   (1) Cycle completes -> prune pass should run.
983    ///   (2) Keys within hysteresis window are retained.
984    #[test]
985    fn scenario_36_post_cycle_triggers_combined_prune_pass() {
986        let config = ReplicationConfig::default();
987
988        // Step 1: Run a full cycle to completion.
989        let peers: Vec<PeerId> = (1..=3).map(peer_id_from_byte).collect();
990        let mut state = NeighborSyncState::new_cycle(peers);
991        let _ = select_sync_batch(&mut state, 3, Duration::from_secs(0));
992        assert!(
993            state.is_cycle_complete(),
994            "cycle must be complete before prune pass triggers"
995        );
996
997        // Step 2: Verify prune hysteresis parameters are configured.
998        assert!(
999            !config.prune_hysteresis_duration.is_zero(),
1000            "PRUNE_HYSTERESIS_DURATION must be non-zero for hysteresis to work"
1001        );
1002
1003        // Step 3: Simulate the prune-pass timestamp tracking for BOTH
1004        // record and paid-list entries (the two independent timestamp
1005        // families that Section 11 requires in a single pass).
1006        //
1007        // Record timestamps and paid timestamps are independent — clearing
1008        // one must not affect the other (tested in scenario_52). Here we
1009        // verify the combined trigger: cycle completion -> both kinds of
1010        // timestamps are eligible for evaluation.
1011        let record_key: [u8; 32] = [0x36; 32];
1012        let paid_key: [u8; 32] = [0x37; 32];
1013
1014        // Simulate: record_key goes out of range, paid_key goes out of range.
1015        let record_first_seen = Instant::now();
1016        let paid_first_seen = Instant::now();
1017
1018        // Both timestamps are recent — well within hysteresis window.
1019        let record_elapsed = record_first_seen.elapsed();
1020        let paid_elapsed = paid_first_seen.elapsed();
1021        assert!(
1022            record_elapsed < config.prune_hysteresis_duration,
1023            "record key should be retained within hysteresis window"
1024        );
1025        assert!(
1026            paid_elapsed < config.prune_hysteresis_duration,
1027            "paid key should be retained within hysteresis window"
1028        );
1029
1030        // The prune pass evaluates both independently. Verify they don't
1031        // interfere by using separate keys.
1032        assert_ne!(
1033            record_key, paid_key,
1034            "record and paid pruning keys must be independent"
1035        );
1036
1037        // Step 4: After the cycle, a new snapshot is taken and cursor resets.
1038        let new_state = NeighborSyncState::new_cycle(vec![
1039            peer_id_from_byte(1),
1040            peer_id_from_byte(2),
1041            peer_id_from_byte(3),
1042        ]);
1043        assert_eq!(new_state.cursor, 0, "cursor resets for new cycle");
1044        assert!(
1045            !new_state.is_cycle_complete(),
1046            "new cycle should not be immediately complete"
1047        );
1048    }
1049
1050    #[test]
1051    fn scenario_38_mid_cycle_peer_join_prioritized() {
1052        // Peer D joins CloseNeighbors mid-cycle. It is queued for priority
1053        // sync without being inserted into the current round-robin snapshot.
1054        let peers = vec![
1055            peer_id_from_byte(0xA),
1056            peer_id_from_byte(0xB),
1057            peer_id_from_byte(0xC),
1058        ];
1059        let mut state = NeighborSyncState::new_cycle(peers);
1060
1061        // Advance cursor to simulate mid-cycle.
1062        let _ = select_sync_batch(&mut state, 1, Duration::from_secs(0));
1063        assert_eq!(state.cursor, 1);
1064
1065        // Peer D "joins" the close-neighbor set. It remains outside the
1066        // stable snapshot but is queued ahead of the cursor.
1067        let peer_d = peer_id_from_byte(0xD);
1068        assert_eq!(state.queue_priority_peers([peer_d]), 1);
1069        assert!(!state.order.contains(&peer_d));
1070        assert!(
1071            !state.is_cycle_complete(),
1072            "pending priority sync keeps the cycle active"
1073        );
1074
1075        let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1076        assert_eq!(batch, vec![peer_d, peer_id_from_byte(0xB)]);
1077    }
1078
1079    #[test]
1080    fn scenario_39_unreachable_peer_removed_slot_filled() {
1081        // Peer P is in snapshot. Sync fails. P removed from order.
1082        // Node resumes scanning and picks next peer Q to fill the slot.
1083        let peers = vec![
1084            peer_id_from_byte(1),
1085            peer_id_from_byte(2),
1086            peer_id_from_byte(3),
1087            peer_id_from_byte(4),
1088            peer_id_from_byte(5),
1089        ];
1090        let mut state = NeighborSyncState::new_cycle(peers);
1091
1092        // First batch selects peers 1,2.
1093        let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1094        assert_eq!(batch, vec![peer_id_from_byte(1), peer_id_from_byte(2)]);
1095
1096        // Peer 2 becomes unreachable. Remove it and fill the slot.
1097        let replacement =
1098            handle_sync_failure(&mut state, &peer_id_from_byte(2), Duration::from_secs(0));
1099        assert!(!state.order.contains(&peer_id_from_byte(2)));
1100
1101        // Slot should be filled by the next available peer (peer 3).
1102        assert_eq!(
1103            replacement,
1104            Some(peer_id_from_byte(3)),
1105            "vacated slot should be filled by next peer in order"
1106        );
1107
1108        // Continue: next batch should resume from after the replacement.
1109        let batch2 = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1110        assert_eq!(batch2, vec![peer_id_from_byte(4), peer_id_from_byte(5)]);
1111        assert!(state.is_cycle_complete());
1112    }
1113
1114    #[test]
1115    fn scenario_40_cooldown_peer_removed_from_snapshot() {
1116        // Peer synced within cooldown period. When batch selection reaches it,
1117        // peer is REMOVED from order (not just skipped). Scanning continues to
1118        // next peer.
1119        let peers = vec![
1120            peer_id_from_byte(1),
1121            peer_id_from_byte(2),
1122            peer_id_from_byte(3),
1123        ];
1124        let mut state = NeighborSyncState::new_cycle(peers);
1125        let cooldown = Duration::from_hours(1);
1126
1127        // Mark peer 2 as recently synced.
1128        state
1129            .last_sync_times
1130            .insert(peer_id_from_byte(2), Instant::now());
1131
1132        let batch = select_sync_batch(&mut state, 3, cooldown);
1133
1134        // Peer 2 should have been REMOVED from order, not just skipped.
1135        assert!(!state.order.contains(&peer_id_from_byte(2)));
1136        assert_eq!(state.order.len(), 2, "order should shrink by 1");
1137
1138        // Batch contains the non-cooldown peers.
1139        assert_eq!(batch, vec![peer_id_from_byte(1), peer_id_from_byte(3)]);
1140
1141        // Cycle is complete since all remaining peers were selected.
1142        assert!(state.is_cycle_complete());
1143    }
1144
1145    #[test]
1146    fn priority_peer_in_snapshot_is_not_selected_twice() {
1147        let peers = vec![
1148            peer_id_from_byte(1),
1149            peer_id_from_byte(2),
1150            peer_id_from_byte(3),
1151        ];
1152        let mut state = NeighborSyncState::new_cycle(peers);
1153        assert_eq!(state.queue_priority_peers([peer_id_from_byte(2)]), 1);
1154
1155        let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1156
1157        assert_eq!(batch, vec![peer_id_from_byte(2), peer_id_from_byte(1)]);
1158        assert_eq!(
1159            state.order,
1160            vec![peer_id_from_byte(1), peer_id_from_byte(3)]
1161        );
1162        assert_eq!(state.cursor, 1);
1163    }
1164
1165    #[test]
1166    fn priority_peer_on_cooldown_is_skipped_and_removed_from_snapshot() {
1167        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1168        let mut state = NeighborSyncState::new_cycle(peers);
1169        let cooldown = Duration::from_secs(1);
1170        let priority_peer = peer_id_from_byte(2);
1171        state.last_sync_times.insert(priority_peer, Instant::now());
1172        assert_eq!(state.queue_priority_peers([priority_peer]), 1);
1173
1174        let batch = select_sync_batch(&mut state, 2, cooldown);
1175
1176        assert_eq!(batch, vec![peer_id_from_byte(1)]);
1177        assert!(state.priority_order.is_empty());
1178        assert!(!state.order.contains(&priority_peer));
1179    }
1180
1181    #[test]
1182    fn failure_replacement_prefers_remaining_priority_peer() {
1183        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1184        let mut state = NeighborSyncState::new_cycle(peers);
1185        let first_priority_peer = peer_id_from_byte(3);
1186        let second_priority_peer = peer_id_from_byte(4);
1187        assert_eq!(
1188            state.queue_priority_peers([first_priority_peer, second_priority_peer]),
1189            2
1190        );
1191
1192        let batch = select_sync_batch(&mut state, 1, Duration::from_secs(0));
1193        assert_eq!(batch, vec![first_priority_peer]);
1194
1195        let replacement =
1196            handle_sync_failure(&mut state, &first_priority_peer, Duration::from_secs(0));
1197
1198        assert_eq!(replacement, Some(second_priority_peer));
1199        assert!(state.priority_order.is_empty());
1200        assert_eq!(state.cursor, 0);
1201    }
1202
1203    #[test]
1204    fn scenario_41_cycle_always_terminates() {
1205        // Under arbitrary cooldowns and removals, cycle always terminates.
1206        // Create 10 peers. Mark ALL on cooldown. select_sync_batch
1207        // should remove all and return empty. Cycle complete.
1208        let peer_count: u8 = 10;
1209        let peers: Vec<PeerId> = (1..=peer_count).map(peer_id_from_byte).collect();
1210        let mut state = NeighborSyncState::new_cycle(peers);
1211        let cooldown = Duration::from_hours(1);
1212
1213        // Mark all peers as recently synced.
1214        for i in 1..=peer_count {
1215            state
1216                .last_sync_times
1217                .insert(peer_id_from_byte(i), Instant::now());
1218        }
1219
1220        let batch = select_sync_batch(&mut state, 4, cooldown);
1221
1222        assert!(
1223            batch.is_empty(),
1224            "all peers on cooldown — batch must be empty"
1225        );
1226        assert!(state.order.is_empty(), "all peers should have been removed");
1227        assert!(
1228            state.is_cycle_complete(),
1229            "cycle must terminate when all peers are removed"
1230        );
1231    }
1232
1233    #[test]
1234    fn consecutive_rounds_advance_through_full_cycle() {
1235        // 6 peers, batch_size=2, no cooldowns.
1236        // Round 1: peers 0,1. Round 2: peers 2,3. Round 3: peers 4,5.
1237        // After round 3: cycle complete.
1238        let peers: Vec<PeerId> = (1..=6).map(peer_id_from_byte).collect();
1239        let mut state = NeighborSyncState::new_cycle(peers);
1240        let batch_size = 2;
1241        let no_cooldown = Duration::from_secs(0);
1242
1243        let round1 = select_sync_batch(&mut state, batch_size, no_cooldown);
1244        assert_eq!(round1, vec![peer_id_from_byte(1), peer_id_from_byte(2)]);
1245        assert_eq!(state.cursor, 2);
1246        assert!(!state.is_cycle_complete());
1247
1248        let round2 = select_sync_batch(&mut state, batch_size, no_cooldown);
1249        assert_eq!(round2, vec![peer_id_from_byte(3), peer_id_from_byte(4)]);
1250        assert_eq!(state.cursor, 4);
1251        assert!(!state.is_cycle_complete());
1252
1253        let round3 = select_sync_batch(&mut state, batch_size, no_cooldown);
1254        assert_eq!(round3, vec![peer_id_from_byte(5), peer_id_from_byte(6)]);
1255        assert_eq!(state.cursor, 6);
1256        assert!(state.is_cycle_complete());
1257
1258        // Extra call after cycle complete returns empty.
1259        let round4 = select_sync_batch(&mut state, batch_size, no_cooldown);
1260        assert!(
1261            round4.is_empty(),
1262            "expected an empty batch once the cycle is complete, got {round4:?}"
1263        );
1264    }
1265
1266    /// Scenario 37: Non-`LocalRT` inbound sync behavior.
1267    ///
1268    /// When a peer not in `LocalRT(self)` opens a sync session:
1269    /// - Receiver STILL builds and sends outbound hints (response always
1270    ///   constructed via `handle_sync_request`).
1271    /// - Receiver drops ALL inbound replica/paid hints from that peer
1272    ///   (caller returns early in `mod.rs:handle_neighbor_sync_request`
1273    ///   when `sender_in_rt` is false).
1274    /// - Sync history is NOT updated for non-RT peers, so no
1275    ///   `RepairOpportunity` is created.
1276    ///
1277    /// Full integration requires a live `P2PNode` (`handle_sync_request`
1278    /// calls `is_in_routing_table`). This test verifies the deterministic
1279    /// contract:
1280    ///   (1) `NeighborSyncResponse` is always constructed regardless of
1281    ///       sender RT membership (outbound hints sent).
1282    ///   (2) When `sender_in_rt` is false, no admission runs and sync
1283    ///       history is not updated.
1284    ///   (3) When `sender_in_rt` is true, sync history IS updated and
1285    ///       inbound hints enter the admission pipeline.
1286    #[test]
1287    fn scenario_37_non_local_rt_inbound_sync_drops_hints() {
1288        let sender = peer_id_from_byte(0x37);
1289
1290        // Simulate what handle_sync_request always builds: outbound hints
1291        // in the response, regardless of whether sender is in LocalRT.
1292        let outbound_replica_hints = vec![[0x01; 32], [0x02; 32]];
1293        let outbound_paid_hints = vec![[0x03; 32]];
1294        let response = NeighborSyncResponse {
1295            replica_hints: outbound_replica_hints.clone(),
1296            paid_hints: outbound_paid_hints.clone(),
1297            bootstrapping: false,
1298            rejected_keys: Vec::new(),
1299            commitment: None,
1300        };
1301
1302        // Inbound hints from the sender (would be in the request).
1303        let inbound_replica_hints = vec![[0xA0; 32], [0xA1; 32]];
1304        let inbound_paid_hints = vec![[0xB0; 32]];
1305
1306        // --- Case 1: sender NOT in LocalRT (sender_in_rt = false) ---
1307        let sender_in_rt = false;
1308        let mut sync_history: HashMap<PeerId, PeerSyncRecord> = HashMap::new();
1309
1310        // Response is still built — outbound hints are sent.
1311        assert_eq!(
1312            response.replica_hints, outbound_replica_hints,
1313            "outbound replica hints must be sent even when sender is not in LocalRT"
1314        );
1315        assert_eq!(
1316            response.paid_hints, outbound_paid_hints,
1317            "outbound paid hints must be sent even when sender is not in LocalRT"
1318        );
1319
1320        // Caller checks sender_in_rt and returns early. No admission runs.
1321        if !sender_in_rt {
1322            // This is the early-return path in mod.rs:964-966.
1323            // Inbound hints are never processed.
1324            let admitted_replica_keys: Vec<[u8; 32]> = Vec::new();
1325            let admitted_paid_keys: Vec<[u8; 32]> = Vec::new();
1326
1327            for key in &inbound_replica_hints {
1328                assert!(
1329                    !admitted_replica_keys.contains(key),
1330                    "inbound replica hints must NOT be admitted from non-RT sender"
1331                );
1332            }
1333            for key in &inbound_paid_hints {
1334                assert!(
1335                    !admitted_paid_keys.contains(key),
1336                    "inbound paid hints must NOT be admitted from non-RT sender"
1337                );
1338            }
1339
1340            // Sync history is NOT updated for non-RT peers.
1341            assert!(
1342                !sync_history.contains_key(&sender),
1343                "sync history must NOT be updated for non-LocalRT sender"
1344            );
1345        }
1346
1347        // --- Case 2: sender IS in LocalRT (sender_in_rt = true) ---
1348        let sender_in_rt = true;
1349        assert!(
1350            sender_in_rt,
1351            "when sender is in LocalRT, inbound hints are processed"
1352        );
1353
1354        // Sync history IS updated for RT peers.
1355        sync_history.insert(
1356            sender,
1357            PeerSyncRecord {
1358                last_sync: Some(Instant::now()),
1359                cycles_since_sync: 0,
1360            },
1361        );
1362        assert!(
1363            sync_history.contains_key(&sender),
1364            "sync history should be updated for LocalRT sender"
1365        );
1366        assert!(
1367            sync_history
1368                .get(&sender)
1369                .expect("sender in history")
1370                .last_sync
1371                .is_some(),
1372            "last_sync should be recorded for RT sender"
1373        );
1374    }
1375
1376    #[test]
1377    fn cycle_completion_resets_cursor_but_keeps_sync_times() {
1378        // Verify that after cycle completes, starting a new cycle
1379        // preserves the last_sync_times from the old state.
1380        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1381        let mut state = NeighborSyncState::new_cycle(peers);
1382
1383        // Sync both peers and record their times.
1384        let _ = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1385        record_successful_sync(&mut state, &peer_id_from_byte(1));
1386        record_successful_sync(&mut state, &peer_id_from_byte(2));
1387        assert!(state.is_cycle_complete());
1388
1389        // Capture sync times before "resetting" for a new cycle.
1390        let old_sync_times = state.last_sync_times.clone();
1391        assert_eq!(old_sync_times.len(), 2);
1392
1393        // Simulate starting a new cycle: create fresh state but carry over
1394        // last_sync_times (as the real driver would).
1395        let new_peers = vec![
1396            peer_id_from_byte(1),
1397            peer_id_from_byte(2),
1398            peer_id_from_byte(3),
1399        ];
1400        let mut new_state = NeighborSyncState::new_cycle(new_peers);
1401        new_state.last_sync_times = old_sync_times;
1402
1403        // Cursor is reset.
1404        assert_eq!(new_state.cursor, 0);
1405        assert!(!new_state.is_cycle_complete());
1406
1407        // Sync times are preserved.
1408        assert_eq!(new_state.last_sync_times.len(), 2);
1409        assert!(new_state
1410            .last_sync_times
1411            .contains_key(&peer_id_from_byte(1)));
1412        assert!(new_state
1413            .last_sync_times
1414            .contains_key(&peer_id_from_byte(2)));
1415
1416        // The preserved cooldowns cause peers 1,2 to be removed, leaving
1417        // only peer 3 selected.
1418        let cooldown = Duration::from_hours(1);
1419        let batch = select_sync_batch(&mut new_state, 3, cooldown);
1420        assert_eq!(
1421            batch,
1422            std::iter::once(peer_id_from_byte(3)).collect::<Vec<_>>(),
1423            "only the new peer should be selected; old peers are on cooldown"
1424        );
1425    }
1426}