1use 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
28const HINT_BUILD_SLOW_LOG_MS: u128 = 250;
30
31#[derive(Debug)]
34pub(crate) struct SentReplicaHint {
35 pub(crate) key: XorName,
37 pub(crate) close_peers: HashSet<PeerId>,
39}
40
41#[derive(Debug)]
43pub(crate) struct NeighborSyncOutcome {
44 pub(crate) response: NeighborSyncResponse,
46 pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
48}
49
50#[derive(Debug, Default)]
52pub(crate) struct PeerSyncHints {
53 pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
56 paid_hints: Vec<XorName>,
58}
59
60pub 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
110pub(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
133fn 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
143async 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
155pub(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
260pub 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
292pub 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
309pub 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 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
377pub 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#[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 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 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
503pub fn handle_sync_failure(
510 state: &mut NeighborSyncState,
511 failed_peer: &PeerId,
512 cooldown: Duration,
513) -> Option<PeerId> {
514 state.remove_peer(failed_peer);
516
517 let now = Instant::now();
520 select_next_sync_peer(state, now, cooldown)
521}
522
523pub fn record_successful_sync(state: &mut NeighborSyncState, peer: &PeerId) {
525 state.last_sync_times.insert(*peer, Instant::now());
526}
527
528pub 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 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 (response, sent_replica_hints, sender_in_rt)
601}
602
603#[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 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 fn key_ending_in(b: u8) -> XorName {
623 let mut key = [0u8; 32];
624 key[31] = b;
625 key
626 }
627
628 #[tokio::test]
631 async fn a_far_key_is_read_for_hints_until_the_list_is_too_large_to_read_whole() {
632 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 #[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 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); let batch = select_sync_batch(&mut state, 2, cooldown);
707
708 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 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 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 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 #[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 state.cursor = 2;
792
793 let replacement =
795 handle_sync_failure(&mut state, &peer_id_from_byte(2), Duration::from_secs(0));
796
797 assert_eq!(state.cursor, 2); assert!(!state.order.contains(&peer_id_from_byte(2)));
800
801 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 let replacement =
820 handle_sync_failure(&mut state, &peer_id_from_byte(3), Duration::from_secs(0));
821
822 assert_eq!(state.cursor, 2); assert!(!state.order.contains(&peer_id_from_byte(3)));
825
826 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; 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 assert_eq!(state.order.len(), 2);
858 assert_eq!(replacement, Some(peer_id_from_byte(2)));
860 assert_eq!(state.cursor, 2);
861 }
862
863 #[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 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 #[test]
904 fn scenario_35_round_robin_with_cooldown_skip() {
905 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 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 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 assert!(!state.order.contains(&peer_id_from_byte(2)));
935 assert!(!state.order.contains(&peer_id_from_byte(4)));
936
937 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 assert!(state.is_cycle_complete());
945 }
946
947 #[test]
948 fn cycle_complete_when_cursor_past_order() {
949 let peers: Vec<PeerId> = (1..=3).map(peer_id_from_byte).collect();
951 let mut state = NeighborSyncState::new_cycle(peers);
952
953 assert!(!state.is_cycle_complete());
955
956 state.cursor = 3;
958 assert!(state.is_cycle_complete());
959
960 state.cursor = 10;
962 assert!(state.is_cycle_complete());
963
964 state.order.clear();
966 state.cursor = 0;
967 assert!(state.is_cycle_complete());
968 }
969
970 #[test]
985 fn scenario_36_post_cycle_triggers_combined_prune_pass() {
986 let config = ReplicationConfig::default();
987
988 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 assert!(
999 !config.prune_hysteresis_duration.is_zero(),
1000 "PRUNE_HYSTERESIS_DURATION must be non-zero for hysteresis to work"
1001 );
1002
1003 let record_key: [u8; 32] = [0x36; 32];
1012 let paid_key: [u8; 32] = [0x37; 32];
1013
1014 let record_first_seen = Instant::now();
1016 let paid_first_seen = Instant::now();
1017
1018 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 assert_ne!(
1033 record_key, paid_key,
1034 "record and paid pruning keys must be independent"
1035 );
1036
1037 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 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 let _ = select_sync_batch(&mut state, 1, Duration::from_secs(0));
1063 assert_eq!(state.cursor, 1);
1064
1065 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 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 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 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 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 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 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 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 assert!(!state.order.contains(&peer_id_from_byte(2)));
1136 assert_eq!(state.order.len(), 2, "order should shrink by 1");
1137
1138 assert_eq!(batch, vec![peer_id_from_byte(1), peer_id_from_byte(3)]);
1140
1141 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 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 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 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 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 #[test]
1287 fn scenario_37_non_local_rt_inbound_sync_drops_hints() {
1288 let sender = peer_id_from_byte(0x37);
1289
1290 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 let inbound_replica_hints = vec![[0xA0; 32], [0xA1; 32]];
1304 let inbound_paid_hints = vec![[0xB0; 32]];
1305
1306 let sender_in_rt = false;
1308 let mut sync_history: HashMap<PeerId, PeerSyncRecord> = HashMap::new();
1309
1310 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 if !sender_in_rt {
1322 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 assert!(
1342 !sync_history.contains_key(&sender),
1343 "sync history must NOT be updated for non-LocalRT sender"
1344 );
1345 }
1346
1347 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.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 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1381 let mut state = NeighborSyncState::new_cycle(peers);
1382
1383 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 let old_sync_times = state.last_sync_times.clone();
1391 assert_eq!(old_sync_times.len(), 2);
1392
1393 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 assert_eq!(new_state.cursor, 0);
1405 assert!(!new_state.is_cycle_complete());
1406
1407 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 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}