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