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