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        let ready = queues.ready_pending_keys(Instant::now());
1875        assert!(
1876            ready.is_empty(),
1877            "expected no ready pending keys before the retry delay elapses, got {ready:?}"
1878        );
1879        assert!(!queues.add_pending_verify(key, test_entry(2)).admitted());
1880        assert_eq!(queues.pending_count(), 1);
1881        assert_eq!(
1882            queues
1883                .get_pending(&key)
1884                .expect("pending entry")
1885                .hint_sources,
1886            HashSet::from([source_a, source_b])
1887        );
1888        assert!(
1889            queues.ready_pending_keys(Instant::now()).is_empty(),
1890            "a duplicate source must not bypass verification retry deferral"
1891        );
1892    }
1893
1894    #[test]
1895    fn repeated_duplicate_from_same_source_does_not_grow_eviction_heap() {
1896        let mut queues = ReplicationQueues::new();
1897        let key = xor_name_from_byte(0x77);
1898        let owner = peer_id_from_byte(1);
1899        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1900
1901        for _ in 0..1_000 {
1902            assert_eq!(
1903                queues.add_pending_verify(key, test_entry(1)),
1904                AdmissionResult::AlreadyPresent
1905            );
1906        }
1907
1908        assert_eq!(
1909            queues
1910                .eviction_candidates_by_owner
1911                .get(&owner)
1912                .map_or(0, BinaryHeap::len),
1913            1
1914        );
1915    }
1916
1917    #[test]
1918    fn ready_pending_keys_prioritizes_more_live_sources_then_age() {
1919        let mut queues = ReplicationQueues::new();
1920        let oldest_singleton = xor_name_from_byte(0x10);
1921        let newer_singleton = xor_name_from_byte(0x20);
1922        let corroborated = xor_name_from_byte(0x30);
1923        let now = Instant::now();
1924
1925        let mut oldest = test_entry(1);
1926        oldest.created_at = now.checked_sub(Duration::from_secs(2)).unwrap();
1927        let mut newer = test_entry(1);
1928        newer.created_at = now.checked_sub(Duration::from_secs(1)).unwrap();
1929        let mut multi = test_entry(1);
1930        multi.created_at = now;
1931
1932        assert!(queues
1933            .add_pending_verify(oldest_singleton, oldest)
1934            .admitted());
1935        assert!(queues.add_pending_verify(newer_singleton, newer).admitted());
1936        assert!(queues.add_pending_verify(corroborated, multi).admitted());
1937        assert_eq!(
1938            queues.add_pending_verify(corroborated, test_entry(2)),
1939            AdmissionResult::AlreadyPresent
1940        );
1941
1942        assert_eq!(
1943            queues.ready_pending_keys(Instant::now()),
1944            vec![corroborated, oldest_singleton, newer_singleton]
1945        );
1946    }
1947
1948    #[test]
1949    fn peer_removal_drops_orphans_and_preserves_corroborated_hints() {
1950        let mut queues = ReplicationQueues::new();
1951        let source_a = peer_id_from_byte(1);
1952        let source_b = peer_id_from_byte(2);
1953        let orphaned_key = xor_name_from_byte(0x40);
1954        let shared_key = xor_name_from_byte(0x41);
1955
1956        assert!(queues
1957            .add_pending_verify(orphaned_key, test_entry(1))
1958            .admitted());
1959        assert!(queues
1960            .add_pending_verify(shared_key, test_entry(1))
1961            .admitted());
1962        assert_eq!(
1963            queues.add_pending_verify(shared_key, test_entry(2)),
1964            AdmissionResult::AlreadyPresent
1965        );
1966
1967        assert_eq!(queues.remove_hint_source(&source_a), vec![orphaned_key]);
1968        let shared = queues
1969            .get_pending(&shared_key)
1970            .expect("shared hint retained");
1971        assert_eq!(shared.hint_sources, HashSet::from([source_b]));
1972        assert_eq!(queues.pending_count_for_owner(&source_a), 0);
1973        assert_eq!(queues.pending_count_for_owner(&source_b), 1);
1974
1975        assert_eq!(queues.remove_hint_source(&source_b), vec![shared_key]);
1976        assert_eq!(queues.pending_count(), 0);
1977    }
1978
1979    #[test]
1980    fn peer_removal_prunes_fetch_and_retry_sources() {
1981        let mut queues = ReplicationQueues::new();
1982        let source_a = peer_id_from_byte(1);
1983        let source_b = peer_id_from_byte(2);
1984        let key = xor_name_from_byte(0x42);
1985
1986        assert!(queues.add_pending_verify(key, test_entry(1)).admitted());
1987        assert_eq!(
1988            queues.add_pending_verify(key, test_entry(2)),
1989            AdmissionResult::AlreadyPresent
1990        );
1991        assert!(queues.promote_pending_to_fetch(
1992            key,
1993            xor_name_from_byte(0x01),
1994            vec![source_a, source_b],
1995        ));
1996
1997        let orphaned = queues.remove_hint_source(&source_a);
1998        assert!(
1999            orphaned.is_empty(),
2000            "expected no orphaned keys while source_b still advertises, got {orphaned:?}"
2001        );
2002        let candidate = queues.dequeue_fetch().expect("candidate remains fetchable");
2003        assert_eq!(candidate.sources, vec![source_b]);
2004        assert_eq!(
2005            candidate
2006                .retry_verification
2007                .as_ref()
2008                .expect("retry provenance retained")
2009                .hint_sources,
2010            HashSet::from([source_b])
2011        );
2012        queues.discard_fetch_candidate(candidate);
2013    }
2014
2015    #[test]
2016    fn add_pending_verify_rejected_if_in_fetch_queue() {
2017        let mut queues = ReplicationQueues::new();
2018        let key = xor_name_from_byte(0x02);
2019        let distance = xor_name_from_byte(0x10);
2020        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(1)]);
2021
2022        assert!(
2023            !queues.add_pending_verify(key, test_entry(1)).admitted(),
2024            "should reject key already in fetch queue"
2025        );
2026    }
2027
2028    #[test]
2029    fn add_pending_verify_merges_source_into_queued_candidate() {
2030        let mut queues = ReplicationQueues::new();
2031        let key = xor_name_from_byte(0x02);
2032        let queued_source = peer_id_from_byte(1);
2033        let extra_source = peer_id_from_byte(2);
2034
2035        queues.enqueue_fetch(key, xor_name_from_byte(0x10), vec![queued_source]);
2036
2037        assert_eq!(
2038            queues.add_pending_verify(key, test_entry(2)),
2039            AdmissionResult::AlreadyPresent
2040        );
2041        // A repeat hint from an already-known advertiser must not duplicate it.
2042        assert_eq!(
2043            queues.add_pending_verify(key, test_entry(1)),
2044            AdmissionResult::AlreadyPresent
2045        );
2046
2047        let candidate = queues.dequeue_fetch().expect("queued candidate");
2048        assert_eq!(
2049            candidate.sources,
2050            vec![queued_source, extra_source],
2051            "a new advertiser is merged as a fetch source exactly once"
2052        );
2053        queues.discard_fetch_candidate(candidate);
2054    }
2055
2056    #[test]
2057    fn add_pending_verify_merge_preserves_fetch_priority_order() {
2058        let mut queues = ReplicationQueues::new();
2059        let near_key = xor_name_from_byte(0x01);
2060        let far_key = xor_name_from_byte(0x02);
2061        let near_dist = [0x00; 32]; // nearest
2062        let far_dist = [0xFF; 32]; // farthest
2063
2064        queues.enqueue_fetch(far_key, far_dist, vec![peer_id_from_byte(1)]);
2065        queues.enqueue_fetch(near_key, near_dist, vec![peer_id_from_byte(2)]);
2066
2067        // Merging a source into the farthest key must not reorder the queue:
2068        // the merge touches no field the heap orders on.
2069        assert_eq!(
2070            queues.add_pending_verify(far_key, test_entry(3)),
2071            AdmissionResult::AlreadyPresent
2072        );
2073
2074        let first = queues.dequeue_fetch().expect("should dequeue");
2075        assert_eq!(
2076            first.key, near_key,
2077            "nearest key still dequeues first after a merge"
2078        );
2079        queues.discard_fetch_candidate(first);
2080
2081        let second = queues.dequeue_fetch().expect("should dequeue");
2082        assert_eq!(second.key, far_key, "farthest key dequeues second");
2083        queues.discard_fetch_candidate(second);
2084    }
2085
2086    #[test]
2087    fn peer_removal_drops_orphaned_fetch_candidate() {
2088        let mut queues = ReplicationQueues::new();
2089        let source = peer_id_from_byte(1);
2090        let key = xor_name_from_byte(0x43);
2091
2092        queues.enqueue_fetch(key, xor_name_from_byte(0x10), vec![source]);
2093
2094        assert_eq!(
2095            queues.remove_hint_source(&source),
2096            vec![key],
2097            "a candidate whose last source departed is reported orphaned"
2098        );
2099        assert_eq!(queues.fetch_queue_count(), 0);
2100        assert!(
2101            !queues.contains_key(&key),
2102            "orphaned key leaves the pipeline entirely"
2103        );
2104        assert!(
2105            queues.dequeue_fetch().is_none(),
2106            "orphaned candidate must not linger in the priority heap"
2107        );
2108    }
2109
2110    #[test]
2111    fn add_pending_verify_rejected_if_in_flight() {
2112        let mut queues = ReplicationQueues::new();
2113        let key = xor_name_from_byte(0x03);
2114        let source = peer_id_from_byte(1);
2115        queues.start_fetch(key, source, vec![source]);
2116
2117        assert!(
2118            !queues.add_pending_verify(key, test_entry(1)).admitted(),
2119            "should reject key already in-flight"
2120        );
2121    }
2122
2123    // -- enqueue/dequeue ordering -----------------------------------------
2124
2125    #[test]
2126    fn dequeue_returns_nearest_first() {
2127        let mut queues = ReplicationQueues::new();
2128
2129        let near_key = xor_name_from_byte(0x01);
2130        let far_key = xor_name_from_byte(0x02);
2131        let near_dist = [0x00; 32]; // nearest
2132        let far_dist = [0xFF; 32]; // farthest
2133
2134        queues.enqueue_fetch(far_key, far_dist, vec![peer_id_from_byte(1)]);
2135        queues.enqueue_fetch(near_key, near_dist, vec![peer_id_from_byte(2)]);
2136
2137        let first = queues.dequeue_fetch().expect("should dequeue");
2138        assert_eq!(first.key, near_key, "nearest key should dequeue first");
2139        queues.discard_fetch_candidate(first);
2140
2141        let second = queues.dequeue_fetch().expect("should dequeue");
2142        assert_eq!(second.key, far_key, "farthest key should dequeue second");
2143        queues.discard_fetch_candidate(second);
2144    }
2145
2146    #[test]
2147    fn enqueue_dedup_prevents_duplicates() {
2148        let mut queues = ReplicationQueues::new();
2149        let key = xor_name_from_byte(0x01);
2150
2151        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(1)]);
2152        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(2)]);
2153
2154        assert_eq!(
2155            queues.fetch_queue_count(),
2156            1,
2157            "duplicate enqueue should be ignored"
2158        );
2159    }
2160
2161    // -- in-flight tracking -----------------------------------------------
2162
2163    #[test]
2164    fn start_and_complete_fetch() {
2165        let mut queues = ReplicationQueues::new();
2166        let key = xor_name_from_byte(0x01);
2167        let source = peer_id_from_byte(1);
2168
2169        queues.start_fetch(key, source, vec![source]);
2170        assert_eq!(queues.in_flight_count(), 1);
2171
2172        let completed = queues.complete_fetch(&key);
2173        assert!(completed.is_some());
2174        assert_eq!(queues.in_flight_count(), 0);
2175    }
2176
2177    #[test]
2178    fn complete_nonexistent_returns_none() {
2179        let mut queues = ReplicationQueues::new();
2180        let key = xor_name_from_byte(0x99);
2181        assert!(queues.complete_fetch(&key).is_none());
2182    }
2183
2184    // -- retry_fetch ------------------------------------------------------
2185
2186    #[test]
2187    fn retry_fetch_returns_next_untried_source() {
2188        let mut queues = ReplicationQueues::new();
2189        let key = xor_name_from_byte(0x01);
2190        let source_a = peer_id_from_byte(1);
2191        let source_b = peer_id_from_byte(2);
2192        let source_c = peer_id_from_byte(3);
2193
2194        queues.start_fetch(key, source_a, vec![source_a, source_b, source_c]);
2195
2196        // First retry: should skip source_a (already tried), return source_b.
2197        let next = queues.retry_fetch(&key);
2198        assert_eq!(next, Some(source_b));
2199
2200        // Second retry: should return source_c.
2201        let next = queues.retry_fetch(&key);
2202        assert_eq!(next, Some(source_c));
2203
2204        // Third retry: all exhausted.
2205        let next = queues.retry_fetch(&key);
2206        assert!(next.is_none(), "all sources exhausted");
2207    }
2208
2209    #[test]
2210    fn retry_fetch_nonexistent_returns_none() {
2211        let mut queues = ReplicationQueues::new();
2212        assert!(queues.retry_fetch(&xor_name_from_byte(0xFF)).is_none());
2213    }
2214
2215    #[test]
2216    fn exhausted_promoted_fetch_requeues_verification() {
2217        const KEY_BYTE: u8 = 0x44;
2218        const DISTANCE_BYTE: u8 = 0x01;
2219        const SOURCE_BYTE: u8 = 2;
2220        const HINT_SENDER_BYTE: u8 = 9;
2221        const RETRY_DELAY: Duration = Duration::from_secs(15);
2222        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2223
2224        let mut queues = ReplicationQueues::new();
2225        let key = xor_name_from_byte(KEY_BYTE);
2226        let distance = xor_name_from_byte(DISTANCE_BYTE);
2227        let source = peer_id_from_byte(SOURCE_BYTE);
2228        let entry = test_entry(HINT_SENDER_BYTE);
2229
2230        assert!(queues.add_pending_verify(key, entry).admitted());
2231        assert!(queues.promote_pending_to_fetch(key, distance, vec![source]));
2232
2233        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2234        queues.start_dequeued_fetch(candidate, source);
2235
2236        assert!(
2237            queues.retry_fetch(&key).is_none(),
2238            "single source should be exhausted"
2239        );
2240        assert!(queues.requeue_fetch_for_verification(&key, RETRY_DELAY));
2241
2242        assert_eq!(queues.in_flight_count(), 0);
2243        assert!(
2244            queues.ready_pending_keys(Instant::now()).is_empty(),
2245            "requeued key should observe retry delay"
2246        );
2247
2248        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2249        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2250        assert_eq!(
2251            queues.pending_count_for_owner(&peer_id_from_byte(HINT_SENDER_BYTE)),
2252            1
2253        );
2254        assert!(queues.protected_pending_keys.contains(&key));
2255        assert_eq!(
2256            queues.capacity_owner_by_key.get(&key),
2257            Some(&peer_id_from_byte(HINT_SENDER_BYTE))
2258        );
2259    }
2260
2261    #[test]
2262    fn no_sources_dequeued_candidate_requeues_for_verification() {
2263        const KEY_INDEX: u32 = 70_000;
2264        const DISTANCE_BYTE: u8 = 0x01;
2265        const HINT_SENDER_BYTE: u8 = 9;
2266        const VERIFIED_SOURCE_BYTE: u8 = 2;
2267        const TRIED_SOURCE_BYTE: u8 = 3;
2268        const RETRY_DELAY: Duration = Duration::from_secs(15);
2269        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2270
2271        let mut queues = ReplicationQueues::new();
2272        let key = xor_name_from_u32(KEY_INDEX);
2273        let distance = xor_name_from_byte(DISTANCE_BYTE);
2274        let verified_source = peer_id_from_byte(VERIFIED_SOURCE_BYTE);
2275        let tried_source = peer_id_from_byte(TRIED_SOURCE_BYTE);
2276        let mut entry = test_entry(HINT_SENDER_BYTE);
2277        entry.state = VerificationState::QueuedForFetch;
2278        entry.verified_sources.push(verified_source);
2279        entry.tried_sources.insert(tried_source);
2280
2281        assert!(queues.add_pending_verify(key, entry).admitted());
2282        assert!(queues.promote_pending_to_fetch(key, distance, Vec::new()));
2283
2284        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2285        assert!(
2286            candidate.sources.is_empty(),
2287            "test candidate should exercise the no-sources branch"
2288        );
2289        assert!(
2290            queues.requeue_candidate_for_verification(candidate, RETRY_DELAY),
2291            "no-sources retry candidate should be restored to pending verification"
2292        );
2293
2294        let pending = queues.get_pending(&key).expect("key should be pending");
2295        assert_eq!(pending.state, VerificationState::PendingVerify);
2296        assert!(
2297            pending.verified_sources.is_empty(),
2298            "verified sources should be cleared before retry"
2299        );
2300        assert!(
2301            pending.tried_sources.is_empty(),
2302            "tried sources should be cleared before retry"
2303        );
2304        assert!(
2305            queues.ready_pending_keys(Instant::now()).is_empty(),
2306            "requeued key should observe retry delay"
2307        );
2308
2309        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2310        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2311
2312        assert!(queues.remove_pending(&key).is_some());
2313    }
2314
2315    #[test]
2316    fn exhausted_direct_fetch_remains_terminal() {
2317        const KEY_BYTE: u8 = 0x45;
2318        const DISTANCE_BYTE: u8 = 0x01;
2319        const SOURCE_BYTE: u8 = 2;
2320        const RETRY_DELAY: Duration = Duration::from_secs(15);
2321
2322        let mut queues = ReplicationQueues::new();
2323        let key = xor_name_from_byte(KEY_BYTE);
2324        let source = peer_id_from_byte(SOURCE_BYTE);
2325
2326        queues.enqueue_fetch(key, xor_name_from_byte(DISTANCE_BYTE), vec![source]);
2327        let candidate = queues.dequeue_fetch().expect("fetch candidate");
2328        queues.start_dequeued_fetch(candidate, source);
2329
2330        assert!(
2331            queues.retry_fetch(&key).is_none(),
2332            "single source should be exhausted"
2333        );
2334        assert!(!queues.requeue_fetch_for_verification(&key, RETRY_DELAY));
2335        assert_eq!(queues.in_flight_count(), 0);
2336        assert_eq!(queues.pending_count(), 0);
2337    }
2338
2339    // -- contains_key across pipelines ------------------------------------
2340
2341    #[test]
2342    fn contains_key_in_pending() {
2343        let mut queues = ReplicationQueues::new();
2344        let key = xor_name_from_byte(0x01);
2345        queues.add_pending_verify(key, test_entry(1));
2346        assert!(queues.contains_key(&key));
2347    }
2348
2349    #[test]
2350    fn contains_key_in_fetch_queue() {
2351        let mut queues = ReplicationQueues::new();
2352        let key = xor_name_from_byte(0x02);
2353        queues.enqueue_fetch(key, [0x10; 32], vec![peer_id_from_byte(1)]);
2354        assert!(queues.contains_key(&key));
2355    }
2356
2357    #[test]
2358    fn contains_key_in_flight() {
2359        let mut queues = ReplicationQueues::new();
2360        let key = xor_name_from_byte(0x03);
2361        queues.start_fetch(key, peer_id_from_byte(1), vec![]);
2362        assert!(queues.contains_key(&key));
2363    }
2364
2365    #[test]
2366    fn contains_key_absent() {
2367        let queues = ReplicationQueues::new();
2368        assert!(!queues.contains_key(&xor_name_from_byte(0xFF)));
2369    }
2370
2371    // -- bootstrap work empty ---------------------------------------------
2372
2373    #[test]
2374    fn bootstrap_work_empty_when_no_keys_present() {
2375        let queues = ReplicationQueues::new();
2376        let bootstrap_keys: HashSet<XorName> = [xor_name_from_byte(0x01), xor_name_from_byte(0x02)]
2377            .into_iter()
2378            .collect();
2379        assert!(queues.is_bootstrap_work_empty(&bootstrap_keys));
2380    }
2381
2382    #[test]
2383    fn bootstrap_work_not_empty_when_key_in_pending() {
2384        let mut queues = ReplicationQueues::new();
2385        let key = xor_name_from_byte(0x01);
2386        queues.add_pending_verify(key, test_entry(1));
2387
2388        let bootstrap_keys: HashSet<XorName> = std::iter::once(key).collect();
2389        assert!(!queues.is_bootstrap_work_empty(&bootstrap_keys));
2390    }
2391
2392    // -- evict_stale ------------------------------------------------------
2393
2394    #[test]
2395    fn evict_stale_removes_old_entries() {
2396        let mut queues = ReplicationQueues::new();
2397        let key = xor_name_from_byte(0x01);
2398
2399        let mut entry = test_entry(1);
2400        // Backdate via the same defensive checked_sub used elsewhere so
2401        // freshly-booted CI clocks don't trip us up.
2402        entry.created_at = Instant::now()
2403            .checked_sub(Duration::from_secs(2))
2404            .unwrap_or_else(Instant::now);
2405        assert!(queues.add_pending_verify(key, entry).admitted());
2406
2407        assert_eq!(queues.pending_count(), 1);
2408
2409        let evicted = queues.evict_stale(Duration::from_secs(1));
2410        assert_eq!(evicted, vec![key]);
2411        assert_eq!(
2412            queues.pending_count(),
2413            0,
2414            "entry older than max_age should be evicted"
2415        );
2416    }
2417
2418    #[test]
2419    fn evict_stale_keeps_fresh_entries() {
2420        let mut queues = ReplicationQueues::new();
2421        let key = xor_name_from_byte(0x01);
2422        queues.add_pending_verify(key, test_entry(1));
2423
2424        let evicted = queues.evict_stale(Duration::from_hours(1));
2425        assert!(
2426            evicted.is_empty(),
2427            "fresh entry should not be reported as evicted"
2428        );
2429        assert_eq!(
2430            queues.pending_count(),
2431            1,
2432            "fresh entry should not be evicted"
2433        );
2434    }
2435
2436    #[test]
2437    fn deferred_pending_key_is_not_ready_until_retry_time() {
2438        const RETRY_DELAY: Duration = Duration::from_secs(15);
2439        const RETRY_DELAY_SLACK: Duration = Duration::from_secs(1);
2440
2441        let mut queues = ReplicationQueues::new();
2442        let key = xor_name_from_byte(0xAA);
2443        queues.add_pending_verify(key, test_entry(1));
2444
2445        assert_eq!(queues.ready_pending_keys(Instant::now()), vec![key]);
2446        assert!(queues.defer_pending(&key, RETRY_DELAY));
2447        assert!(
2448            queues.ready_pending_keys(Instant::now()).is_empty(),
2449            "deferred key should not be retried immediately"
2450        );
2451
2452        let after_retry = Instant::now() + RETRY_DELAY + RETRY_DELAY_SLACK;
2453        assert_eq!(queues.ready_pending_keys(after_retry), vec![key]);
2454    }
2455
2456    #[test]
2457    fn repeated_deferrals_back_off_and_saturate_at_the_cap() {
2458        const BASE: Duration = Duration::from_secs(15);
2459
2460        let mut queues = ReplicationQueues::new();
2461        let key = xor_name_from_byte(0xAB);
2462        queues.add_pending_verify(key, test_entry(1));
2463
2464        // 15s doubling per consecutive unresolved round.
2465        for (attempt, expected_secs) in [(1, 15), (2, 30), (3, 60), (4, 120), (5, 240)] {
2466            let outcome = queues
2467                .defer_unresolved(&key, BASE)
2468                .expect("pending key should defer");
2469            assert_eq!(outcome.attempt, attempt);
2470            assert_eq!(
2471                outcome.retry_after,
2472                Duration::from_secs(expected_secs),
2473                "attempt {attempt} should back off to {expected_secs}s"
2474            );
2475        }
2476
2477        // Everything past the cap stays at the cap rather than overflowing the
2478        // shift into a short (or zero) delay.
2479        for _ in 0..64 {
2480            let outcome = queues
2481                .defer_unresolved(&key, BASE)
2482                .expect("pending key should defer");
2483            assert_eq!(
2484                outcome.retry_after, VERIFICATION_RETRY_BACKOFF_MAX,
2485                "backoff must saturate at the cap, never wrap"
2486            );
2487        }
2488    }
2489
2490    /// The counter and the warning answer different questions, so a round that
2491    /// advances the count without producing a no-holder result — an
2492    /// inconclusive quorum — must leave the warning unclaimed. Deriving the
2493    /// report from `attempt == 1` loses the first and only warning for every
2494    /// key whose opening round is inconclusive.
2495    #[test]
2496    fn a_non_reporting_round_does_not_consume_the_no_holder_warning() {
2497        const BASE: Duration = Duration::from_secs(15);
2498
2499        let mut queues = ReplicationQueues::new();
2500        let key = xor_name_from_byte(0xAE);
2501        queues.add_pending_verify(key, test_entry(1));
2502
2503        // Round 1: inconclusive quorum. Backs off, reports nothing.
2504        let first = queues
2505            .defer_unresolved(&key, BASE)
2506            .expect("pending key should defer");
2507        assert_eq!(first.attempt, 1);
2508
2509        // Round 2 is the first that actually finds no holder. It is at
2510        // attempt 2, but it is the first report and must still warn.
2511        let second = queues
2512            .defer_unresolved(&key, BASE)
2513            .expect("pending key should defer");
2514        assert_eq!(second.attempt, 2, "the inconclusive round still counts");
2515        assert!(
2516            queues.claim_no_holder_report(&key),
2517            "the first no-holder result must warn even at attempt 2"
2518        );
2519        assert!(
2520            !queues.claim_no_holder_report(&key),
2521            "the warning is claimed exactly once per entry"
2522        );
2523    }
2524
2525    /// A round that found a holder ends the run of failures, even when a full
2526    /// fetch queue leaves the key pending. It must not inherit the old backoff,
2527    /// and a later relapse deserves a fresh warning.
2528    #[test]
2529    fn finding_a_holder_clears_the_backoff_and_rearms_the_warning() {
2530        const BASE: Duration = Duration::from_secs(15);
2531
2532        let mut queues = ReplicationQueues::new();
2533        let key = xor_name_from_byte(0xAF);
2534        queues.add_pending_verify(key, test_entry(1));
2535
2536        for _ in 0..4 {
2537            queues
2538                .defer_unresolved(&key, BASE)
2539                .expect("pending key should defer");
2540        }
2541        assert!(queues.claim_no_holder_report(&key));
2542
2543        assert!(queues.clear_unresolved(&key));
2544
2545        let outcome = queues
2546            .defer_unresolved(&key, BASE)
2547            .expect("pending key should defer");
2548        assert_eq!(outcome.attempt, 1, "a resolved round restarts the run");
2549        assert_eq!(outcome.retry_after, BASE);
2550        assert!(
2551            queues.claim_no_holder_report(&key),
2552            "a relapse after a good round is reported again"
2553        );
2554    }
2555
2556    /// The whole fix rests on a duplicate hint merging into the live entry
2557    /// rather than replacing it. A refactor that replaced would silently revert
2558    /// the backoff with every other test here still green.
2559    #[test]
2560    fn a_duplicate_hint_does_not_reset_the_backoff_or_the_retry_time() {
2561        const BASE: Duration = Duration::from_secs(15);
2562
2563        let mut queues = ReplicationQueues::new();
2564        let key = xor_name_from_byte(0xB0);
2565        queues.add_pending_verify(key, test_entry(1));
2566
2567        for _ in 0..3 {
2568            queues
2569                .defer_unresolved(&key, BASE)
2570                .expect("pending key should defer");
2571        }
2572        assert!(queues.claim_no_holder_report(&key));
2573        let deferred_until = queues.pending_verify[&key].next_verify_at;
2574
2575        // A second advertiser re-hints the same key.
2576        assert!(!queues.add_pending_verify(key, test_entry(2)).admitted());
2577
2578        let entry = &queues.pending_verify[&key];
2579        assert_eq!(
2580            entry.unresolved_retries, 3,
2581            "a re-hint must not restart the backoff"
2582        );
2583        assert!(
2584            entry.no_holder_reported,
2585            "a re-hint must not re-arm the warning; only eviction ends an episode"
2586        );
2587        assert_eq!(
2588            entry.next_verify_at, deferred_until,
2589            "a re-hint must not pull the key forward into an earlier round"
2590        );
2591    }
2592
2593    /// The write-blocked capacity gate defers without asking anyone, so it must
2594    /// not consume the entry's first-failure warning or advance its backoff:
2595    /// nothing was learned about the key.
2596    #[test]
2597    fn flat_defer_does_not_advance_the_unresolved_backoff() {
2598        const BASE: Duration = Duration::from_secs(15);
2599
2600        let mut queues = ReplicationQueues::new();
2601        let key = xor_name_from_byte(0xAD);
2602        queues.add_pending_verify(key, test_entry(1));
2603
2604        for _ in 0..10 {
2605            assert!(queues.defer_pending(&key, Duration::from_mins(5)));
2606        }
2607
2608        let outcome = queues
2609            .defer_unresolved(&key, BASE)
2610            .expect("pending key should defer");
2611        assert_eq!(
2612            outcome.attempt, 1,
2613            "a flat deferral is not a failed round and must not consume attempt 1"
2614        );
2615        assert_eq!(outcome.retry_after, BASE);
2616        assert!(
2617            queues.claim_no_holder_report(&key),
2618            "nor may it consume the warning"
2619        );
2620    }
2621
2622    #[test]
2623    fn defer_unresolved_reports_none_for_unknown_key() {
2624        let mut queues = ReplicationQueues::new();
2625        assert!(queues
2626            .defer_unresolved(&xor_name_from_byte(0xFF), Duration::from_secs(15))
2627            .is_none());
2628    }
2629
2630    #[test]
2631    fn re_admission_after_eviction_restarts_the_backoff() {
2632        const BASE: Duration = Duration::from_secs(15);
2633
2634        let mut queues = ReplicationQueues::new();
2635        let key = xor_name_from_byte(0xAC);
2636        queues.add_pending_verify(key, test_entry(1));
2637
2638        for _ in 0..5 {
2639            queues
2640                .defer_unresolved(&key, BASE)
2641                .expect("pending key should defer");
2642        }
2643
2644        // Stale eviction drops the entry; the next hint admits a fresh one. The
2645        // count lives on the entry, so the episode — and its single warning —
2646        // starts over.
2647        queues.evict_stale(Duration::ZERO);
2648        assert_eq!(queues.pending_count(), 0);
2649        queues.add_pending_verify(key, test_entry(1));
2650
2651        let outcome = queues
2652            .defer_unresolved(&key, BASE)
2653            .expect("re-admitted key should defer");
2654        assert_eq!(outcome.attempt, 1, "re-admission starts a new episode");
2655        assert_eq!(outcome.retry_after, BASE);
2656    }
2657
2658    #[test]
2659    fn backoff_never_retries_faster_than_the_caller_base() {
2660        // A base above the cap (an unusual config, but representable) must not
2661        // be shortened into a tighter retry loop than the caller asked for.
2662        let long_base = VERIFICATION_RETRY_BACKOFF_MAX + Duration::from_mins(1);
2663        assert_eq!(backoff_delay(long_base, 1), long_base);
2664        assert_eq!(backoff_delay(long_base, 9), long_base);
2665    }
2666
2667    // -- remove_pending ---------------------------------------------------
2668
2669    #[test]
2670    fn remove_pending_returns_entry() {
2671        let mut queues = ReplicationQueues::new();
2672        let key = xor_name_from_byte(0x01);
2673        queues.add_pending_verify(key, test_entry(1));
2674
2675        let removed = queues.remove_pending(&key);
2676        assert!(removed.is_some());
2677        assert_eq!(queues.pending_count(), 0);
2678    }
2679
2680    #[test]
2681    fn remove_pending_nonexistent_returns_none() {
2682        let mut queues = ReplicationQueues::new();
2683        assert!(queues.remove_pending(&xor_name_from_byte(0xFF)).is_none());
2684    }
2685
2686    // -----------------------------------------------------------------------
2687    // Section 18 scenarios
2688    // -----------------------------------------------------------------------
2689
2690    /// Scenario 8: A key already in `PendingVerify` cannot be enqueued into
2691    /// `FetchQueue` (cross-queue dedup). Also, a key in `FetchQueue` cannot be
2692    /// re-added to `PendingVerify`.
2693    #[test]
2694    fn scenario_8_duplicate_key_not_double_queued() {
2695        let mut queues = ReplicationQueues::new();
2696        let key = xor_name_from_byte(0xE0);
2697        let distance = xor_name_from_byte(0x10);
2698
2699        // Step 1: Add to PendingVerify.
2700        assert!(
2701            queues.add_pending_verify(key, test_entry(1)).admitted(),
2702            "first add to PendingVerify should succeed"
2703        );
2704        assert!(
2705            queues.contains_key(&key),
2706            "key should be present in pipeline"
2707        );
2708
2709        // Step 2: Attempt to enqueue fetch while still in PendingVerify.
2710        // enqueue_fetch checks all three stages (pending_verify,
2711        // fetch_queue_keys, in_flight), so this is a no-op while the key
2712        // is still in PendingVerify.
2713        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(2)]);
2714        // Verify the key is still tracked via the cross-stage check.
2715        assert!(queues.contains_key(&key), "key should still be in pipeline");
2716
2717        // Step 3: Remove from PendingVerify, add to FetchQueue.
2718        queues.remove_pending(&key);
2719        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(3)]);
2720        assert_eq!(queues.fetch_queue_count(), 1);
2721
2722        // Step 4: Attempt to re-add to PendingVerify -> should fail.
2723        assert!(
2724            !queues.add_pending_verify(key, test_entry(4)).admitted(),
2725            "key in FetchQueue should be rejected from PendingVerify"
2726        );
2727
2728        // Step 5: Dequeue, start fetch -> key is in-flight.
2729        let candidate = queues.dequeue_fetch().expect("should dequeue");
2730        let source = candidate.sources[0];
2731        queues.start_dequeued_fetch(candidate, source);
2732
2733        // Step 6: Attempt to add to PendingVerify while in-flight -> reject.
2734        assert!(
2735            !queues.add_pending_verify(key, test_entry(5)).admitted(),
2736            "key in-flight should be rejected from PendingVerify"
2737        );
2738
2739        // Step 7: Attempt to enqueue fetch while in-flight -> no-op.
2740        queues.enqueue_fetch(key, distance, vec![peer_id_from_byte(6)]);
2741        // fetch_queue should still be empty (the enqueue was a no-op).
2742        assert_eq!(
2743            queues.fetch_queue_count(),
2744            0,
2745            "enqueue_fetch should be no-op for in-flight key"
2746        );
2747    }
2748
2749    /// Scenario 8 (continued): Verify that pipeline field for a key
2750    /// admitted as both replica and paid hint collapses to Replica only,
2751    /// because cross-set precedence in admission gives replica priority.
2752    #[test]
2753    fn scenario_8_replica_and_paid_hint_collapses_to_replica() {
2754        let mut queues = ReplicationQueues::new();
2755        let key = xor_name_from_byte(0xE1);
2756
2757        // Simulate admission result: key was in both replica_hints and
2758        // paid_hints, so admission records a possession claim for it.
2759        let entry = VerificationEntry {
2760            state: VerificationState::PendingVerify,
2761            verified_sources: Vec::new(),
2762            tried_sources: HashSet::new(),
2763            created_at: Instant::now(),
2764            next_verify_at: Instant::now(),
2765            hint_sources: HashSet::from([peer_id_from_byte(1)]),
2766            replica_hint_sources: HashSet::from([peer_id_from_byte(1)]),
2767            unresolved_retries: 0,
2768            no_holder_reported: false,
2769        };
2770
2771        assert!(queues.add_pending_verify(key, entry).admitted());
2772
2773        let pending = queues.get_pending(&key).expect("should be pending");
2774        assert_eq!(
2775            pending.pipeline(),
2776            crate::replication::types::HintPipeline::Replica,
2777            "key in both hint sets should be Replica pipeline"
2778        );
2779
2780        // A second add (e.g. from paid hints arriving separately) is rejected.
2781        let paid_entry = VerificationEntry {
2782            state: VerificationState::PendingVerify,
2783            verified_sources: Vec::new(),
2784            tried_sources: HashSet::new(),
2785            created_at: Instant::now(),
2786            next_verify_at: Instant::now(),
2787            hint_sources: HashSet::from([peer_id_from_byte(2)]),
2788            replica_hint_sources: HashSet::new(),
2789            unresolved_retries: 0,
2790            no_holder_reported: false,
2791        };
2792
2793        assert!(
2794            !queues.add_pending_verify(key, paid_entry).admitted(),
2795            "duplicate key should be rejected regardless of pipeline"
2796        );
2797
2798        // Pipeline stays Replica: merging a paid-only advertiser adds no
2799        // possession claim, so it cannot demote the existing one.
2800        let pending = queues.get_pending(&key).expect("should still be pending");
2801        assert_eq!(
2802            pending.pipeline(),
2803            crate::replication::types::HintPipeline::Replica,
2804            "pipeline should remain Replica after duplicate rejection"
2805        );
2806    }
2807
2808    /// A paid-only key cannot be escalated into the fetch-eligible pipeline by
2809    /// a peer re-advertising it as a replica hint.
2810    ///
2811    /// The queue still records the possession claim — that is what the sender
2812    /// asserted, and it makes the sender a fetch-source candidate. What it must
2813    /// not do is turn that claim into permission to store: the storage-
2814    /// admission check at download time is what decides, and it consults live
2815    /// routing state rather than this tag.
2816    #[test]
2817    fn replica_hint_on_paid_only_key_does_not_grant_storage_admission() {
2818        let mut queues = ReplicationQueues::new();
2819        let key = xor_name_from_byte(0xE2);
2820        let paid_advertiser = peer_id_from_byte(1);
2821        let replica_advertiser = peer_id_from_byte(2);
2822
2823        let paid_entry = VerificationEntry {
2824            state: VerificationState::PendingVerify,
2825            verified_sources: Vec::new(),
2826            tried_sources: HashSet::new(),
2827            created_at: Instant::now(),
2828            next_verify_at: Instant::now(),
2829            hint_sources: HashSet::from([paid_advertiser]),
2830            replica_hint_sources: HashSet::new(),
2831            unresolved_retries: 0,
2832            no_holder_reported: false,
2833        };
2834        assert!(queues.add_pending_verify(key, paid_entry).admitted());
2835        assert_eq!(
2836            queues
2837                .get_pending(&key)
2838                .expect("should be pending")
2839                .pipeline(),
2840            crate::replication::types::HintPipeline::PaidOnly,
2841        );
2842
2843        // Second message re-advertises the same key as a replica hint.
2844        let replica_entry = VerificationEntry {
2845            state: VerificationState::PendingVerify,
2846            verified_sources: Vec::new(),
2847            tried_sources: HashSet::new(),
2848            created_at: Instant::now(),
2849            next_verify_at: Instant::now(),
2850            hint_sources: HashSet::from([replica_advertiser]),
2851            replica_hint_sources: HashSet::from([replica_advertiser]),
2852            unresolved_retries: 0,
2853            no_holder_reported: false,
2854        };
2855        assert!(!queues.add_pending_verify(key, replica_entry).admitted());
2856
2857        let pending = queues.get_pending(&key).expect("should still be pending");
2858        assert!(
2859            pending.replica_hint_sources.contains(&replica_advertiser),
2860            "the possession claim is recorded for fetch-source discovery"
2861        );
2862        assert!(
2863            !pending.replica_hint_sources.contains(&paid_advertiser),
2864            "a paid-only advertiser never becomes a fetch source"
2865        );
2866    }
2867
2868    /// Losing the only replica advertiser demotes the derived pipeline without
2869    /// any explicit bookkeeping, because the tag *is* the possession-claim set.
2870    #[test]
2871    fn departing_sole_replica_advertiser_demotes_derived_pipeline() {
2872        let mut queues = ReplicationQueues::new();
2873        let key = xor_name_from_byte(0xE3);
2874        let replica_advertiser = peer_id_from_byte(1);
2875        let paid_advertiser = peer_id_from_byte(2);
2876
2877        let entry = VerificationEntry {
2878            state: VerificationState::PendingVerify,
2879            verified_sources: Vec::new(),
2880            tried_sources: HashSet::new(),
2881            created_at: Instant::now(),
2882            next_verify_at: Instant::now(),
2883            hint_sources: HashSet::from([replica_advertiser, paid_advertiser]),
2884            replica_hint_sources: HashSet::from([replica_advertiser]),
2885            unresolved_retries: 0,
2886            no_holder_reported: false,
2887        };
2888        assert!(queues.add_pending_verify(key, entry).admitted());
2889
2890        queues.remove_hint_source(&replica_advertiser);
2891
2892        let pending = queues
2893            .get_pending(&key)
2894            .expect("paid advertiser still holds the entry open");
2895        assert_eq!(
2896            pending.pipeline(),
2897            crate::replication::types::HintPipeline::PaidOnly,
2898            "no possession claims remain, so the key is paid-only again"
2899        );
2900    }
2901
2902    /// Scenario 3: Neighbor-sync unknown key transitions through the full
2903    /// state machine to stored.
2904    ///
2905    /// Exercises the complete queue pipeline that a key follows when it
2906    /// arrives as a neighbor-sync hint, passes quorum verification, is
2907    /// fetched, and completes:
2908    ///   `PendingVerify` → (quorum pass) → `QueuedForFetch` → `Fetching` → `Stored`
2909    #[test]
2910    fn scenario_3_neighbor_sync_quorum_pass_full_pipeline() {
2911        let mut queues = ReplicationQueues::new();
2912        let key = xor_name_from_byte(0x03);
2913        let distance = xor_name_from_byte(0x01);
2914        let source_a = peer_id_from_byte(1);
2915        let source_b = peer_id_from_byte(2);
2916
2917        // Stage 1: Hint admitted → PendingVerify
2918        let entry = VerificationEntry {
2919            state: VerificationState::PendingVerify,
2920            verified_sources: Vec::new(),
2921            tried_sources: HashSet::new(),
2922            created_at: Instant::now(),
2923            next_verify_at: Instant::now(),
2924            hint_sources: HashSet::from([peer_id_from_byte(3)]),
2925            replica_hint_sources: HashSet::from([peer_id_from_byte(3)]),
2926            unresolved_retries: 0,
2927            no_holder_reported: false,
2928        };
2929        assert!(
2930            queues.add_pending_verify(key, entry).admitted(),
2931            "new key should be admitted to PendingVerify"
2932        );
2933        assert!(queues.contains_key(&key));
2934        assert_eq!(queues.pending_count(), 1);
2935
2936        // Stage 2: Quorum passes — remove from pending and enqueue for fetch
2937        // with the verified sources discovered during the quorum round.
2938        let removed = queues.remove_pending(&key);
2939        assert!(removed.is_some(), "key should exist in pending");
2940        assert_eq!(queues.pending_count(), 0);
2941
2942        queues.enqueue_fetch(key, distance, vec![source_a, source_b]);
2943        assert_eq!(queues.fetch_queue_count(), 1);
2944        assert!(
2945            queues.contains_key(&key),
2946            "key should be in pipeline (fetch queue)"
2947        );
2948
2949        // Stage 3: Dequeue → Fetching
2950        let candidate = queues.dequeue_fetch().expect("should dequeue");
2951        assert_eq!(candidate.key, key);
2952        assert_eq!(candidate.sources.len(), 2);
2953        queues.start_dequeued_fetch(candidate, source_a);
2954        assert_eq!(queues.in_flight_count(), 1);
2955        assert_eq!(queues.fetch_queue_count(), 0);
2956        assert!(
2957            queues.contains_key(&key),
2958            "key should be in pipeline (in-flight)"
2959        );
2960
2961        // Stage 4: Fetch completes → Stored
2962        let completed = queues.complete_fetch(&key);
2963        assert!(
2964            completed.is_some(),
2965            "should have in-flight entry to complete"
2966        );
2967        assert_eq!(queues.in_flight_count(), 0);
2968        assert!(
2969            !queues.contains_key(&key),
2970            "key should be fully processed out of pipeline"
2971        );
2972    }
2973
2974    // -- capacity gate -----------------------------------------------------
2975
2976    /// Deferral moves the next look, not the entry's birth, so a blocked key
2977    /// still ages out on the ordinary schedule.
2978    ///
2979    /// This is why the change carries no eviction protection for deferred keys:
2980    /// protecting them would preserve, against a bounded queue, exactly the duty
2981    /// a full node cannot discharge. The deferred key here is older than the age
2982    /// limit and the control is not, so the assertion fails both if deferral
2983    /// exempted a key from eviction and if it refreshed `created_at` — either
2984    /// would let a full node hold entries indefinitely.
2985    ///
2986    /// What this does not show: that either gate calls `defer_pending`. The
2987    /// gates need a network, so the e2e covers them.
2988    #[test]
2989    fn capacity_deferral_does_not_extend_entry_lifetime() {
2990        // Small enough that the back-dated instant is representable on a
2991        // machine that only just booted, wide enough that the control cannot
2992        // age out while three in-memory queue operations run.
2993        const MAX_AGE: Duration = Duration::from_secs(1);
2994
2995        let mut queues = ReplicationQueues::new();
2996        let aged = xor_name_from_byte(1);
2997        let fresh = xor_name_from_byte(2);
2998
2999        let mut aged_entry = test_entry(1);
3000        aged_entry.created_at = Instant::now()
3001            .checked_sub(MAX_AGE * 2)
3002            .expect("backdate the aged entry");
3003        assert!(queues.add_pending_verify(aged, aged_entry).admitted());
3004        assert!(queues.add_pending_verify(fresh, test_entry(2)).admitted());
3005
3006        // The deferral puts the next look beyond the age limit, so an eviction
3007        // that read the next look instead of the creation time would spare it.
3008        assert!(queues.defer_pending(&aged, CAPACITY_BLOCKED_RETRY));
3009
3010        let evicted = queues.evict_stale(MAX_AGE);
3011        assert!(
3012            evicted.contains(&aged),
3013            "a capacity-deferred key must still age out on its creation time"
3014        );
3015        assert!(
3016            !evicted.contains(&fresh),
3017            "the age limit, not the deferral, is what retires an entry"
3018        );
3019        assert_eq!(queues.pending_count(), 1);
3020    }
3021}