Skip to main content

ant_node/replication/
scheduling.rs

1//! Scheduling and queue management (Section 12).
2//!
3//! Manages `PendingVerify`, `FetchQueue`, and `InFlightFetch` queues for the
4//! replication pipeline. Each key progresses through at most one queue at a
5//! time, with strict dedup across all three stages.
6
7use std::cmp::Ordering;
8use std::collections::{BTreeMap, BinaryHeap, HashMap, HashSet, VecDeque};
9use std::time::{Duration, Instant};
10
11use crate::logging::debug;
12
13use crate::ant_protocol::XorName;
14use crate::replication::config::VERIFICATION_RETRY_BACKOFF_MAX;
15use crate::replication::types::{
16    FetchCandidate, FetchOrder, FetchPayload, VerificationEntry, VerificationState,
17};
18use saorsa_core::identity::PeerId;
19
20/// Result of deferring a pending key to a later verification round.
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct DeferralOutcome {
23    /// Consecutive unresolved rounds for this entry, counting this one. `1` is
24    /// the entry's first failure, which is the one worth reporting.
25    pub attempt: u32,
26    /// Delay applied before this key is eligible for another round.
27    pub retry_after: Duration,
28}
29
30/// Exponential backoff for an unresolved pending key.
31///
32/// `attempt` is 1-based, so the first deferral waits `base` and each subsequent
33/// one doubles, saturating at [`VERIFICATION_RETRY_BACKOFF_MAX`]. The shift is
34/// bounded before it is applied so a long-lived entry cannot overflow into a
35/// short delay.
36fn backoff_delay(base: Duration, attempt: u32) -> Duration {
37    // Clamp the exponent before shifting: `1u32 << 32` is undefined behaviour
38    // territory in release builds, and any base doubled 31 times has long since
39    // saturated the cap anyway.
40    let exponent = attempt.saturating_sub(1).min(31);
41    base.saturating_mul(1u32 << exponent)
42        .min(VERIFICATION_RETRY_BACKOFF_MAX)
43        // Never retry faster than the caller asked for, even if a config sets a
44        // base above the cap.
45        .max(base)
46}
47
48/// Global hard upper bound on the number of keys held in `pending_verify`.
49///
50/// Without a bound, a peer in the local routing table can flood
51/// `NeighborSyncRequest` messages (each capped only by
52/// `MAX_REPLICATION_MESSAGE_SIZE` ≈ 10 MiB, i.e. ~320k 32-byte hints per
53/// message) and grow this map without limit, exhausting node memory and
54/// driving a self-amplifying storm of outbound verification requests.
55///
56/// `131_072` entries is far above any legitimate aggregate need while
57/// bounding worst-case memory to a few tens of MiB (each `VerificationEntry`
58/// is on the order of a few hundred bytes; its sub-collections are populated
59/// only from close-group-sized verification evidence, never from attacker
60/// hint volume).
61///
62/// The global cap is paired with elastic max-min sender accounting: one peer
63/// may borrow otherwise-unused capacity for a large bootstrap snapshot, but a
64/// later under-represented sender reclaims slots from an over-represented one.
65/// Verification service is round-robin across capacity owners, so arrival
66/// order cannot turn this memory circuit breaker into sender starvation.
67pub const MAX_PENDING_VERIFY: usize = 131_072;
68
69/// Hard upper bound on the number of keys held in `fetch_queue`.
70///
71/// `fetch_queue` is fed only by `enqueue_fetch`, which is reached **after** a
72/// key passes quorum verification in `run_verification_cycle` — attacker junk
73/// keys (no real holder) fail quorum and never reach this stage, so the
74/// bounded-and-fair `pending_verify` upstream is the primary protection. This
75/// global cap remains as a defence-in-depth memory backstop and is dropped
76/// (consistent with the existing cross-queue-dedup no-op contract of
77/// `enqueue_fetch`) when full.
78pub const MAX_FETCH_QUEUE: usize = 131_072;
79
80/// Maximum distinct hint sources retained per pending key.
81///
82/// [`MAX_PENDING_VERIFY`] bounds unique *keys*, not the peers remembered
83/// against each one. Duplicate advertisements take the `AlreadyPresent` path,
84/// which merges the advertiser into two per-key sets plus the reverse index at
85/// no capacity cost — and re-advertising an already-pending key is the cheapest
86/// path through admission, since `is_relevant` short-circuits on it without
87/// even a routing-table lookup. Left unbounded, N routing-table peers
88/// re-advertising a full queue costs `N * MAX_PENDING_VERIFY` associations
89/// against a cap that only ever counted keys.
90///
91/// Sized at the close-group width: source diversity is only useful as fetch
92/// candidates and corroboration weight, and both saturate well before this.
93/// See [`ReplicationQueues::add_pending_verify`] for the retention policy that
94/// decides *which* sources survive the cap.
95pub const MAX_HINT_SOURCES_PER_KEY: usize = 8;
96
97/// Outcome of [`ReplicationQueues::add_pending_verify`].
98///
99/// Distinguishes "the key is already being handled" from "the key was
100/// silently dropped due to a queue capacity bound". Bootstrap drain
101/// accounting and source-side retry logic MUST treat `CapacityRejected` as
102/// outstanding work; treating it like a dedup hit was the silent-drop
103/// regression introduced when the queues first became bounded.
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105pub enum AdmissionResult {
106    /// New entry inserted into `pending_verify`.
107    Admitted,
108    /// Key was already in some pipeline stage; the existing entry is left
109    /// in place. No retry required.
110    AlreadyPresent,
111    /// Global capacity bound rejected the entry. The caller
112    /// MUST treat this as work still to do (not as silently completed).
113    CapacityRejected,
114}
115
116impl AdmissionResult {
117    /// `true` only for [`AdmissionResult::Admitted`]. Preserves call sites
118    /// that only want to know "did the insert happen".
119    #[must_use]
120    pub fn admitted(self) -> bool {
121        matches!(self, Self::Admitted)
122    }
123}
124
125/// An existing pending hint displaced to restore sender fairness.
126///
127/// Bootstrap accounting uses this to keep the displaced source's work
128/// outstanding until that source re-advertises it.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub(crate) struct CapacityDisplacement {
131    /// Key removed from `pending_verify`.
132    pub(crate) key: XorName,
133    /// Authenticated source whose borrowed capacity slot was reclaimed.
134    pub(crate) owner: PeerId,
135}
136
137/// Lazy heap entry for choosing the least valuable reclaimable hint owned by
138/// an over-represented sender.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140struct EvictionOrder {
141    key: XorName,
142    source_count: usize,
143    paid_only: bool,
144    created_at: Instant,
145}
146
147impl Ord for EvictionOrder {
148    fn cmp(&self, other: &Self) -> Ordering {
149        // BinaryHeap pops the greatest item. Prefer singleton, paid-only,
150        // newest entries for eviction, with a deterministic key tie-break.
151        other
152            .source_count
153            .cmp(&self.source_count)
154            .then_with(|| self.paid_only.cmp(&other.paid_only))
155            .then_with(|| self.created_at.cmp(&other.created_at))
156            .then_with(|| self.key.cmp(&other.key))
157    }
158}
159
160impl PartialOrd for EvictionOrder {
161    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
162        Some(self.cmp(other))
163    }
164}
165
166// ---------------------------------------------------------------------------
167// In-flight entry
168// ---------------------------------------------------------------------------
169
170/// An in-flight fetch entry tracking an active download.
171#[derive(Debug, Clone)]
172pub struct InFlightEntry {
173    /// The key being fetched.
174    pub key: XorName,
175    /// The peer we are currently fetching from.
176    pub source: PeerId,
177    /// When the fetch started.
178    pub started_at: Instant,
179    /// All verified sources for this key.
180    pub all_sources: Vec<PeerId>,
181    /// Sources already attempted (failed or in progress).
182    pub tried: HashSet<PeerId>,
183    /// Pending-verification entry to restore if all fetch sources fail.
184    pub retry_verification: Option<VerificationEntry>,
185}
186
187// ---------------------------------------------------------------------------
188// Central queue manager
189// ---------------------------------------------------------------------------
190
191/// Central queue manager for the replication pipeline.
192///
193/// Maintains three stages of the pipeline with global dedup:
194/// 1. **`PendingVerify`** -- keys awaiting quorum verification.
195/// 2. **`FetchQueue`** -- quorum-passed keys waiting for a fetch slot.
196/// 3. **`InFlightFetch`** -- keys actively being downloaded.
197///
198/// A key promoted from `PendingVerify` to fetch keeps a reserved verification
199/// slot until it either stores successfully or returns to `PendingVerify`.
200/// That reservation prevents unrelated new hints from stealing the capacity
201/// needed to retry verification after every fetch source fails.
202pub struct ReplicationQueues {
203    /// Keys awaiting quorum result (dedup by key).
204    ///
205    /// Capacity-bounded by [`MAX_PENDING_VERIFY`]. At capacity, max-min sender
206    /// accounting reclaims borrowed entries before rejecting new work.
207    pending_verify: HashMap<XorName, VerificationEntry>,
208    /// Nearest-first priority order over the keys in `fetch_payloads`.
209    ///
210    /// Holds ordering data only: every entry has exactly one matching
211    /// `fetch_payloads` entry, and vice versa. Splitting the mutable half of a
212    /// queued fetch out into `fetch_payloads` keeps this heap's ordering
213    /// immutable for as long as a key is queued, so a source merge never has
214    /// to rebuild it.
215    fetch_queue: BinaryHeap<FetchOrder>,
216    /// The mutable half of each queued fetch, keyed for O(1) lookup.
217    ///
218    /// Doubles as the `fetch_queue` membership index (Rule 8 cross-queue
219    /// dedup) and as the authoritative queue length.
220    ///
221    /// Capacity-bounded by [`MAX_FETCH_QUEUE`]: enqueues are dropped once
222    /// full, preventing unbounded growth under a network hint flood.
223    fetch_payloads: HashMap<XorName, FetchPayload>,
224    /// Active downloads keyed by `XorName`.
225    in_flight_fetch: HashMap<XorName, InFlightEntry>,
226    /// Reverse index for removing a departed peer from every pending hint
227    /// without scanning the entire pending table.
228    pending_keys_by_source: HashMap<PeerId, HashSet<XorName>>,
229    /// Capacity owner for every retry-capable key, retained while the key
230    /// moves through pending, fetch-queued, and in-flight states.
231    capacity_owner_by_key: HashMap<XorName, PeerId>,
232    /// Pending keys charged to each authenticated source.
233    pending_keys_by_owner: HashMap<PeerId, HashSet<XorName>>,
234    /// Lazy per-owner victim heaps used when borrowed capacity is reclaimed.
235    eviction_candidates_by_owner: HashMap<PeerId, BinaryHeap<EvictionOrder>>,
236    /// Verified fetch retries restored to pending verification. These entries
237    /// are not eligible for fairness eviction.
238    protected_pending_keys: HashSet<XorName>,
239    /// Last owner selected by the fair verification scheduler.
240    last_served_owner: Option<PeerId>,
241    /// Fairness evictions accumulated since the caller last drained them.
242    capacity_displacements: Vec<CapacityDisplacement>,
243    /// Owners proven unable to reclaim a slot at the current queue state.
244    /// Cleared by every capacity-changing mutation, this avoids repeating the
245    /// max-min calculation for every key in an oversized rejected suffix.
246    fair_rejection_cache: HashSet<PeerId>,
247    /// Pending-verification capacity slots reserved by retry-capable keys that
248    /// have left `pending_verify` for `fetch_queue` / `in_flight_fetch`.
249    retry_reserved_slots: usize,
250    /// The same reservations, attributed to the capacity owner that holds them.
251    ///
252    /// A promoted key leaves `pending_keys_by_owner` but keeps its reservation
253    /// against the global pool. Without this attribution the reservation is
254    /// subtracted from everyone's share while being charged to no one, so an
255    /// owner with many in-flight retries reads as under-loaded to
256    /// [`Self::reclaim_borrowed_slot`] and wins a larger allocation than it has
257    /// earned — a skew that grows with exactly how much work it already holds.
258    retry_reserved_by_owner: HashMap<PeerId, usize>,
259}
260
261impl Default for ReplicationQueues {
262    fn default() -> Self {
263        Self::new()
264    }
265}
266
267impl ReplicationQueues {
268    /// Create new empty queues.
269    #[must_use]
270    pub fn new() -> Self {
271        Self {
272            pending_verify: HashMap::new(),
273            fetch_queue: BinaryHeap::new(),
274            fetch_payloads: HashMap::new(),
275            in_flight_fetch: HashMap::new(),
276            pending_keys_by_source: HashMap::new(),
277            capacity_owner_by_key: HashMap::new(),
278            pending_keys_by_owner: HashMap::new(),
279            eviction_candidates_by_owner: HashMap::new(),
280            protected_pending_keys: HashSet::new(),
281            last_served_owner: None,
282            capacity_displacements: Vec::new(),
283            fair_rejection_cache: HashSet::new(),
284            retry_reserved_slots: 0,
285            retry_reserved_by_owner: HashMap::new(),
286        }
287    }
288
289    // -----------------------------------------------------------------------
290    // PendingVerify
291    // -----------------------------------------------------------------------
292
293    /// Add a key to pending verification if not already present in any queue.
294    ///
295    /// Returns an [`AdmissionResult`] distinguishing the three outcomes:
296    /// * `Admitted` — newly inserted.
297    /// * `AlreadyPresent` — Rule 8 cross-queue dedup. For a key still in
298    ///   `pending_verify`, the new advertiser is merged into its source set.
299    /// * `CapacityRejected` — the global bound was hit and no over-represented
300    ///   sender had reclaimable borrowed work; the incoming work is
301    ///   genuinely lost and the caller (e.g. bootstrap drain accounting,
302    ///   source-side retry) MUST treat this as still-outstanding work, not as
303    ///   "done". Without this distinction a bootstrap snapshot whose hints
304    ///   are capacity-rejected would silently mark itself drained.
305    pub fn add_pending_verify(
306        &mut self,
307        key: XorName,
308        entry: VerificationEntry,
309    ) -> AdmissionResult {
310        if self.pending_verify.contains_key(&key) {
311            // Read before the mutable borrow: the capacity owner must survive
312            // any displacement, since `insert_pending_owned_unchecked` requires
313            // it to remain a live hint source.
314            let owner = self.capacity_owner_by_key.get(&key).copied();
315            let Some(existing) = self.pending_verify.get_mut(&key) else {
316                debug_assert!(false, "pending entry vanished between lookups");
317                return AdmissionResult::AlreadyPresent;
318            };
319            let mut changed = false;
320
321            // Replica claimants first. They are the only sources that assert
322            // possession, so they are the ones worth a slot: a paid-only
323            // advertiser adds corroboration weight but can never be fetched
324            // from, and yields its place when the cap binds.
325            for source in entry.replica_hint_sources.iter().copied() {
326                if existing.replica_hint_sources.contains(&source) {
327                    continue;
328                }
329                if existing.hint_sources.len() >= MAX_HINT_SOURCES_PER_KEY
330                    && !Self::displace_paid_only_source(
331                        existing,
332                        &mut self.pending_keys_by_source,
333                        &key,
334                        owner,
335                    )
336                {
337                    // Cap reached with nothing droppable: every slot is held by
338                    // a replica claimant or the capacity owner.
339                    break;
340                }
341                existing.replica_hint_sources.insert(source);
342                existing.hint_sources.insert(source);
343                self.pending_keys_by_source
344                    .entry(source)
345                    .or_default()
346                    .insert(key);
347                changed = true;
348            }
349
350            // Then paid-only advertisers, strictly while under the cap. Losing
351            // one costs a unit of corroboration weight — never a fetch
352            // candidate, and never the key itself.
353            for source in entry.hint_sources {
354                if existing.hint_sources.len() >= MAX_HINT_SOURCES_PER_KEY {
355                    break;
356                }
357                if existing.hint_sources.insert(source) {
358                    self.pending_keys_by_source
359                        .entry(source)
360                        .or_default()
361                        .insert(key);
362                    changed = true;
363                }
364            }
365
366            // Any change to `hint_sources` invalidates the key's queued
367            // eviction candidate, whose `source_count` snapshot is compared for
368            // equality in `pop_reclaimable_victim`. Re-push it or the key
369            // becomes permanently un-reclaimable.
370            if changed {
371                self.refresh_eviction_candidate(&key);
372            }
373            return AdmissionResult::AlreadyPresent;
374        }
375        // Merging a source touches only `FetchPayload`, which no ordering
376        // reads, so the fetch heap is left completely untouched here.
377        if let Some(payload) = self.fetch_payloads.get_mut(&key) {
378            for source in &entry.replica_hint_sources {
379                if !payload.sources.contains(source) {
380                    payload.sources.push(*source);
381                }
382            }
383            if let Some(retry) = &mut payload.retry_verification {
384                retry
385                    .replica_hint_sources
386                    .extend(entry.replica_hint_sources);
387                retry.hint_sources.extend(entry.hint_sources);
388            }
389            return AdmissionResult::AlreadyPresent;
390        }
391        if let Some(in_flight) = self.in_flight_fetch.get_mut(&key) {
392            for source in &entry.replica_hint_sources {
393                if !in_flight.all_sources.contains(source) {
394                    in_flight.all_sources.push(*source);
395                }
396            }
397            if let Some(retry) = &mut in_flight.retry_verification {
398                retry
399                    .replica_hint_sources
400                    .extend(entry.replica_hint_sources);
401                retry.hint_sources.extend(entry.hint_sources);
402            }
403            return AdmissionResult::AlreadyPresent;
404        }
405        let Some(owner) = self.least_loaded_source(&entry.hint_sources) else {
406            debug_assert!(false, "pending hint admitted without a source");
407            return AdmissionResult::CapacityRejected;
408        };
409
410        if self.pending_capacity_used() >= MAX_PENDING_VERIFY {
411            if self.fair_rejection_cache.contains(&owner) {
412                return AdmissionResult::CapacityRejected;
413            }
414            if let Some(displaced) = self.reclaim_borrowed_slot(owner) {
415                self.insert_pending_owned_unchecked(key, entry, owner, false);
416                self.capacity_displacements.push(displaced);
417                return AdmissionResult::Admitted;
418            }
419            debug!(
420                "pending_verify at capacity ({MAX_PENDING_VERIFY}); source {owner} has no fair \
421                 reclaimable slot for key {}",
422                hex::encode(key),
423            );
424            self.fair_rejection_cache.insert(owner);
425            return AdmissionResult::CapacityRejected;
426        }
427        self.insert_pending_owned_unchecked(key, entry, owner, false);
428        AdmissionResult::Admitted
429    }
430
431    /// Drain fairness displacements produced by recent admissions.
432    ///
433    /// Neighbor-sync admission calls this while it still holds the queue lock
434    /// so bootstrap can attribute every displaced key to its former owner.
435    pub(crate) fn take_capacity_displacements(&mut self) -> Vec<CapacityDisplacement> {
436        std::mem::take(&mut self.capacity_displacements)
437    }
438
439    fn pending_capacity_used(&self) -> usize {
440        self.pending_verify
441            .len()
442            .saturating_add(self.retry_reserved_slots)
443    }
444
445    fn pending_count_for_owner_internal(&self, owner: &PeerId) -> usize {
446        self.pending_keys_by_owner
447            .get(owner)
448            .map_or(0, HashSet::len)
449    }
450
451    fn retry_reserved_for_owner(&self, owner: &PeerId) -> usize {
452        self.retry_reserved_by_owner
453            .get(owner)
454            .copied()
455            .unwrap_or(0)
456    }
457
458    /// Total pending capacity charged to `owner`: keys resident in
459    /// `pending_verify` plus the slots its promoted keys still reserve.
460    ///
461    /// This is the per-owner counterpart of [`Self::pending_capacity_used`],
462    /// and the two must stay in step: a reservation occupies a slot in the
463    /// global cap, so it has to be charged to somebody's share or fair-share
464    /// targets are computed against a pool that nobody is billed for.
465    fn charged_count_for_owner(&self, owner: &PeerId) -> usize {
466        self.pending_count_for_owner_internal(owner)
467            .saturating_add(self.retry_reserved_for_owner(owner))
468    }
469
470    fn least_loaded_source(&self, sources: &HashSet<PeerId>) -> Option<PeerId> {
471        sources.iter().copied().min_by(|a, b| {
472            self.charged_count_for_owner(a)
473                .cmp(&self.charged_count_for_owner(b))
474                .then_with(|| a.cmp(b))
475        })
476    }
477
478    fn reclaim_borrowed_slot(&mut self, incoming_owner: PeerId) -> Option<CapacityDisplacement> {
479        // Allocate the FULL pool and charge reservations to their holders,
480        // rather than deducting reservations off the top and billing no one.
481        let mut demands = BTreeMap::new();
482        for owner in self
483            .pending_keys_by_owner
484            .keys()
485            .chain(self.retry_reserved_by_owner.keys())
486        {
487            demands.insert(*owner, self.charged_count_for_owner(owner));
488        }
489        *demands.entry(incoming_owner).or_default() += 1;
490
491        let targets = max_min_allocations(&demands, MAX_PENDING_VERIFY);
492        let incoming_count = self.charged_count_for_owner(&incoming_owner);
493        if targets.get(&incoming_owner).copied().unwrap_or(0) <= incoming_count {
494            return None;
495        }
496
497        // Only a resident key can actually be reclaimed — a reservation has no
498        // entry to evict — so an owner over its target purely on reservations
499        // is skipped rather than chased.
500        let mut over_represented = self
501            .pending_keys_by_owner
502            .iter()
503            .filter_map(|(owner, keys)| {
504                if keys.is_empty() {
505                    return None;
506                }
507                let target = targets.get(owner).copied().unwrap_or(0);
508                let excess = self.charged_count_for_owner(owner).saturating_sub(target);
509                (excess > 0).then_some((*owner, excess))
510            })
511            .collect::<Vec<_>>();
512        over_represented.sort_unstable_by(|(owner_a, excess_a), (owner_b, excess_b)| {
513            excess_b.cmp(excess_a).then_with(|| owner_a.cmp(owner_b))
514        });
515
516        for (owner, _) in over_represented {
517            if let Some(key) = self.pop_reclaimable_victim(owner) {
518                let removed = self.remove_pending(&key);
519                debug_assert!(removed.is_some(), "fairness victim vanished before removal");
520                return Some(CapacityDisplacement { key, owner });
521            }
522        }
523        None
524    }
525
526    fn pop_reclaimable_victim(&mut self, owner: PeerId) -> Option<XorName> {
527        loop {
528            let candidate = self
529                .eviction_candidates_by_owner
530                .get_mut(&owner)
531                .and_then(BinaryHeap::pop)?;
532            let Some(entry) = self.pending_verify.get(&candidate.key) else {
533                continue;
534            };
535            let valid = self.capacity_owner_by_key.get(&candidate.key) == Some(&owner)
536                && !self.protected_pending_keys.contains(&candidate.key)
537                && candidate.source_count == entry.hint_sources.len()
538                && candidate.paid_only == entry.replica_hint_sources.is_empty()
539                && candidate.created_at == entry.created_at;
540            if valid {
541                return Some(candidate.key);
542            }
543        }
544    }
545
546    fn refresh_eviction_candidate(&mut self, key: &XorName) {
547        if self.protected_pending_keys.contains(key) {
548            return;
549        }
550        let (Some(entry), Some(owner)) = (
551            self.pending_verify.get(key),
552            self.capacity_owner_by_key.get(key).copied(),
553        ) else {
554            return;
555        };
556        self.eviction_candidates_by_owner
557            .entry(owner)
558            .or_default()
559            .push(EvictionOrder {
560                key: *key,
561                source_count: entry.hint_sources.len(),
562                paid_only: entry.replica_hint_sources.is_empty(),
563                created_at: entry.created_at,
564            });
565
566        let owner_len = self.pending_count_for_owner_internal(&owner);
567        let heap_len = self
568            .eviction_candidates_by_owner
569            .get(&owner)
570            .map_or(0, BinaryHeap::len);
571        if heap_len > owner_len.saturating_mul(2).saturating_add(64) {
572            self.rebuild_eviction_heap(owner);
573        }
574    }
575
576    fn rebuild_eviction_heap(&mut self, owner: PeerId) {
577        let candidates = self
578            .pending_keys_by_owner
579            .get(&owner)
580            .into_iter()
581            .flatten()
582            .filter(|key| !self.protected_pending_keys.contains(*key))
583            .filter_map(|key| {
584                self.pending_verify.get(key).map(|entry| EvictionOrder {
585                    key: *key,
586                    source_count: entry.hint_sources.len(),
587                    paid_only: entry.replica_hint_sources.is_empty(),
588                    created_at: entry.created_at,
589                })
590            })
591            .collect::<BinaryHeap<_>>();
592        self.eviction_candidates_by_owner.insert(owner, candidates);
593    }
594
595    fn insert_pending_owned_unchecked(
596        &mut self,
597        key: XorName,
598        entry: VerificationEntry,
599        owner: PeerId,
600        protected_retry: bool,
601    ) {
602        debug_assert!(
603            !entry.hint_sources.is_empty(),
604            "pending hint inserted without a live source"
605        );
606        debug_assert!(
607            entry.replica_hint_sources.is_subset(&entry.hint_sources),
608            "replica advertisers must be included in all hint sources"
609        );
610        debug_assert!(
611            entry.hint_sources.contains(&owner),
612            "capacity owner must be a live hint source"
613        );
614        for source in &entry.hint_sources {
615            self.pending_keys_by_source
616                .entry(*source)
617                .or_default()
618                .insert(key);
619        }
620        let replaced = self.pending_verify.insert(key, entry);
621        debug_assert!(
622            replaced.is_none(),
623            "pending entry inserted twice for {}",
624            hex::encode(key)
625        );
626        self.capacity_owner_by_key.insert(key, owner);
627        self.fair_rejection_cache.clear();
628        self.pending_keys_by_owner
629            .entry(owner)
630            .or_default()
631            .insert(key);
632        if protected_retry {
633            self.protected_pending_keys.insert(key);
634        } else {
635            self.refresh_eviction_candidate(&key);
636        }
637    }
638
639    /// Free one hint-source slot on `entry` by dropping a paid-only advertiser.
640    ///
641    /// Returns whether a slot was freed. Replica claimants are never chosen —
642    /// they are the fetch candidates the set exists to hold — and neither is
643    /// `protected_owner`, which must remain a live hint source for the capacity
644    /// accounting in `insert_pending_owned_unchecked` to stay valid.
645    ///
646    /// The victim among eligible paid-only sources is arbitrary: they are
647    /// interchangeable, each contributing one unit of corroboration weight and
648    /// nothing else.
649    fn displace_paid_only_source(
650        entry: &mut VerificationEntry,
651        keys_by_source: &mut HashMap<PeerId, HashSet<XorName>>,
652        key: &XorName,
653        protected_owner: Option<PeerId>,
654    ) -> bool {
655        let victim = entry.hint_sources.iter().copied().find(|source| {
656            !entry.replica_hint_sources.contains(source) && protected_owner != Some(*source)
657        });
658        let Some(victim) = victim else {
659            return false;
660        };
661        entry.hint_sources.remove(&victim);
662        if let Some(keys) = keys_by_source.get_mut(&victim) {
663            keys.remove(key);
664            if keys.is_empty() {
665                keys_by_source.remove(&victim);
666            }
667        }
668        true
669    }
670
671    /// Reserve a pending slot for `key`, charged to its capacity owner.
672    ///
673    /// Must be called while `capacity_owner_by_key` still holds `key`, which is
674    /// why `promote_pending_to_fetch` takes the pending entry with
675    /// `forget_capacity_owner: false`.
676    fn reserve_retry_slot(&mut self, key: &XorName) {
677        self.retry_reserved_slots = self.retry_reserved_slots.saturating_add(1);
678        if let Some(owner) = self.capacity_owner_by_key.get(key).copied() {
679            *self.retry_reserved_by_owner.entry(owner).or_default() += 1;
680        }
681        self.fair_rejection_cache.clear();
682    }
683
684    /// Release `key`'s reserved pending slot.
685    ///
686    /// Call before dropping `key` from `capacity_owner_by_key`, or the
687    /// per-owner charge is stranded.
688    fn release_retry_slot(&mut self, key: &XorName) {
689        self.retry_reserved_slots = self.retry_reserved_slots.saturating_sub(1);
690        if let Some(owner) = self.capacity_owner_by_key.get(key).copied() {
691            if let Some(count) = self.retry_reserved_by_owner.get_mut(&owner) {
692                *count = count.saturating_sub(1);
693                if *count == 0 {
694                    self.retry_reserved_by_owner.remove(&owner);
695                }
696            }
697        }
698        self.fair_rejection_cache.clear();
699    }
700
701    fn release_retry_slot_for_entry(&mut self, entry: &InFlightEntry) {
702        if entry.retry_verification.is_some() {
703            self.release_retry_slot(&entry.key);
704        }
705    }
706
707    fn release_retry_slot_for_candidate(&mut self, candidate: &FetchCandidate) {
708        if candidate.retry_verification.is_some() {
709            self.release_retry_slot(&candidate.key);
710        }
711    }
712
713    /// Test-only: number of live verification retry-slot reservations, so
714    /// tests can assert a terminal fetch outcome released its reservation.
715    #[cfg(any(test, feature = "test-utils"))]
716    #[must_use]
717    pub fn retry_reserved_slot_count(&self) -> usize {
718        self.retry_reserved_slots
719    }
720
721    /// Get a reference to a pending verification entry.
722    #[must_use]
723    pub fn get_pending(&self, key: &XorName) -> Option<&VerificationEntry> {
724        self.pending_verify.get(key)
725    }
726
727    /// Advance a pending entry's verification `state`, reporting whether the
728    /// key was found.
729    ///
730    /// Narrow mutation API used by the verification state machine.
731    pub fn set_pending_state(&mut self, key: &XorName, state: VerificationState) -> bool {
732        let Some(entry) = self.pending_verify.get_mut(key) else {
733            return false;
734        };
735        entry.state = state;
736        true
737    }
738
739    /// Remove a key from pending verification.
740    pub fn remove_pending(&mut self, key: &XorName) -> Option<VerificationEntry> {
741        self.take_pending(key, true)
742    }
743
744    fn take_pending(
745        &mut self,
746        key: &XorName,
747        forget_capacity_owner: bool,
748    ) -> Option<VerificationEntry> {
749        let removed = self.pending_verify.remove(key);
750        if let Some(entry) = &removed {
751            self.fair_rejection_cache.clear();
752            self.remove_key_from_source_index(key, &entry.hint_sources);
753            if let Some(owner) = self.capacity_owner_by_key.get(key).copied() {
754                self.remove_key_from_owner_index(key, &owner);
755            }
756            self.protected_pending_keys.remove(key);
757            if forget_capacity_owner {
758                self.capacity_owner_by_key.remove(key);
759            }
760        }
761        removed
762    }
763
764    fn remove_key_from_source_index(&mut self, key: &XorName, sources: &HashSet<PeerId>) {
765        for source in sources {
766            if let Some(keys) = self.pending_keys_by_source.get_mut(source) {
767                keys.remove(key);
768                if keys.is_empty() {
769                    self.pending_keys_by_source.remove(source);
770                }
771            }
772        }
773    }
774
775    fn remove_key_from_owner_index(&mut self, key: &XorName, owner: &PeerId) {
776        if let Some(keys) = self.pending_keys_by_owner.get_mut(owner) {
777            keys.remove(key);
778            if keys.is_empty() {
779                self.pending_keys_by_owner.remove(owner);
780                self.eviction_candidates_by_owner.remove(owner);
781            }
782        }
783    }
784
785    /// Collect all pending verification keys (for batch processing).
786    #[must_use]
787    pub fn pending_keys(&self) -> Vec<XorName> {
788        self.pending_verify.keys().copied().collect()
789    }
790
791    /// Collect pending verification keys whose retry delay has elapsed.
792    #[must_use]
793    pub fn ready_pending_keys(&self, now: Instant) -> Vec<XorName> {
794        let mut ready = self
795            .pending_verify
796            .iter()
797            .filter_map(|(key, entry)| (entry.next_verify_at <= now).then_some(*key))
798            .collect::<Vec<_>>();
799        ready.sort_unstable_by(|a, b| {
800            let entry_a = &self.pending_verify[a];
801            let entry_b = &self.pending_verify[b];
802            entry_b
803                .hint_sources
804                .len()
805                .cmp(&entry_a.hint_sources.len())
806                .then_with(|| entry_a.created_at.cmp(&entry_b.created_at))
807                .then_with(|| a.cmp(b))
808        });
809        ready
810    }
811
812    /// Select a bounded, sender-fair set of ready verification keys.
813    ///
814    /// Owners are served round-robin with persistent rotation between cycles;
815    /// unused service is immediately redistributed. Within an owner's share,
816    /// protected retries and corroborated/older hints retain priority.
817    pub fn select_ready_pending_keys(&mut self, now: Instant, limit: usize) -> Vec<XorName> {
818        if limit == 0 {
819            return Vec::new();
820        }
821
822        let mut grouped = BTreeMap::<PeerId, Vec<XorName>>::new();
823        for (key, entry) in &self.pending_verify {
824            if entry.next_verify_at > now {
825                continue;
826            }
827            let Some(owner) = self.capacity_owner_by_key.get(key).copied() else {
828                debug_assert!(false, "pending key has no capacity owner");
829                continue;
830            };
831            grouped.entry(owner).or_default().push(*key);
832        }
833
834        for keys in grouped.values_mut() {
835            keys.sort_unstable_by(|a, b| {
836                let entry_a = &self.pending_verify[a];
837                let entry_b = &self.pending_verify[b];
838                self.protected_pending_keys
839                    .contains(b)
840                    .cmp(&self.protected_pending_keys.contains(a))
841                    .then_with(|| entry_b.hint_sources.len().cmp(&entry_a.hint_sources.len()))
842                    .then_with(|| entry_a.created_at.cmp(&entry_b.created_at))
843                    .then_with(|| a.cmp(b))
844            });
845        }
846
847        let mut owners = grouped.keys().copied().collect::<Vec<_>>();
848        if owners.is_empty() {
849            return Vec::new();
850        }
851        if let Some(last) = self.last_served_owner {
852            let start = owners.iter().position(|owner| *owner > last).unwrap_or(0);
853            owners.rotate_left(start);
854        }
855
856        let mut queues = grouped
857            .into_iter()
858            .map(|(owner, keys)| (owner, VecDeque::from(keys)))
859            .collect::<HashMap<_, _>>();
860        let mut active = VecDeque::from(owners);
861        let mut selected = Vec::with_capacity(limit.min(self.pending_verify.len()));
862        let mut last_selected = None;
863
864        while selected.len() < limit {
865            let Some(owner) = active.pop_front() else {
866                break;
867            };
868            let Some(owner_queue) = queues.get_mut(&owner) else {
869                continue;
870            };
871            let Some(key) = owner_queue.pop_front() else {
872                continue;
873            };
874            selected.push(key);
875            last_selected = Some(owner);
876            if !owner_queue.is_empty() {
877                active.push_back(owner);
878            }
879        }
880
881        if let Some(owner) = last_selected {
882            self.last_served_owner = Some(owner);
883        }
884        selected
885    }
886
887    /// Remove a departed routing-table peer from every pending hint it
888    /// advertised. Entries with no remaining live advertisers are dropped.
889    ///
890    /// Returns keys that became orphaned so bootstrap accounting can retire
891    /// them and re-check its drain transition.
892    pub fn remove_hint_source(&mut self, source: &PeerId) -> Vec<XorName> {
893        let keys = self
894            .pending_keys_by_source
895            .remove(source)
896            .unwrap_or_default();
897        let mut orphaned = Vec::new();
898
899        for key in keys {
900            let remaining_sources = if let Some(entry) = self.pending_verify.get_mut(&key) {
901                entry.hint_sources.remove(source);
902                entry.replica_hint_sources.remove(source);
903                Some(entry.hint_sources.clone())
904            } else {
905                None
906            };
907
908            let Some(remaining_sources) = remaining_sources else {
909                continue;
910            };
911            if remaining_sources.is_empty() {
912                self.remove_pending(&key);
913                orphaned.push(key);
914                continue;
915            }
916
917            if self.capacity_owner_by_key.get(&key) == Some(source) {
918                if let Some(new_owner) = self.least_loaded_source(&remaining_sources) {
919                    self.transfer_pending_owner(key, *source, new_owner);
920                }
921            } else {
922                self.refresh_eviction_candidate(&key);
923            }
924        }
925
926        let mut retry_owner_updates = Vec::new();
927        let mut orphaned_fetch_keys = HashSet::new();
928        for (key, payload) in &mut self.fetch_payloads {
929            payload.sources.retain(|peer| peer != source);
930            if let Some(verification) = &mut payload.retry_verification {
931                if verification.hint_sources.remove(source) {
932                    verification.replica_hint_sources.remove(source);
933                    if verification.hint_sources.is_empty() {
934                        payload.retry_verification = None;
935                        retry_owner_updates.push((*key, None));
936                    } else if self.capacity_owner_by_key.get(key) == Some(source) {
937                        retry_owner_updates
938                            .push((*key, verification.hint_sources.iter().copied().min()));
939                    }
940                }
941            }
942            if payload.sources.is_empty() && payload.retry_verification.is_none() {
943                orphaned_fetch_keys.insert(*key);
944            }
945        }
946        // Only an orphaned key changes heap *membership*; the source edits
947        // above cannot, so the heap is rebuilt at most once per departed peer
948        // and not at all when the peer left nothing orphaned.
949        if !orphaned_fetch_keys.is_empty() {
950            self.fetch_payloads
951                .retain(|key, _| !orphaned_fetch_keys.contains(key));
952            self.fetch_queue
953                .retain(|order| !orphaned_fetch_keys.contains(&order.key));
954            orphaned.extend(orphaned_fetch_keys);
955        }
956
957        for entry in self.in_flight_fetch.values_mut() {
958            entry.all_sources.retain(|peer| peer != source);
959            if let Some(verification) = &mut entry.retry_verification {
960                if verification.hint_sources.remove(source) {
961                    verification.replica_hint_sources.remove(source);
962                    if verification.hint_sources.is_empty() {
963                        entry.retry_verification = None;
964                        retry_owner_updates.push((entry.key, None));
965                    } else if self.capacity_owner_by_key.get(&entry.key) == Some(source) {
966                        retry_owner_updates
967                            .push((entry.key, verification.hint_sources.iter().copied().min()));
968                    }
969                }
970            }
971        }
972
973        // Every key here holds a retry reservation charged to its current
974        // capacity owner, so each release must happen while
975        // `capacity_owner_by_key` still names that owner.
976        for (key, owner) in retry_owner_updates {
977            self.release_retry_slot(&key);
978            if let Some(new_owner) = owner {
979                // The retry survives but changes hands: re-charge it to the new
980                // owner, or it stays billed to a peer that has just departed
981                // and is never recovered.
982                self.capacity_owner_by_key.insert(key, new_owner);
983                self.reserve_retry_slot(&key);
984            } else {
985                // The retry itself is gone with its last hint source.
986                self.capacity_owner_by_key.remove(&key);
987            }
988        }
989
990        orphaned
991    }
992
993    fn transfer_pending_owner(&mut self, key: XorName, old_owner: PeerId, new_owner: PeerId) {
994        if old_owner == new_owner {
995            self.refresh_eviction_candidate(&key);
996            return;
997        }
998        self.fair_rejection_cache.clear();
999        self.remove_key_from_owner_index(&key, &old_owner);
1000        self.capacity_owner_by_key.insert(key, new_owner);
1001        self.pending_keys_by_owner
1002            .entry(new_owner)
1003            .or_default()
1004            .insert(key);
1005        self.refresh_eviction_candidate(&key);
1006    }
1007
1008    /// Defer a pending key before its next verification attempt, by a flat
1009    /// delay.
1010    ///
1011    /// For deferrals that are *not* a failed round: the caller chose not to ask
1012    /// (a full disk, say), so nothing was learned about the key and the
1013    /// unresolved-round count must not move.
1014    pub fn defer_pending(&mut self, key: &XorName, retry_after: Duration) -> bool {
1015        let Some(entry) = self.pending_verify.get_mut(key) else {
1016            return false;
1017        };
1018        entry.next_verify_at = Instant::now() + retry_after;
1019        true
1020    }
1021
1022    /// Defer a pending key whose verification round left it unresolved.
1023    ///
1024    /// `base_retry_after` is the delay for the entry's *first* such deferral.
1025    /// Each consecutive one doubles it, capped at
1026    /// [`VERIFICATION_RETRY_BACKOFF_MAX`]. A key that keeps failing is failing
1027    /// for a reason a faster retry cannot change, so the cost of asking decays
1028    /// rather than being paid in full every 15 seconds.
1029    ///
1030    /// Returns `None` if the key is not pending, otherwise the resulting
1031    /// [`DeferralOutcome`], whose `attempt` is 1 on this entry's first
1032    /// unresolved round — the one worth reporting.
1033    pub fn defer_unresolved(
1034        &mut self,
1035        key: &XorName,
1036        base_retry_after: Duration,
1037    ) -> Option<DeferralOutcome> {
1038        let entry = self.pending_verify.get_mut(key)?;
1039        entry.unresolved_retries = entry.unresolved_retries.saturating_add(1);
1040        let attempt = entry.unresolved_retries;
1041        let retry_after = backoff_delay(base_retry_after, attempt);
1042        entry.next_verify_at = Instant::now() + retry_after;
1043        Some(DeferralOutcome {
1044            attempt,
1045            retry_after,
1046        })
1047    }
1048
1049    /// Claim this entry's single no-holder warning.
1050    ///
1051    /// Returns `true` the first time it is called for a given entry and `false`
1052    /// after, so the caller can warn once and drop to `debug` thereafter.
1053    ///
1054    /// Kept separate from [`Self::defer_unresolved`] on purpose. A round can
1055    /// legitimately advance the failure count without producing a no-holder
1056    /// result — an inconclusive quorum does exactly that — and if the two
1057    /// shared state, such a round would consume the warning before the
1058    /// condition it describes had ever been observed.
1059    pub fn claim_no_holder_report(&mut self, key: &XorName) -> bool {
1060        let Some(entry) = self.pending_verify.get_mut(key) else {
1061            return false;
1062        };
1063        !std::mem::replace(&mut entry.no_holder_reported, true)
1064    }
1065
1066    /// Clear an entry's unresolved history after a round that found a holder.
1067    ///
1068    /// The round succeeded even if the key could not move on — a full fetch
1069    /// queue leaves it pending — so it must not inherit the earlier backoff, and
1070    /// a later relapse deserves a fresh warning. Returns whether an entry was
1071    /// present to clear.
1072    pub fn clear_unresolved(&mut self, key: &XorName) -> bool {
1073        let Some(entry) = self.pending_verify.get_mut(key) else {
1074            return false;
1075        };
1076        entry.unresolved_retries = 0;
1077        entry.no_holder_reported = false;
1078        true
1079    }
1080
1081    /// Number of keys in pending verification.
1082    #[must_use]
1083    pub fn pending_count(&self) -> usize {
1084        self.pending_verify.len()
1085    }
1086
1087    /// Number of pending entries currently charged to one capacity owner.
1088    /// Useful for fairness observability and invariant tests.
1089    #[must_use]
1090    pub fn pending_count_for_owner(&self, owner: &PeerId) -> usize {
1091        self.pending_count_for_owner_internal(owner)
1092    }
1093
1094    // -----------------------------------------------------------------------
1095    // FetchQueue
1096    // -----------------------------------------------------------------------
1097
1098    /// Enqueue a key for fetch with its distance and verified sources.
1099    ///
1100    /// Returns `true` if the candidate was enqueued, `false` if it was
1101    /// already present in any pipeline stage (Rule 8: cross-queue dedup) or
1102    /// the `fetch_queue` is at [`MAX_FETCH_QUEUE`].
1103    ///
1104    /// Callers that have removed the key from `pending_verify` immediately
1105    /// before this call should prefer [`promote_pending_to_fetch`](Self::promote_pending_to_fetch),
1106    /// which performs the move atomically and leaves the pending entry in
1107    /// place when the fetch queue is full (so verified work is retried on
1108    /// the next cycle instead of being silently lost).
1109    pub fn enqueue_fetch(&mut self, key: XorName, distance: XorName, sources: Vec<PeerId>) -> bool {
1110        self.enqueue_fetch_with_retry(key, distance, sources, None)
1111    }
1112
1113    fn enqueue_fetch_with_retry(
1114        &mut self,
1115        key: XorName,
1116        distance: XorName,
1117        sources: Vec<PeerId>,
1118        retry_verification: Option<VerificationEntry>,
1119    ) -> bool {
1120        if self.pending_verify.contains_key(&key)
1121            || self.fetch_payloads.contains_key(&key)
1122            || self.in_flight_fetch.contains_key(&key)
1123        {
1124            return false;
1125        }
1126        if self.fetch_payloads.len() >= MAX_FETCH_QUEUE {
1127            debug!(
1128                "fetch_queue at capacity ({MAX_FETCH_QUEUE}); dropping new key {}",
1129                hex::encode(key)
1130            );
1131            return false;
1132        }
1133        self.fetch_payloads.insert(
1134            key,
1135            FetchPayload {
1136                sources,
1137                retry_verification,
1138            },
1139        );
1140        self.fetch_queue.push(FetchOrder { key, distance });
1141        true
1142    }
1143
1144    /// Atomically promote a key from `pending_verify` to `fetch_queue`.
1145    ///
1146    /// Checks `fetch_queue` capacity FIRST, then removes the pending entry
1147    /// and enqueues the fetch candidate. If `fetch_queue` is full, the
1148    /// pending entry is **left in place** so the next verification cycle
1149    /// can retry — preventing the silent-drop regression where a verified
1150    /// key removed from `pending_verify` could be dropped by a full fetch
1151    /// queue and lost from every stage.
1152    ///
1153    /// Returns `true` on successful promotion, `false` when the fetch queue
1154    /// is at capacity (pending entry preserved).
1155    pub fn promote_pending_to_fetch(
1156        &mut self,
1157        key: XorName,
1158        distance: XorName,
1159        sources: Vec<PeerId>,
1160    ) -> bool {
1161        if self.fetch_payloads.len() >= MAX_FETCH_QUEUE {
1162            debug!(
1163                "fetch_queue at capacity ({MAX_FETCH_QUEUE}); leaving {} pending \
1164                 for retry next cycle",
1165                hex::encode(key)
1166            );
1167            return false;
1168        }
1169        // Capacity confirmed; safe to release the pending slot and enqueue.
1170        let retry_verification = self.take_pending(&key, false);
1171        let reserved_retry = retry_verification.is_some();
1172        if reserved_retry {
1173            self.reserve_retry_slot(&key);
1174        }
1175        // enqueue_fetch returns false only on capacity or already-queued; the
1176        // capacity check above and the just-removed pending state make this
1177        // succeed. If a concurrent path put the key into fetch_queue/in_flight
1178        // between, dropping the duplicate is fine.
1179        let enqueued = self.enqueue_fetch_with_retry(key, distance, sources, retry_verification);
1180        if !enqueued && reserved_retry {
1181            self.release_retry_slot(&key);
1182            self.capacity_owner_by_key.remove(&key);
1183        }
1184        enqueued
1185    }
1186
1187    /// Dequeue the nearest fetch candidate.
1188    ///
1189    /// Returns `None` when the queue is empty.  Silently skips candidates
1190    /// that are somehow already in-flight.  Concurrency is enforced by the
1191    /// fetch worker, not by this method.
1192    ///
1193    /// A returned candidate may carry a live verification retry-slot
1194    /// reservation. Callers must consume it with
1195    /// [`Self::start_dequeued_fetch`], [`Self::discard_fetch_candidate`], or
1196    /// [`Self::requeue_candidate_for_verification`] so that reservation is
1197    /// either transferred, released, or restored to `pending_verify`.
1198    pub fn dequeue_fetch(&mut self) -> Option<FetchCandidate> {
1199        while let Some(order) = self.fetch_queue.pop() {
1200            let Some(payload) = self.fetch_payloads.remove(&order.key) else {
1201                debug_assert!(
1202                    false,
1203                    "fetch order without payload for {}",
1204                    hex::encode(order.key)
1205                );
1206                continue;
1207            };
1208            let candidate = FetchCandidate {
1209                key: order.key,
1210                distance: order.distance,
1211                sources: payload.sources,
1212                retry_verification: payload.retry_verification,
1213            };
1214            if !self.in_flight_fetch.contains_key(&candidate.key) {
1215                return Some(candidate);
1216            }
1217            self.release_retry_slot_for_candidate(&candidate);
1218        }
1219        None
1220    }
1221
1222    /// Number of keys waiting in the fetch queue.
1223    #[must_use]
1224    pub fn fetch_queue_count(&self) -> usize {
1225        self.fetch_payloads.len()
1226    }
1227
1228    // -----------------------------------------------------------------------
1229    // InFlightFetch
1230    // -----------------------------------------------------------------------
1231
1232    /// Mark a key as in-flight (actively being fetched from `source`).
1233    ///
1234    /// Candidates returned by [`Self::dequeue_fetch`] MUST be consumed by a
1235    /// by-value dequeued-candidate method instead. They may carry a live
1236    /// verification retry-slot reservation; [`Self::start_dequeued_fetch`]
1237    /// transfers that reservation into the in-flight entry.
1238    pub fn start_fetch(&mut self, key: XorName, source: PeerId, all_sources: Vec<PeerId>) {
1239        self.start_fetch_with_retry(key, source, all_sources, None);
1240    }
1241
1242    /// Mark a key as in-flight and retain verification retry metadata.
1243    ///
1244    /// This is for direct starts where the caller already owns any retry
1245    /// reservation paired with `retry_verification`. Candidates obtained from
1246    /// [`Self::dequeue_fetch`] MUST be consumed intact via a by-value
1247    /// dequeued-candidate method, otherwise their reserved verification
1248    /// capacity can be orphaned.
1249    pub fn start_fetch_with_retry(
1250        &mut self,
1251        key: XorName,
1252        source: PeerId,
1253        all_sources: Vec<PeerId>,
1254        retry_verification: Option<VerificationEntry>,
1255    ) {
1256        let mut tried = HashSet::new();
1257        tried.insert(source);
1258        let replaced = self.in_flight_fetch.insert(
1259            key,
1260            InFlightEntry {
1261                key,
1262                source,
1263                started_at: Instant::now(),
1264                all_sources,
1265                tried,
1266                retry_verification,
1267            },
1268        );
1269        if let Some(entry) = replaced {
1270            self.release_retry_slot_for_entry(&entry);
1271        }
1272    }
1273
1274    /// Consume a dequeued fetch candidate and transfer its retry reservation
1275    /// into the in-flight entry.
1276    pub fn start_dequeued_fetch(&mut self, candidate: FetchCandidate, source: PeerId) {
1277        let FetchCandidate {
1278            key,
1279            sources,
1280            retry_verification,
1281            ..
1282        } = candidate;
1283        self.start_fetch_with_retry(key, source, sources, retry_verification);
1284    }
1285
1286    /// Mark a fetch as completed (success or permanent failure).
1287    pub fn complete_fetch(&mut self, key: &XorName) -> Option<InFlightEntry> {
1288        let removed = self.in_flight_fetch.remove(key);
1289        if let Some(entry) = &removed {
1290            self.release_retry_slot_for_entry(entry);
1291            self.capacity_owner_by_key.remove(key);
1292        }
1293        removed
1294    }
1295
1296    /// Drop a dequeued fetch candidate without starting it.
1297    pub fn discard_fetch_candidate(&mut self, candidate: FetchCandidate) {
1298        let FetchCandidate {
1299            key,
1300            retry_verification,
1301            ..
1302        } = candidate;
1303        if retry_verification.is_some() {
1304            self.release_retry_slot(&key);
1305            self.capacity_owner_by_key.remove(&key);
1306        }
1307    }
1308
1309    /// Mark the current fetch attempt as failed and try the next untried source.
1310    ///
1311    /// Returns the next source peer if one is available, or `None` if all
1312    /// sources have been exhausted.
1313    pub fn retry_fetch(&mut self, key: &XorName) -> Option<PeerId> {
1314        let entry = self.in_flight_fetch.get_mut(key)?;
1315        entry.tried.insert(entry.source);
1316
1317        let next = entry
1318            .all_sources
1319            .iter()
1320            .find(|p| !entry.tried.contains(p))
1321            .copied();
1322
1323        if let Some(next_peer) = next {
1324            entry.source = next_peer;
1325            entry.tried.insert(next_peer);
1326            Some(next_peer)
1327        } else {
1328            None
1329        }
1330    }
1331
1332    /// Consume a dequeued candidate and restore its verification entry for a
1333    /// later retry when retry metadata exists.
1334    pub fn requeue_candidate_for_verification(
1335        &mut self,
1336        candidate: FetchCandidate,
1337        retry_after: Duration,
1338    ) -> bool {
1339        let FetchCandidate {
1340            key,
1341            retry_verification,
1342            ..
1343        } = candidate;
1344        let Some(mut verification) = retry_verification else {
1345            return false;
1346        };
1347        verification.state = VerificationState::PendingVerify;
1348        verification.verified_sources.clear();
1349        verification.tried_sources.clear();
1350        verification.next_verify_at = Instant::now() + retry_after;
1351
1352        let owner = self
1353            .capacity_owner_by_key
1354            .get(&key)
1355            .copied()
1356            .or_else(|| self.least_loaded_source(&verification.hint_sources));
1357        let Some(owner) = owner else {
1358            self.release_retry_slot(&key);
1359            return false;
1360        };
1361        // Release before re-inserting: the reservation is charged to the owner
1362        // recorded now, which `insert_pending_owned_unchecked` may replace.
1363        self.release_retry_slot(&key);
1364        self.insert_pending_owned_unchecked(key, verification, owner, true);
1365        true
1366    }
1367
1368    /// Complete an exhausted fetch and restore its verification entry for a
1369    /// later retry when retry metadata exists.
1370    pub fn requeue_fetch_for_verification(&mut self, key: &XorName, retry_after: Duration) -> bool {
1371        let Some(mut entry) = self.in_flight_fetch.remove(key) else {
1372            return false;
1373        };
1374        let Some(mut verification) = entry.retry_verification.take() else {
1375            self.capacity_owner_by_key.remove(key);
1376            return false;
1377        };
1378        verification.state = VerificationState::PendingVerify;
1379        verification.verified_sources.clear();
1380        verification.tried_sources.clear();
1381        verification.next_verify_at = Instant::now() + retry_after;
1382
1383        let owner = self
1384            .capacity_owner_by_key
1385            .get(key)
1386            .copied()
1387            .or_else(|| self.least_loaded_source(&verification.hint_sources));
1388        let Some(owner) = owner else {
1389            self.release_retry_slot(key);
1390            return false;
1391        };
1392        // Release before re-inserting: the reservation is charged to the owner
1393        // recorded now, which `insert_pending_owned_unchecked` may replace.
1394        self.release_retry_slot(key);
1395        self.insert_pending_owned_unchecked(*key, verification, owner, true);
1396        true
1397    }
1398
1399    /// Number of in-flight fetches.
1400    #[must_use]
1401    pub fn in_flight_count(&self) -> usize {
1402        self.in_flight_fetch.len()
1403    }
1404
1405    // -----------------------------------------------------------------------
1406    // Cross-queue queries
1407    // -----------------------------------------------------------------------
1408
1409    /// Check if a key is present in any pipeline stage.
1410    #[must_use]
1411    pub fn contains_key(&self, key: &XorName) -> bool {
1412        self.pending_verify.contains_key(key)
1413            || self.fetch_payloads.contains_key(key)
1414            || self.in_flight_fetch.contains_key(key)
1415    }
1416
1417    /// Check if all bootstrap-related work is done.
1418    ///
1419    /// Returns `true` when none of the given bootstrap keys remain in any queue.
1420    #[must_use]
1421    pub fn is_bootstrap_work_empty(&self, bootstrap_keys: &HashSet<XorName>) -> bool {
1422        !bootstrap_keys.iter().any(|k| self.contains_key(k))
1423    }
1424
1425    /// Evict stale pending-verification entries older than `max_age`.
1426    pub fn evict_stale(&mut self, max_age: Duration) -> Vec<XorName> {
1427        let now = Instant::now();
1428        let evicted_keys = self
1429            .pending_verify
1430            .iter()
1431            .filter_map(|(key, entry)| {
1432                (now.duration_since(entry.created_at) >= max_age).then_some(*key)
1433            })
1434            .collect::<Vec<_>>();
1435
1436        for key in &evicted_keys {
1437            self.remove_pending(key);
1438        }
1439
1440        if !evicted_keys.is_empty() {
1441            debug!(
1442                "Evicted {} stale pending-verification entries",
1443                evicted_keys.len()
1444            );
1445        }
1446
1447        evicted_keys
1448    }
1449}
1450
1451/// Integer max-min allocation with deterministic remainder distribution.
1452///
1453/// Small demands are satisfied in full. Remaining capacity is divided evenly
1454/// between saturated senders, so unused capacity is automatically borrowable.
1455fn max_min_allocations(
1456    demands: &BTreeMap<PeerId, usize>,
1457    capacity: usize,
1458) -> BTreeMap<PeerId, usize> {
1459    if demands.values().copied().sum::<usize>() <= capacity {
1460        return demands.clone();
1461    }
1462
1463    let mut by_demand = demands
1464        .iter()
1465        .map(|(owner, demand)| (*owner, *demand))
1466        .collect::<Vec<_>>();
1467    by_demand.sort_unstable_by(|(owner_a, demand_a), (owner_b, demand_b)| {
1468        demand_a.cmp(demand_b).then_with(|| owner_a.cmp(owner_b))
1469    });
1470
1471    let mut allocations = BTreeMap::new();
1472    let mut remaining_capacity = capacity;
1473    let mut index = 0usize;
1474
1475    while index < by_demand.len() {
1476        let remaining_senders = by_demand.len() - index;
1477        let even_share = remaining_capacity / remaining_senders;
1478        let (owner, demand) = by_demand[index];
1479        if demand <= even_share {
1480            allocations.insert(owner, demand);
1481            remaining_capacity = remaining_capacity.saturating_sub(demand);
1482            index += 1;
1483            continue;
1484        }
1485
1486        let base = even_share;
1487        let remainder = remaining_capacity % remaining_senders;
1488        let mut saturated = by_demand[index..]
1489            .iter()
1490            .map(|(owner, _)| *owner)
1491            .collect::<Vec<_>>();
1492        saturated.sort_unstable();
1493        for (position, owner) in saturated.into_iter().enumerate() {
1494            allocations.insert(owner, base + usize::from(position < remainder));
1495        }
1496        break;
1497    }
1498
1499    allocations
1500}
1501
1502// ---------------------------------------------------------------------------
1503// Tests
1504// ---------------------------------------------------------------------------
1505
1506#[cfg(test)]
1507#[allow(clippy::unwrap_used, clippy::expect_used)]
1508mod tests {
1509    use super::*;
1510    use crate::replication::config::CAPACITY_BLOCKED_RETRY;
1511
1512    /// Build a `PeerId` from a single byte (zero-padded to 32 bytes).
1513    fn peer_id_from_byte(b: u8) -> PeerId {
1514        let mut bytes = [0u8; 32];
1515        bytes[0] = b;
1516        PeerId::from_bytes(bytes)
1517    }
1518
1519    /// Build an `XorName` from a single byte (repeated to 32 bytes).
1520    fn xor_name_from_byte(b: u8) -> XorName {
1521        [b; 32]
1522    }
1523
1524    fn xor_name_from_u32(value: u32) -> XorName {
1525        let mut name = [0u8; 32];
1526        name[..4].copy_from_slice(&value.to_le_bytes());
1527        name
1528    }
1529
1530    /// Create a minimal `VerificationEntry` for testing.
1531    fn test_entry(sender_byte: u8) -> VerificationEntry {
1532        let now = Instant::now();
1533        VerificationEntry {
1534            state: VerificationState::PendingVerify,
1535            verified_sources: Vec::new(),
1536            tried_sources: HashSet::new(),
1537            created_at: now,
1538            next_verify_at: now,
1539            hint_sources: HashSet::from([peer_id_from_byte(sender_byte)]),
1540            replica_hint_sources: HashSet::from([peer_id_from_byte(sender_byte)]),
1541            unresolved_retries: 0,
1542            no_holder_reported: false,
1543        }
1544    }
1545
1546    #[test]
1547    fn max_min_allocation_lends_unused_capacity() {
1548        let attacker = peer_id_from_byte(1);
1549        let honest = peer_id_from_byte(2);
1550        let demands = BTreeMap::from([(attacker, MAX_PENDING_VERIFY), (honest, 50_000)]);
1551
1552        let allocated = max_min_allocations(&demands, MAX_PENDING_VERIFY);
1553
1554        assert_eq!(allocated[&honest], 50_000);
1555        assert_eq!(allocated[&attacker], MAX_PENDING_VERIFY - 50_000);
1556        assert_eq!(allocated.values().sum::<usize>(), MAX_PENDING_VERIFY);
1557    }
1558
1559    #[test]
1560    fn max_min_allocation_is_even_under_saturation() {
1561        let demands = (0..20u8)
1562            .map(|index| (peer_id_from_byte(index), MAX_PENDING_VERIFY))
1563            .collect::<BTreeMap<_, _>>();
1564
1565        let allocated = max_min_allocations(&demands, MAX_PENDING_VERIFY);
1566        let min = allocated.values().copied().min().unwrap();
1567        let max = allocated.values().copied().max().unwrap();
1568
1569        assert!(max - min <= 1);
1570        assert_eq!(allocated.values().sum::<usize>(), MAX_PENDING_VERIFY);
1571    }
1572
1573    #[test]
1574    fn fair_verification_selection_shares_service_and_redistributes_slack() {
1575        let mut queues = ReplicationQueues::new();
1576        let first = peer_id_from_byte(1);
1577        let second = peer_id_from_byte(2);
1578        for index in 0..12u32 {
1579            assert!(queues
1580                .add_pending_verify(xor_name_from_u32(index), test_entry(1))
1581                .admitted());
1582        }
1583        for index in 100..104u32 {
1584            assert!(queues
1585                .add_pending_verify(xor_name_from_u32(index), test_entry(2))
1586                .admitted());
1587        }
1588
1589        let selected = queues.select_ready_pending_keys(Instant::now(), 12);
1590        let first_count = selected
1591            .iter()
1592            .filter(|key| queues.capacity_owner_by_key.get(*key) == Some(&first))
1593            .count();
1594        let second_count = selected
1595            .iter()
1596            .filter(|key| queues.capacity_owner_by_key.get(*key) == Some(&second))
1597            .count();
1598
1599        assert_eq!(
1600            second_count, 4,
1601            "small sender should receive all its ready work"
1602        );
1603        assert_eq!(
1604            first_count, 8,
1605            "unused service should return to the busy sender"
1606        );
1607    }
1608
1609    #[test]
1610    fn fair_verification_selection_prevents_cycle_monopoly() {
1611        const PER_OWNER: u32 = 10_000;
1612        const CYCLE: usize = 8_192;
1613        let mut queues = ReplicationQueues::new();
1614        let first = peer_id_from_byte(1);
1615        let second = peer_id_from_byte(2);
1616        for index in 0..PER_OWNER {
1617            assert!(queues
1618                .add_pending_verify(xor_name_from_u32(index), test_entry(1))
1619                .admitted());
1620            assert!(queues
1621                .add_pending_verify(xor_name_from_u32(1_000_000 + index), test_entry(2),)
1622                .admitted());
1623        }
1624
1625        let selected = queues.select_ready_pending_keys(Instant::now(), CYCLE);
1626        let first_count = selected
1627            .iter()
1628            .filter(|key| queues.capacity_owner_by_key.get(*key) == Some(&first))
1629            .count();
1630        let second_count = selected
1631            .iter()
1632            .filter(|key| queues.capacity_owner_by_key.get(*key) == Some(&second))
1633            .count();
1634
1635        assert_eq!(first_count, CYCLE / 2);
1636        assert_eq!(second_count, CYCLE / 2);
1637    }
1638
1639    // -- add_pending_verify dedup ------------------------------------------
1640
1641    #[test]
1642    fn add_pending_verify_new_key_succeeds() {
1643        let mut queues = ReplicationQueues::new();
1644        let key = xor_name_from_byte(0x01);
1645        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1646        assert_eq!(queues.pending_count(), 1);
1647    }
1648
1649    #[test]
1650    fn large_single_source_backlog_is_not_subject_to_a_per_peer_cap() {
1651        const KEY_COUNT: u32 = 10_000;
1652        let mut queues = ReplicationQueues::new();
1653
1654        for index in 0..KEY_COUNT {
1655            assert!(
1656                queues
1657                    .add_pending_verify(xor_name_from_u32(index), test_entry(1))
1658                    .admitted(),
1659                "key {index} should be admitted below the global emergency bound"
1660            );
1661        }
1662        assert_eq!(queues.pending_count(), KEY_COUNT as usize);
1663    }
1664
1665    /// Duplicate advertisements must not grow a key's source set without bound.
1666    ///
1667    /// `MAX_PENDING_VERIFY` counts keys, not the peers remembered against each
1668    /// one, so before the cap N peers re-advertising a full queue cost
1669    /// `N * MAX_PENDING_VERIFY` associations charged to nothing.
1670    #[test]
1671    fn duplicate_hints_cannot_grow_a_keys_source_set_without_bound() {
1672        const ADVERTISERS: u8 = 40;
1673
1674        let mut queues = ReplicationQueues::new();
1675        let key = xor_name_from_byte(0x5A);
1676        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1677
1678        for advertiser in 2..=ADVERTISERS {
1679            queues.add_pending_verify(key, test_entry(advertiser));
1680        }
1681
1682        let entry = queues.get_pending(&key).expect("pending entry");
1683        assert!(
1684            entry.hint_sources.len() <= MAX_HINT_SOURCES_PER_KEY,
1685            "hint sources must stay capped, got {}",
1686            entry.hint_sources.len()
1687        );
1688        assert!(
1689            entry.replica_hint_sources.len() <= MAX_HINT_SOURCES_PER_KEY,
1690            "replica hint sources must stay capped"
1691        );
1692        let indexed: usize = queues
1693            .pending_keys_by_source
1694            .values()
1695            .map(|keys| keys.iter().filter(|k| **k == key).count())
1696            .sum();
1697        assert_eq!(
1698            indexed,
1699            entry.hint_sources.len(),
1700            "the reverse index must not outlive the sources it mirrors"
1701        );
1702    }
1703
1704    /// Replica claimants outrank paid-only advertisers for a capped slot: they
1705    /// are the only sources that assert possession, so only they are usable as
1706    /// fetch candidates.
1707    #[test]
1708    fn replica_claimants_displace_paid_only_sources_at_the_cap() {
1709        let mut queues = ReplicationQueues::new();
1710        let key = xor_name_from_byte(0x5B);
1711
1712        // Fill the cap with paid-only advertisers (no possession claim).
1713        let mut first = test_entry(1);
1714        first.replica_hint_sources.clear();
1715        assert!(queues.add_pending_verify(key, first).admitted());
1716        for advertiser in 2..=u8::try_from(MAX_HINT_SOURCES_PER_KEY).unwrap_or(u8::MAX) {
1717            let mut paid_only = test_entry(advertiser);
1718            paid_only.replica_hint_sources.clear();
1719            queues.add_pending_verify(key, paid_only);
1720        }
1721        assert_eq!(
1722            queues
1723                .get_pending(&key)
1724                .expect("pending entry")
1725                .hint_sources
1726                .len(),
1727            MAX_HINT_SOURCES_PER_KEY,
1728            "the cap should now be saturated with paid-only advertisers"
1729        );
1730
1731        let claimant = peer_id_from_byte(0xF0);
1732        let mut replica = test_entry(0xF0);
1733        replica.hint_sources = HashSet::from([claimant]);
1734        replica.replica_hint_sources = HashSet::from([claimant]);
1735        queues.add_pending_verify(key, replica);
1736
1737        let entry = queues.get_pending(&key).expect("pending entry");
1738        assert!(
1739            entry.replica_hint_sources.contains(&claimant),
1740            "a replica claimant must take a slot from a paid-only advertiser"
1741        );
1742        assert_eq!(
1743            entry.hint_sources.len(),
1744            MAX_HINT_SOURCES_PER_KEY,
1745            "displacement must not grow the set"
1746        );
1747        assert!(
1748            entry.hint_sources.contains(&claimant),
1749            "the claimant must also be recorded as a live hint source"
1750        );
1751    }
1752
1753    /// A promoted key's retry reservation must stay charged to its owner.
1754    ///
1755    /// Reservations are deducted from the global pool, so if they are billed to
1756    /// nobody an owner with many in-flight retries reads as under-loaded and
1757    /// wins a larger fair share than it earned.
1758    #[test]
1759    fn promoted_retry_reservation_stays_charged_to_its_owner() {
1760        let mut queues = ReplicationQueues::new();
1761        let key = xor_name_from_byte(0x5C);
1762        let owner = peer_id_from_byte(1);
1763
1764        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1765        assert_eq!(queues.charged_count_for_owner(&owner), 1);
1766
1767        assert!(queues.promote_pending_to_fetch(key, key, vec![owner]));
1768        assert_eq!(
1769            queues.retry_reserved_slot_count(),
1770            1,
1771            "promotion must reserve a slot for the later retry"
1772        );
1773        assert_eq!(
1774            queues.charged_count_for_owner(&owner),
1775            1,
1776            "the reservation must remain charged to the promoting owner while \
1777             the key sits in the fetch queue"
1778        );
1779
1780        let candidate = queues.dequeue_fetch().expect("promoted key is fetchable");
1781        queues.start_dequeued_fetch(candidate, owner);
1782        assert_eq!(
1783            queues.charged_count_for_owner(&owner),
1784            1,
1785            "the charge must survive the transfer into in-flight fetch"
1786        );
1787
1788        queues.complete_fetch(&key);
1789        assert_eq!(queues.retry_reserved_slot_count(), 0);
1790        assert_eq!(
1791            queues.charged_count_for_owner(&owner),
1792            0,
1793            "a terminal fetch must clear the owner's charge"
1794        );
1795    }
1796
1797    /// ADR-0005 decision 7: a sole sender may borrow the whole pool, but a
1798    /// later sender reclaims its fair share within a bounded number of
1799    /// admissions. This pins that convergence — the property that replaced the
1800    /// removed `MAX_PENDING_VERIFY_PER_PEER` hard cap.
1801    #[test]
1802    fn borrowed_capacity_converges_to_fair_share_for_a_late_sender() {
1803        /// Admissions the late sender is allowed before fairness must hold.
1804        /// Each one reclaims at most a single borrowed slot, so reaching an
1805        /// even split needs at least half the pool; the doubling is headroom
1806        /// for skipped candidates, not an expectation.
1807        const RECLAIM_BUDGET: usize = MAX_PENDING_VERIFY;
1808
1809        let mut queues = ReplicationQueues::new();
1810        let borrower = peer_id_from_byte(1);
1811        let late = peer_id_from_byte(2);
1812
1813        // A sole sender borrows the entire pool — permitted by design, and the
1814        // behaviour that replaced the removed per-peer hard cap.
1815        for index in 0..MAX_PENDING_VERIFY {
1816            let index = u32::try_from(index).unwrap_or(u32::MAX);
1817            assert!(queues
1818                .add_pending_verify(xor_name_from_u32(index), test_entry(1))
1819                .admitted());
1820        }
1821        assert_eq!(
1822            queues.charged_count_for_owner(&borrower),
1823            MAX_PENDING_VERIFY
1824        );
1825        assert!(
1826            !queues
1827                .add_pending_verify(xor_name_from_u32(u32::MAX), test_entry(1))
1828                .admitted(),
1829            "the borrower cannot exceed the global pool"
1830        );
1831
1832        // A second sender arrives and keeps offering work. Every admission it
1833        // wins must come out of the over-represented borrower's share.
1834        let mut late_admitted = 0usize;
1835        for offset in 0..RECLAIM_BUDGET {
1836            let index = u32::try_from(MAX_PENDING_VERIFY + offset).unwrap_or(u32::MAX);
1837            if queues
1838                .add_pending_verify(xor_name_from_u32(index), test_entry(2))
1839                .admitted()
1840            {
1841                late_admitted += 1;
1842            }
1843            if late_admitted >= MAX_PENDING_VERIFY / 2 {
1844                break;
1845            }
1846        }
1847
1848        assert_eq!(
1849            queues.charged_count_for_owner(&late),
1850            MAX_PENDING_VERIFY / 2,
1851            "a late sender must reclaim an even share within its budget"
1852        );
1853        assert_eq!(
1854            queues.charged_count_for_owner(&borrower) + late_admitted,
1855            MAX_PENDING_VERIFY,
1856            "reclaim must move slots between owners, never create them"
1857        );
1858        assert_eq!(
1859            queues.pending_count(),
1860            MAX_PENDING_VERIFY,
1861            "the global bound must hold throughout"
1862        );
1863    }
1864
1865    #[test]
1866    fn duplicate_pending_hint_adds_live_source_without_bypassing_deferral() {
1867        let mut queues = ReplicationQueues::new();
1868        let key = xor_name_from_byte(0x01);
1869        let source_a = peer_id_from_byte(1);
1870        let source_b = peer_id_from_byte(2);
1871        let mut first = test_entry(1);
1872        first.next_verify_at = Instant::now() + Duration::from_mins(1);
1873        assert!(queues.add_pending_verify(key, first).admitted());
1874        assert!(queues.ready_pending_keys(Instant::now()).is_empty());
1875        assert!(!queues.add_pending_verify(key, test_entry(2)).admitted());
1876        assert_eq!(queues.pending_count(), 1);
1877        assert_eq!(
1878            queues
1879                .get_pending(&key)
1880                .expect("pending entry")
1881                .hint_sources,
1882            HashSet::from([source_a, source_b])
1883        );
1884        assert!(
1885            queues.ready_pending_keys(Instant::now()).is_empty(),
1886            "a duplicate source must not bypass verification retry deferral"
1887        );
1888    }
1889
1890    #[test]
1891    fn repeated_duplicate_from_same_source_does_not_grow_eviction_heap() {
1892        let mut queues = ReplicationQueues::new();
1893        let key = xor_name_from_byte(0x77);
1894        let owner = peer_id_from_byte(1);
1895        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1896
1897        for _ in 0..1_000 {
1898            assert_eq!(
1899                queues.add_pending_verify(key, test_entry(1)),
1900                AdmissionResult::AlreadyPresent
1901            );
1902        }
1903
1904        assert_eq!(
1905            queues
1906                .eviction_candidates_by_owner
1907                .get(&owner)
1908                .map_or(0, BinaryHeap::len),
1909            1
1910        );
1911    }
1912
1913    #[test]
1914    fn ready_pending_keys_prioritizes_more_live_sources_then_age() {
1915        let mut queues = ReplicationQueues::new();
1916        let oldest_singleton = xor_name_from_byte(0x10);
1917        let newer_singleton = xor_name_from_byte(0x20);
1918        let corroborated = xor_name_from_byte(0x30);
1919        let now = Instant::now();
1920
1921        let mut oldest = test_entry(1);
1922        oldest.created_at = now.checked_sub(Duration::from_secs(2)).unwrap();
1923        let mut newer = test_entry(1);
1924        newer.created_at = now.checked_sub(Duration::from_secs(1)).unwrap();
1925        let mut multi = test_entry(1);
1926        multi.created_at = now;
1927
1928        assert!(queues
1929            .add_pending_verify(oldest_singleton, oldest)
1930            .admitted());
1931        assert!(queues.add_pending_verify(newer_singleton, newer).admitted());
1932        assert!(queues.add_pending_verify(corroborated, multi).admitted());
1933        assert_eq!(
1934            queues.add_pending_verify(corroborated, test_entry(2)),
1935            AdmissionResult::AlreadyPresent
1936        );
1937
1938        assert_eq!(
1939            queues.ready_pending_keys(Instant::now()),
1940            vec![corroborated, oldest_singleton, newer_singleton]
1941        );
1942    }
1943
1944    #[test]
1945    fn peer_removal_drops_orphans_and_preserves_corroborated_hints() {
1946        let mut queues = ReplicationQueues::new();
1947        let source_a = peer_id_from_byte(1);
1948        let source_b = peer_id_from_byte(2);
1949        let orphaned_key = xor_name_from_byte(0x40);
1950        let shared_key = xor_name_from_byte(0x41);
1951
1952        assert!(queues
1953            .add_pending_verify(orphaned_key, test_entry(1))
1954            .admitted());
1955        assert!(queues
1956            .add_pending_verify(shared_key, test_entry(1))
1957            .admitted());
1958        assert_eq!(
1959            queues.add_pending_verify(shared_key, test_entry(2)),
1960            AdmissionResult::AlreadyPresent
1961        );
1962
1963        assert_eq!(queues.remove_hint_source(&source_a), vec![orphaned_key]);
1964        let shared = queues
1965            .get_pending(&shared_key)
1966            .expect("shared hint retained");
1967        assert_eq!(shared.hint_sources, HashSet::from([source_b]));
1968        assert_eq!(queues.pending_count_for_owner(&source_a), 0);
1969        assert_eq!(queues.pending_count_for_owner(&source_b), 1);
1970
1971        assert_eq!(queues.remove_hint_source(&source_b), vec![shared_key]);
1972        assert_eq!(queues.pending_count(), 0);
1973    }
1974
1975    #[test]
1976    fn peer_removal_prunes_fetch_and_retry_sources() {
1977        let mut queues = ReplicationQueues::new();
1978        let source_a = peer_id_from_byte(1);
1979        let source_b = peer_id_from_byte(2);
1980        let key = xor_name_from_byte(0x42);
1981
1982        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1983        assert_eq!(
1984            queues.add_pending_verify(key, test_entry(2)),
1985            AdmissionResult::AlreadyPresent
1986        );
1987        assert!(queues.promote_pending_to_fetch(
1988            key,
1989            xor_name_from_byte(0x01),
1990            vec![source_a, source_b],
1991        ));
1992
1993        assert!(queues.remove_hint_source(&source_a).is_empty());
1994        let candidate = queues.dequeue_fetch().expect("candidate remains fetchable");
1995        assert_eq!(candidate.sources, vec![source_b]);
1996        assert_eq!(
1997            candidate
1998                .retry_verification
1999                .as_ref()
2000                .expect("retry provenance retained")
2001                .hint_sources,
2002            HashSet::from([source_b])
2003        );
2004        queues.discard_fetch_candidate(candidate);
2005    }
2006
2007    #[test]
2008    fn add_pending_verify_rejected_if_in_fetch_queue() {
2009        let mut queues = ReplicationQueues::new();
2010        let key = xor_name_from_byte(0x02);
2011        let distance = xor_name_from_byte(0x10);
2012        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(1)]);
2013
2014        assert!(
2015            !queues.add_pending_verify(key, test_entry(1)).admitted(),
2016            "should reject key already in fetch queue"
2017        );
2018    }
2019
2020    #[test]
2021    fn add_pending_verify_merges_source_into_queued_candidate() {
2022        let mut queues = ReplicationQueues::new();
2023        let key = xor_name_from_byte(0x02);
2024        let queued_source = peer_id_from_byte(1);
2025        let extra_source = peer_id_from_byte(2);
2026
2027        queues.enqueue_fetch(key, xor_name_from_byte(0x10), vec![queued_source]);
2028
2029        assert_eq!(
2030            queues.add_pending_verify(key, test_entry(2)),
2031            AdmissionResult::AlreadyPresent
2032        );
2033        // A repeat hint from an already-known advertiser must not duplicate it.
2034        assert_eq!(
2035            queues.add_pending_verify(key, test_entry(1)),
2036            AdmissionResult::AlreadyPresent
2037        );
2038
2039        let candidate = queues.dequeue_fetch().expect("queued candidate");
2040        assert_eq!(
2041            candidate.sources,
2042            vec![queued_source, extra_source],
2043            "a new advertiser is merged as a fetch source exactly once"
2044        );
2045        queues.discard_fetch_candidate(candidate);
2046    }
2047
2048    #[test]
2049    fn add_pending_verify_merge_preserves_fetch_priority_order() {
2050        let mut queues = ReplicationQueues::new();
2051        let near_key = xor_name_from_byte(0x01);
2052        let far_key = xor_name_from_byte(0x02);
2053        let near_dist = [0x00; 32]; // nearest
2054        let far_dist = [0xFF; 32]; // farthest
2055
2056        queues.enqueue_fetch(far_key, far_dist, vec![peer_id_from_byte(1)]);
2057        queues.enqueue_fetch(near_key, near_dist, vec![peer_id_from_byte(2)]);
2058
2059        // Merging a source into the farthest key must not reorder the queue:
2060        // the merge touches no field the heap orders on.
2061        assert_eq!(
2062            queues.add_pending_verify(far_key, test_entry(3)),
2063            AdmissionResult::AlreadyPresent
2064        );
2065
2066        let first = queues.dequeue_fetch().expect("should dequeue");
2067        assert_eq!(
2068            first.key, near_key,
2069            "nearest key still dequeues first after a merge"
2070        );
2071        queues.discard_fetch_candidate(first);
2072
2073        let second = queues.dequeue_fetch().expect("should dequeue");
2074        assert_eq!(second.key, far_key, "farthest key dequeues second");
2075        queues.discard_fetch_candidate(second);
2076    }
2077
2078    #[test]
2079    fn peer_removal_drops_orphaned_fetch_candidate() {
2080        let mut queues = ReplicationQueues::new();
2081        let source = peer_id_from_byte(1);
2082        let key = xor_name_from_byte(0x43);
2083
2084        queues.enqueue_fetch(key, xor_name_from_byte(0x10), vec![source]);
2085
2086        assert_eq!(
2087            queues.remove_hint_source(&source),
2088            vec![key],
2089            "a candidate whose last source departed is reported orphaned"
2090        );
2091        assert_eq!(queues.fetch_queue_count(), 0);
2092        assert!(
2093            !queues.contains_key(&key),
2094            "orphaned key leaves the pipeline entirely"
2095        );
2096        assert!(
2097            queues.dequeue_fetch().is_none(),
2098            "orphaned candidate must not linger in the priority heap"
2099        );
2100    }
2101
2102    #[test]
2103    fn add_pending_verify_rejected_if_in_flight() {
2104        let mut queues = ReplicationQueues::new();
2105        let key = xor_name_from_byte(0x03);
2106        let source = peer_id_from_byte(1);
2107        queues.start_fetch(key, source, vec![source]);
2108
2109        assert!(
2110            !queues.add_pending_verify(key, test_entry(1)).admitted(),
2111            "should reject key already in-flight"
2112        );
2113    }
2114
2115    // -- enqueue/dequeue ordering -----------------------------------------
2116
2117    #[test]
2118    fn dequeue_returns_nearest_first() {
2119        let mut queues = ReplicationQueues::new();
2120
2121        let near_key = xor_name_from_byte(0x01);
2122        let far_key = xor_name_from_byte(0x02);
2123        let near_dist = [0x00; 32]; // nearest
2124        let far_dist = [0xFF; 32]; // farthest
2125
2126        queues.enqueue_fetch(far_key, far_dist, vec![peer_id_from_byte(1)]);
2127        queues.enqueue_fetch(near_key, near_dist, vec![peer_id_from_byte(2)]);
2128
2129        let first = queues.dequeue_fetch().expect("should dequeue");
2130        assert_eq!(first.key, near_key, "nearest key should dequeue first");
2131        queues.discard_fetch_candidate(first);
2132
2133        let second = queues.dequeue_fetch().expect("should dequeue");
2134        assert_eq!(second.key, far_key, "farthest key should dequeue second");
2135        queues.discard_fetch_candidate(second);
2136    }
2137
2138    #[test]
2139    fn enqueue_dedup_prevents_duplicates() {
2140        let mut queues = ReplicationQueues::new();
2141        let key = xor_name_from_byte(0x01);
2142
2143        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(1)]);
2144        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(2)]);
2145
2146        assert_eq!(
2147            queues.fetch_queue_count(),
2148            1,
2149            "duplicate enqueue should be ignored"
2150        );
2151    }
2152
2153    // -- in-flight tracking -----------------------------------------------
2154
2155    #[test]
2156    fn start_and_complete_fetch() {
2157        let mut queues = ReplicationQueues::new();
2158        let key = xor_name_from_byte(0x01);
2159        let source = peer_id_from_byte(1);
2160
2161        queues.start_fetch(key, source, vec![source]);
2162        assert_eq!(queues.in_flight_count(), 1);
2163
2164        let completed = queues.complete_fetch(&key);
2165        assert!(completed.is_some());
2166        assert_eq!(queues.in_flight_count(), 0);
2167    }
2168
2169    #[test]
2170    fn complete_nonexistent_returns_none() {
2171        let mut queues = ReplicationQueues::new();
2172        let key = xor_name_from_byte(0x99);
2173        assert!(queues.complete_fetch(&key).is_none());
2174    }
2175
2176    // -- retry_fetch ------------------------------------------------------
2177
2178    #[test]
2179    fn retry_fetch_returns_next_untried_source() {
2180        let mut queues = ReplicationQueues::new();
2181        let key = xor_name_from_byte(0x01);
2182        let source_a = peer_id_from_byte(1);
2183        let source_b = peer_id_from_byte(2);
2184        let source_c = peer_id_from_byte(3);
2185
2186        queues.start_fetch(key, source_a, vec![source_a, source_b, source_c]);
2187
2188        // First retry: should skip source_a (already tried), return source_b.
2189        let next = queues.retry_fetch(&key);
2190        assert_eq!(next, Some(source_b));
2191
2192        // Second retry: should return source_c.
2193        let next = queues.retry_fetch(&key);
2194        assert_eq!(next, Some(source_c));
2195
2196        // Third retry: all exhausted.
2197        let next = queues.retry_fetch(&key);
2198        assert!(next.is_none(), "all sources exhausted");
2199    }
2200
2201    #[test]
2202    fn retry_fetch_nonexistent_returns_none() {
2203        let mut queues = ReplicationQueues::new();
2204        assert!(queues.retry_fetch(&xor_name_from_byte(0xFF)).is_none());
2205    }
2206
2207    #[test]
2208    fn exhausted_promoted_fetch_requeues_verification() {
2209        const KEY_BYTE: u8 = 0x44;
2210        const DISTANCE_BYTE: u8 = 0x01;
2211        const SOURCE_BYTE: u8 = 2;
2212        const HINT_SENDER_BYTE: u8 = 9;
2213        const RETRY_DELAY: Duration = Duration::from_secs(15);
2214        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2215
2216        let mut queues = ReplicationQueues::new();
2217        let key = xor_name_from_byte(KEY_BYTE);
2218        let distance = xor_name_from_byte(DISTANCE_BYTE);
2219        let source = peer_id_from_byte(SOURCE_BYTE);
2220        let entry = test_entry(HINT_SENDER_BYTE);
2221
2222        assert!(queues.add_pending_verify(key, entry).admitted());
2223        assert!(queues.promote_pending_to_fetch(key, distance, vec![source]));
2224
2225        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2226        queues.start_dequeued_fetch(candidate, source);
2227
2228        assert!(
2229            queues.retry_fetch(&key).is_none(),
2230            "single source should be exhausted"
2231        );
2232        assert!(queues.requeue_fetch_for_verification(&key, RETRY_DELAY));
2233
2234        assert_eq!(queues.in_flight_count(), 0);
2235        assert!(
2236            queues.ready_pending_keys(Instant::now()).is_empty(),
2237            "requeued key should observe retry delay"
2238        );
2239
2240        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2241        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2242        assert_eq!(
2243            queues.pending_count_for_owner(&peer_id_from_byte(HINT_SENDER_BYTE)),
2244            1
2245        );
2246        assert!(queues.protected_pending_keys.contains(&key));
2247        assert_eq!(
2248            queues.capacity_owner_by_key.get(&key),
2249            Some(&peer_id_from_byte(HINT_SENDER_BYTE))
2250        );
2251    }
2252
2253    #[test]
2254    fn no_sources_dequeued_candidate_requeues_for_verification() {
2255        const KEY_INDEX: u32 = 70_000;
2256        const DISTANCE_BYTE: u8 = 0x01;
2257        const HINT_SENDER_BYTE: u8 = 9;
2258        const VERIFIED_SOURCE_BYTE: u8 = 2;
2259        const TRIED_SOURCE_BYTE: u8 = 3;
2260        const RETRY_DELAY: Duration = Duration::from_secs(15);
2261        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2262
2263        let mut queues = ReplicationQueues::new();
2264        let key = xor_name_from_u32(KEY_INDEX);
2265        let distance = xor_name_from_byte(DISTANCE_BYTE);
2266        let verified_source = peer_id_from_byte(VERIFIED_SOURCE_BYTE);
2267        let tried_source = peer_id_from_byte(TRIED_SOURCE_BYTE);
2268        let mut entry = test_entry(HINT_SENDER_BYTE);
2269        entry.state = VerificationState::QueuedForFetch;
2270        entry.verified_sources.push(verified_source);
2271        entry.tried_sources.insert(tried_source);
2272
2273        assert!(queues.add_pending_verify(key, entry).admitted());
2274        assert!(queues.promote_pending_to_fetch(key, distance, Vec::new()));
2275
2276        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2277        assert!(
2278            candidate.sources.is_empty(),
2279            "test candidate should exercise the no-sources branch"
2280        );
2281        assert!(
2282            queues.requeue_candidate_for_verification(candidate, RETRY_DELAY),
2283            "no-sources retry candidate should be restored to pending verification"
2284        );
2285
2286        let pending = queues.get_pending(&key).expect("key should be pending");
2287        assert_eq!(pending.state, VerificationState::PendingVerify);
2288        assert!(
2289            pending.verified_sources.is_empty(),
2290            "verified sources should be cleared before retry"
2291        );
2292        assert!(
2293            pending.tried_sources.is_empty(),
2294            "tried sources should be cleared before retry"
2295        );
2296        assert!(
2297            queues.ready_pending_keys(Instant::now()).is_empty(),
2298            "requeued key should observe retry delay"
2299        );
2300
2301        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2302        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2303
2304        assert!(queues.remove_pending(&key).is_some());
2305    }
2306
2307    #[test]
2308    fn exhausted_direct_fetch_remains_terminal() {
2309        const KEY_BYTE: u8 = 0x45;
2310        const DISTANCE_BYTE: u8 = 0x01;
2311        const SOURCE_BYTE: u8 = 2;
2312        const RETRY_DELAY: Duration = Duration::from_secs(15);
2313
2314        let mut queues = ReplicationQueues::new();
2315        let key = xor_name_from_byte(KEY_BYTE);
2316        let source = peer_id_from_byte(SOURCE_BYTE);
2317
2318        queues.enqueue_fetch(key, xor_name_from_byte(DISTANCE_BYTE), vec![source]);
2319        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2320        queues.start_dequeued_fetch(candidate, source);
2321
2322        assert!(
2323            queues.retry_fetch(&key).is_none(),
2324            "single source should be exhausted"
2325        );
2326        assert!(!queues.requeue_fetch_for_verification(&key, RETRY_DELAY));
2327        assert_eq!(queues.in_flight_count(), 0);
2328        assert_eq!(queues.pending_count(), 0);
2329    }
2330
2331    // -- contains_key across pipelines ------------------------------------
2332
2333    #[test]
2334    fn contains_key_in_pending() {
2335        let mut queues = ReplicationQueues::new();
2336        let key = xor_name_from_byte(0x01);
2337        queues.add_pending_verify(key, test_entry(1));
2338        assert!(queues.contains_key(&key));
2339    }
2340
2341    #[test]
2342    fn contains_key_in_fetch_queue() {
2343        let mut queues = ReplicationQueues::new();
2344        let key = xor_name_from_byte(0x02);
2345        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(1)]);
2346        assert!(queues.contains_key(&key));
2347    }
2348
2349    #[test]
2350    fn contains_key_in_flight() {
2351        let mut queues = ReplicationQueues::new();
2352        let key = xor_name_from_byte(0x03);
2353        queues.start_fetch(key, peer_id_from_byte(1), vec![]);
2354        assert!(queues.contains_key(&key));
2355    }
2356
2357    #[test]
2358    fn contains_key_absent() {
2359        let queues = ReplicationQueues::new();
2360        assert!(!queues.contains_key(&xor_name_from_byte(0xFF)));
2361    }
2362
2363    // -- bootstrap work empty ---------------------------------------------
2364
2365    #[test]
2366    fn bootstrap_work_empty_when_no_keys_present() {
2367        let queues = ReplicationQueues::new();
2368        let bootstrap_keys: HashSet<XorName> = [xor_name_from_byte(0x01), xor_name_from_byte(0x02)]
2369            .into_iter()
2370            .collect();
2371        assert!(queues.is_bootstrap_work_empty(&bootstrap_keys));
2372    }
2373
2374    #[test]
2375    fn bootstrap_work_not_empty_when_key_in_pending() {
2376        let mut queues = ReplicationQueues::new();
2377        let key = xor_name_from_byte(0x01);
2378        queues.add_pending_verify(key, test_entry(1));
2379
2380        let bootstrap_keys: HashSet<XorName> = std::iter::once(key).collect();
2381        assert!(!queues.is_bootstrap_work_empty(&bootstrap_keys));
2382    }
2383
2384    // -- evict_stale ------------------------------------------------------
2385
2386    #[test]
2387    fn evict_stale_removes_old_entries() {
2388        let mut queues = ReplicationQueues::new();
2389        let key = xor_name_from_byte(0x01);
2390
2391        let mut entry = test_entry(1);
2392        // Backdate via the same defensive checked_sub used elsewhere so
2393        // freshly-booted CI clocks don't trip us up.
2394        entry.created_at = Instant::now()
2395            .checked_sub(Duration::from_secs(2))
2396            .unwrap_or_else(Instant::now);
2397        assert!(queues.add_pending_verify(key, entry).admitted());
2398
2399        assert_eq!(queues.pending_count(), 1);
2400
2401        let evicted = queues.evict_stale(Duration::from_secs(1));
2402        assert_eq!(evicted, vec![key]);
2403        assert_eq!(
2404            queues.pending_count(),
2405            0,
2406            "entry older than max_age should be evicted"
2407        );
2408    }
2409
2410    #[test]
2411    fn evict_stale_keeps_fresh_entries() {
2412        let mut queues = ReplicationQueues::new();
2413        let key = xor_name_from_byte(0x01);
2414        queues.add_pending_verify(key, test_entry(1));
2415
2416        let evicted = queues.evict_stale(Duration::from_hours(1));
2417        assert!(
2418            evicted.is_empty(),
2419            "fresh entry should not be reported as evicted"
2420        );
2421        assert_eq!(
2422            queues.pending_count(),
2423            1,
2424            "fresh entry should not be evicted"
2425        );
2426    }
2427
2428    #[test]
2429    fn deferred_pending_key_is_not_ready_until_retry_time() {
2430        const RETRY_DELAY: Duration = Duration::from_secs(15);
2431        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2432
2433        let mut queues = ReplicationQueues::new();
2434        let key = xor_name_from_byte(0xAA);
2435        queues.add_pending_verify(key, test_entry(1));
2436
2437        assert_eq!(queues.ready_pending_keys(Instant::now()), vec![key]);
2438        assert!(queues.defer_pending(&key, RETRY_DELAY));
2439        assert!(
2440            queues.ready_pending_keys(Instant::now()).is_empty(),
2441            "deferred key should not be retried immediately"
2442        );
2443
2444        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2445        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2446    }
2447
2448    #[test]
2449    fn repeated_deferrals_back_off_and_saturate_at_the_cap() {
2450        const BASE: Duration = Duration::from_secs(15);
2451
2452        let mut queues = ReplicationQueues::new();
2453        let key = xor_name_from_byte(0xAB);
2454        queues.add_pending_verify(key, test_entry(1));
2455
2456        // 15s doubling per consecutive unresolved round.
2457        for (attempt, expected_secs) in [(1, 15), (2, 30), (3, 60), (4, 120), (5, 240)] {
2458            let outcome = queues
2459                .defer_unresolved(&key, BASE)
2460                .expect("pending key should defer");
2461            assert_eq!(outcome.attempt, attempt);
2462            assert_eq!(
2463                outcome.retry_after,
2464                Duration::from_secs(expected_secs),
2465                "attempt {attempt} should back off to {expected_secs}s"
2466            );
2467        }
2468
2469        // Everything past the cap stays at the cap rather than overflowing the
2470        // shift into a short (or zero) delay.
2471        for _ in 0..64 {
2472            let outcome = queues
2473                .defer_unresolved(&key, BASE)
2474                .expect("pending key should defer");
2475            assert_eq!(
2476                outcome.retry_after, VERIFICATION_RETRY_BACKOFF_MAX,
2477                "backoff must saturate at the cap, never wrap"
2478            );
2479        }
2480    }
2481
2482    /// The counter and the warning answer different questions, so a round that
2483    /// advances the count without producing a no-holder result — an
2484    /// inconclusive quorum — must leave the warning unclaimed. Deriving the
2485    /// report from `attempt == 1` loses the first and only warning for every
2486    /// key whose opening round is inconclusive.
2487    #[test]
2488    fn a_non_reporting_round_does_not_consume_the_no_holder_warning() {
2489        const BASE: Duration = Duration::from_secs(15);
2490
2491        let mut queues = ReplicationQueues::new();
2492        let key = xor_name_from_byte(0xAE);
2493        queues.add_pending_verify(key, test_entry(1));
2494
2495        // Round 1: inconclusive quorum. Backs off, reports nothing.
2496        let first = queues
2497            .defer_unresolved(&key, BASE)
2498            .expect("pending key should defer");
2499        assert_eq!(first.attempt, 1);
2500
2501        // Round 2 is the first that actually finds no holder. It is at
2502        // attempt 2, but it is the first report and must still warn.
2503        let second = queues
2504            .defer_unresolved(&key, BASE)
2505            .expect("pending key should defer");
2506        assert_eq!(second.attempt, 2, "the inconclusive round still counts");
2507        assert!(
2508            queues.claim_no_holder_report(&key),
2509            "the first no-holder result must warn even at attempt 2"
2510        );
2511        assert!(
2512            !queues.claim_no_holder_report(&key),
2513            "the warning is claimed exactly once per entry"
2514        );
2515    }
2516
2517    /// A round that found a holder ends the run of failures, even when a full
2518    /// fetch queue leaves the key pending. It must not inherit the old backoff,
2519    /// and a later relapse deserves a fresh warning.
2520    #[test]
2521    fn finding_a_holder_clears_the_backoff_and_rearms_the_warning() {
2522        const BASE: Duration = Duration::from_secs(15);
2523
2524        let mut queues = ReplicationQueues::new();
2525        let key = xor_name_from_byte(0xAF);
2526        queues.add_pending_verify(key, test_entry(1));
2527
2528        for _ in 0..4 {
2529            queues
2530                .defer_unresolved(&key, BASE)
2531                .expect("pending key should defer");
2532        }
2533        assert!(queues.claim_no_holder_report(&key));
2534
2535        assert!(queues.clear_unresolved(&key));
2536
2537        let outcome = queues
2538            .defer_unresolved(&key, BASE)
2539            .expect("pending key should defer");
2540        assert_eq!(outcome.attempt, 1, "a resolved round restarts the run");
2541        assert_eq!(outcome.retry_after, BASE);
2542        assert!(
2543            queues.claim_no_holder_report(&key),
2544            "a relapse after a good round is reported again"
2545        );
2546    }
2547
2548    /// The whole fix rests on a duplicate hint merging into the live entry
2549    /// rather than replacing it. A refactor that replaced would silently revert
2550    /// the backoff with every other test here still green.
2551    #[test]
2552    fn a_duplicate_hint_does_not_reset_the_backoff_or_the_retry_time() {
2553        const BASE: Duration = Duration::from_secs(15);
2554
2555        let mut queues = ReplicationQueues::new();
2556        let key = xor_name_from_byte(0xB0);
2557        queues.add_pending_verify(key, test_entry(1));
2558
2559        for _ in 0..3 {
2560            queues
2561                .defer_unresolved(&key, BASE)
2562                .expect("pending key should defer");
2563        }
2564        assert!(queues.claim_no_holder_report(&key));
2565        let deferred_until = queues.pending_verify[&key].next_verify_at;
2566
2567        // A second advertiser re-hints the same key.
2568        assert!(!queues.add_pending_verify(key, test_entry(2)).admitted());
2569
2570        let entry = &queues.pending_verify[&key];
2571        assert_eq!(
2572            entry.unresolved_retries, 3,
2573            "a re-hint must not restart the backoff"
2574        );
2575        assert!(
2576            entry.no_holder_reported,
2577            "a re-hint must not re-arm the warning; only eviction ends an episode"
2578        );
2579        assert_eq!(
2580            entry.next_verify_at, deferred_until,
2581            "a re-hint must not pull the key forward into an earlier round"
2582        );
2583    }
2584
2585    /// The write-blocked capacity gate defers without asking anyone, so it must
2586    /// not consume the entry's first-failure warning or advance its backoff:
2587    /// nothing was learned about the key.
2588    #[test]
2589    fn flat_defer_does_not_advance_the_unresolved_backoff() {
2590        const BASE: Duration = Duration::from_secs(15);
2591
2592        let mut queues = ReplicationQueues::new();
2593        let key = xor_name_from_byte(0xAD);
2594        queues.add_pending_verify(key, test_entry(1));
2595
2596        for _ in 0..10 {
2597            assert!(queues.defer_pending(&key, Duration::from_mins(5)));
2598        }
2599
2600        let outcome = queues
2601            .defer_unresolved(&key, BASE)
2602            .expect("pending key should defer");
2603        assert_eq!(
2604            outcome.attempt, 1,
2605            "a flat deferral is not a failed round and must not consume attempt 1"
2606        );
2607        assert_eq!(outcome.retry_after, BASE);
2608        assert!(
2609            queues.claim_no_holder_report(&key),
2610            "nor may it consume the warning"
2611        );
2612    }
2613
2614    #[test]
2615    fn defer_unresolved_reports_none_for_unknown_key() {
2616        let mut queues = ReplicationQueues::new();
2617        assert!(queues
2618            .defer_unresolved(&xor_name_from_byte(0xFF), Duration::from_secs(15))
2619            .is_none());
2620    }
2621
2622    #[test]
2623    fn re_admission_after_eviction_restarts_the_backoff() {
2624        const BASE: Duration = Duration::from_secs(15);
2625
2626        let mut queues = ReplicationQueues::new();
2627        let key = xor_name_from_byte(0xAC);
2628        queues.add_pending_verify(key, test_entry(1));
2629
2630        for _ in 0..5 {
2631            queues
2632                .defer_unresolved(&key, BASE)
2633                .expect("pending key should defer");
2634        }
2635
2636        // Stale eviction drops the entry; the next hint admits a fresh one. The
2637        // count lives on the entry, so the episode — and its single warning —
2638        // starts over.
2639        queues.evict_stale(Duration::ZERO);
2640        assert_eq!(queues.pending_count(), 0);
2641        queues.add_pending_verify(key, test_entry(1));
2642
2643        let outcome = queues
2644            .defer_unresolved(&key, BASE)
2645            .expect("re-admitted key should defer");
2646        assert_eq!(outcome.attempt, 1, "re-admission starts a new episode");
2647        assert_eq!(outcome.retry_after, BASE);
2648    }
2649
2650    #[test]
2651    fn backoff_never_retries_faster_than_the_caller_base() {
2652        // A base above the cap (an unusual config, but representable) must not
2653        // be shortened into a tighter retry loop than the caller asked for.
2654        let long_base = VERIFICATION_RETRY_BACKOFF_MAX + Duration::from_mins(1);
2655        assert_eq!(backoff_delay(long_base, 1), long_base);
2656        assert_eq!(backoff_delay(long_base, 9), long_base);
2657    }
2658
2659    // -- remove_pending ---------------------------------------------------
2660
2661    #[test]
2662    fn remove_pending_returns_entry() {
2663        let mut queues = ReplicationQueues::new();
2664        let key = xor_name_from_byte(0x01);
2665        queues.add_pending_verify(key, test_entry(1));
2666
2667        let removed = queues.remove_pending(&key);
2668        assert!(removed.is_some());
2669        assert_eq!(queues.pending_count(), 0);
2670    }
2671
2672    #[test]
2673    fn remove_pending_nonexistent_returns_none() {
2674        let mut queues = ReplicationQueues::new();
2675        assert!(queues.remove_pending(&xor_name_from_byte(0xFF)).is_none());
2676    }
2677
2678    // -----------------------------------------------------------------------
2679    // Section 18 scenarios
2680    // -----------------------------------------------------------------------
2681
2682    /// Scenario 8: A key already in `PendingVerify` cannot be enqueued into
2683    /// `FetchQueue` (cross-queue dedup). Also, a key in `FetchQueue` cannot be
2684    /// re-added to `PendingVerify`.
2685    #[test]
2686    fn scenario_8_duplicate_key_not_double_queued() {
2687        let mut queues = ReplicationQueues::new();
2688        let key = xor_name_from_byte(0xE0);
2689        let distance = xor_name_from_byte(0x10);
2690
2691        // Step 1: Add to PendingVerify.
2692        assert!(
2693            queues.add_pending_verify(key, test_entry(1)).admitted(),
2694            "first add to PendingVerify should succeed"
2695        );
2696        assert!(
2697            queues.contains_key(&key),
2698            "key should be present in pipeline"
2699        );
2700
2701        // Step 2: Attempt to enqueue fetch while still in PendingVerify.
2702        // enqueue_fetch checks all three stages (pending_verify,
2703        // fetch_queue_keys, in_flight), so this is a no-op while the key
2704        // is still in PendingVerify.
2705        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(2)]);
2706        // Verify the key is still tracked via the cross-stage check.
2707        assert!(queues.contains_key(&key), "key should still be in pipeline");
2708
2709        // Step 3: Remove from PendingVerify, add to FetchQueue.
2710        queues.remove_pending(&key);
2711        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(3)]);
2712        assert_eq!(queues.fetch_queue_count(), 1);
2713
2714        // Step 4: Attempt to re-add to PendingVerify -> should fail.
2715        assert!(
2716            !queues.add_pending_verify(key, test_entry(4)).admitted(),
2717            "key in FetchQueue should be rejected from PendingVerify"
2718        );
2719
2720        // Step 5: Dequeue, start fetch -> key is in-flight.
2721        let candidate = queues.dequeue_fetch().expect("should dequeue");
2722        let source = candidate.sources[0];
2723        queues.start_dequeued_fetch(candidate, source);
2724
2725        // Step 6: Attempt to add to PendingVerify while in-flight -> reject.
2726        assert!(
2727            !queues.add_pending_verify(key, test_entry(5)).admitted(),
2728            "key in-flight should be rejected from PendingVerify"
2729        );
2730
2731        // Step 7: Attempt to enqueue fetch while in-flight -> no-op.
2732        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(6)]);
2733        // fetch_queue should still be empty (the enqueue was a no-op).
2734        assert_eq!(
2735            queues.fetch_queue_count(),
2736            0,
2737            "enqueue_fetch should be no-op for in-flight key"
2738        );
2739    }
2740
2741    /// Scenario 8 (continued): Verify that pipeline field for a key
2742    /// admitted as both replica and paid hint collapses to Replica only,
2743    /// because cross-set precedence in admission gives replica priority.
2744    #[test]
2745    fn scenario_8_replica_and_paid_hint_collapses_to_replica() {
2746        let mut queues = ReplicationQueues::new();
2747        let key = xor_name_from_byte(0xE1);
2748
2749        // Simulate admission result: key was in both replica_hints and
2750        // paid_hints, so admission records a possession claim for it.
2751        let entry = VerificationEntry {
2752            state: VerificationState::PendingVerify,
2753            verified_sources: Vec::new(),
2754            tried_sources: HashSet::new(),
2755            created_at: Instant::now(),
2756            next_verify_at: Instant::now(),
2757            hint_sources: HashSet::from([peer_id_from_byte(1)]),
2758            replica_hint_sources: HashSet::from([peer_id_from_byte(1)]),
2759            unresolved_retries: 0,
2760            no_holder_reported: false,
2761        };
2762
2763        assert!(queues.add_pending_verify(key, entry).admitted());
2764
2765        let pending = queues.get_pending(&key).expect("should be pending");
2766        assert_eq!(
2767            pending.pipeline(),
2768            crate::replication::types::HintPipeline::Replica,
2769            "key in both hint sets should be Replica pipeline"
2770        );
2771
2772        // A second add (e.g. from paid hints arriving separately) is rejected.
2773        let paid_entry = VerificationEntry {
2774            state: VerificationState::PendingVerify,
2775            verified_sources: Vec::new(),
2776            tried_sources: HashSet::new(),
2777            created_at: Instant::now(),
2778            next_verify_at: Instant::now(),
2779            hint_sources: HashSet::from([peer_id_from_byte(2)]),
2780            replica_hint_sources: HashSet::new(),
2781            unresolved_retries: 0,
2782            no_holder_reported: false,
2783        };
2784
2785        assert!(
2786            !queues.add_pending_verify(key, paid_entry).admitted(),
2787            "duplicate key should be rejected regardless of pipeline"
2788        );
2789
2790        // Pipeline stays Replica: merging a paid-only advertiser adds no
2791        // possession claim, so it cannot demote the existing one.
2792        let pending = queues.get_pending(&key).expect("should still be pending");
2793        assert_eq!(
2794            pending.pipeline(),
2795            crate::replication::types::HintPipeline::Replica,
2796            "pipeline should remain Replica after duplicate rejection"
2797        );
2798    }
2799
2800    /// A paid-only key cannot be escalated into the fetch-eligible pipeline by
2801    /// a peer re-advertising it as a replica hint.
2802    ///
2803    /// The queue still records the possession claim — that is what the sender
2804    /// asserted, and it makes the sender a fetch-source candidate. What it must
2805    /// not do is turn that claim into permission to store: the storage-
2806    /// admission check at download time is what decides, and it consults live
2807    /// routing state rather than this tag.
2808    #[test]
2809    fn replica_hint_on_paid_only_key_does_not_grant_storage_admission() {
2810        let mut queues = ReplicationQueues::new();
2811        let key = xor_name_from_byte(0xE2);
2812        let paid_advertiser = peer_id_from_byte(1);
2813        let replica_advertiser = peer_id_from_byte(2);
2814
2815        let paid_entry = VerificationEntry {
2816            state: VerificationState::PendingVerify,
2817            verified_sources: Vec::new(),
2818            tried_sources: HashSet::new(),
2819            created_at: Instant::now(),
2820            next_verify_at: Instant::now(),
2821            hint_sources: HashSet::from([paid_advertiser]),
2822            replica_hint_sources: HashSet::new(),
2823            unresolved_retries: 0,
2824            no_holder_reported: false,
2825        };
2826        assert!(queues.add_pending_verify(key, paid_entry).admitted());
2827        assert_eq!(
2828            queues
2829                .get_pending(&key)
2830                .expect("should be pending")
2831                .pipeline(),
2832            crate::replication::types::HintPipeline::PaidOnly,
2833        );
2834
2835        // Second message re-advertises the same key as a replica hint.
2836        let replica_entry = VerificationEntry {
2837            state: VerificationState::PendingVerify,
2838            verified_sources: Vec::new(),
2839            tried_sources: HashSet::new(),
2840            created_at: Instant::now(),
2841            next_verify_at: Instant::now(),
2842            hint_sources: HashSet::from([replica_advertiser]),
2843            replica_hint_sources: HashSet::from([replica_advertiser]),
2844            unresolved_retries: 0,
2845            no_holder_reported: false,
2846        };
2847        assert!(!queues.add_pending_verify(key, replica_entry).admitted());
2848
2849        let pending = queues.get_pending(&key).expect("should still be pending");
2850        assert!(
2851            pending.replica_hint_sources.contains(&replica_advertiser),
2852            "the possession claim is recorded for fetch-source discovery"
2853        );
2854        assert!(
2855            !pending.replica_hint_sources.contains(&paid_advertiser),
2856            "a paid-only advertiser never becomes a fetch source"
2857        );
2858    }
2859
2860    /// Losing the only replica advertiser demotes the derived pipeline without
2861    /// any explicit bookkeeping, because the tag *is* the possession-claim set.
2862    #[test]
2863    fn departing_sole_replica_advertiser_demotes_derived_pipeline() {
2864        let mut queues = ReplicationQueues::new();
2865        let key = xor_name_from_byte(0xE3);
2866        let replica_advertiser = peer_id_from_byte(1);
2867        let paid_advertiser = peer_id_from_byte(2);
2868
2869        let entry = VerificationEntry {
2870            state: VerificationState::PendingVerify,
2871            verified_sources: Vec::new(),
2872            tried_sources: HashSet::new(),
2873            created_at: Instant::now(),
2874            next_verify_at: Instant::now(),
2875            hint_sources: HashSet::from([replica_advertiser, paid_advertiser]),
2876            replica_hint_sources: HashSet::from([replica_advertiser]),
2877            unresolved_retries: 0,
2878            no_holder_reported: false,
2879        };
2880        assert!(queues.add_pending_verify(key, entry).admitted());
2881
2882        queues.remove_hint_source(&replica_advertiser);
2883
2884        let pending = queues
2885            .get_pending(&key)
2886            .expect("paid advertiser still holds the entry open");
2887        assert_eq!(
2888            pending.pipeline(),
2889            crate::replication::types::HintPipeline::PaidOnly,
2890            "no possession claims remain, so the key is paid-only again"
2891        );
2892    }
2893
2894    /// Scenario 3: Neighbor-sync unknown key transitions through the full
2895    /// state machine to stored.
2896    ///
2897    /// Exercises the complete queue pipeline that a key follows when it
2898    /// arrives as a neighbor-sync hint, passes quorum verification, is
2899    /// fetched, and completes:
2900    ///   `PendingVerify` → (quorum pass) → `QueuedForFetch` → `Fetching` → `Stored`
2901    #[test]
2902    fn scenario_3_neighbor_sync_quorum_pass_full_pipeline() {
2903        let mut queues = ReplicationQueues::new();
2904        let key = xor_name_from_byte(0x03);
2905        let distance = xor_name_from_byte(0x01);
2906        let source_a = peer_id_from_byte(1);
2907        let source_b = peer_id_from_byte(2);
2908
2909        // Stage 1: Hint admitted → PendingVerify
2910        let entry = VerificationEntry {
2911            state: VerificationState::PendingVerify,
2912            verified_sources: Vec::new(),
2913            tried_sources: HashSet::new(),
2914            created_at: Instant::now(),
2915            next_verify_at: Instant::now(),
2916            hint_sources: HashSet::from([peer_id_from_byte(3)]),
2917            replica_hint_sources: HashSet::from([peer_id_from_byte(3)]),
2918            unresolved_retries: 0,
2919            no_holder_reported: false,
2920        };
2921        assert!(
2922            queues.add_pending_verify(key, entry).admitted(),
2923            "new key should be admitted to PendingVerify"
2924        );
2925        assert!(queues.contains_key(&key));
2926        assert_eq!(queues.pending_count(), 1);
2927
2928        // Stage 2: Quorum passes — remove from pending and enqueue for fetch
2929        // with the verified sources discovered during the quorum round.
2930        let removed = queues.remove_pending(&key);
2931        assert!(removed.is_some(), "key should exist in pending");
2932        assert_eq!(queues.pending_count(), 0);
2933
2934        queues.enqueue_fetch(key, distance, vec![source_a, source_b]);
2935        assert_eq!(queues.fetch_queue_count(), 1);
2936        assert!(
2937            queues.contains_key(&key),
2938            "key should be in pipeline (fetch queue)"
2939        );
2940
2941        // Stage 3: Dequeue → Fetching
2942        let candidate = queues.dequeue_fetch().expect("should dequeue");
2943        assert_eq!(candidate.key, key);
2944        assert_eq!(candidate.sources.len(), 2);
2945        queues.start_dequeued_fetch(candidate, source_a);
2946        assert_eq!(queues.in_flight_count(), 1);
2947        assert_eq!(queues.fetch_queue_count(), 0);
2948        assert!(
2949            queues.contains_key(&key),
2950            "key should be in pipeline (in-flight)"
2951        );
2952
2953        // Stage 4: Fetch completes → Stored
2954        let completed = queues.complete_fetch(&key);
2955        assert!(
2956            completed.is_some(),
2957            "should have in-flight entry to complete"
2958        );
2959        assert_eq!(queues.in_flight_count(), 0);
2960        assert!(
2961            !queues.contains_key(&key),
2962            "key should be fully processed out of pipeline"
2963        );
2964    }
2965
2966    // -- capacity gate -----------------------------------------------------
2967
2968    /// Deferral moves the next look, not the entry's birth, so a blocked key
2969    /// still ages out on the ordinary schedule.
2970    ///
2971    /// This is why the change carries no eviction protection for deferred keys:
2972    /// protecting them would preserve, against a bounded queue, exactly the duty
2973    /// a full node cannot discharge. The deferred key here is older than the age
2974    /// limit and the control is not, so the assertion fails both if deferral
2975    /// exempted a key from eviction and if it refreshed `created_at` — either
2976    /// would let a full node hold entries indefinitely.
2977    ///
2978    /// What this does not show: that either gate calls `defer_pending`. The
2979    /// gates need a network, so the e2e covers them.
2980    #[test]
2981    fn capacity_deferral_does_not_extend_entry_lifetime() {
2982        // Small enough that the back-dated instant is representable on a
2983        // machine that only just booted, wide enough that the control cannot
2984        // age out while three in-memory queue operations run.
2985        const MAX_AGE: Duration = Duration::from_secs(1);
2986
2987        let mut queues = ReplicationQueues::new();
2988        let aged = xor_name_from_byte(1);
2989        let fresh = xor_name_from_byte(2);
2990
2991        let mut aged_entry = test_entry(1);
2992        aged_entry.created_at = Instant::now()
2993            .checked_sub(MAX_AGE * 2)
2994            .expect("backdate the aged entry");
2995        assert!(queues.add_pending_verify(aged, aged_entry).admitted());
2996        assert!(queues.add_pending_verify(fresh, test_entry(2)).admitted());
2997
2998        // The deferral puts the next look beyond the age limit, so an eviction
2999        // that read the next look instead of the creation time would spare it.
3000        assert!(queues.defer_pending(&aged, CAPACITY_BLOCKED_RETRY));
3001
3002        let evicted = queues.evict_stale(MAX_AGE);
3003        assert!(
3004            evicted.contains(&aged),
3005            "a capacity-deferred key must still age out on its creation time"
3006        );
3007        assert!(
3008            !evicted.contains(&fresh),
3009            "the age limit, not the deferral, is what retires an entry"
3010        );
3011        assert_eq!(queues.pending_count(), 1);
3012    }
3013}