Skip to main content

ant_node/replication/
types.rs

1//! Core types for the replication subsystem.
2//!
3//! These types represent the state machine states, queue entries, and domain
4//! concepts from the Kademlia-style replication design (see
5//! `docs/REPLICATION_DESIGN.md`).
6
7use std::cmp::Ordering;
8use std::collections::{HashMap, HashSet, VecDeque};
9use std::time::{Duration, Instant};
10
11use serde::{Deserialize, Serialize};
12
13use crate::ant_protocol::XorName;
14use crate::replication::config::REPAIR_HINT_MIN_AGE;
15use saorsa_core::identity::PeerId;
16
17// ---------------------------------------------------------------------------
18// Verification state machine (Section 8 of REPLICATION_DESIGN.md)
19// ---------------------------------------------------------------------------
20
21/// Verification state machine.
22///
23/// Each unknown key transitions through these states exactly once per offer
24/// lifecycle.  See Section 8 of `REPLICATION_DESIGN.md` for the full
25/// state-transition diagram.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum VerificationState {
28    /// Offer received, not yet processed.
29    OfferReceived,
30    /// Passed admission filter, awaiting quorum / paid-list verification.
31    PendingVerify,
32    /// Presence quorum passed (>= `QuorumNeeded` positives from
33    /// `QuorumTargets`).
34    QuorumVerified,
35    /// Paid-list authorisation succeeded (>= `ConfirmNeeded` confirmations or
36    /// derived from replica majority).
37    PaidListVerified,
38    /// Queued for record fetch.
39    QueuedForFetch,
40    /// Actively fetching from a verified source.
41    Fetching,
42    /// Successfully stored locally.
43    Stored,
44    /// Fetch failed but retryable (alternate sources remain).
45    FetchRetryable,
46    /// Fetch permanently abandoned (terminal failure or no alternate sources).
47    FetchAbandoned,
48    /// Quorum failed definitively (both paid-list and presence impossible this
49    /// round).
50    QuorumFailed,
51    /// Quorum inconclusive (timeout with neither success nor fail-fast).
52    QuorumInconclusive,
53    /// Terminal: quorum abandoned, key forgotten.
54    QuorumAbandoned,
55    /// Terminal: key returned to idle (forgotten, requires new offer to
56    /// re-enter).
57    Idle,
58}
59
60// ---------------------------------------------------------------------------
61// Hint pipeline classification
62// ---------------------------------------------------------------------------
63
64/// Whether a key was admitted via replica hints or paid hints only.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
66pub enum HintPipeline {
67    /// Key is in the admitted replica-hint pipeline (fetch-eligible).
68    Replica,
69    /// Key is in the paid-hint-only pipeline (`PaidForList` update only, no
70    /// fetch).
71    PaidOnly,
72}
73
74// ---------------------------------------------------------------------------
75// Pending-verification table entry
76// ---------------------------------------------------------------------------
77
78/// Entry in the pending-verification table.
79///
80/// Tracks a single key through the verification FSM, recording which peers
81/// responded and which have been tried for fetch.
82#[derive(Debug, Clone)]
83pub struct VerificationEntry {
84    /// Current state in the verification FSM.
85    pub state: VerificationState,
86    /// Peers that responded `Present` during verification (verified fetch
87    /// sources).
88    pub verified_sources: Vec<PeerId>,
89    /// Peers already tried for fetch (to avoid retrying the same source).
90    pub tried_sources: HashSet<PeerId>,
91    /// When this entry was created.
92    pub created_at: Instant,
93    /// Earliest time this key should be included in another verification
94    /// round.
95    pub next_verify_at: Instant,
96    /// Routing-table peers that advertised this key and have not subsequently
97    /// departed. Duplicate hints add to this set instead of being discarded.
98    pub hint_sources: HashSet<PeerId>,
99    /// Subset of [`Self::hint_sources`] that advertised a replica hint and
100    /// therefore claimed chunk possession. Paid-only advertisers are excluded.
101    pub replica_hint_sources: HashSet<PeerId>,
102}
103
104impl VerificationEntry {
105    /// Which pipeline this key arrived on.
106    ///
107    /// Derived from [`Self::replica_hint_sources`] rather than stored: the
108    /// pipeline *is* "did any peer claim to hold this key", so a stored copy
109    /// can only drift from its own definition as advertisers are merged in and
110    /// departed peers are pruned out.
111    ///
112    /// This describes hint *provenance*, not authorization. It selects fetch
113    /// sources (only a peer claiming possession is worth fetching from) and
114    /// scopes sole-source trust penalties. It must never gate storage:
115    /// possession claims come from the sender, so treating one as permission to
116    /// store lets a peer conscript a node that carries no responsibility for
117    /// the key. Storage responsibility is decided separately, against live
118    /// routing state, by `is_responsible(storage_admission_width)` at the point
119    /// of download.
120    #[must_use]
121    pub fn pipeline(&self) -> HintPipeline {
122        if self.replica_hint_sources.is_empty() {
123            HintPipeline::PaidOnly
124        } else {
125            HintPipeline::Replica
126        }
127    }
128}
129
130// ---------------------------------------------------------------------------
131// Fetch queue
132// ---------------------------------------------------------------------------
133
134/// Heap-ordering key for the fetch queue, ordered by relevance
135/// (nearest-first).
136///
137/// Carries **only** the two fields the ordering reads, and both are fixed for
138/// as long as a key stays queued. The mutable half of a queued fetch lives in
139/// [`FetchPayload`], outside the heap, so that merging a newly-discovered
140/// source into an already-queued key cannot disturb heap order — and therefore
141/// needs no heap rebuild.
142///
143/// Implements [`Ord`] with *reversed* distance comparison so that a
144/// [`BinaryHeap`](std::collections::BinaryHeap) (max-heap) dequeues the
145/// nearest key first.
146#[derive(Debug, Clone, Copy)]
147pub struct FetchOrder {
148    /// The key to fetch.
149    pub key: XorName,
150    /// XOR distance from self to key (for priority ordering).
151    pub distance: XorName,
152}
153
154impl Eq for FetchOrder {}
155
156impl PartialEq for FetchOrder {
157    fn eq(&self, other: &Self) -> bool {
158        self.distance == other.distance && self.key == other.key
159    }
160}
161
162impl Ord for FetchOrder {
163    fn cmp(&self, other: &Self) -> Ordering {
164        // Reverse ordering: smaller distance = higher priority (BinaryHeap is
165        // max-heap).  Tie-break on key for consistency with PartialEq.
166        other
167            .distance
168            .cmp(&self.distance)
169            .then_with(|| self.key.cmp(&other.key))
170    }
171}
172
173impl PartialOrd for FetchOrder {
174    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
175        Some(self.cmp(other))
176    }
177}
178
179/// The mutable half of a queued fetch, held outside the priority heap.
180///
181/// Neither field participates in [`FetchOrder`]'s ordering, and both are read
182/// only once the key is dequeued. Holding them in a key-indexed map is what
183/// lets a further source be merged into an already-queued key in O(1) instead
184/// of costing a full rebuild of the fetch heap.
185#[derive(Debug, Clone)]
186pub struct FetchPayload {
187    /// Verified source peers that responded `Present`.
188    pub sources: Vec<PeerId>,
189    /// Pending-verification entry to restore if every fetch source is
190    /// exhausted before the chunk is recovered.
191    pub retry_verification: Option<VerificationEntry>,
192}
193
194/// A candidate dequeued for fetch: a [`FetchOrder`] rejoined with its
195/// [`FetchPayload`].
196#[derive(Debug, Clone)]
197pub struct FetchCandidate {
198    /// The key to fetch.
199    pub key: XorName,
200    /// XOR distance from self to key.
201    pub distance: XorName,
202    /// Verified source peers that responded `Present`.
203    pub sources: Vec<PeerId>,
204    /// Pending-verification entry to restore if every fetch source is
205    /// exhausted before the chunk is recovered.
206    pub retry_verification: Option<VerificationEntry>,
207}
208
209// ---------------------------------------------------------------------------
210// Verification evidence types
211// ---------------------------------------------------------------------------
212
213/// Per-key presence evidence from a verification round.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
215pub enum PresenceEvidence {
216    /// Peer holds the record.
217    Present,
218    /// Peer does not hold the record.
219    Absent,
220    /// Peer did not respond in time (neutral, not negative).
221    Unresolved,
222}
223
224/// Per-key paid-list evidence from a verification round.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
226pub enum PaidListEvidence {
227    /// Peer confirms key is in its `PaidForList`.
228    Confirmed,
229    /// Peer says key is NOT in its `PaidForList`.
230    NotFound,
231    /// Peer did not respond in time (neutral).
232    Unresolved,
233}
234
235/// Aggregated verification evidence for a single key from one verification
236/// round.
237#[derive(Debug, Clone)]
238pub struct KeyVerificationEvidence {
239    /// Presence evidence per peer (from `QuorumTargets`).
240    pub presence: HashMap<PeerId, PresenceEvidence>,
241    /// Paid-list evidence per peer (from `PaidTargets`).
242    pub paid_list: HashMap<PeerId, PaidListEvidence>,
243}
244
245// ---------------------------------------------------------------------------
246// Failure evidence (Section 14 — TrustEngine integration)
247// ---------------------------------------------------------------------------
248
249/// Counts that describe a confirmed audit failure without logging per-key
250/// detail at `ERROR` level.
251#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
252pub struct AuditFailureSummary {
253    /// Number of keys in the original audit challenge.
254    pub challenged_keys: usize,
255    /// Number of keys that still failed after responsibility confirmation.
256    pub failed_keys: usize,
257    /// Confirmed failures where the responder returned the absent-key sentinel.
258    pub absent_keys: usize,
259    /// Confirmed failures where the responder returned a digest that did not
260    /// match the challenger's local bytes.
261    pub digest_mismatch_keys: usize,
262}
263
264/// Failure evidence types emitted to `TrustEngine` (Section 14).
265#[derive(Debug, Clone)]
266pub enum FailureEvidence {
267    /// Failed fetch attempt from a source peer.
268    ReplicationFailure {
269        /// The peer that failed to serve the record.
270        peer: PeerId,
271        /// The key that could not be fetched.
272        key: XorName,
273    },
274    /// Audit failure with confirmed responsible keys.
275    AuditFailure {
276        /// Unique identifier for the audit challenge.
277        challenge_id: u64,
278        /// The peer that was challenged.
279        challenged_peer: PeerId,
280        /// Keys confirmed as failed.
281        confirmed_failed_keys: Vec<XorName>,
282        /// Aggregated reason counts for the confirmed failures.
283        summary: AuditFailureSummary,
284        /// Why the audit failed.
285        reason: AuditFailureReason,
286    },
287    /// Peer claiming bootstrap past grace period.
288    BootstrapClaimAbuse {
289        /// The offending peer.
290        peer: PeerId,
291        /// When this peer was first seen.
292        first_seen: Instant,
293    },
294    /// ADR-0004: a quote's claimed committed key count contradicts the signed
295    /// commitment it pinned. The quote and the commitment are both signed by
296    /// the same key, so this is a deterministic, first-occurrence
297    /// contradiction — not bad luck — and lands in the same trust lane as a
298    /// confirmed deterministic audit failure. Reported only in the
299    /// client-put context (a replication receipt's pin has legitimately aged
300    /// out). The fields are the portable contradiction: any third party
301    /// holding the two signed artifacts can recompute it.
302    QuoteCommitmentMismatch {
303        /// The peer whose quote and commitment disagree.
304        peer: PeerId,
305        /// The commitment hash the quote pinned (identifies the signed
306        /// commitment artifact); equals `commitment.hash()`.
307        pinned_commitment: [u8; 32],
308        /// The key count the quote claimed (and priced against).
309        quoted_key_count: u32,
310        /// The key count the pinned commitment actually attests.
311        committed_key_count: u32,
312        /// The signed quote artifact that carries the contradicting
313        /// `committed_key_count` + pin, ML-DSA-signed by `peer`, as canonical
314        /// serialized bytes. Carried opaquely (rmp of a `PaymentQuote` on the
315        /// single-node path, or a `MerklePaymentCandidateNode` on the merkle
316        /// path) so the one variant serves both paths; a third party
317        /// deserializes and re-verifies it against `peer`.
318        quote_artifact: Vec<u8>,
319        /// The signed commitment artifact the quote pinned (ML-DSA-signed by
320        /// the same `peer`). Together with `quote_artifact`, this is the
321        /// PORTABLE evidence: any third party re-verifies both signatures and
322        /// recomputes `quoted_key_count != commitment.key_count` without
323        /// trusting the reporter.
324        commitment: Box<crate::replication::commitment::StorageCommitment>,
325    },
326}
327
328/// Reason for audit failure.
329#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
330pub enum AuditFailureReason {
331    /// Peer timed out (no response within deadline).
332    Timeout,
333    /// Response was malformed.
334    MalformedResponse,
335    /// One or more per-key digest mismatches.
336    DigestMismatch,
337    /// Key was absent (signalled by sentinel digest).
338    KeyAbsent,
339    /// Peer explicitly rejected the audit challenge.
340    Rejected,
341}
342
343// ---------------------------------------------------------------------------
344// Peer sync tracking
345// ---------------------------------------------------------------------------
346
347/// Record of sync history with a peer, for `RepairOpportunity` tracking.
348#[derive(Debug, Clone)]
349pub struct PeerSyncRecord {
350    /// Last time we successfully synced with this peer.
351    pub last_sync: Option<Instant>,
352    /// Number of full neighbor-sync cycles completed since last sync with this
353    /// peer.
354    pub cycles_since_sync: u32,
355}
356
357impl PeerSyncRecord {
358    /// Whether this peer has had a repair opportunity (synced at least once
359    /// and at least one subsequent cycle has completed).
360    #[must_use]
361    pub fn has_repair_opportunity(&self) -> bool {
362        self.last_sync.is_some() && self.cycles_since_sync >= 1
363    }
364}
365
366// ---------------------------------------------------------------------------
367// Repair proof tracking
368// ---------------------------------------------------------------------------
369
370/// Evidence that this node has sent a replica repair hint for a key to a peer.
371#[derive(Debug, Clone)]
372struct RepairProof {
373    /// Local neighbor-sync cycle epoch when the hint was sent.
374    hinted_at_epoch: u64,
375    /// Monotonic local time when the hint was sent.
376    hinted_at: Instant,
377}
378
379/// Repair proofs for one key, tied to the close-group snapshot they were
380/// recorded against.
381#[derive(Debug, Clone)]
382struct RepairProofEntry {
383    /// Self-inclusive close group observed when these proofs were recorded.
384    close_peers: HashSet<PeerId>,
385    /// Per-peer proof metadata for peers in `close_peers`.
386    peer_proofs: HashMap<PeerId, RepairProof>,
387}
388
389impl RepairProofEntry {
390    fn new(close_peers: HashSet<PeerId>) -> Self {
391        Self {
392            close_peers,
393            peer_proofs: HashMap::new(),
394        }
395    }
396}
397
398/// Evidence that this node has sent replica repair hints for local keys.
399///
400/// The map is keyed by record key so each key retains only one close-group
401/// snapshot and at most that snapshot's peers. This bounds memory by local key
402/// count times the replication close-group size rather than by churn history.
403#[derive(Debug, Clone, Default)]
404pub struct RepairProofs {
405    /// Key-scoped repair proofs.
406    proofs_by_key: HashMap<XorName, RepairProofEntry>,
407}
408
409impl RepairProofs {
410    /// Create an empty repair-proof table.
411    #[must_use]
412    pub fn new() -> Self {
413        Self::default()
414    }
415
416    /// Record that `peer` was sent a replica repair hint for `key`.
417    ///
418    /// `current_close_peers` must be the current self-inclusive close group for
419    /// `key`. If that close group differs from the previous proof snapshot,
420    /// proofs for peers that left the close group are invalidated before
421    /// recording. Stable peers keep their proofs, while a peer that leaves and
422    /// later re-enters still needs a fresh hint.
423    pub fn record_replica_hint_sent(
424        &mut self,
425        peer: PeerId,
426        key: XorName,
427        current_close_peers: &HashSet<PeerId>,
428        hinted_at_epoch: u64,
429    ) -> bool {
430        self.insert_replica_hint_sent(
431            peer,
432            key,
433            current_close_peers,
434            hinted_at_epoch,
435            Instant::now(),
436        )
437    }
438
439    /// Record that `peer` was sent a replica repair hint at a caller-provided
440    /// time.
441    ///
442    /// This is exposed only for deterministic tests and test harnesses. Normal
443    /// production callers use [`Self::record_replica_hint_sent`] so the proof
444    /// timestamp is captured internally at send-recording time.
445    #[cfg(any(test, feature = "test-utils"))]
446    pub fn record_replica_hint_sent_at(
447        &mut self,
448        peer: PeerId,
449        key: XorName,
450        current_close_peers: &HashSet<PeerId>,
451        hinted_at_epoch: u64,
452        hinted_at: Instant,
453    ) -> bool {
454        self.insert_replica_hint_sent(peer, key, current_close_peers, hinted_at_epoch, hinted_at)
455    }
456
457    fn insert_replica_hint_sent(
458        &mut self,
459        peer: PeerId,
460        key: XorName,
461        current_close_peers: &HashSet<PeerId>,
462        hinted_at_epoch: u64,
463        hinted_at: Instant,
464    ) -> bool {
465        self.reconcile_key_close_group(&key, current_close_peers);
466
467        if !current_close_peers.contains(&peer) {
468            return false;
469        }
470
471        let entry = self
472            .proofs_by_key
473            .entry(key)
474            .or_insert_with(|| RepairProofEntry::new(current_close_peers.clone()));
475
476        if entry.peer_proofs.contains_key(&peer) {
477            return false;
478        }
479
480        entry.peer_proofs.insert(
481            peer,
482            RepairProof {
483                hinted_at_epoch,
484                hinted_at,
485            },
486        );
487        true
488    }
489
490    /// Whether this node has mature repair-hint evidence for `(peer, key)`.
491    ///
492    /// The check invalidates proofs for peers that have left the current
493    /// self-inclusive close group. A proof is mature only after at least one
494    /// later local sync-cycle epoch and the repair hint is at least
495    /// [`REPAIR_HINT_MIN_AGE`] old.
496    pub fn has_mature_replica_hint(
497        &mut self,
498        peer: &PeerId,
499        key: &XorName,
500        current_close_peers: &HashSet<PeerId>,
501        current_epoch: u64,
502        now: Instant,
503    ) -> bool {
504        self.reconcile_key_close_group(key, current_close_peers);
505
506        self.proofs_by_key
507            .get(key)
508            .and_then(|entry| entry.peer_proofs.get(peer))
509            .is_some_and(|proof| {
510                proof.hinted_at_epoch < current_epoch
511                    && now.saturating_duration_since(proof.hinted_at) >= REPAIR_HINT_MIN_AGE
512            })
513    }
514
515    /// Remove all repair proofs for a key, e.g. after local deletion.
516    pub fn remove_key(&mut self, key: &XorName) {
517        self.proofs_by_key.remove(key);
518    }
519
520    /// Remove all repair proofs for a peer, e.g. after routing-table removal.
521    pub fn remove_peer(&mut self, peer: &PeerId) {
522        self.proofs_by_key.retain(|_, entry| {
523            entry.peer_proofs.remove(peer);
524            !entry.peer_proofs.is_empty()
525        });
526    }
527
528    fn reconcile_key_close_group(&mut self, key: &XorName, current_close_peers: &HashSet<PeerId>) {
529        let should_remove = if let Some(entry) = self.proofs_by_key.get_mut(key) {
530            if entry.close_peers == *current_close_peers {
531                return;
532            }
533
534            entry.close_peers.clone_from(current_close_peers);
535            entry
536                .peer_proofs
537                .retain(|peer, _| current_close_peers.contains(peer));
538            entry.peer_proofs.is_empty()
539        } else {
540            false
541        };
542
543        if should_remove {
544            self.proofs_by_key.remove(key);
545        }
546    }
547}
548
549// ---------------------------------------------------------------------------
550// Neighbor sync cycle state
551// ---------------------------------------------------------------------------
552
553/// Result of observing a peer's bootstrap claim.
554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
555pub enum BootstrapClaimObservation {
556    /// The peer is inside its first and only bootstrap-claim grace window.
557    WithinGrace {
558        /// First time this peer claimed bootstrap status.
559        first_seen: Instant,
560    },
561    /// The peer has continuously claimed bootstrap status past the grace period.
562    PastGrace {
563        /// First time this peer claimed bootstrap status.
564        first_seen: Instant,
565    },
566    /// The peer previously stopped claiming bootstrap and then claimed it again.
567    Repeated {
568        /// First time this peer ever claimed bootstrap status.
569        first_seen: Instant,
570    },
571}
572
573/// Neighbor sync cycle state.
574///
575/// Tracks a deterministic walk through the current close-group snapshot,
576/// per-peer cooldown times, active bootstrap claims, and peers that have already
577/// used their one bootstrap-claim window.
578#[derive(Debug)]
579pub struct NeighborSyncState {
580    /// Newly-entered close peers to sync before the normal cycle cursor.
581    ///
582    /// This queue is populated from `KClosestPeersChanged` routing-table
583    /// events and is intentionally separate from `order`: priority syncs do
584    /// not restart the current round-robin cycle or discard already-scanned
585    /// peers.
586    pub priority_order: VecDeque<PeerId>,
587    /// Deterministic ordering of peers for the current cycle (snapshot).
588    pub order: Vec<PeerId>,
589    /// Current cursor position into `order`.
590    pub cursor: usize,
591    /// Per-peer last successful sync time (for cooldown).
592    pub last_sync_times: HashMap<PeerId, Instant>,
593    /// Active bootstrap claim first-seen timestamps per peer.
594    ///
595    /// Entries are removed when a peer stops claiming bootstrap. The peer
596    /// remains in `bootstrap_claim_history`, so a later claim is repeated-claim
597    /// abuse instead of a fresh grace period.
598    pub bootstrap_claims: HashMap<PeerId, Instant>,
599    /// First-ever bootstrap claim timestamp per peer.
600    ///
601    /// This is retained after active claims are cleared so each peer gets at
602    /// most one bootstrap-claim grace window. Under Sybil attack with many
603    /// distinct peer IDs claiming bootstrap, this map grows unboundedly. In
604    /// practice the trust engine limits Sybil impact before this becomes a
605    /// memory issue.
606    pub bootstrap_claim_history: HashMap<PeerId, Instant>,
607    /// Cursor used by post-cycle pruning to rotate through stored records when
608    /// the per-pass prune-confirmation budget is exhausted.
609    pub prune_cursor: usize,
610}
611
612impl NeighborSyncState {
613    /// Create a new cycle from the given close neighbors.
614    #[must_use]
615    pub fn new_cycle(close_neighbors: Vec<PeerId>) -> Self {
616        Self {
617            priority_order: VecDeque::new(),
618            order: close_neighbors,
619            cursor: 0,
620            last_sync_times: HashMap::new(),
621            bootstrap_claims: HashMap::new(),
622            bootstrap_claim_history: HashMap::new(),
623            prune_cursor: 0,
624        }
625    }
626
627    /// Observe a peer claiming bootstrap status.
628    ///
629    /// A peer receives one grace window from its first observed bootstrap claim.
630    /// If it later stops claiming bootstrap, callers should clear only the
631    /// active claim with [`Self::clear_active_bootstrap_claim`]. A subsequent
632    /// claim is then reported as [`BootstrapClaimObservation::Repeated`].
633    #[must_use]
634    pub fn observe_bootstrap_claim(
635        &mut self,
636        peer: PeerId,
637        now: Instant,
638        grace_period: Duration,
639    ) -> BootstrapClaimObservation {
640        if let Some(first_seen) = self.bootstrap_claims.get(&peer).copied() {
641            if now.duration_since(first_seen) > grace_period {
642                BootstrapClaimObservation::PastGrace { first_seen }
643            } else {
644                BootstrapClaimObservation::WithinGrace { first_seen }
645            }
646        } else if let Some(first_seen) = self.bootstrap_claim_history.get(&peer).copied() {
647            BootstrapClaimObservation::Repeated { first_seen }
648        } else {
649            self.bootstrap_claims.insert(peer, now);
650            self.bootstrap_claim_history.insert(peer, now);
651            BootstrapClaimObservation::WithinGrace { first_seen: now }
652        }
653    }
654
655    /// Clear the active bootstrap claim for a peer, retaining claim history.
656    pub fn clear_active_bootstrap_claim(&mut self, peer: &PeerId) -> bool {
657        self.bootstrap_claims.remove(peer).is_some()
658    }
659
660    /// Queue newly-entered close peers for priority sync.
661    ///
662    /// Existing queued peers are retained in their original position and
663    /// duplicates from the same routing-table churn burst are ignored.
664    pub fn queue_priority_peers<I>(&mut self, peers: I) -> usize
665    where
666        I: IntoIterator<Item = PeerId>,
667    {
668        let mut queued = 0;
669        for peer in peers {
670            if self.priority_order.contains(&peer) {
671                continue;
672            }
673            self.priority_order.push_back(peer);
674            queued += 1;
675        }
676        queued
677    }
678
679    /// Drop pending sync peers that are no longer in the close-peer set.
680    ///
681    /// Peers still in `close_peers` keep their relative position. The cursor is
682    /// adjusted so already-scanned retained peers are not selected again.
683    pub fn retain_sync_peers(&mut self, close_peers: &HashSet<PeerId>) -> usize {
684        let old_priority_len = self.priority_order.len();
685        self.priority_order
686            .retain(|peer| close_peers.contains(peer));
687
688        let old_order_len = self.order.len();
689        let old_cursor = self.cursor;
690        let mut retained_before_cursor = 0;
691        let mut retained_order = Vec::with_capacity(old_order_len);
692        for (idx, peer) in self.order.drain(..).enumerate() {
693            if close_peers.contains(&peer) {
694                if idx < old_cursor {
695                    retained_before_cursor += 1;
696                }
697                retained_order.push(peer);
698            }
699        }
700
701        self.order = retained_order;
702        self.cursor = retained_before_cursor;
703
704        (old_priority_len - self.priority_order.len()) + (old_order_len - self.order.len())
705    }
706
707    /// Remove a peer from any pending neighbor-sync state.
708    pub fn remove_peer(&mut self, peer: &PeerId) -> bool {
709        let old_priority_len = self.priority_order.len();
710        self.priority_order.retain(|queued| queued != peer);
711
712        let old_order_len = self.order.len();
713        if let Some(pos) = self.order.iter().position(|queued| queued == peer) {
714            self.order.remove(pos);
715            if pos < self.cursor {
716                self.cursor = self.cursor.saturating_sub(1);
717            }
718        }
719
720        old_priority_len != self.priority_order.len() || old_order_len != self.order.len()
721    }
722
723    /// Whether the current cycle is complete.
724    #[must_use]
725    pub fn is_cycle_complete(&self) -> bool {
726        self.priority_order.is_empty() && self.cursor >= self.order.len()
727    }
728
729    /// Whether topology-change (priority) peers are still queued.
730    ///
731    /// The neighbor-sync loop drains these back-to-back rather than parking on
732    /// the periodic tick, so a churn burst converges at round-trip speed. The
733    /// `sync_trigger` `Notify` coalesces multiple wakeups into one, so it cannot
734    /// be the sole signal for pending work — this queue is the source of truth.
735    #[must_use]
736    pub fn has_priority_peers(&self) -> bool {
737        !self.priority_order.is_empty()
738    }
739}
740
741// ---------------------------------------------------------------------------
742// Bootstrap drain state (Section 16)
743// ---------------------------------------------------------------------------
744
745/// Bootstrap drain state tracking (Section 16).
746#[derive(Debug)]
747pub struct BootstrapState {
748    /// Whether bootstrap is complete (all peer requests done, queues empty).
749    pub drained: bool,
750    /// Number of bootstrap peer requests still pending.
751    pub pending_peer_requests: usize,
752    /// Keys discovered during bootstrap that are still in the verification /
753    /// fetch pipeline.
754    pub pending_keys: HashSet<XorName>,
755    /// Peers whose bootstrap admission unit had one or more hints rejected at
756    /// capacity, mapped to the time of their **first** such rejection. Each
757    /// entry means "this source still owes us at least one re-hinted key after
758    /// the queues drain".
759    /// `check_bootstrap_drained` refuses to claim the node fully drained
760    /// while this map is non-empty: a source's presence is cleared by its
761    /// next admission cycle that completes with zero capacity rejections
762    /// (i.e. the source successfully re-delivered everything that
763    /// previously overflowed). Tracking per-source instead of a global
764    /// counter prevents one peer's rejection from being "cleared" by an
765    /// unrelated peer's clean cycle.
766    ///
767    /// The recorded time is **first-seen and never refreshed** (see
768    /// [`Self::note_capacity_rejected`]). A repeat rejection re-asserts that
769    /// the source still owes work, but it must not restart the expiry clock:
770    /// a source that keeps overflowing the queue would otherwise keep its own
771    /// record permanently fresh and wedge bootstrap open forever, which
772    /// disables auditing (Invariant 19) for the lifetime of the pressure.
773    /// First-seen semantics bound the wedge at
774    /// `ReplicationConfig::capacity_rejected_max_age` regardless of how a
775    /// source behaves.
776    ///
777    /// Entries expire once that first-rejection time is older than
778    /// `capacity_rejected_max_age` (see
779    /// `super::bootstrap::expire_capacity_rejected`): the source either
780    /// abandoned re-delivery, is overflowing us faster than it can re-deliver,
781    /// or its `PeerRemoved` cleanup raced the recording of the rejection and
782    /// left an entry no future event can clear. Expiring an entry means
783    /// bootstrap may drain without ever admitting keys that source
784    /// advertised. This is acceptable and consistent with
785    /// `update_bootstrap_after_peer_removed`, which already forfeits a
786    /// departed source's owed work wholesale — post-bootstrap periodic
787    /// neighbor sync and the audit/repair pipeline are the recovery path for
788    /// missed keys.
789    ///
790    /// Sources whose key was *displaced* by another sender reclaiming a
791    /// borrowed slot are deliberately NOT recorded here: fairness reclamation
792    /// is our decision, not a failure of theirs, and stamping the victim lets
793    /// a third party block our drain through an unrelated honest peer. The
794    /// displaced key is forfeited to the same post-bootstrap recovery path.
795    pub capacity_rejected_sources: HashMap<PeerId, Instant>,
796}
797
798impl BootstrapState {
799    /// Create initial bootstrap state.
800    #[must_use]
801    pub fn new() -> Self {
802        Self {
803            drained: false,
804            pending_peer_requests: 0,
805            pending_keys: HashSet::new(),
806            capacity_rejected_sources: HashMap::new(),
807        }
808    }
809
810    /// Record that `source` had one or more hints rejected at capacity.
811    ///
812    /// First-seen semantics: a repeat rejection re-asserts the debt but leaves
813    /// the original timestamp alone, so the expiry clock in
814    /// `super::bootstrap::expire_capacity_rejected` measures how long the
815    /// source has owed us work rather than how recently it last overflowed us.
816    /// See [`Self::capacity_rejected_sources`] for why refreshing wedges
817    /// bootstrap open.
818    ///
819    /// Returns whether this was the source's first outstanding rejection.
820    pub fn note_capacity_rejected(&mut self, source: PeerId, now: Instant) -> bool {
821        let first = !self.capacity_rejected_sources.contains_key(&source);
822        self.capacity_rejected_sources.entry(source).or_insert(now);
823        first
824    }
825
826    /// Check if bootstrap is drained.
827    ///
828    /// Only returns `true` after [`super::bootstrap::check_bootstrap_drained`] or
829    /// [`super::bootstrap::mark_bootstrap_drained`] has explicitly set the flag. A fresh
830    /// `BootstrapState` is NOT drained — the audit loop must wait until
831    /// bootstrap work has actually completed (Invariant 19).
832    #[must_use]
833    pub fn is_drained(&self) -> bool {
834        self.drained
835    }
836
837    /// Remove a key from the bootstrap pending set.
838    ///
839    /// Called when a key terminally leaves the verification/fetch pipeline
840    /// (stored, abandoned, quorum failed, etc.) so the drain check set
841    /// shrinks incrementally rather than being re-scanned in full.
842    pub fn remove_key(&mut self, key: &XorName) {
843        self.pending_keys.remove(key);
844    }
845}
846
847impl Default for BootstrapState {
848    fn default() -> Self {
849        Self::new()
850    }
851}
852
853// ---------------------------------------------------------------------------
854// Tests
855// ---------------------------------------------------------------------------
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860
861    /// Helper: build a `PeerId` from a single byte (zero-padded to 32 bytes).
862    fn peer_id_from_byte(b: u8) -> PeerId {
863        let mut bytes = [0u8; 32];
864        bytes[0] = b;
865        PeerId::from_bytes(bytes)
866    }
867
868    fn mature_hint_times() -> (Instant, Instant) {
869        let hinted_at = Instant::now();
870        let now = hinted_at
871            .checked_add(REPAIR_HINT_MIN_AGE)
872            .unwrap_or(hinted_at);
873        (hinted_at, now)
874    }
875
876    // -- FetchOrder ordering -----------------------------------------------
877
878    #[test]
879    fn fetch_order_nearest_key_has_highest_priority() {
880        let near = FetchOrder {
881            key: [1u8; 32],
882            distance: [
883                0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
884                0, 0, 0, 0,
885            ],
886        };
887
888        let far = FetchOrder {
889            key: [2u8; 32],
890            distance: [
891                0xFF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
892                0, 0, 0, 0, 0,
893            ],
894        };
895
896        // In a max-heap the "greatest" element pops first.
897        // Our reversed Ord makes smaller-distance candidates greater.
898        assert!(near > far, "nearer candidate should compare greater");
899
900        let mut heap = std::collections::BinaryHeap::new();
901        heap.push(far);
902        heap.push(near);
903
904        assert_eq!(heap.len(), 2, "heap should contain both candidates");
905
906        let first = heap.pop();
907        assert!(first.is_some(), "first pop should succeed");
908        assert_eq!(
909            first.map(|c| c.key),
910            Some(near.key),
911            "nearest key should pop first"
912        );
913
914        let second = heap.pop();
915        assert!(second.is_some(), "second pop should succeed");
916        assert_eq!(
917            second.map(|c| c.key),
918            Some(far.key),
919            "farthest key should pop second"
920        );
921    }
922
923    #[test]
924    fn fetch_order_same_distance_and_key_is_equal() {
925        let a = FetchOrder {
926            key: [1u8; 32],
927            distance: [5u8; 32],
928        };
929
930        let b = FetchOrder {
931            key: [1u8; 32],
932            distance: [5u8; 32],
933        };
934
935        assert_eq!(
936            a.cmp(&b),
937            Ordering::Equal,
938            "same distance + same key should yield Equal"
939        );
940        assert_eq!(a, b, "PartialEq must agree with Ord");
941    }
942
943    #[test]
944    fn fetch_order_same_distance_different_key_is_deterministic() {
945        let a = FetchOrder {
946            key: [1u8; 32],
947            distance: [5u8; 32],
948        };
949
950        let b = FetchOrder {
951            key: [2u8; 32],
952            distance: [5u8; 32],
953        };
954
955        assert_ne!(
956            a.cmp(&b),
957            Ordering::Equal,
958            "same distance + different key must not be Equal"
959        );
960        assert_ne!(a, b, "PartialEq must agree with Ord");
961    }
962
963    // -- PeerSyncRecord ----------------------------------------------------
964
965    #[test]
966    fn peer_sync_record_no_sync_yet() {
967        let record = PeerSyncRecord {
968            last_sync: None,
969            cycles_since_sync: 0,
970        };
971        assert!(
972            !record.has_repair_opportunity(),
973            "never-synced peer has no repair opportunity"
974        );
975    }
976
977    #[test]
978    fn peer_sync_record_synced_but_no_cycle() {
979        let record = PeerSyncRecord {
980            last_sync: Some(Instant::now()),
981            cycles_since_sync: 0,
982        };
983        assert!(
984            !record.has_repair_opportunity(),
985            "synced peer with zero subsequent cycles has no repair opportunity"
986        );
987    }
988
989    #[test]
990    fn peer_sync_record_synced_with_cycle() {
991        let record = PeerSyncRecord {
992            last_sync: Some(Instant::now()),
993            cycles_since_sync: 1,
994        };
995        assert!(
996            record.has_repair_opportunity(),
997            "synced peer with >= 1 cycle should have repair opportunity"
998        );
999    }
1000
1001    #[test]
1002    fn peer_sync_record_no_sync_many_cycles() {
1003        let record = PeerSyncRecord {
1004            last_sync: None,
1005            cycles_since_sync: 10,
1006        };
1007        assert!(
1008            !record.has_repair_opportunity(),
1009            "never-synced peer has no repair opportunity regardless of cycle count"
1010        );
1011    }
1012
1013    // -- RepairProofs --------------------------------------------------------
1014
1015    #[test]
1016    fn repair_proofs_record_sent_hint_for_close_peer() {
1017        const HINT_EPOCH: u64 = 7;
1018        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1019
1020        let key = [0xA1; 32];
1021        let peer = peer_id_from_byte(1);
1022        let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1023        let mut proofs = RepairProofs::new();
1024        let (hinted_at, now) = mature_hint_times();
1025
1026        assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1027
1028        assert!(
1029            proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1030            "old sent hint should make key auditable for that peer"
1031        );
1032    }
1033
1034    #[test]
1035    fn repair_proofs_reject_peer_outside_current_close_group() {
1036        const HINT_EPOCH: u64 = 7;
1037        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1038
1039        let key = [0xA2; 32];
1040        let peer = peer_id_from_byte(1);
1041        let close_peers = HashSet::from([peer_id_from_byte(2), peer_id_from_byte(3)]);
1042        let mut proofs = RepairProofs::new();
1043        let (hinted_at, now) = mature_hint_times();
1044
1045        assert!(!proofs.record_replica_hint_sent_at(
1046            peer,
1047            key,
1048            &close_peers,
1049            HINT_EPOCH,
1050            hinted_at,
1051        ));
1052
1053        assert!(
1054            !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1055            "peers outside current close group must not get repair proof"
1056        );
1057    }
1058
1059    #[test]
1060    fn repair_proofs_require_later_epoch() {
1061        const HINT_EPOCH: u64 = 7;
1062        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1063
1064        let key = [0xA3; 32];
1065        let peer = peer_id_from_byte(1);
1066        let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1067        let mut proofs = RepairProofs::new();
1068        let (hinted_at, now) = mature_hint_times();
1069
1070        assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1071
1072        assert!(
1073            !proofs.has_mature_replica_hint(&peer, &key, &close_peers, HINT_EPOCH, now),
1074            "same-cycle proof should not be audit-eligible"
1075        );
1076        assert!(
1077            proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1078            "old proof should mature after a later local sync-cycle epoch"
1079        );
1080    }
1081
1082    #[test]
1083    fn repair_proofs_require_min_hint_age() {
1084        const HINT_EPOCH: u64 = 7;
1085        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1086
1087        let key = [0xA8; 32];
1088        let peer = peer_id_from_byte(1);
1089        let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1090        let mut proofs = RepairProofs::new();
1091        let hinted_at = Instant::now();
1092
1093        assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at));
1094
1095        assert!(
1096            !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, hinted_at),
1097            "fresh repair hints should not be audit-eligible"
1098        );
1099        assert!(
1100            proofs.has_mature_replica_hint(
1101                &peer,
1102                &key,
1103                &close_peers,
1104                CURRENT_EPOCH,
1105                hinted_at
1106                    .checked_add(REPAIR_HINT_MIN_AGE)
1107                    .unwrap_or(hinted_at),
1108            ),
1109            "repair hints should mature once they are at least the minimum age"
1110        );
1111    }
1112
1113    #[test]
1114    fn repair_proofs_repeated_hint_does_not_reset_maturity() {
1115        const HINT_EPOCH: u64 = 7;
1116        const REPEATED_HINT_EPOCH: u64 = HINT_EPOCH + 1;
1117
1118        let key = [0xA5; 32];
1119        let peer = peer_id_from_byte(1);
1120        let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1121        let mut proofs = RepairProofs::new();
1122        let (hinted_at, now) = mature_hint_times();
1123
1124        assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1125        assert!(
1126            !proofs.record_replica_hint_sent_at(peer, key, &close_peers, REPEATED_HINT_EPOCH, now),
1127            "duplicate hint in the same close group should keep existing proof"
1128        );
1129        assert!(
1130            proofs.has_mature_replica_hint(&peer, &key, &close_peers, REPEATED_HINT_EPOCH, now),
1131            "duplicate hint must not reset an already mature proof"
1132        );
1133    }
1134
1135    #[test]
1136    fn repair_proofs_retain_stable_peers_on_close_group_change() {
1137        const HINT_EPOCH: u64 = 7;
1138        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1139
1140        let key = [0xA7; 32];
1141        let stable_peer = peer_id_from_byte(1);
1142        let departing_peer = peer_id_from_byte(2);
1143        let retained_peer = peer_id_from_byte(3);
1144        let new_peer = peer_id_from_byte(4);
1145        let old_group = HashSet::from([stable_peer, departing_peer, retained_peer]);
1146        let changed_group = HashSet::from([stable_peer, retained_peer, new_peer]);
1147        let mut proofs = RepairProofs::new();
1148        let (hinted_at, now) = mature_hint_times();
1149
1150        assert!(proofs.record_replica_hint_sent_at(
1151            stable_peer,
1152            key,
1153            &old_group,
1154            HINT_EPOCH,
1155            hinted_at,
1156        ));
1157        assert!(proofs.record_replica_hint_sent_at(
1158            departing_peer,
1159            key,
1160            &old_group,
1161            HINT_EPOCH,
1162            hinted_at,
1163        ));
1164
1165        assert!(
1166            proofs.has_mature_replica_hint(&stable_peer, &key, &changed_group, CURRENT_EPOCH, now),
1167            "stable peers should keep mature repair proofs across unrelated close-group churn"
1168        );
1169        assert!(
1170            !proofs.has_mature_replica_hint(
1171                &departing_peer,
1172                &key,
1173                &changed_group,
1174                CURRENT_EPOCH,
1175                now,
1176            ),
1177            "peers that left the close group should lose repair proofs"
1178        );
1179        assert!(
1180            !proofs.has_mature_replica_hint(&new_peer, &key, &changed_group, CURRENT_EPOCH, now),
1181            "new close-group peers need their own repair hint before auditing"
1182        );
1183    }
1184
1185    #[test]
1186    fn repair_proofs_evicted_peer_reentry_requires_fresh_hint() {
1187        const FIRST_HINT_EPOCH: u64 = 7;
1188        const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1189        const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1190
1191        let key = [0xA3; 32];
1192        let returning_peer = peer_id_from_byte(1);
1193        let new_peer = peer_id_from_byte(4);
1194        let old_group = HashSet::from([returning_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1195        let changed_group = HashSet::from([new_peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1196        let mut proofs = RepairProofs::new();
1197        let (hinted_at, now) = mature_hint_times();
1198
1199        assert!(proofs.record_replica_hint_sent_at(
1200            returning_peer,
1201            key,
1202            &old_group,
1203            FIRST_HINT_EPOCH,
1204            hinted_at,
1205        ));
1206
1207        assert!(
1208            !proofs.has_mature_replica_hint(
1209                &new_peer,
1210                &key,
1211                &changed_group,
1212                SECOND_HINT_EPOCH,
1213                now
1214            ),
1215            "new close-group peer should not inherit another peer's repair proof"
1216        );
1217        assert!(
1218            !proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1219            "a peer that re-enters must receive a fresh repair hint"
1220        );
1221
1222        assert!(proofs.record_replica_hint_sent_at(
1223            returning_peer,
1224            key,
1225            &old_group,
1226            SECOND_HINT_EPOCH,
1227            hinted_at,
1228        ));
1229        assert!(
1230            proofs.has_mature_replica_hint(&returning_peer, &key, &old_group, CURRENT_EPOCH, now),
1231            "fresh repair hint after re-entry should be eligible once mature"
1232        );
1233    }
1234
1235    #[test]
1236    fn repair_proofs_remove_peer_requires_fresh_hint_after_reentry() {
1237        const FIRST_HINT_EPOCH: u64 = 7;
1238        const SECOND_HINT_EPOCH: u64 = FIRST_HINT_EPOCH + 1;
1239        const CURRENT_EPOCH: u64 = SECOND_HINT_EPOCH + 1;
1240
1241        let key = [0xA6; 32];
1242        let peer = peer_id_from_byte(1);
1243        let close_peers = HashSet::from([peer, peer_id_from_byte(2), peer_id_from_byte(3)]);
1244        let mut proofs = RepairProofs::new();
1245        let (hinted_at, now) = mature_hint_times();
1246
1247        assert!(proofs.record_replica_hint_sent_at(
1248            peer,
1249            key,
1250            &close_peers,
1251            FIRST_HINT_EPOCH,
1252            hinted_at,
1253        ));
1254        proofs.remove_peer(&peer);
1255
1256        assert!(
1257            !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1258            "routing-table removal should clear proof even if peer re-enters same close group"
1259        );
1260
1261        assert!(proofs.record_replica_hint_sent_at(
1262            peer,
1263            key,
1264            &close_peers,
1265            SECOND_HINT_EPOCH,
1266            hinted_at,
1267        ));
1268        assert!(
1269            proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1270            "fresh hint after re-entry should become eligible after a later epoch"
1271        );
1272    }
1273
1274    #[test]
1275    fn repair_proofs_remove_key_clears_all_peer_entries() {
1276        const HINT_EPOCH: u64 = 7;
1277        const CURRENT_EPOCH: u64 = HINT_EPOCH + 1;
1278
1279        let key = [0xA4; 32];
1280        let peer = peer_id_from_byte(1);
1281        let close_peers = HashSet::from([peer]);
1282        let mut proofs = RepairProofs::new();
1283        let (hinted_at, now) = mature_hint_times();
1284
1285        assert!(proofs.record_replica_hint_sent_at(peer, key, &close_peers, HINT_EPOCH, hinted_at,));
1286        proofs.remove_key(&key);
1287
1288        assert!(
1289            !proofs.has_mature_replica_hint(&peer, &key, &close_peers, CURRENT_EPOCH, now),
1290            "deleted local key should not retain repair proof entries"
1291        );
1292    }
1293
1294    // -- NeighborSyncState -------------------------------------------------
1295
1296    #[test]
1297    fn neighbor_sync_empty_cycle_is_immediately_complete() {
1298        let state = NeighborSyncState::new_cycle(vec![]);
1299        assert!(
1300            state.is_cycle_complete(),
1301            "empty neighbor list means cycle is complete"
1302        );
1303    }
1304
1305    #[test]
1306    fn neighbor_sync_new_cycle_not_complete() {
1307        let peers = vec![peer_id_from_byte(1), peer_id_from_byte(2)];
1308        let state = NeighborSyncState::new_cycle(peers);
1309        assert!(
1310            !state.is_cycle_complete(),
1311            "fresh cycle with peers should not be complete"
1312        );
1313    }
1314
1315    #[test]
1316    fn neighbor_sync_cycle_completes_when_cursor_reaches_end() {
1317        let peers = vec![
1318            peer_id_from_byte(1),
1319            peer_id_from_byte(2),
1320            peer_id_from_byte(3),
1321        ];
1322        let mut state = NeighborSyncState::new_cycle(peers);
1323
1324        // Simulate stepping through the cycle.
1325        state.cursor = 2;
1326        assert!(
1327            !state.is_cycle_complete(),
1328            "cursor at len-1 should not be complete"
1329        );
1330
1331        state.cursor = 3;
1332        assert!(
1333            state.is_cycle_complete(),
1334            "cursor at len should be complete"
1335        );
1336    }
1337
1338    #[test]
1339    fn neighbor_sync_cursor_past_end_is_still_complete() {
1340        let peers = vec![peer_id_from_byte(1)];
1341        let mut state = NeighborSyncState::new_cycle(peers);
1342        state.cursor = 5;
1343        assert!(
1344            state.is_cycle_complete(),
1345            "cursor past end should still report complete"
1346        );
1347    }
1348
1349    #[test]
1350    fn neighbor_sync_priority_queue_blocks_cycle_completion() {
1351        let peer = peer_id_from_byte(2);
1352        let mut state = NeighborSyncState::new_cycle(Vec::new());
1353
1354        assert!(state.is_cycle_complete());
1355        assert_eq!(state.queue_priority_peers([peer]), 1);
1356        assert!(
1357            !state.is_cycle_complete(),
1358            "pending priority peers must sync before the cycle completes"
1359        );
1360    }
1361
1362    #[test]
1363    fn neighbor_sync_priority_queue_deduplicates_peers() {
1364        let peer = peer_id_from_byte(3);
1365        let mut state = NeighborSyncState::new_cycle(Vec::new());
1366
1367        assert_eq!(state.queue_priority_peers([peer, peer]), 1);
1368        assert_eq!(state.priority_order.len(), 1);
1369    }
1370
1371    #[test]
1372    fn neighbor_sync_has_priority_peers_tracks_queue_and_drain() {
1373        // The neighbor-sync loop drains the priority queue back-to-back and only
1374        // parks once `has_priority_peers` reports false. Draining removes each
1375        // queued peer (as `select_next_sync_peer` does via `remove_peer`), so the
1376        // signal must flip to false once every entrant is consumed — this is the
1377        // loop's termination guarantee.
1378        let first = peer_id_from_byte(6);
1379        let second = peer_id_from_byte(7);
1380        let mut state = NeighborSyncState::new_cycle(Vec::new());
1381        assert!(!state.has_priority_peers());
1382
1383        assert_eq!(state.queue_priority_peers([first, second]), 2);
1384        assert!(state.has_priority_peers());
1385
1386        assert!(state.remove_peer(&first));
1387        assert!(state.has_priority_peers(), "one entrant still pending");
1388
1389        assert!(state.remove_peer(&second));
1390        assert!(
1391            !state.has_priority_peers(),
1392            "drained queue must let the loop park"
1393        );
1394    }
1395
1396    #[test]
1397    fn neighbor_sync_remove_peer_clears_order_and_priority_queue() {
1398        let peer = peer_id_from_byte(4);
1399        let retained = peer_id_from_byte(5);
1400        let mut state = NeighborSyncState::new_cycle(vec![peer, retained]);
1401        assert_eq!(state.queue_priority_peers([peer]), 1);
1402        state.cursor = 1;
1403
1404        assert!(state.remove_peer(&peer));
1405
1406        assert!(!state.order.contains(&peer));
1407        assert!(!state.priority_order.contains(&peer));
1408        assert_eq!(state.order, vec![retained]);
1409        assert_eq!(state.cursor, 0);
1410    }
1411
1412    #[test]
1413    fn neighbor_sync_retain_sync_peers_prunes_only_departed_peers() {
1414        let already_scanned = peer_id_from_byte(1);
1415        let stable_scanned = peer_id_from_byte(2);
1416        let departed_priority = peer_id_from_byte(3);
1417        let stable_unscanned = peer_id_from_byte(4);
1418        let stable_priority = peer_id_from_byte(5);
1419        let mut state = NeighborSyncState::new_cycle(vec![
1420            already_scanned,
1421            stable_scanned,
1422            departed_priority,
1423            stable_unscanned,
1424        ]);
1425        assert_eq!(
1426            state.queue_priority_peers([departed_priority, stable_priority]),
1427            2
1428        );
1429        state.cursor = 2;
1430        let close_peers = HashSet::from([stable_scanned, stable_unscanned, stable_priority]);
1431
1432        let removed = state.retain_sync_peers(&close_peers);
1433
1434        assert_eq!(removed, 3);
1435        assert_eq!(state.order, vec![stable_scanned, stable_unscanned]);
1436        assert_eq!(
1437            state.priority_order.iter().copied().collect::<Vec<_>>(),
1438            vec![stable_priority]
1439        );
1440        assert_eq!(
1441            state.cursor, 1,
1442            "stable peer scanned before churn must not be selected again"
1443        );
1444    }
1445
1446    #[test]
1447    fn bootstrap_claim_history_prevents_second_grace_window() {
1448        let peer = peer_id_from_byte(9);
1449        let mut state = NeighborSyncState::new_cycle(vec![peer]);
1450        let first_seen = Instant::now();
1451        let grace = Duration::from_secs(60);
1452
1453        assert_eq!(
1454            state.observe_bootstrap_claim(peer, first_seen, grace),
1455            BootstrapClaimObservation::WithinGrace { first_seen }
1456        );
1457        assert!(state.clear_active_bootstrap_claim(&peer));
1458        assert!(!state.bootstrap_claims.contains_key(&peer));
1459        assert!(state.bootstrap_claim_history.contains_key(&peer));
1460
1461        assert_eq!(
1462            state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(1), grace),
1463            BootstrapClaimObservation::Repeated { first_seen }
1464        );
1465        assert!(
1466            !state.bootstrap_claims.contains_key(&peer),
1467            "repeated claims must not recreate an active grace window"
1468        );
1469        assert_eq!(
1470            state.observe_bootstrap_claim(peer, first_seen + Duration::from_secs(2), grace),
1471            BootstrapClaimObservation::Repeated { first_seen }
1472        );
1473    }
1474
1475    #[test]
1476    fn bootstrap_claim_active_window_reports_past_grace() {
1477        let peer = peer_id_from_byte(10);
1478        let mut state = NeighborSyncState::new_cycle(vec![peer]);
1479        let first_seen = Instant::now();
1480        let grace = Duration::from_secs(60);
1481
1482        let _ = state.observe_bootstrap_claim(peer, first_seen, grace);
1483
1484        assert_eq!(
1485            state.observe_bootstrap_claim(peer, first_seen + grace + Duration::from_secs(1), grace),
1486            BootstrapClaimObservation::PastGrace { first_seen }
1487        );
1488    }
1489
1490    // -- BootstrapState ----------------------------------------------------
1491
1492    #[test]
1493    fn bootstrap_state_initial_not_drained() {
1494        // A freshly created state must NOT report drained — the bootstrap
1495        // sync task has not started yet (Invariant 19 race prevention).
1496        let state = BootstrapState::new();
1497        assert!(
1498            !state.is_drained(),
1499            "initial state must not be drained before bootstrap begins"
1500        );
1501    }
1502
1503    #[test]
1504    fn bootstrap_state_pending_requests_block_drain() {
1505        let mut state = BootstrapState::new();
1506        state.pending_peer_requests = 3;
1507        assert!(
1508            !state.is_drained(),
1509            "pending peer requests should block drain"
1510        );
1511    }
1512
1513    #[test]
1514    fn bootstrap_state_pending_keys_block_drain() {
1515        let mut state = BootstrapState::new();
1516        state.pending_keys.insert([42u8; 32]);
1517        assert!(!state.is_drained(), "pending keys should block drain");
1518    }
1519
1520    #[test]
1521    fn bootstrap_state_explicit_drained_overrides() {
1522        let mut state = BootstrapState::new();
1523        state.pending_peer_requests = 5;
1524        state.pending_keys.insert([99u8; 32]);
1525        state.drained = true;
1526        assert!(
1527            state.is_drained(),
1528            "explicit drained flag should override pending counts"
1529        );
1530    }
1531
1532    #[test]
1533    fn bootstrap_state_requires_explicit_drain() {
1534        let mut state = BootstrapState::new();
1535        state.pending_peer_requests = 2;
1536        state.pending_keys.insert([1u8; 32]);
1537
1538        // Simulate completing work — but without explicit drain flag.
1539        state.pending_peer_requests = 0;
1540        state.pending_keys.clear();
1541
1542        assert!(
1543            !state.is_drained(),
1544            "clearing counters alone must not drain — requires check_bootstrap_drained"
1545        );
1546
1547        // Explicit drain (set by check_bootstrap_drained or mark_bootstrap_drained).
1548        state.drained = true;
1549        assert!(state.is_drained(), "explicit flag should drain");
1550    }
1551
1552    #[test]
1553    fn bootstrap_state_default_matches_new() {
1554        let from_new = BootstrapState::new();
1555        let from_default = BootstrapState::default();
1556
1557        assert_eq!(from_new.drained, from_default.drained);
1558        assert_eq!(
1559            from_new.pending_peer_requests,
1560            from_default.pending_peer_requests
1561        );
1562        assert_eq!(from_new.pending_keys, from_default.pending_keys);
1563    }
1564
1565    // -- Scenario tests -------------------------------------------------------
1566
1567    /// #13: Bootstrap not drained while `pending_keys` overlap with the
1568    /// pipeline. Keys must be removed from `pending_keys` for drain to occur.
1569    #[test]
1570    fn bootstrap_drain_requires_empty_pending_keys() {
1571        let key_a: XorName = [0xA0; 32];
1572        let key_b: XorName = [0xB0; 32];
1573        let key_c: XorName = [0xC0; 32];
1574
1575        let mut state = BootstrapState::new();
1576        state.pending_peer_requests = 0; // requests already done
1577        state.pending_keys = std::iter::once(key_a)
1578            .chain(std::iter::once(key_b))
1579            .chain(std::iter::once(key_c))
1580            .collect();
1581
1582        assert!(
1583            !state.is_drained(),
1584            "should NOT be drained while pending_keys still has entries"
1585        );
1586
1587        // Simulate pipeline processing — remove one key at a time.
1588        state.pending_keys.remove(&key_a);
1589        assert!(!state.is_drained(), "still not drained with 2 pending keys");
1590
1591        state.pending_keys.remove(&key_b);
1592        assert!(!state.is_drained(), "still not drained with 1 pending key");
1593
1594        state.pending_keys.remove(&key_c);
1595        assert!(
1596            !state.is_drained(),
1597            "removing all keys is necessary but not sufficient — needs explicit drain"
1598        );
1599
1600        // Simulate check_bootstrap_drained setting the flag.
1601        state.drained = true;
1602        assert!(state.is_drained(), "explicit drain flag should finalize");
1603    }
1604
1605    /// Verify that the FSM terminal states are distinguishable and document
1606    /// which variants are logically terminal (no outgoing transitions).
1607    #[test]
1608    fn verification_state_terminal_variants() {
1609        let terminal_states = [
1610            VerificationState::QuorumAbandoned,
1611            VerificationState::FetchAbandoned,
1612            VerificationState::Stored,
1613            VerificationState::Idle,
1614        ];
1615
1616        // All terminal states must be distinct from each other.
1617        for (i, a) in terminal_states.iter().enumerate() {
1618            for (j, b) in terminal_states.iter().enumerate() {
1619                if i != j {
1620                    assert_ne!(
1621                        a, b,
1622                        "terminal states at indices {i} and {j} must be distinct"
1623                    );
1624                }
1625            }
1626        }
1627
1628        // Terminal states must be distinct from all non-terminal states.
1629        let non_terminal_states = [
1630            VerificationState::OfferReceived,
1631            VerificationState::PendingVerify,
1632            VerificationState::QuorumVerified,
1633            VerificationState::PaidListVerified,
1634            VerificationState::QueuedForFetch,
1635            VerificationState::Fetching,
1636            VerificationState::FetchRetryable,
1637            VerificationState::QuorumFailed,
1638            VerificationState::QuorumInconclusive,
1639        ];
1640
1641        for terminal in &terminal_states {
1642            for non_terminal in &non_terminal_states {
1643                assert_ne!(
1644                    terminal, non_terminal,
1645                    "terminal state {terminal:?} must not equal non-terminal state {non_terminal:?}"
1646                );
1647            }
1648        }
1649    }
1650
1651    /// `has_repair_opportunity` requires BOTH a previous sync AND at least
1652    /// one subsequent cycle.
1653    #[test]
1654    fn repair_opportunity_requires_both_sync_and_cycle() {
1655        // last_sync = Some, cycles_since_sync = 0 → false (synced but no cycle yet)
1656        let synced_no_cycle = PeerSyncRecord {
1657            last_sync: Some(
1658                Instant::now()
1659                    .checked_sub(std::time::Duration::from_secs(2))
1660                    .unwrap_or_else(Instant::now),
1661            ),
1662            cycles_since_sync: 0,
1663        };
1664        assert!(
1665            !synced_no_cycle.has_repair_opportunity(),
1666            "synced with zero subsequent cycles should NOT have repair opportunity"
1667        );
1668
1669        // last_sync = None, cycles_since_sync = 5 → false (never synced)
1670        let never_synced = PeerSyncRecord {
1671            last_sync: None,
1672            cycles_since_sync: 5,
1673        };
1674        assert!(
1675            !never_synced.has_repair_opportunity(),
1676            "never-synced peer should NOT have repair opportunity regardless of cycles"
1677        );
1678
1679        // last_sync = Some, cycles_since_sync = 1 → true
1680        let ready = PeerSyncRecord {
1681            last_sync: Some(
1682                Instant::now()
1683                    .checked_sub(std::time::Duration::from_secs(5))
1684                    .unwrap_or_else(Instant::now),
1685            ),
1686            cycles_since_sync: 1,
1687        };
1688        assert!(
1689            ready.has_repair_opportunity(),
1690            "synced peer with >= 1 cycle SHOULD have repair opportunity"
1691        );
1692    }
1693}