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