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::replication::config::{ReplicationConfig, REPLICATION_PROTOCOL_ID};
17use crate::replication::paid_list::PaidList;
18use crate::replication::protocol::{
19 NeighborSyncRequest, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
20};
21use crate::replication::types::NeighborSyncState;
22use crate::storage::ChunkStore;
23
24const HINT_BUILD_SLOW_LOG_MS: u128 = 250;
26
27#[derive(Debug)]
30pub(crate) struct SentReplicaHint {
31 pub(crate) key: XorName,
33 pub(crate) close_peers: HashSet<PeerId>,
35}
36
37#[derive(Debug)]
39pub(crate) struct NeighborSyncOutcome {
40 pub(crate) response: NeighborSyncResponse,
42 pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
44}
45
46#[derive(Debug, Default)]
48pub(crate) struct PeerSyncHints {
49 pub(crate) sent_replica_hints: Vec<SentReplicaHint>,
52 paid_hints: Vec<XorName>,
54}
55
56pub async fn build_replica_hints_for_peer(
66 peer: &PeerId,
67 storage: &Arc<ChunkStore>,
68 p2p_node: &Arc<P2PNode>,
69 close_group_size: usize,
70) -> Vec<XorName> {
71 build_replica_hints_for_peer_with_close_groups(peer, storage, p2p_node, close_group_size)
72 .await
73 .into_iter()
74 .map(|hint| hint.key)
75 .collect()
76}
77
78pub(crate) async fn build_replica_hints_for_peer_with_close_groups(
79 peer: &PeerId,
80 storage: &Arc<ChunkStore>,
81 p2p_node: &Arc<P2PNode>,
82 close_group_size: usize,
83) -> Vec<SentReplicaHint> {
84 let all_keys = match storage.all_keys().await {
85 Ok(keys) => keys,
86 Err(e) => {
87 warn!("Failed to read stored keys for hint construction: {e}");
88 return Vec::new();
89 }
90 };
91
92 let dht = p2p_node.dht_manager();
93 let mut hints = Vec::new();
94 for key in all_keys {
95 let closest = dht
96 .find_closest_nodes_local_with_self(&key, close_group_size)
97 .await;
98 let close_peers = closest.iter().map(|n| n.peer_id).collect::<HashSet<_>>();
99 if close_peers.contains(peer) {
100 hints.push(SentReplicaHint { key, close_peers });
101 }
102 }
103 hints
104}
105
106pub(crate) async fn build_sync_hints_for_peers(
109 peers: &[PeerId],
110 storage: &Arc<ChunkStore>,
111 paid_list: &Arc<PaidList>,
112 p2p_node: &Arc<P2PNode>,
113 close_group_size: usize,
114 paid_list_close_group_size: usize,
115) -> HashMap<PeerId, PeerSyncHints> {
116 let started = Instant::now();
117 let target_peers = peers.iter().copied().collect::<HashSet<_>>();
118 let mut hints_by_peer = peers
119 .iter()
120 .copied()
121 .map(|peer| (peer, PeerSyncHints::default()))
122 .collect::<HashMap<_, _>>();
123
124 if peers.is_empty() {
125 return hints_by_peer;
126 }
127
128 let all_keys = match storage.all_keys().await {
129 Ok(keys) => keys,
130 Err(e) => {
131 warn!("Failed to read stored keys for batch hint construction: {e}");
132 Vec::new()
133 }
134 };
135 let stored_key_count = all_keys.len();
136
137 let dht = p2p_node.dht_manager();
138 for key in all_keys {
139 let closest = dht
140 .find_closest_nodes_local_with_self(&key, close_group_size)
141 .await;
142 let close_peers = closest.iter().map(|n| n.peer_id).collect::<HashSet<_>>();
143 for peer in close_peers.intersection(&target_peers) {
144 if let Some(peer_hints) = hints_by_peer.get_mut(peer) {
145 peer_hints.sent_replica_hints.push(SentReplicaHint {
146 key,
147 close_peers: close_peers.clone(),
148 });
149 }
150 }
151 }
152
153 let all_paid_keys = match paid_list.all_keys() {
154 Ok(keys) => keys,
155 Err(e) => {
156 warn!("Failed to read PaidForList for batch hint construction: {e}");
157 Vec::new()
158 }
159 };
160 let paid_key_count = all_paid_keys.len();
161
162 for key in all_paid_keys {
163 let closest = dht
164 .find_closest_nodes_local_with_self(&key, paid_list_close_group_size)
165 .await;
166 for node in closest {
167 if target_peers.contains(&node.peer_id) {
168 if let Some(peer_hints) = hints_by_peer.get_mut(&node.peer_id) {
169 peer_hints.paid_hints.push(key);
170 }
171 }
172 }
173 }
174
175 let replica_hint_count = hints_by_peer
176 .values()
177 .map(|hints| hints.sent_replica_hints.len())
178 .sum::<usize>();
179 let paid_hint_count = hints_by_peer
180 .values()
181 .map(|hints| hints.paid_hints.len())
182 .sum::<usize>();
183 let elapsed_ms = started.elapsed().as_millis();
184
185 if elapsed_ms >= HINT_BUILD_SLOW_LOG_MS {
186 info!(
187 target: "ant_node::replication::neighbor_sync",
188 "Slow neighbor-sync hint build: peers={}, stored_keys={}, paid_keys={}, replica_hints={}, paid_hints={}, elapsed_ms={elapsed_ms}",
189 peers.len(),
190 stored_key_count,
191 paid_key_count,
192 replica_hint_count,
193 paid_hint_count,
194 );
195 } else {
196 debug!(
197 target: "ant_node::replication::neighbor_sync",
198 "Neighbor-sync hint build: peers={}, stored_keys={}, paid_keys={}, replica_hints={}, paid_hints={}, elapsed_ms={elapsed_ms}",
199 peers.len(),
200 stored_key_count,
201 paid_key_count,
202 replica_hint_count,
203 paid_hint_count,
204 );
205 }
206
207 hints_by_peer
208}
209
210pub async fn build_paid_hints_for_peer(
215 peer: &PeerId,
216 paid_list: &Arc<PaidList>,
217 p2p_node: &Arc<P2PNode>,
218 paid_list_close_group_size: usize,
219) -> Vec<XorName> {
220 let all_paid_keys = match paid_list.all_keys() {
221 Ok(keys) => keys,
222 Err(e) => {
223 warn!("Failed to read PaidForList for hint construction: {e}");
224 return Vec::new();
225 }
226 };
227
228 let dht = p2p_node.dht_manager();
229 let mut hints = Vec::new();
230 for key in all_paid_keys {
231 let closest = dht
232 .find_closest_nodes_local_with_self(&key, paid_list_close_group_size)
233 .await;
234 if closest.iter().any(|n| n.peer_id == *peer) {
235 hints.push(key);
236 }
237 }
238 hints
239}
240
241pub async fn snapshot_close_neighbors(
246 p2p_node: &Arc<P2PNode>,
247 self_id: &PeerId,
248 scope: usize,
249) -> Vec<PeerId> {
250 let self_xor: XorName = *self_id.as_bytes();
251 let closest = p2p_node
252 .dht_manager()
253 .find_closest_nodes_local(&self_xor, scope)
254 .await;
255 closest.iter().map(|n| n.peer_id).collect()
256}
257
258pub fn select_sync_batch(
264 state: &mut NeighborSyncState,
265 peer_count: usize,
266 cooldown: Duration,
267) -> Vec<PeerId> {
268 let mut batch = Vec::new();
269 let now = Instant::now();
270
271 while batch.len() < peer_count {
272 let Some(peer) = select_next_sync_peer(state, now, cooldown) else {
273 break;
274 };
275 batch.push(peer);
276 }
277
278 batch
279}
280
281fn select_next_sync_peer(
282 state: &mut NeighborSyncState,
283 now: Instant,
284 cooldown: Duration,
285) -> Option<PeerId> {
286 while let Some(peer) = state.priority_order.pop_front() {
287 if peer_on_cooldown(state, &peer, now, cooldown) {
288 state.remove_peer(&peer);
289 continue;
290 }
291
292 state.remove_peer(&peer);
293 return Some(peer);
294 }
295
296 while state.cursor < state.order.len() {
297 let peer = state.order[state.cursor];
298
299 if peer_on_cooldown(state, &peer, now, cooldown) {
303 state.order.remove(state.cursor);
304 continue;
305 }
306
307 state.cursor += 1;
308 return Some(peer);
309 }
310
311 None
312}
313
314fn peer_on_cooldown(
315 state: &NeighborSyncState,
316 peer: &PeerId,
317 now: Instant,
318 cooldown: Duration,
319) -> bool {
320 state
321 .last_sync_times
322 .get(peer)
323 .is_some_and(|last_sync| now.duration_since(*last_sync) < cooldown)
324}
325
326pub async fn sync_with_peer(
331 peer: &PeerId,
332 p2p_node: &Arc<P2PNode>,
333 storage: &Arc<ChunkStore>,
334 paid_list: &Arc<PaidList>,
335 config: &ReplicationConfig,
336 is_bootstrapping: bool,
337) -> Option<NeighborSyncResponse> {
338 sync_with_peer_with_outcome(
339 peer,
340 p2p_node,
341 storage,
342 paid_list,
343 config,
344 is_bootstrapping,
345 None,
346 )
347 .await
348 .map(|outcome| outcome.response)
349}
350
351#[allow(clippy::too_many_arguments)]
355pub(crate) async fn sync_with_peer_with_outcome(
356 peer: &PeerId,
357 p2p_node: &Arc<P2PNode>,
358 storage: &Arc<ChunkStore>,
359 paid_list: &Arc<PaidList>,
360 config: &ReplicationConfig,
361 is_bootstrapping: bool,
362 commitment: Option<crate::replication::commitment::StorageCommitment>,
363) -> Option<NeighborSyncOutcome> {
364 let mut hints_by_peer = build_sync_hints_for_peers(
366 std::slice::from_ref(peer),
367 storage,
368 paid_list,
369 p2p_node,
370 config.close_group_size,
371 config.paid_list_close_group_size,
372 )
373 .await;
374 let hints = hints_by_peer.remove(peer).unwrap_or_default();
375 sync_with_peer_with_hints(peer, p2p_node, config, is_bootstrapping, hints, commitment).await
376}
377
378#[allow(clippy::too_many_arguments)]
379pub(crate) async fn sync_with_peer_with_hints(
380 peer: &PeerId,
381 p2p_node: &Arc<P2PNode>,
382 config: &ReplicationConfig,
383 is_bootstrapping: bool,
384 hints: PeerSyncHints,
385 commitment: Option<crate::replication::commitment::StorageCommitment>,
389) -> Option<NeighborSyncOutcome> {
390 let replica_hints = hints
391 .sent_replica_hints
392 .iter()
393 .map(|hint| hint.key)
394 .collect::<Vec<_>>();
395 let sent_replica_hints = hints.sent_replica_hints;
396
397 let request = NeighborSyncRequest {
398 replica_hints,
399 paid_hints: hints.paid_hints,
400 bootstrapping: is_bootstrapping,
401 commitment,
402 };
403 let request_id = rand::thread_rng().gen::<u64>();
404 let msg = ReplicationMessage {
405 request_id,
406 body: ReplicationMessageBody::NeighborSyncRequest(request),
407 };
408
409 let encoded = match msg.encode() {
410 Ok(data) => data,
411 Err(e) => {
412 warn!("Failed to encode sync request for {peer}: {e}");
413 return None;
414 }
415 };
416
417 let response = match p2p_node
418 .send_request(
419 peer,
420 REPLICATION_PROTOCOL_ID,
421 encoded,
422 config.verification_request_timeout,
423 )
424 .await
425 {
426 Ok(resp) => resp,
427 Err(e) => {
428 debug!("Sync with {peer} failed: {e}");
429 return None;
430 }
431 };
432
433 match ReplicationMessage::decode(&response.data) {
434 Ok(decoded) => {
435 if let ReplicationMessageBody::NeighborSyncResponse(resp) = decoded.body {
436 Some(NeighborSyncOutcome {
437 response: resp,
438 sent_replica_hints,
439 })
440 } else {
441 warn!("Unexpected response type from {peer} during sync");
442 None
443 }
444 }
445 Err(e) => {
446 warn!("Failed to decode sync response from {peer}: {e}");
447 None
448 }
449 }
450}
451
452pub fn handle_sync_failure(
459 state: &mut NeighborSyncState,
460 failed_peer: &PeerId,
461 cooldown: Duration,
462) -> Option<PeerId> {
463 state.remove_peer(failed_peer);
465
466 let now = Instant::now();
469 select_next_sync_peer(state, now, cooldown)
470}
471
472pub fn record_successful_sync(state: &mut NeighborSyncState, peer: &PeerId) {
474 state.last_sync_times.insert(*peer, Instant::now());
475}
476
477pub async fn handle_sync_request(
485 sender: &PeerId,
486 request: &NeighborSyncRequest,
487 p2p_node: &Arc<P2PNode>,
488 storage: &Arc<ChunkStore>,
489 paid_list: &Arc<PaidList>,
490 config: &ReplicationConfig,
491 is_bootstrapping: bool,
492) -> (NeighborSyncResponse, bool) {
493 let (response, _, sender_in_rt) = handle_sync_request_with_proofs(
494 sender,
495 request,
496 p2p_node,
497 storage,
498 paid_list,
499 config,
500 is_bootstrapping,
501 None,
502 )
503 .await;
504 (response, sender_in_rt)
505}
506
507#[allow(clippy::too_many_arguments)]
508pub(crate) async fn handle_sync_request_with_proofs(
509 sender: &PeerId,
510 _request: &NeighborSyncRequest,
511 p2p_node: &Arc<P2PNode>,
512 storage: &Arc<ChunkStore>,
513 paid_list: &Arc<PaidList>,
514 config: &ReplicationConfig,
515 is_bootstrapping: bool,
516 my_commitment: Option<crate::replication::commitment::StorageCommitment>,
517) -> (NeighborSyncResponse, Vec<SentReplicaHint>, bool) {
518 let sender_in_rt = p2p_node.dht_manager().is_in_routing_table(sender).await;
519
520 let sent_replica_hints = build_replica_hints_for_peer_with_close_groups(
522 sender,
523 storage,
524 p2p_node,
525 config.close_group_size,
526 )
527 .await;
528 let replica_hints = sent_replica_hints
529 .iter()
530 .map(|hint| hint.key)
531 .collect::<Vec<_>>();
532 let paid_hints = build_paid_hints_for_peer(
533 sender,
534 paid_list,
535 p2p_node,
536 config.paid_list_close_group_size,
537 )
538 .await;
539
540 let response = NeighborSyncResponse {
541 replica_hints,
542 paid_hints,
543 bootstrapping: is_bootstrapping,
544 rejected_keys: Vec::new(),
545 commitment: my_commitment,
546 };
547
548 (response, sent_replica_hints, sender_in_rt)
550}
551
552#[cfg(test)]
557#[allow(clippy::unwrap_used, clippy::expect_used)]
558mod tests {
559 use super::*;
560 use crate::replication::types::PeerSyncRecord;
561 use std::collections::HashMap;
562
563 fn peer_id_from_byte(b: u8) -> PeerId {
565 let mut bytes = [0u8; 32];
566 bytes[0] = b;
567 PeerId::from_bytes(bytes)
568 }
569
570 #[test]
573 fn select_sync_batch_returns_up_to_peer_count() {
574 let peers = vec![
575 peer_id_from_byte(1),
576 peer_id_from_byte(2),
577 peer_id_from_byte(3),
578 peer_id_from_byte(4),
579 peer_id_from_byte(5),
580 ];
581 let mut state = NeighborSyncState::new_cycle(peers);
582 let batch_size = 3;
583
584 let batch = select_sync_batch(&mut state, batch_size, Duration::from_secs(0));
585
586 assert_eq!(batch.len(), batch_size);
587 assert_eq!(batch[0], peer_id_from_byte(1));
588 assert_eq!(batch[1], peer_id_from_byte(2));
589 assert_eq!(batch[2], peer_id_from_byte(3));
590 assert_eq!(state.cursor, 3);
591 }
592
593 #[test]
594 fn select_sync_batch_skips_cooldown_peers() {
595 let peers = vec![
596 peer_id_from_byte(1),
597 peer_id_from_byte(2),
598 peer_id_from_byte(3),
599 peer_id_from_byte(4),
600 ];
601 let mut state = NeighborSyncState::new_cycle(peers);
602
603 state
605 .last_sync_times
606 .insert(peer_id_from_byte(1), Instant::now());
607 state
608 .last_sync_times
609 .insert(peer_id_from_byte(3), Instant::now());
610
611 let cooldown = Duration::from_hours(1); let batch = select_sync_batch(&mut state, 2, cooldown);
613
614 assert_eq!(batch.len(), 2);
616 assert_eq!(batch[0], peer_id_from_byte(2));
617 assert_eq!(batch[1], peer_id_from_byte(4));
618
619 assert!(!state.order.contains(&peer_id_from_byte(1)));
621 assert!(!state.order.contains(&peer_id_from_byte(3)));
622 }
623
624 #[test]
625 fn select_sync_batch_expired_cooldown_not_skipped() {
626 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
627 let mut state = NeighborSyncState::new_cycle(peers);
628
629 state.last_sync_times.insert(
634 peer_id_from_byte(1),
635 Instant::now()
636 .checked_sub(Duration::from_secs(2))
637 .unwrap_or_else(Instant::now),
638 );
639
640 let cooldown = Duration::from_secs(1);
641 let batch = select_sync_batch(&mut state, 2, cooldown);
642
643 assert_eq!(batch.len(), 2);
645 assert_eq!(batch[0], peer_id_from_byte(1));
646 assert_eq!(batch[1], peer_id_from_byte(2));
647 }
648
649 #[test]
650 fn select_sync_batch_empty_order() {
651 let mut state = NeighborSyncState::new_cycle(vec![]);
652
653 let batch = select_sync_batch(&mut state, 4, Duration::from_secs(0));
654
655 assert!(batch.is_empty(), "expected an empty batch, got {batch:?}");
656 assert_eq!(state.cursor, 0);
657 }
658
659 #[test]
660 fn select_sync_batch_all_on_cooldown() {
661 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
662 let mut state = NeighborSyncState::new_cycle(peers);
663
664 state
665 .last_sync_times
666 .insert(peer_id_from_byte(1), Instant::now());
667 state
668 .last_sync_times
669 .insert(peer_id_from_byte(2), Instant::now());
670
671 let cooldown = Duration::from_hours(1);
672 let batch = select_sync_batch(&mut state, 4, cooldown);
673
674 assert!(
675 batch.is_empty(),
676 "expected an empty batch while every peer is in cooldown, got {batch:?}"
677 );
678 assert!(
679 state.order.is_empty(),
680 "expected an empty order, got {:?}",
681 state.order
682 );
683 }
684
685 #[test]
688 fn handle_sync_failure_removes_peer_and_adjusts_cursor() {
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 state.cursor = 2;
698
699 let replacement =
701 handle_sync_failure(&mut state, &peer_id_from_byte(2), Duration::from_secs(0));
702
703 assert_eq!(state.cursor, 2); assert!(!state.order.contains(&peer_id_from_byte(2)));
706
707 assert!(replacement.is_some());
711 }
712
713 #[test]
714 fn handle_sync_failure_removes_peer_after_cursor() {
715 let peers = vec![
716 peer_id_from_byte(1),
717 peer_id_from_byte(2),
718 peer_id_from_byte(3),
719 peer_id_from_byte(4),
720 ];
721 let mut state = NeighborSyncState::new_cycle(peers);
722 state.cursor = 1;
723
724 let replacement =
726 handle_sync_failure(&mut state, &peer_id_from_byte(3), Duration::from_secs(0));
727
728 assert_eq!(state.cursor, 2); assert!(!state.order.contains(&peer_id_from_byte(3)));
731
732 assert_eq!(replacement, Some(peer_id_from_byte(2)));
734 }
735
736 #[test]
737 fn handle_sync_failure_no_replacement_when_exhausted() {
738 let peers = vec![peer_id_from_byte(1)];
739 let mut state = NeighborSyncState::new_cycle(peers);
740 state.cursor = 1; let replacement =
743 handle_sync_failure(&mut state, &peer_id_from_byte(1), Duration::from_secs(0));
744
745 assert!(
746 state.order.is_empty(),
747 "expected the order to be exhausted, got {:?}",
748 state.order
749 );
750 assert!(replacement.is_none());
751 }
752
753 #[test]
754 fn handle_sync_failure_unknown_peer_is_noop() {
755 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
756 let mut state = NeighborSyncState::new_cycle(peers);
757 state.cursor = 1;
758
759 let replacement =
760 handle_sync_failure(&mut state, &peer_id_from_byte(99), Duration::from_secs(0));
761
762 assert_eq!(state.order.len(), 2);
764 assert_eq!(replacement, Some(peer_id_from_byte(2)));
766 assert_eq!(state.cursor, 2);
767 }
768
769 #[test]
772 fn record_successful_sync_updates_last_sync_time() {
773 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
774 let mut state = NeighborSyncState::new_cycle(peers);
775 let peer = peer_id_from_byte(1);
776
777 assert!(!state.last_sync_times.contains_key(&peer));
778
779 let before = Instant::now();
780 record_successful_sync(&mut state, &peer);
781 let after = Instant::now();
782
783 let ts = state.last_sync_times.get(&peer).expect("timestamp exists");
784 assert!(*ts >= before);
785 assert!(*ts <= after);
786 }
787
788 #[test]
789 fn record_successful_sync_overwrites_previous() {
790 let peers = vec![peer_id_from_byte(1)];
791 let mut state = NeighborSyncState::new_cycle(peers);
792 let peer = peer_id_from_byte(1);
793
794 let old_time = Instant::now()
797 .checked_sub(Duration::from_secs(2))
798 .unwrap_or_else(Instant::now);
799 state.last_sync_times.insert(peer, old_time);
800
801 record_successful_sync(&mut state, &peer);
802
803 let ts = state.last_sync_times.get(&peer).expect("timestamp exists");
804 assert!(*ts > old_time, "sync time should be updated");
805 }
806
807 #[test]
810 fn scenario_35_round_robin_with_cooldown_skip() {
811 let peers: Vec<PeerId> = (1..=8).map(peer_id_from_byte).collect();
818 let mut state = NeighborSyncState::new_cycle(peers);
819 let batch_size = 4;
820 let cooldown = Duration::from_hours(1);
821
822 state
824 .last_sync_times
825 .insert(peer_id_from_byte(2), Instant::now());
826 state
827 .last_sync_times
828 .insert(peer_id_from_byte(4), Instant::now());
829
830 let batch1 = select_sync_batch(&mut state, batch_size, cooldown);
833 assert_eq!(batch1.len(), 4);
834 assert_eq!(batch1[0], peer_id_from_byte(1));
835 assert_eq!(batch1[1], peer_id_from_byte(3));
836 assert_eq!(batch1[2], peer_id_from_byte(5));
837 assert_eq!(batch1[3], peer_id_from_byte(6));
838
839 assert!(!state.order.contains(&peer_id_from_byte(2)));
841 assert!(!state.order.contains(&peer_id_from_byte(4)));
842
843 let batch2 = select_sync_batch(&mut state, batch_size, cooldown);
845 assert_eq!(batch2.len(), 2);
846 assert_eq!(batch2[0], peer_id_from_byte(7));
847 assert_eq!(batch2[1], peer_id_from_byte(8));
848
849 assert!(state.is_cycle_complete());
851 }
852
853 #[test]
854 fn cycle_complete_when_cursor_past_order() {
855 let peers: Vec<PeerId> = (1..=3).map(peer_id_from_byte).collect();
857 let mut state = NeighborSyncState::new_cycle(peers);
858
859 assert!(!state.is_cycle_complete());
861
862 state.cursor = 3;
864 assert!(state.is_cycle_complete());
865
866 state.cursor = 10;
868 assert!(state.is_cycle_complete());
869
870 state.order.clear();
872 state.cursor = 0;
873 assert!(state.is_cycle_complete());
874 }
875
876 #[test]
893 fn scenario_36_post_cycle_triggers_combined_prune_pass() {
894 let config = ReplicationConfig::default();
895
896 let peers: Vec<PeerId> = (1..=3).map(peer_id_from_byte).collect();
898 let mut state = NeighborSyncState::new_cycle(peers);
899 let _ = select_sync_batch(&mut state, 3, Duration::from_secs(0));
900 assert!(
901 state.is_cycle_complete(),
902 "cycle must be complete before prune pass triggers"
903 );
904
905 assert!(
907 !config.prune_hysteresis_duration.is_zero(),
908 "PRUNE_HYSTERESIS_DURATION must be non-zero for hysteresis to work"
909 );
910
911 let record_key: [u8; 32] = [0x36; 32];
920 let paid_key: [u8; 32] = [0x37; 32];
921
922 let record_first_seen = Instant::now();
924 let paid_first_seen = Instant::now();
925
926 let record_elapsed = record_first_seen.elapsed();
928 let paid_elapsed = paid_first_seen.elapsed();
929 assert!(
930 record_elapsed < config.prune_hysteresis_duration,
931 "record key should be retained within hysteresis window"
932 );
933 assert!(
934 paid_elapsed < config.prune_hysteresis_duration,
935 "paid key should be retained within hysteresis window"
936 );
937
938 assert_ne!(
941 record_key, paid_key,
942 "record and paid pruning keys must be independent"
943 );
944
945 let new_state = NeighborSyncState::new_cycle(vec![
947 peer_id_from_byte(1),
948 peer_id_from_byte(2),
949 peer_id_from_byte(3),
950 ]);
951 assert_eq!(new_state.cursor, 0, "cursor resets for new cycle");
952 assert!(
953 !new_state.is_cycle_complete(),
954 "new cycle should not be immediately complete"
955 );
956 }
957
958 #[test]
959 fn scenario_38_mid_cycle_peer_join_prioritized() {
960 let peers = vec![
963 peer_id_from_byte(0xA),
964 peer_id_from_byte(0xB),
965 peer_id_from_byte(0xC),
966 ];
967 let mut state = NeighborSyncState::new_cycle(peers);
968
969 let _ = select_sync_batch(&mut state, 1, Duration::from_secs(0));
971 assert_eq!(state.cursor, 1);
972
973 let peer_d = peer_id_from_byte(0xD);
976 assert_eq!(state.queue_priority_peers([peer_d]), 1);
977 assert!(!state.order.contains(&peer_d));
978 assert!(
979 !state.is_cycle_complete(),
980 "pending priority sync keeps the cycle active"
981 );
982
983 let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
984 assert_eq!(batch, vec![peer_d, peer_id_from_byte(0xB)]);
985 }
986
987 #[test]
988 fn scenario_39_unreachable_peer_removed_slot_filled() {
989 let peers = vec![
992 peer_id_from_byte(1),
993 peer_id_from_byte(2),
994 peer_id_from_byte(3),
995 peer_id_from_byte(4),
996 peer_id_from_byte(5),
997 ];
998 let mut state = NeighborSyncState::new_cycle(peers);
999
1000 let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1002 assert_eq!(batch, vec![peer_id_from_byte(1), peer_id_from_byte(2)]);
1003
1004 let replacement =
1006 handle_sync_failure(&mut state, &peer_id_from_byte(2), Duration::from_secs(0));
1007 assert!(!state.order.contains(&peer_id_from_byte(2)));
1008
1009 assert_eq!(
1011 replacement,
1012 Some(peer_id_from_byte(3)),
1013 "vacated slot should be filled by next peer in order"
1014 );
1015
1016 let batch2 = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1018 assert_eq!(batch2, vec![peer_id_from_byte(4), peer_id_from_byte(5)]);
1019 assert!(state.is_cycle_complete());
1020 }
1021
1022 #[test]
1023 fn scenario_40_cooldown_peer_removed_from_snapshot() {
1024 let peers = vec![
1028 peer_id_from_byte(1),
1029 peer_id_from_byte(2),
1030 peer_id_from_byte(3),
1031 ];
1032 let mut state = NeighborSyncState::new_cycle(peers);
1033 let cooldown = Duration::from_hours(1);
1034
1035 state
1037 .last_sync_times
1038 .insert(peer_id_from_byte(2), Instant::now());
1039
1040 let batch = select_sync_batch(&mut state, 3, cooldown);
1041
1042 assert!(!state.order.contains(&peer_id_from_byte(2)));
1044 assert_eq!(state.order.len(), 2, "order should shrink by 1");
1045
1046 assert_eq!(batch, vec![peer_id_from_byte(1), peer_id_from_byte(3)]);
1048
1049 assert!(state.is_cycle_complete());
1051 }
1052
1053 #[test]
1054 fn priority_peer_in_snapshot_is_not_selected_twice() {
1055 let peers = vec![
1056 peer_id_from_byte(1),
1057 peer_id_from_byte(2),
1058 peer_id_from_byte(3),
1059 ];
1060 let mut state = NeighborSyncState::new_cycle(peers);
1061 assert_eq!(state.queue_priority_peers([peer_id_from_byte(2)]), 1);
1062
1063 let batch = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1064
1065 assert_eq!(batch, vec![peer_id_from_byte(2), peer_id_from_byte(1)]);
1066 assert_eq!(
1067 state.order,
1068 vec![peer_id_from_byte(1), peer_id_from_byte(3)]
1069 );
1070 assert_eq!(state.cursor, 1);
1071 }
1072
1073 #[test]
1074 fn priority_peer_on_cooldown_is_skipped_and_removed_from_snapshot() {
1075 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1076 let mut state = NeighborSyncState::new_cycle(peers);
1077 let cooldown = Duration::from_secs(1);
1078 let priority_peer = peer_id_from_byte(2);
1079 state.last_sync_times.insert(priority_peer, Instant::now());
1080 assert_eq!(state.queue_priority_peers([priority_peer]), 1);
1081
1082 let batch = select_sync_batch(&mut state, 2, cooldown);
1083
1084 assert_eq!(batch, vec![peer_id_from_byte(1)]);
1085 assert!(state.priority_order.is_empty());
1086 assert!(!state.order.contains(&priority_peer));
1087 }
1088
1089 #[test]
1090 fn failure_replacement_prefers_remaining_priority_peer() {
1091 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1092 let mut state = NeighborSyncState::new_cycle(peers);
1093 let first_priority_peer = peer_id_from_byte(3);
1094 let second_priority_peer = peer_id_from_byte(4);
1095 assert_eq!(
1096 state.queue_priority_peers([first_priority_peer, second_priority_peer]),
1097 2
1098 );
1099
1100 let batch = select_sync_batch(&mut state, 1, Duration::from_secs(0));
1101 assert_eq!(batch, vec![first_priority_peer]);
1102
1103 let replacement =
1104 handle_sync_failure(&mut state, &first_priority_peer, Duration::from_secs(0));
1105
1106 assert_eq!(replacement, Some(second_priority_peer));
1107 assert!(state.priority_order.is_empty());
1108 assert_eq!(state.cursor, 0);
1109 }
1110
1111 #[test]
1112 fn scenario_41_cycle_always_terminates() {
1113 let peer_count: u8 = 10;
1117 let peers: Vec<PeerId> = (1..=peer_count).map(peer_id_from_byte).collect();
1118 let mut state = NeighborSyncState::new_cycle(peers);
1119 let cooldown = Duration::from_hours(1);
1120
1121 for i in 1..=peer_count {
1123 state
1124 .last_sync_times
1125 .insert(peer_id_from_byte(i), Instant::now());
1126 }
1127
1128 let batch = select_sync_batch(&mut state, 4, cooldown);
1129
1130 assert!(
1131 batch.is_empty(),
1132 "all peers on cooldown — batch must be empty"
1133 );
1134 assert!(state.order.is_empty(), "all peers should have been removed");
1135 assert!(
1136 state.is_cycle_complete(),
1137 "cycle must terminate when all peers are removed"
1138 );
1139 }
1140
1141 #[test]
1142 fn consecutive_rounds_advance_through_full_cycle() {
1143 let peers: Vec<PeerId> = (1..=6).map(peer_id_from_byte).collect();
1147 let mut state = NeighborSyncState::new_cycle(peers);
1148 let batch_size = 2;
1149 let no_cooldown = Duration::from_secs(0);
1150
1151 let round1 = select_sync_batch(&mut state, batch_size, no_cooldown);
1152 assert_eq!(round1, vec![peer_id_from_byte(1), peer_id_from_byte(2)]);
1153 assert_eq!(state.cursor, 2);
1154 assert!(!state.is_cycle_complete());
1155
1156 let round2 = select_sync_batch(&mut state, batch_size, no_cooldown);
1157 assert_eq!(round2, vec![peer_id_from_byte(3), peer_id_from_byte(4)]);
1158 assert_eq!(state.cursor, 4);
1159 assert!(!state.is_cycle_complete());
1160
1161 let round3 = select_sync_batch(&mut state, batch_size, no_cooldown);
1162 assert_eq!(round3, vec![peer_id_from_byte(5), peer_id_from_byte(6)]);
1163 assert_eq!(state.cursor, 6);
1164 assert!(state.is_cycle_complete());
1165
1166 let round4 = select_sync_batch(&mut state, batch_size, no_cooldown);
1168 assert!(
1169 round4.is_empty(),
1170 "expected an empty batch once the cycle is complete, got {round4:?}"
1171 );
1172 }
1173
1174 #[test]
1195 fn scenario_37_non_local_rt_inbound_sync_drops_hints() {
1196 let sender = peer_id_from_byte(0x37);
1197
1198 let outbound_replica_hints = vec![[0x01; 32], [0x02; 32]];
1201 let outbound_paid_hints = vec![[0x03; 32]];
1202 let response = NeighborSyncResponse {
1203 replica_hints: outbound_replica_hints.clone(),
1204 paid_hints: outbound_paid_hints.clone(),
1205 bootstrapping: false,
1206 rejected_keys: Vec::new(),
1207 commitment: None,
1208 };
1209
1210 let inbound_replica_hints = vec![[0xA0; 32], [0xA1; 32]];
1212 let inbound_paid_hints = vec![[0xB0; 32]];
1213
1214 let sender_in_rt = false;
1216 let mut sync_history: HashMap<PeerId, PeerSyncRecord> = HashMap::new();
1217
1218 assert_eq!(
1220 response.replica_hints, outbound_replica_hints,
1221 "outbound replica hints must be sent even when sender is not in LocalRT"
1222 );
1223 assert_eq!(
1224 response.paid_hints, outbound_paid_hints,
1225 "outbound paid hints must be sent even when sender is not in LocalRT"
1226 );
1227
1228 if !sender_in_rt {
1230 let admitted_replica_keys: Vec<[u8; 32]> = Vec::new();
1233 let admitted_paid_keys: Vec<[u8; 32]> = Vec::new();
1234
1235 for key in &inbound_replica_hints {
1236 assert!(
1237 !admitted_replica_keys.contains(key),
1238 "inbound replica hints must NOT be admitted from non-RT sender"
1239 );
1240 }
1241 for key in &inbound_paid_hints {
1242 assert!(
1243 !admitted_paid_keys.contains(key),
1244 "inbound paid hints must NOT be admitted from non-RT sender"
1245 );
1246 }
1247
1248 assert!(
1250 !sync_history.contains_key(&sender),
1251 "sync history must NOT be updated for non-LocalRT sender"
1252 );
1253 }
1254
1255 let sender_in_rt = true;
1257 assert!(
1258 sender_in_rt,
1259 "when sender is in LocalRT, inbound hints are processed"
1260 );
1261
1262 sync_history.insert(
1264 sender,
1265 PeerSyncRecord {
1266 last_sync: Some(Instant::now()),
1267 cycles_since_sync: 0,
1268 },
1269 );
1270 assert!(
1271 sync_history.contains_key(&sender),
1272 "sync history should be updated for LocalRT sender"
1273 );
1274 assert!(
1275 sync_history
1276 .get(&sender)
1277 .expect("sender in history")
1278 .last_sync
1279 .is_some(),
1280 "last_sync should be recorded for RT sender"
1281 );
1282 }
1283
1284 #[test]
1285 fn cycle_completion_resets_cursor_but_keeps_sync_times() {
1286 let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1289 let mut state = NeighborSyncState::new_cycle(peers);
1290
1291 let _ = select_sync_batch(&mut state, 2, Duration::from_secs(0));
1293 record_successful_sync(&mut state, &peer_id_from_byte(1));
1294 record_successful_sync(&mut state, &peer_id_from_byte(2));
1295 assert!(state.is_cycle_complete());
1296
1297 let old_sync_times = state.last_sync_times.clone();
1299 assert_eq!(old_sync_times.len(), 2);
1300
1301 let new_peers = vec![
1304 peer_id_from_byte(1),
1305 peer_id_from_byte(2),
1306 peer_id_from_byte(3),
1307 ];
1308 let mut new_state = NeighborSyncState::new_cycle(new_peers);
1309 new_state.last_sync_times = old_sync_times;
1310
1311 assert_eq!(new_state.cursor, 0);
1313 assert!(!new_state.is_cycle_complete());
1314
1315 assert_eq!(new_state.last_sync_times.len(), 2);
1317 assert!(new_state
1318 .last_sync_times
1319 .contains_key(&peer_id_from_byte(1)));
1320 assert!(new_state
1321 .last_sync_times
1322 .contains_key(&peer_id_from_byte(2)));
1323
1324 let cooldown = Duration::from_hours(1);
1327 let batch = select_sync_batch(&mut new_state, 3, cooldown);
1328 assert_eq!(
1329 batch,
1330 std::iter::once(peer_id_from_byte(3)).collect::<Vec<_>>(),
1331 "only the new peer should be selected; old peers are on cooldown"
1332 );
1333 }
1334}