Skip to main content

ant_node/replication/
mod.rs

1//! Replication subsystem for the Autonomi network.
2//!
3//! Implements Kademlia-style replication with:
4//! - Fresh replication with `PoP` verification
5//! - Neighbor sync with round-robin cycle management
6//! - Batched quorum verification
7//! - Storage audit protocol (anti-outsourcing)
8//! - `PaidForList` persistence and convergence
9//! - Responsibility pruning with hysteresis
10
11// The replication engine intentionally holds `RwLock` read guards across await
12// boundaries (e.g. reading sync_history while calling audit_tick). Clippy's
13// nursery lint `significant_drop_tightening` flags these, but the guards must
14// remain live for the duration of the call.
15#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod pointer;
29pub mod possession;
30pub mod protocol;
31pub mod pruning;
32pub mod quorum;
33pub mod recent_provers;
34pub mod scheduling;
35pub mod slice;
36pub mod storage_commitment_audit;
37pub mod subtree;
38pub mod types;
39
40use std::collections::{HashMap, HashSet, VecDeque};
41use std::fmt;
42use std::num::NonZeroUsize;
43use std::ops::ControlFlow;
44use std::path::{Path, PathBuf};
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::Arc;
47use std::time::{Duration, Instant, SystemTime};
48
49use lru::LruCache;
50use std::pin::Pin;
51
52use crate::logging::{debug, error, info, warn};
53use futures::stream::FuturesUnordered;
54use futures::{future::join_all, Future, StreamExt};
55use parking_lot::Mutex;
56use rand::rngs::StdRng;
57use rand::{Rng, SeedableRng};
58use tokio::sync::broadcast::error::RecvError;
59use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
60use tokio::task::JoinHandle;
61use tokio_util::sync::CancellationToken;
62use tokio_util::task::TaskTracker;
63
64use crate::ant_protocol::XorName;
65use crate::error::{Error, Result};
66use crate::payment::{
67    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
68    MIN_PAYMENT_PROOF_SIZE_BYTES,
69};
70use crate::pointer::store::PointerStore;
71use crate::replication::audit::AuditTickResult;
72use crate::replication::audit_coordinator::AuditChallengeCoordinator;
73use crate::replication::audit_metrics::{
74    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
75    ReplicationResponderClass, ResponderAdmissionCeiling,
76};
77use crate::replication::commitment::{commitment_hash, StorageCommitment};
78use crate::replication::commitment_state::{
79    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
80};
81use crate::replication::config::{
82    max_parallel_fetch, storage_admission_width, ReplicationConfig, MAX_AUDIT_RESPONSES_PER_PEER,
83    MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
84    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_INCOMING_VERIFICATION_KEYS,
85    MAX_SUBTREE_ROUND1_PER_PEER, MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE,
86    REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
87    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
88};
89use crate::replication::paid_list::PaidList;
90use crate::replication::protocol::{
91    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
92    VerificationResponse,
93};
94use crate::replication::quorum::KeyVerificationOutcome;
95use crate::replication::recent_provers::RecentProvers;
96use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
97use crate::replication::types::{
98    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
99    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
100    VerificationState,
101};
102use crate::storage::{CapacityVerdict, ChunkStore};
103use saorsa_core::identity::{NodeIdentity, PeerId};
104use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
105use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
106
107/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
108/// because it was full (Amendment 2). Process-global because the producer is
109/// the payment verifier (a different module) and the drop happens before the
110/// per-drainer `received` counter. A non-zero value is the rollout signal that
111/// nomination ingress is saturating — benign (penalty-free, lottery/next-
112/// payment covered) but worth watching. `Closed` (engine shut down) is not
113/// counted: it is not a saturation signal.
114static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
115
116/// Record one ingress-full drop. Called by the payment verifier's `try_send`
117/// sites; read by the drainer's periodic summary.
118pub(crate) fn note_monetized_ingress_drop() {
119    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
120}
121
122#[derive(Default)]
123struct FirstAuditObservability {
124    received: AtomicU64,
125    queued: AtomicU64,
126    coalesced: AtomicU64,
127    duplicates: AtomicU64,
128    capacity_evicted: AtomicU64,
129    /// An event targeting the local peer itself, dropped at ingress: the node
130    /// cannot network-audit itself (no dialable address for the local peer).
131    self_target_skipped: AtomicU64,
132    /// A strictly-lower-count same-peer nomination that was dropped so a
133    /// higher-count pending pin survived. A sustained rise is the signal of an
134    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
135    suppressed_lower: AtomicU64,
136    cooldown_deferred_attempts: AtomicU64,
137    rate_deferred_attempts: AtomicU64,
138    window_deduped: AtomicU64,
139    launched: AtomicU64,
140    passed: AtomicU64,
141    timed_out: AtomicU64,
142    failed: AtomicU64,
143    bootstrap_claims: AtomicU64,
144    idle: AtomicU64,
145    insufficient_keys: AtomicU64,
146    outside_answerability_window: AtomicU64,
147    inflight: AtomicU64,
148}
149
150/// Test-only snapshot of the first-audit scheduler counters.
151///
152/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
153/// self-targeting monetized pin was dropped and never launched) instead of
154/// scraping log lines.
155#[cfg(any(test, feature = "test-utils"))]
156#[derive(Debug, Clone, Copy)]
157pub struct FirstAuditStats {
158    /// Events ingested from the monetized-pin channel.
159    pub received: u64,
160    /// Events accepted into the pending first-audit queue.
161    pub queued: u64,
162    /// Events dropped because they targeted the local peer.
163    pub self_target_skipped: u64,
164    /// Audits launched.
165    pub launched: u64,
166    /// Launched audits that passed.
167    pub passed: u64,
168    /// Launched audits that timed out (non-response lane).
169    pub timed_out: u64,
170    /// Launched audits that ended in a confirmed failure.
171    pub failed: u64,
172}
173
174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
175enum FirstAuditTerminalOutcome {
176    Passed,
177    Timeout,
178    Failed,
179    BootstrapClaim,
180    Idle,
181    InsufficientKeys,
182}
183
184impl FirstAuditTerminalOutcome {
185    #[cfg(any(feature = "logging", test))]
186    const fn as_str(self) -> &'static str {
187        match self {
188            Self::Passed => "passed",
189            Self::Timeout => "timeout",
190            Self::Failed => "failed",
191            Self::BootstrapClaim => "bootstrap_claim",
192            Self::Idle => "idle",
193            Self::InsufficientKeys => "insufficient_keys",
194        }
195    }
196}
197
198fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
199    match result {
200        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
201        AuditTickResult::Failed {
202            evidence:
203                FailureEvidence::AuditFailure {
204                    reason: AuditFailureReason::Timeout,
205                    ..
206                },
207            ..
208        } => FirstAuditTerminalOutcome::Timeout,
209        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
210        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
211        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
212        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
213    }
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq)]
217enum FirstAuditQueueOutcome {
218    /// New peer inserted with free capacity.
219    Queued,
220    /// Collapsed with an existing same-peer entry; the incoming won (higher
221    /// count, or equal count and newer) and replaced it.
222    Coalesced,
223    /// Collapsed with an existing same-peer entry; the incoming LOST because it
224    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
225    /// in place. This is the attempted cheaper-pin self-erasure signal.
226    SuppressedLower,
227    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
228    /// lost the freshness tie (it was not the newer of the two) and the
229    /// existing entry was retained. Benign, not an attack signal.
230    RetainedOnTie,
231    /// A DIFFERENT peer's entry was displaced from the capped pending queue
232    /// (random victim) to make room.
233    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
234}
235
236/// Coalesce a monetized nomination into the per-peer pending queue with a
237/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
238/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
239///
240/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
241/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
242/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
243/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
244/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
245/// cannot promote the retained pin's lane position.
246///
247/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
248/// last, so it wins an equal-count tie for freshness) from a cooldown-race
249/// requeue of an older reserved event (the pending successor is newer, so it
250/// wins the tie).
251fn coalesce_first_audit_event(
252    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
253    incoming: MonetizedPinEvent,
254    incoming_is_newer: bool,
255    rng: &mut StdRng,
256) -> FirstAuditQueueOutcome {
257    if let Some(existing) = pending.peek(&incoming.peer) {
258        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
259        // the retained pin's recency (the security-relevant self-erasure case).
260        if incoming.key_count < existing.key_count {
261            return FirstAuditQueueOutcome::SuppressedLower;
262        }
263        // Equal count -> keep the fresher; an older incoming loses a benign tie.
264        if incoming.key_count == existing.key_count && !incoming_is_newer {
265            return FirstAuditQueueOutcome::RetainedOnTie;
266        }
267        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
268        // the value and bumps MRU; replacing an existing key never evicts a
269        // different peer.
270        let _ = pending.push(incoming.peer, incoming);
271        return FirstAuditQueueOutcome::Coalesced;
272    }
273    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
274    // never the LRU: deterministic keep-newest would let an ordered batch of
275    // `cap` distinct-peer nominations flush a chosen target before any launch
276    // lane sees it, cutting the eviction cost from probabilistic to exact. A
277    // random victim caps an attacker's per-nomination eviction probability at
278    // `1/cap` regardless of arrival order or timing, so suppressing a specific
279    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
280    // nominations and is never certain (ADR-0004 Amendment 4).
281    if pending.len() >= pending.cap().get() {
282        let victim = {
283            let idx = rng.gen_range(0..pending.len());
284            pending.iter().nth(idx).map(|(p, _)| *p)
285        };
286        if let Some(victim_peer) = victim {
287            if let Some(evicted) = pending.pop(&victim_peer) {
288                let _ = pending.push(incoming.peer, incoming);
289                return FirstAuditQueueOutcome::CapacityEvicted {
290                    peer: victim_peer,
291                    pin: evicted.pin,
292                };
293            }
294        }
295    }
296    match pending.push(incoming.peer, incoming) {
297        None => FirstAuditQueueOutcome::Queued,
298        // Unreachable: the random-displacement branch above guarantees
299        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
300        // exists). Kept so any future logic error surfaces as an ACCOUNTED
301        // eviction rather than silent loss — but note this arm would be
302        // LRU-order, not random, so it must stay unreachable.
303        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
304            peer: evicted_peer,
305            pin: evicted.pin,
306        },
307    }
308}
309
310/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
311/// prefiltering a nomination's answerability at schedule time, covering the
312/// spawn/dispatch latency between the timer firing and the wire challenge so a
313/// jitter==MAX pin is not admitted only to fail the authoritative check by a
314/// few milliseconds. Tiny against the multi-hour answerability window.
315const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
316
317/// A first audit the limiter recently launched at a peer: when, and the
318/// committed key count that was audited (for the count-jump override).
319#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320struct RecentFirstAudit {
321    launched_at: Instant,
322    key_count: u32,
323}
324
325/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
326/// panicking or cancelled audit task can never leak a slot and wedge the
327/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
328struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
329
330impl FirstAuditInflightSlot {
331    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
332        observability.inflight.fetch_add(1, Ordering::Relaxed);
333        Self(Arc::clone(observability))
334    }
335}
336
337impl Drop for FirstAuditInflightSlot {
338    fn drop(&mut self) {
339        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
340    }
341}
342
343/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
344/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
345/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
346/// overflow-free integer math). A jump re-nominates a peer despite a recent
347/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
348/// only, so no gossip-lottery audit can ever cover it.
349const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
350    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
351        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
352}
353
354/// The launch limiter's verdict for one pending monetized pin.
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356enum LimiterVerdict {
357    /// Within budget and window: the caller may reserve a launch (and consumes
358    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
359    Admit,
360    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
361    /// pin pending and retry on a later tick.
362    RateDeferred,
363    /// The peer had a first audit within
364    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
365    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
366    /// gossip-lottery re-audit path is unaffected).
367    WindowDeduped,
368}
369
370/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
371/// (launch rate), an in-flight cap, and a per-peer re-audit window that
372/// survives pin rotation.
373///
374/// This is the load-bearing aggregate bound the original scheduler lacked:
375/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
376/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
377/// `now`/`inflight` values so every decision is unit-testable without a
378/// runtime.
379struct FirstAuditLimiter {
380    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
381    tokens: u32,
382    /// Refill anchor. While the bucket is full this tracks `now` (a full
383    /// bucket accrues nothing); while below capacity it advances only by
384    /// whole refill intervals so fractional elapsed time is never lost.
385    last_refill: Instant,
386    /// Peers given a first audit recently, with the audited key count.
387    /// Bounded like the drainer's other per-peer maps.
388    recent: LruCache<PeerId, RecentFirstAudit>,
389}
390
391impl FirstAuditLimiter {
392    fn new(now: Instant) -> Self {
393        Self {
394            tokens: config::FIRST_AUDIT_BUDGET_BURST,
395            last_refill: now,
396            recent: LruCache::new(
397                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
398            ),
399        }
400    }
401
402    /// Whether the per-peer re-audit window admits a nomination for `peer`
403    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
404    /// call at ENQUEUE time — suppressed nominations never occupy pending
405    /// slots — without disturbing LRU recency.
406    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
407        self.recent.peek(peer).is_none_or(|prev| {
408            now.saturating_duration_since(prev.launched_at)
409                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
410                || first_audit_count_jump(prev.key_count, key_count)
411        })
412    }
413
414    /// Refill the token bucket for the time elapsed up to `now`.
415    fn refill(&mut self, now: Instant) {
416        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
417            // Full bucket accrues nothing; keep the anchor current so the
418            // next consumption starts its interval from here.
419            self.last_refill = now;
420            return;
421        }
422        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
423        let elapsed = now.saturating_duration_since(self.last_refill);
424        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
425        if earned == 0 {
426            return;
427        }
428        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
429        if earned >= capacity_gap {
430            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
431            self.last_refill = now;
432        } else {
433            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
434            self.tokens = self
435                .tokens
436                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
437            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
438            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
439        }
440    }
441
442    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
443    /// caller runs the remaining (per-peer cooldown) gate and calls
444    /// [`Self::commit_launch`] only for a launch that actually happens, so a
445    /// deferral elsewhere never burns budget or stamps the window.
446    fn assess(
447        &mut self,
448        peer: &PeerId,
449        key_count: u32,
450        now: Instant,
451        inflight: u64,
452    ) -> LimiterVerdict {
453        if !self.window_allows(peer, key_count, now) {
454            return LimiterVerdict::WindowDeduped;
455        }
456        self.refill(now);
457        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
458            return LimiterVerdict::RateDeferred;
459        }
460        LimiterVerdict::Admit
461    }
462
463    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
464    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
465    /// only at [`Self::promote`], after the authoritative post-jitter
466    /// answerability check, so a reservation that is later cancelled leaves no
467    /// suppression behind.
468    fn reserve_token(&mut self) {
469        self.tokens = self.tokens.saturating_sub(1);
470    }
471
472    /// Return a token consumed by a reservation that was cancelled before it
473    /// launched (answerability lapsed or a concurrent gossip audit won the
474    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
475    /// the bucket.
476    fn refund_token(&mut self) {
477        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
478    }
479
480    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
481    /// (promotion). Separated from token consumption so suppression is only
482    /// ever recorded for a real send.
483    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
484        self.recent.put(
485            peer,
486            RecentFirstAudit {
487                launched_at: now,
488                key_count,
489            },
490        );
491    }
492
493    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
494    /// and stamp the window in one call. Production splits these across
495    /// reservation and promotion; the limiter's own budget/window unit tests do
496    /// not model the jitter reservation and use this shorthand.
497    #[cfg(test)]
498    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
499        self.reserve_token();
500        self.promote(peer, key_count, now);
501    }
502}
503
504/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
505/// across the ENTIRE launch-jitter window ending at
506/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
507/// for it cannot later require aborting an out-of-window challenge. The
508/// too-future bound is enforced at `now` (a jitter delay only ages a pin
509/// forward, never toward the future); the too-old bound is enforced at the
510/// latest possible send time. This is a conservative admission prefilter; the
511/// authoritative answerability check still runs at promotion against the real
512/// send-time wall clock, so A1 (no false conviction) holds regardless of how
513/// jitter and the answerability margin are sized. `checked_add` overflow fails
514/// closed (skip the pin).
515fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
516    let Some(latest_send) = now
517        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
518        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
519    else {
520        return false;
521    };
522    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
523}
524
525/// Open the single first-audit reservation from `pending` if none is
526/// outstanding: samples the launch jitter, snapshots the shared cooldown
527/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
528/// shared implementation for both drainer call sites — the per-wake launch
529/// phase and the pre-overflow opportunity inside the ingress batch — so the
530/// two cannot drift.
531async fn open_first_audit_reservation(
532    scheduler: &mut FirstAuditScheduler,
533    cooldown: &RwLock<HashMap<PeerId, Instant>>,
534    observability: &Arc<FirstAuditObservability>,
535) {
536    if scheduler.has_reservation() {
537        return;
538    }
539    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
540        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
541    ));
542    let inflight = observability.inflight.load(Ordering::Relaxed);
543    let reserved = {
544        let cooldown = cooldown.read().await;
545        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
546    };
547    if reserved {
548        if let Some(peer) = scheduler.reserved_peer() {
549            debug!(
550                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
551                scheduler.pending_len()
552            );
553        }
554    }
555}
556
557/// A far-future `Instant` used to effectively DISABLE the promotion-timer
558/// select arm when no reservation is outstanding. The drainer still wakes at
559/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
560/// needs to be comfortably past the next tick.
561fn first_audit_far_future() -> Instant {
562    Instant::now()
563        .checked_add(Duration::from_hours(1))
564        .unwrap_or_else(Instant::now)
565}
566
567/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
568/// its in-flight slot and launch token from schedule time until the jitter
569/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
570/// only if the authoritative post-jitter answerability + cooldown checks pass at
571/// promotion, so a cancelled reservation leaves NO suppression behind.
572struct FirstAuditReservation {
573    event: MonetizedPinEvent,
574    ready_at: Instant,
575    inflight: FirstAuditInflightSlot,
576}
577
578/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
579/// pending queue, the dedup set, the launch limiter, the alternating lane, and
580/// the single outstanding reservation. All mutation is single-threaded in the
581/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
582/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
583/// state machine is unit-testable with injected clocks.
584struct FirstAuditScheduler {
585    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
586    /// (a real send), never at reservation, so a cancelled reservation can be
587    /// re-nominated.
588    first_audited: LruCache<[u8; 32], ()>,
589    /// Highest-count-per-peer pending nominations not yet launched. Capped at
590    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
591    /// one effective answerability window); at capacity a uniformly RANDOM
592    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
593    /// of a specific entry can never be forced deterministically. One further
594    /// entry may be held in `reserved` outside this queue — a deliberate
595    /// one-entry guard slot, so total schedulable occupancy is at most
596    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
597    pending: LruCache<PeerId, MonetizedPinEvent>,
598    /// Token bucket + per-peer re-audit window.
599    limiter: FirstAuditLimiter,
600    /// The single outstanding reservation (E′ serializes reservations so the
601    /// per-launch lane alternation is preserved and at most one jitter timer is
602    /// live).
603    reserved: Option<FirstAuditReservation>,
604    /// Alternating launch lane, flipped on every PROMOTION (real launch).
605    oldest_first_lane: bool,
606    /// The local node's own peer ID. A verified payment's quote list includes
607    /// the node's own quote, so the verifier emits a monetized-pin event for
608    /// the local peer on every payment it verifies. The node cannot
609    /// network-audit itself (there is no dialable address for the local peer,
610    /// so the challenge fails instantly and is miscounted as a timeout), while
611    /// any other payee that verifies the same payment schedules its own first
612    /// audit of this node's pin — a self-dial adds no coverage either way.
613    /// Such an event is dropped at ingress: never queued, and hence never
614    /// launched nor marked first-audited.
615    self_peer: PeerId,
616    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
617    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
618    /// production seeds from OS entropy at construction.
619    rng: StdRng,
620}
621
622impl FirstAuditScheduler {
623    fn new(now: Instant, self_peer: PeerId) -> Self {
624        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
625        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
626        Self {
627            first_audited: LruCache::new(dedup_cap),
628            pending: LruCache::new(pending_cap),
629            limiter: FirstAuditLimiter::new(now),
630            reserved: None,
631            oldest_first_lane: false,
632            self_peer,
633            rng: StdRng::from_entropy(),
634        }
635    }
636
637    /// Observability getter: used by the scheduler summary log and unit tests,
638    /// both absent from a release `--no-default-features` build, so it is dead
639    /// only in that configuration.
640    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
641    fn pending_len(&self) -> usize {
642        self.pending.len()
643    }
644
645    /// Observability getter (see [`Self::pending_len`]).
646    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
647    fn tokens(&self) -> u32 {
648        self.limiter.tokens
649    }
650
651    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
652    /// signed quote timestamp of the oldest pin still awaiting a first audit:
653    /// how close the longest-waiting pending pin is to aging out of the
654    /// answerability window. A value climbing toward the window means pending
655    /// work is expiring unaudited instead of launching; a small, steady value
656    /// means the queue is draining promptly. Returns `0` when `pending` is empty
657    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
658    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
659    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
660        self.pending
661            .iter()
662            .map(|(_, e)| e.quote_ts)
663            .min()
664            .and_then(|oldest| now.duration_since(oldest).ok())
665            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
666    }
667
668    /// Drop every pending nomination that has aged past the answerability
669    /// horizon. `try_reserve` collects expired entries only while it can scan —
670    /// under token starvation it returns at the budget gate first — so without
671    /// a periodic sweep dead entries squat the capped pending queue (displacing
672    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
673    /// telemetry. Each removal is accounted as `outside_answerability_window`,
674    /// exactly like a scan-time expiry. Returns how many entries were dropped;
675    /// survivor recency is untouched.
676    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
677        let expired: Vec<PeerId> = self
678            .pending
679            .iter()
680            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
681            .map(|(peer, _)| *peer)
682            .collect();
683        for peer in &expired {
684            self.pending.pop(peer);
685        }
686        if !expired.is_empty() {
687            obs.outside_answerability_window.fetch_add(
688                u64::try_from(expired.len()).unwrap_or(u64::MAX),
689                Ordering::Relaxed,
690            );
691        }
692        expired.len()
693    }
694
695    fn has_reservation(&self) -> bool {
696        self.reserved.is_some()
697    }
698
699    /// Whether admitting `event` would displace a DIFFERENT peer's pending
700    /// entry: the queue is at capacity and `event.peer` has no incumbent to
701    /// coalesce into. The drainer checks this before enqueueing so pending
702    /// work gets a reservation opportunity BEFORE destructive overflow
703    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
704    /// of `pending`, freeing the slot without any eviction.
705    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
706        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
707    }
708
709    /// When the outstanding reservation becomes eligible for promotion.
710    fn reserved_ready_at(&self) -> Option<Instant> {
711        self.reserved.as_ref().map(|r| r.ready_at)
712    }
713
714    /// The peer of the outstanding reservation, if any.
715    fn reserved_peer(&self) -> Option<PeerId> {
716        self.reserved.as_ref().map(|r| r.event.peer)
717    }
718
719    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
720    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
721    /// if already first-audited; the window screen is bypassed for the currently
722    /// reserved peer (so a successor is retained across the reservation, never
723    /// window-dropped); otherwise window-screened. Coalescing is
724    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
725    /// displaces a higher-count pending pin. An incumbent that has aged past
726    /// the answerability horizon is dropped (and accounted as an expiry) before
727    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
728    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
729    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
730    /// displacement is accounted as `capacity_evicted` and stamps no
731    /// suppression, so a displaced peer's next nomination is judged like any
732    /// newcomer. The drainer additionally offers a reservation opportunity
733    /// via [`Self::would_displace`] before calling this on an overflowing
734    /// arrival.
735    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
736        if event.peer == self.self_peer {
737            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
738            return;
739        }
740        if self.first_audited.contains(&event.pin) {
741            obs.duplicates.fetch_add(1, Ordering::Relaxed);
742            return;
743        }
744        let reserved_peer = self.reserved_peer();
745        let is_reserved_peer = reserved_peer == Some(event.peer);
746        if !is_reserved_peer
747            && !self
748                .limiter
749                .window_allows(&event.peer, event.key_count, Instant::now())
750        {
751            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
752            return;
753        }
754        // A pending incumbent past the answerability horizon can never launch,
755        // yet its (possibly higher) key count would still win the coalesce
756        // against a live incoming — e.g. a fresh post-prune lower-count pin —
757        // and under token starvation no reserve scan runs to collect it. Drop
758        // it first so the incoming is judged on its own merits.
759        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
760            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
761        });
762        if stale_incumbent {
763            self.pending.pop(&event.peer);
764            obs.outside_answerability_window
765                .fetch_add(1, Ordering::Relaxed);
766        }
767        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
768        // tie.
769        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
770            FirstAuditQueueOutcome::Queued => {
771                obs.queued.fetch_add(1, Ordering::Relaxed);
772            }
773            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
774                obs.coalesced.fetch_add(1, Ordering::Relaxed);
775            }
776            FirstAuditQueueOutcome::SuppressedLower => {
777                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
778            }
779            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
780                obs.queued.fetch_add(1, Ordering::Relaxed);
781                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
782            }
783        }
784    }
785
786    /// Attempt to create the single reservation from `pending` (E′ reserve).
787    /// Scans in the current lane order and reserves the FIRST eligible pin:
788    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
789    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
790    /// flip the lane — those happen only at promotion. Returns whether a
791    /// reservation was made. `cooldown` is a read-only snapshot (the
792    /// authoritative check-and-stamp is at promotion).
793    fn try_reserve(
794        &mut self,
795        mono_now: Instant,
796        inflight: u64,
797        jitter: Duration,
798        cooldown: &HashMap<PeerId, Instant>,
799        obs: &Arc<FirstAuditObservability>,
800    ) -> bool {
801        if self.reserved.is_some() || self.pending.is_empty() {
802            return false;
803        }
804        self.limiter.refill(mono_now);
805        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
806            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
807            return false;
808        }
809        // MRU->LRU order; reverse for the oldest-first lane so the preferred
810        // end is at the front.
811        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
812            .pending
813            .iter()
814            .enumerate()
815            .map(|(i, (p, e))| (i, *p, *e))
816            .collect();
817        self.pending.clear();
818        if self.oldest_first_lane {
819            ordered.reverse();
820        }
821        let mut chosen: Option<MonetizedPinEvent> = None;
822        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
823        for (idx, peer, event) in ordered {
824            if chosen.is_some() {
825                kept.push((idx, peer, event));
826                continue;
827            }
828            if self.first_audited.contains(&event.pin) {
829                obs.duplicates.fetch_add(1, Ordering::Relaxed);
830                continue; // drop: already audited
831            }
832            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
833                obs.outside_answerability_window
834                    .fetch_add(1, Ordering::Relaxed);
835                continue; // drop: cannot stay answerable through the jitter
836            }
837            // Window + budget + inflight. Tokens do not decrease during the
838            // scan (reserve happens after the loop) and `inflight` is fixed, so
839            // after the upfront budget gate `assess` never returns RateDeferred
840            // here; a defensive RateDeferred keeps the pin.
841            match self
842                .limiter
843                .assess(&peer, event.key_count, mono_now, inflight)
844            {
845                LimiterVerdict::WindowDeduped => {
846                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
847                    continue; // drop: recently first-audited, no count jump
848                }
849                LimiterVerdict::RateDeferred => {
850                    kept.push((idx, peer, event));
851                    continue; // keep (defensive; unreachable after upfront gate)
852                }
853                LimiterVerdict::Admit => {}
854            }
855            if !cooldown_would_allow(cooldown, &peer, mono_now) {
856                obs.cooldown_deferred_attempts
857                    .fetch_add(1, Ordering::Relaxed);
858                kept.push((idx, peer, event));
859                continue; // keep: on shared cooldown, retry later
860            }
861            chosen = Some(event);
862        }
863        // Restore relative recency (oldest re-put first -> newest stays MRU).
864        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
865        for (_, peer, event) in kept {
866            self.pending.put(peer, event);
867        }
868        let Some(event) = chosen else {
869            return false;
870        };
871        self.limiter.reserve_token();
872        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
873        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
874        self.reserved = Some(FirstAuditReservation {
875            event,
876            ready_at,
877            inflight: inflight_slot,
878        });
879        true
880    }
881
882    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
883    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
884        if self
885            .reserved
886            .as_ref()
887            .is_some_and(|r| mono_now >= r.ready_at)
888        {
889            self.reserved.take()
890        } else {
891            None
892        }
893    }
894
895    /// Authoritative promotion of a due reservation (E′). The caller holds the
896    /// shared cooldown write lock and passes the real send-time `wall_now` and
897    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
898    /// launch, or `None` when the launch was cancelled (answerability lapsed
899    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
900    /// On both `None` paths the token is refunded, the in-flight slot released,
901    /// and NO suppression is recorded.
902    ///
903    /// Known operational residual: suppression is stamped here, at promotion,
904    /// while the wire challenge is sent by the detached task the caller spawns
905    /// with the returned event. A task-start or encoding failure between the
906    /// two therefore leaves a stamped-but-unsent window. No remote input can
907    /// force that failure (it requires local task-spawn/alloc failure), so it
908    /// is accepted rather than closed; closing it would require stamping from
909    /// inside the spawned task and re-introduce the cancel-leaves-suppression
910    /// race this design exists to prevent.
911    fn resolve(
912        &mut self,
913        reservation: FirstAuditReservation,
914        wall_now: SystemTime,
915        mono_now: Instant,
916        cooldown: &mut HashMap<PeerId, Instant>,
917        obs: &Arc<FirstAuditObservability>,
918    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
919        let FirstAuditReservation {
920            event, inflight, ..
921        } = reservation;
922        // Authoritative answerability at the REAL send time.
923        if !quote_within_audit_window(event.quote_ts, wall_now) {
924            self.limiter.refund_token();
925            obs.outside_answerability_window
926                .fetch_add(1, Ordering::Relaxed);
927            drop(inflight);
928            return None; // cancelled; nothing stamped, nothing to roll back
929        }
930        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
931        // concurrent gossip audit requeues the reserved event through the SAME
932        // security-aware coalescing: the reserved event is OLDER than any
933        // same-peer successor (`incoming_is_newer = false`), so a higher-count
934        // reserved event still wins over a lower-count successor (the inflated
935        // pin must be audited), while an equal/higher successor is preserved.
936        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
937            self.limiter.refund_token();
938            obs.cooldown_deferred_attempts
939                .fetch_add(1, Ordering::Relaxed);
940            drop(inflight);
941            // Account for the requeue outcome (the nomination itself was already
942            // counted at ingress, so `queued` is not re-incremented): a capacity
943            // eviction of a DIFFERENT peer and a suppressed reserved event are
944            // both observable per the ADR funnel.
945            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
946                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
947                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
948                }
949                FirstAuditQueueOutcome::SuppressedLower => {
950                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
951                }
952                FirstAuditQueueOutcome::Queued
953                | FirstAuditQueueOutcome::Coalesced
954                | FirstAuditQueueOutcome::RetainedOnTie => {}
955            }
956            return None;
957        }
958        // Promote: stamp durable suppression, flip the lane, count the launch.
959        self.limiter.promote(event.peer, event.key_count, mono_now);
960        self.first_audited.put(event.pin, ());
961        self.oldest_first_lane = !self.oldest_first_lane;
962        obs.launched.fetch_add(1, Ordering::Relaxed);
963        Some((event, inflight))
964    }
965}
966
967// ---------------------------------------------------------------------------
968// Constants
969// ---------------------------------------------------------------------------
970
971/// Prefix used by saorsa-core's request-response mechanism.
972const RR_PREFIX: &str = "/rr/";
973
974/// Bounded handoff from the P2P broadcast receiver to serial non-audit
975/// replication processing.
976///
977/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
978/// bulk/non-audit messages here. If this fills, the message is **dropped** —
979/// `start_message_handler` must never block on a full queue, because a stalled
980/// receiver laps the P2P broadcast ring and silently loses messages it never
981/// observed. Every serial-lane class has protocol recovery, so a drop costs a
982/// retry rather than the message.
983///
984/// This bounds a message COUNT, but a queued item is an owned decoded message
985/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
986/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
987/// for: the lane carries small requests and challenges alongside
988/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
989/// right for both. Responses never reach here — `replication_payload_from_event`
990/// filters them out and their requesters correlate them. ADR-0005 decision 12
991/// records the trade and why byte accounting is the correct eventual fix.
992const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
993
994/// Maximum fresh-replication offers processed concurrently, away from the
995/// serial non-audit loop.
996///
997/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
998/// write. Four workers keep that latency off the responder dispatch path while
999/// keeping concurrent EVM/storage pressure small and predictable.
1000const FRESH_OFFER_WORKER_LIMIT: usize = 4;
1001
1002/// Maximum fresh offers admitted at once, counting both those running on a
1003/// worker and those queued for one.
1004///
1005/// An admitted offer holds its payload until it completes, so this bounds
1006/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1007/// Offers past the bound are refused rather than queued or handled inline —
1008/// handling one on the message loop stalls every other non-audit message behind
1009/// a payment verification and a multi-MiB write. A refusal is not free: the
1010/// sender does not read it, so it resurfaces as a missing key at the delayed
1011/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1012/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1013/// bound is sized to make refusal rare rather than cheap.
1014const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1015
1016/// Distinct payment proofs queued for one fresh-offer key.
1017///
1018/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1019/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1020/// chunk out to the close group, so a receiver sees the same key from about that
1021/// many senders. They differ only in their proof — the bytes are provably
1022/// identical, since `fresh_offer_structural_rejection` has confirmed
1023/// `key == BLAKE3(data)` before any of them is queued.
1024///
1025/// Sizing the queue to the number of legitimate senders is what lets a failing
1026/// proof fall through to the next one instead of costing the node the record.
1027///
1028/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1029/// admitted, and a proof the handler has popped has spent its slot rather than
1030/// returned it. That distinction is what bounds the work an attacker can buy —
1031/// at most this many on-chain verifications per key, after which the entry
1032/// refuses everyone until it closes. Gating on the queue's instantaneous length
1033/// instead would let a stream of distinct sources refill each popped slot and
1034/// run unbounded sequential verifications while holding one of the four worker
1035/// slots. One attempt per source additionally means a single peer can only ever
1036/// consume one of these.
1037const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1038
1039/// Fresh-offer slots kept reachable by sources that hold none.
1040///
1041/// The property worth guaranteeing is that one peer cannot *starve* others, not
1042/// that any peer is held to a small quota. Expressing the bound as a reserve
1043/// rather than a quota is what keeps those two apart.
1044const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1045
1046/// Maximum fresh offers admitted from one source peer.
1047///
1048/// Without a per-source bound, one peer can hold every slot in the global pool
1049/// and every honest offer arriving in that window is refused — and because a
1050/// refusal is later read as absence by the sender's delayed possession check,
1051/// those refusals land as audit-severity trust penalties on the *refuser*.
1052/// That makes an unbounded global pool a targeted eviction primitive.
1053///
1054/// The bound is deliberately far looser than the other responder classes'
1055/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1056/// the opposite shape. Those are request/response: a requester needs only a
1057/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1058/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1059/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1060/// for request/response traffic therefore binds on completely legitimate
1061/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1062/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1063/// ceiling and none to the global pool.
1064///
1065/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1066/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1067/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1068// The cast is from a compile-time constant difference of two small literals
1069// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1070// relationship visible in the code rather than only in a test.
1071#[allow(clippy::cast_possible_truncation)]
1072const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1073    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1074
1075/// Maximum paid-list notifications served concurrently.
1076///
1077/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1078/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1079/// Two workers keep cross-peer progress without multiplying concurrent EVM
1080/// and DHT lookup pressure.
1081const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1082
1083/// Maximum paid-list notifications admitted across workers and their waiters.
1084///
1085/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1086/// is one-way: the protocol defines no response and the sender never retries,
1087/// so a refused notify is information permanently lost to this node until a
1088/// later verification cycle happens to re-derive the key's paid status from a
1089/// paid-list quorum. A tight admission bound therefore does not shed load, it
1090/// discards durable state — which is why the class's real protection is
1091/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1092/// is actually expensive, rather than this queue depth.
1093///
1094/// A client PUT fans one notify per key out to the whole paid close group, so
1095/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1096/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1097/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1098/// carry no chunk payload.
1099const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1100
1101/// Maximum admitted paid-list notifications from one source peer.
1102///
1103/// A quarter of the pool. One peer legitimately supplies a whole upload's
1104/// worth of notifies, so this must comfortably exceed a typical file's chunk
1105/// count in flight; it exists to stop a single source evicting every other
1106/// peer's durable paid-list evidence, not to ration ordinary traffic.
1107const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1108
1109/// Maximum fetch responses served concurrently.
1110///
1111/// Each successful response can upload a 4 MiB chunk. Matching
1112/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1113/// simultaneous chunk data, which avoids saturating typical home upload links.
1114const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1115
1116/// Maximum fetch requests admitted across workers and their bounded waiters.
1117///
1118/// Four worker waves absorb short bursts without retaining chunk bytes—the
1119/// request contains only a key—while the dequeue deadline sheds work before a
1120/// sustained flood can keep the node serving requests whose callers timed out.
1121const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1122
1123/// Maximum admitted fetch requests from one source peer.
1124///
1125/// Two requests let one peer pipeline useful reads while leaving at least one
1126/// of the three workers available to other peers under a single-source flood.
1127const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1128
1129/// Maximum verification batches served concurrently.
1130///
1131/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1132/// workers isolate that synchronous work from message dispatch without turning
1133/// large batches into an I/O fan-out throughput contest.
1134const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1135
1136/// Maximum verification batches admitted across workers and bounded waiters.
1137///
1138/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1139/// deadline prevents queued batches from consuming lookup capacity after their
1140/// requesters have stopped waiting.
1141const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1142
1143/// Maximum admitted verification batches from one source peer.
1144///
1145/// Senders already aggregate a peer's keys into one batch. One outstanding
1146/// batch therefore preserves useful work while reserving the other worker and
1147/// the bounded queue for different peers.
1148const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1149
1150/// Maximum neighbor-sync requests served concurrently across source peers.
1151///
1152/// Building a response scans local keys and performs DHT lookups, so two
1153/// workers allow cross-peer progress without multiplying that expensive scan
1154/// into broad network and storage contention.
1155const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1156
1157/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1158///
1159/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1160/// payloads bounded; expired waiters are shed before any key scan begins.
1161const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1162
1163/// Maximum admitted neighbor-sync requests from one source peer.
1164///
1165/// Sync history must be updated before repair proofs for the same peer. A
1166/// single slot preserves that ordering while independent peers remain parallel.
1167const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1168
1169/// Match an inbound topic against the replication protocol ids, in both the bare
1170/// gossip form and the `/rr/<id>` request-response form.
1171///
1172/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1173/// was the RR form. The matched id is carried into the handler so it can enforce
1174/// that subtree messages only arrive on the subtree id.
1175fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1176    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1177        if topic == id {
1178            return Some((id, false));
1179        }
1180        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1181            if rest == id {
1182                return Some((id, true));
1183            }
1184        }
1185    }
1186    None
1187}
1188
1189/// Whether a decoded body belongs on the protocol id it arrived on:
1190/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1191/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1192///
1193/// The receive guard drops any mismatch (a cross-version or misrouted message);
1194/// sharing this one predicate between the guard and its regression test means a
1195/// change to the rule cannot pass the test unnoticed.
1196fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1197    protocol == response_protocol_for(body)
1198}
1199
1200/// The protocol id a body belongs on — the single source of truth for BOTH
1201/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1202/// response selector in `send_replication_response_checked`.
1203///
1204/// Sharing one function makes the subtree/core isolation symmetric.
1205fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1206    if body.is_subtree_audit() {
1207        SUBTREE_AUDIT_PROTOCOL_ID
1208    } else {
1209        REPLICATION_PROTOCOL_ID
1210    }
1211}
1212
1213fn fresh_offer_payment_context() -> VerificationContext {
1214    VerificationContext::FreshReplication
1215}
1216
1217fn paid_notify_payment_context() -> VerificationContext {
1218    VerificationContext::PaidListAdmission
1219}
1220
1221/// Boxed future type for in-flight fetch tasks.
1222type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1223
1224/// Fresh-offer keys currently being handled, each with the proofs still to try.
1225///
1226/// Concurrent duplicates are routine: a client PUT is confirmed by
1227/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1228/// commonly arrives from several senders at once. Collapsing them onto one
1229/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1230/// and an on-chain verification per copy.
1231///
1232/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1233/// refusing every later offer outright made the first arrival the only arrival:
1234/// if its proof failed, the record was lost even though a valid proof for the
1235/// same bytes was queued behind it, and the resulting absence was charged to
1236/// this node by the delayed possession check. So the entry holds the bytes once
1237/// and queues each sender's proof, and the handler works down that queue. A
1238/// later offer therefore costs a proof, not a payload — sound only because
1239/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1240/// every one of them before it is queued, which is what makes their bytes
1241/// provably identical.
1242///
1243/// Entries are exact keys rather than hash shards. A node only receives offers
1244/// for keys it is close to, so the accepted key set clusters tightly around its
1245/// own ID — any index derived from the key would land nearly every offer on one
1246/// shard and serialize unrelated keys behind each other. Exact keys keep them
1247/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1248/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1249///
1250/// The critical section is a map insert, pop, or remove and is never held across
1251/// an await, so this is a blocking mutex rather than an async one.
1252type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1253
1254/// One sender's unverified claim to have paid for a key already in flight.
1255///
1256/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1257/// content-address check ran before this attempt was queued.
1258struct FreshOfferAttempt {
1259    source: PeerId,
1260    proof_of_payment: Vec<u8>,
1261    request_id: u64,
1262    rr_message_id: Option<String>,
1263}
1264
1265/// Proofs still to try for one in-flight key, and who supplied them.
1266///
1267/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1268/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1269struct FreshOfferEntry {
1270    /// Untried proofs in arrival order. The handler holds the current one.
1271    pending: VecDeque<FreshOfferAttempt>,
1272    /// Sources already represented, so one peer cannot fill the queue alone.
1273    sources: HashSet<PeerId>,
1274    /// Proofs admitted over this entry's whole life, **never decremented**.
1275    ///
1276    /// The budget has to be spent by admissions rather than held by the queue.
1277    /// The handler pops a proof before verifying it, so gating on
1278    /// `pending.len()` would let a fresh source refill the slot that pop just
1279    /// freed, and a stream of distinct sources could then run unbounded
1280    /// sequential payment verifications while holding one of only four worker
1281    /// slots. Counting admissions makes the cap a lifetime budget instead.
1282    admitted: usize,
1283}
1284
1285/// How an arriving fresh offer joined the work already in flight for its key.
1286enum FreshOfferAdmission {
1287    /// Opened the entry. This offer's handler owns the key and drives every
1288    /// queued proof, including proofs that arrive later.
1289    Opened(Box<FreshOfferEntryGuard>),
1290    /// Merged into an entry another offer opened; its handler reaches this proof
1291    /// if the ones ahead of it fail.
1292    Joined,
1293    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1294    Full,
1295    /// This source already has a proof queued for this key.
1296    DuplicateSource,
1297}
1298
1299// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1300// `debug!`, which compiles to nothing without the feature.
1301#[cfg(feature = "logging")]
1302impl FreshOfferAdmission {
1303    /// Why the offer added nothing to the work already queued for its key.
1304    ///
1305    /// Local logging only — the wire reason stays uniform so a probing peer
1306    /// cannot tell a full queue from a repeat of its own proof.
1307    const fn surplus_reason(&self) -> &'static str {
1308        match self {
1309            Self::DuplicateSource => "this source already has a proof queued",
1310            Self::Full => "the key already holds its full complement of proofs",
1311            Self::Opened(_) | Self::Joined => "not surplus",
1312        }
1313    }
1314}
1315
1316/// RAII ownership of one in-flight fresh-offer key.
1317///
1318/// Clears the entry on drop, so an early return, an error, or a panic cannot
1319/// strand a key as permanently in flight. Also owns the single copy of the
1320/// offered bytes that every queued proof is tried against.
1321struct FreshOfferEntryGuard {
1322    in_flight: FreshOfferInFlight,
1323    key: XorName,
1324    /// The bytes every attempt for this key shares, held exactly once.
1325    data: Vec<u8>,
1326    /// Arrival of the offer that opened the entry.
1327    received_at: Instant,
1328    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1329    /// a *later* offer has since opened for the same key.
1330    holds_entry: bool,
1331}
1332
1333impl FreshOfferEntryGuard {
1334    /// Open an entry for this offer's key, or queue its proof behind the entry
1335    /// already open.
1336    ///
1337    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1338    /// on every other outcome they are dropped here rather than held for the
1339    /// lifetime of the entry.
1340    fn admit(
1341        in_flight: &FreshOfferInFlight,
1342        offer: protocol::FreshReplicationOffer,
1343        source: PeerId,
1344        request_id: u64,
1345        rr_message_id: Option<String>,
1346        received_at: Instant,
1347    ) -> FreshOfferAdmission {
1348        let key = offer.key;
1349        let attempt = FreshOfferAttempt {
1350            source,
1351            proof_of_payment: offer.proof_of_payment,
1352            request_id,
1353            rr_message_id,
1354        };
1355
1356        let mut in_flight_map = in_flight.lock();
1357        if let Some(entry) = in_flight_map.get_mut(&key) {
1358            if entry.sources.contains(&source) {
1359                return FreshOfferAdmission::DuplicateSource;
1360            }
1361            // Lifetime budget, not queue depth: a proof the handler has already
1362            // popped has spent its slot, not returned it.
1363            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1364                return FreshOfferAdmission::Full;
1365            }
1366            entry.admitted = entry.admitted.saturating_add(1);
1367            entry.sources.insert(source);
1368            entry.pending.push_back(attempt);
1369            return FreshOfferAdmission::Joined;
1370        }
1371
1372        let mut sources = HashSet::new();
1373        sources.insert(source);
1374        let mut pending = VecDeque::new();
1375        pending.push_back(attempt);
1376        in_flight_map.insert(
1377            key,
1378            FreshOfferEntry {
1379                pending,
1380                sources,
1381                admitted: 1,
1382            },
1383        );
1384        drop(in_flight_map);
1385        FreshOfferAdmission::Opened(Box::new(Self {
1386            in_flight: Arc::clone(in_flight),
1387            key,
1388            data: offer.data,
1389            received_at,
1390            holds_entry: true,
1391        }))
1392    }
1393
1394    /// The bytes every proof for this key is tried against.
1395    fn data(&self) -> &[u8] {
1396        &self.data
1397    }
1398
1399    /// When the first offer for this key arrived.
1400    fn received_at(&self) -> Instant {
1401        self.received_at
1402    }
1403
1404    /// Take the next untried proof, releasing the key when none remain.
1405    ///
1406    /// Popping and releasing happen under one lock so a proof arriving exactly
1407    /// as the queue empties is never silently discarded: it either lands in this
1408    /// entry and is returned here, or finds no entry and opens its own.
1409    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1410        let mut in_flight = self.in_flight.lock();
1411        let Some(entry) = in_flight.get_mut(&self.key) else {
1412            self.holds_entry = false;
1413            return None;
1414        };
1415        if let Some(attempt) = entry.pending.pop_front() {
1416            return Some(attempt);
1417        }
1418        in_flight.remove(&self.key);
1419        self.holds_entry = false;
1420        None
1421    }
1422
1423    /// Release the key and return the proofs that were never tried, so their
1424    /// senders can be told the outcome the key reached without them.
1425    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1426        let mut in_flight = self.in_flight.lock();
1427        self.holds_entry = false;
1428        in_flight
1429            .remove(&self.key)
1430            .map(|entry| entry.pending.into_iter().collect())
1431            .unwrap_or_default()
1432    }
1433}
1434
1435impl Drop for FreshOfferEntryGuard {
1436    fn drop(&mut self) {
1437        if self.holds_entry {
1438            self.in_flight.lock().remove(&self.key);
1439        }
1440    }
1441}
1442
1443/// Shared dependencies for one verification worker cycle.
1444struct VerificationCycleContext<'a> {
1445    p2p_node: &'a Arc<P2PNode>,
1446    paid_list: &'a Arc<PaidList>,
1447    storage: &'a Arc<ChunkStore>,
1448    queues: &'a Arc<RwLock<ReplicationQueues>>,
1449    config: &'a ReplicationConfig,
1450    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1451    is_bootstrapping: &'a Arc<RwLock<bool>>,
1452    bootstrap_complete_notify: &'a Arc<Notify>,
1453    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1454    /// peer's Present claim to Unresolved unless they're a credited
1455    /// holder of the key (i.e. they recently passed a commitment-bound
1456    /// audit on it under their currently-credited commitment hash).
1457    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1458    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1459    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1460}
1461
1462/// Fetch worker polling interval in milliseconds.
1463const FETCH_WORKER_POLL_MS: u64 = 100;
1464
1465/// Verification worker polling interval in milliseconds.
1466const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1467
1468/// Verification cycle duration that is worth surfacing at info level.
1469const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1470
1471/// Standard trust event weight for per-operation success/failure signals.
1472///
1473/// Used for individual replication fetch outcomes, integrity check failures,
1474/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1475/// is reserved for confirmed audit failures.
1476const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1477/// Bound trust updates from one verification cycle. A malicious peer can
1478/// advertise thousands of bad singleton keys at once; a few independent
1479/// contradictions are enough for the trust engine without flooding it.
1480const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1481
1482/// Bootstrap drain check interval in seconds.
1483const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1484
1485/// Grace period `shutdown()` waits for each long-lived background task to
1486/// observe the cancellation token and terminate before aborting it.
1487///
1488/// Detached tasks are drained without a timeout because storage-capable work
1489/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1490/// if its async waiter is dropped.
1491const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1492
1493/// How often the responder rebuilds + rotates its storage commitment.
1494///
1495/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1496/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1497/// rotation-anchored: the responder stays answerable for the current
1498/// commitment plus every root it recently gossiped that is still in-window
1499/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1500/// its last emission (see `commitment_state`). So the rotation cadence does
1501/// not by itself bound answerability — a gossiped commitment stays
1502/// answerable across rotations until its gossip TTL lapses.
1503///
1504/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1505/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1506/// comfortably exceeds the gap between our rotation and the next gossip
1507/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1508/// Idle audit-skip pattern from being the common case.
1509///
1510/// Why not faster: the v12 pin is bound to a specific point-in-time
1511/// commitment, so rotation isn't security-critical for pin freshness —
1512/// only for keeping the committed key set current as the responder
1513/// writes new keys. 1 hour is plenty for that, and slow enough that
1514/// honest auditors mostly hit `current` or `previous` rather than the
1515/// "rotated past" case.
1516const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1517
1518/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1519/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1520/// durable well before it could matter to a restart, while the write-on-change
1521/// guard keeps idle nodes from needless disk writes.
1522const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1523
1524/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1525/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1526/// default that keeps log volume negligible.
1527const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1528
1529/// Cadence of the read-only bootstrap state snapshot used to separate drain
1530/// debt from cache and broader connectivity failures in fleet logs.
1531#[cfg(feature = "logging")]
1532const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1533
1534/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1535/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1536/// for first audit only if its SIGNED `quote_ts` lands in
1537/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1538/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1539/// badly-skewed or replayed quote) and one too old (the responder may have aged
1540/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1541/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1542/// within this margin); a legit first audit fires moments after payment
1543/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1544/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1545/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1546const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_mins(30);
1547
1548/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1549/// inside the answerability window relative to `now`, so first-auditing it cannot
1550/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1551/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1552/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1553/// All comparisons use `duration_since` (no `Duration` overflow).
1554fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1555    let too_future = quote_ts
1556        .duration_since(now)
1557        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1558    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1559    let too_old = now
1560        .duration_since(quote_ts)
1561        .is_ok_and(|age| age >= audit_cutoff);
1562    !(too_future || too_old)
1563}
1564
1565/// Minimum interval between commitment signature verifications for a
1566/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1567///
1568/// A sybil that bypasses the routing-table gate (e.g. by transient
1569/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1570/// per gossip message. This rate limit caps the verify-per-peer rate
1571/// at 1/min, which is comfortably above the legitimate gossip cadence
1572/// (the 10-20 min neighbor-sync round on each peer).
1573const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_mins(1);
1574
1575/// Hard cap on the size of `last_commitment_by_peer`.
1576///
1577/// Bounds the per-process memory cost of the auditor's per-peer
1578/// commitment cache. Each entry holds a `StorageCommitment`
1579/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1580/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1581/// realistic close-group neighborhood. When the cap is hit, one
1582/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1583/// order is unspecified; we do not track insertion order). The
1584/// `PeerRemoved` handler proactively drops entries as the DHT
1585/// detects departures, and `ingest_peer_commitment` only admits
1586/// commitments from peers currently in the routing table — together
1587/// the cap is the third line of defence against sybil/churn flooding.
1588const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1589
1590/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1591/// sized to the launch budget instead of the commitment cache.
1592///
1593/// The token bucket can launch at most one audit per
1594/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1595/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1596/// launchable for at most the effective answerability window
1597/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1598/// occupancy beyond `window / interval + burst` is work that cannot launch
1599/// before it expires, so admitting it only builds an aging backlog whose
1600/// telemetry measures the backlog instead of schedulable work.
1601///
1602/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1603/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1604/// rolling sample in which no arrival order lets an attacker deterministically
1605/// flush a chosen target; a fresh pin always enters the sample with an
1606/// unpredictable chance of near-immediate audit, whereas refusing at the door
1607/// would let a sustained payment flood guarantee that every later pin is never
1608/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1609/// ADR-0004 Amendment 4 for the eviction-cost math.
1610///
1611/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1612/// is usable only if the quote stays answerable through `a` plus the maximum
1613/// launch jitter and send slack, so the last usable refill is the largest
1614/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1615/// simulates the shipped predicate instant-by-instant and must agree.
1616#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1617const FIRST_AUDIT_PENDING_CAP: usize = {
1618    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1619        .as_secs()
1620        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1621        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1622        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1623    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1624    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1625    // if the launch interval is ever zeroed: a zero interval makes the budget
1626    // (and this cap) meaningless.
1627    let refills =
1628        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1629    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1630};
1631
1632// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1633// strictly tighter than the commitment-cache bound it replaced.
1634const _: () = {
1635    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1636    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1637};
1638
1639/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1640/// long-running bootstrap node cannot have the set grow without limit
1641/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1642/// the set comfortably outlives normal LRU churn but still caps the
1643/// blast radius of identity-rotation attacks. Once full we refuse new
1644/// inserts (no eviction) — keeps the historic set stable; new v12
1645/// peers above the cap are treated as legacy on rejoin, which matches
1646/// the behaviour before this set existed, not a security regression.
1647const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1648
1649// ---------------------------------------------------------------------------
1650// ReplicationEngine
1651// ---------------------------------------------------------------------------
1652
1653/// The replication engine manages all replication background tasks and state.
1654pub struct ReplicationEngine {
1655    /// Replication configuration (shared across spawned tasks).
1656    config: Arc<ReplicationConfig>,
1657    /// P2P networking node.
1658    p2p_node: Arc<P2PNode>,
1659    /// Local chunk storage.
1660    storage: Arc<ChunkStore>,
1661    /// Persistent paid-for-list.
1662    paid_list: Arc<PaidList>,
1663    /// Payment verifier for `PoP` validation.
1664    payment_verifier: Arc<PaymentVerifier>,
1665    /// Replication pipeline queues.
1666    queues: Arc<RwLock<ReplicationQueues>>,
1667    /// Neighbor sync cycle state.
1668    sync_state: Arc<RwLock<NeighborSyncState>>,
1669    /// Per-peer sync history (for `RepairOpportunity`).
1670    ///
1671    /// This map grows with peer churn and is intentionally unbounded: entries
1672    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1673    /// naturally bounded by the routing table's k-bucket capacity.
1674    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1675    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1676    ///
1677    /// Records when each peer was last audited so a burst of gossiped
1678    /// commitment changes cannot spawn back-to-back audits of the same peer.
1679    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1680    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1681    /// Gossip-private lottery attempt window (one roll per peer per window,
1682    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1683    /// ticket never stamps the shared map and thus never defers a monetized
1684    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1685    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1686    /// Completed local neighbor-sync cycle epoch for proof maturity.
1687    sync_cycle_epoch: Arc<RwLock<u64>>,
1688    /// Per-key repair proof tracking for audit eligibility.
1689    repair_proofs: Arc<RwLock<RepairProofs>>,
1690    /// Bootstrap state tracking.
1691    bootstrap_state: Arc<RwLock<BootstrapState>>,
1692    /// Whether this node is currently bootstrapping.
1693    is_bootstrapping: Arc<RwLock<bool>>,
1694    /// Trigger for early neighbor sync (signalled on topology changes).
1695    sync_trigger: Arc<Notify>,
1696    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1697    bootstrap_complete_notify: Arc<Notify>,
1698    /// Node identity (for signing storage commitments).
1699    ///
1700    /// Phase 3 of the v12 storage-bound audit design. The responder
1701    /// uses this to sign its periodically-built `StorageCommitment`.
1702    identity: Arc<NodeIdentity>,
1703    /// Responder-side commitment state (two-slot atomic rotation).
1704    ///
1705    /// Periodically rebuilt from the live LMDB key set; gossiped on
1706    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1707    /// commitment-bound audit handler.
1708    commitment_state: Arc<ResponderCommitmentState>,
1709    /// Path to the persisted responder retention snapshot
1710    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1711    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1712    /// removing audit grace safe (an unanswerable in-window pin is then provable
1713    /// misbehaviour, not an honest crash-restart).
1714    retention_path: PathBuf,
1715    /// Auditor-side per-peer commitment record (last known commitment +
1716    /// sticky `commitment_capable` flag).
1717    ///
1718    /// Populated whenever an inbound gossip carries a verified
1719    /// commitment from the sender. Used by `audit_tick` to snapshot
1720    /// `expected_commitment_hash` into outbound challenges, and by
1721    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1722    /// proof should be honoured. The sticky `commitment_capable` flag
1723    /// flips true on first successful ingest and never reverts (§2
1724    /// step 5).
1725    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1726    /// Sticky set of peer IDs we have EVER seen carrying a v12
1727    /// commitment, independent of whether their commitment bytes are
1728    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1729    /// closure consults this set to keep treating churned-out
1730    /// previously-v12 peers as v12-capable (rather than degrading them
1731    /// to "legacy" credit-unconditionally) when they re-appear on the
1732    /// network before their next gossip arrives. Bounded growth: even
1733    /// at one million peers seen over the node's lifetime, the set is
1734    /// 32 MB.
1735    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1736    /// Auditor-side holder-eligibility cache (v12 §6).
1737    ///
1738    /// Recorded on successful commitment-bound audit; read by future
1739    /// quorum / paid-list eligibility checks (phase-3 stretch).
1740    recent_provers: Arc<RwLock<RecentProvers>>,
1741    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1742    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1743    /// failure) so a peer we've never successfully verified can't burn
1744    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1745    /// Lives separately from `last_commitment_by_peer` because that
1746    /// map's records only exist after a successful verify.
1747    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1748    /// Limits concurrent outbound replication sends to prevent bandwidth
1749    /// saturation on home broadband connections.
1750    send_semaphore: Arc<Semaphore>,
1751    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1752    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1753    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1754    /// message loop so disk
1755    /// reads don't block replication; the semaphore restores a global
1756    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1757    /// / multi-MiB byte serves.
1758    audit_responder_semaphore: Arc<Semaphore>,
1759    /// Per-source in-flight audit-responder counts, capped at
1760    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1761    /// flood-fair: one peer spamming challenges could occupy every slot and
1762    /// starve honest auditors, whose dropped challenges then convert to
1763    /// audit timeouts against HONEST peers (codex-r2 A). This
1764    /// per-peer cap guarantees no single source can hold more than its share,
1765    /// so a flood self-throttles without denying service to everyone else.
1766    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1767    /// Windowed per-origin capacity and processing-time telemetry for every
1768    /// request sharing the audit responder pool.
1769    audit_responder_metrics: Arc<AuditResponderMetrics>,
1770    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1771    ///
1772    /// Responsible-chunk audits, prune confirmations, and possession checks
1773    /// all use this before sending so local bursts wait instead of breaching
1774    /// the responder's deployed per-source admission cap.
1775    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1776    /// Worker permits for bandwidth-bound fetch responses.
1777    fetch_responder_worker_semaphore: Arc<Semaphore>,
1778    /// Admission permits bounding fetch workers and queued waiters together.
1779    fetch_responder_admission_semaphore: Arc<Semaphore>,
1780    /// Per-source fetch responder counts for flood-fair admission.
1781    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1782    /// Worker permits for lookup-heavy verification batches.
1783    verification_responder_worker_semaphore: Arc<Semaphore>,
1784    /// Admission permits bounding verification workers and queued waiters.
1785    verification_responder_admission_semaphore: Arc<Semaphore>,
1786    /// Per-source verification responder counts for flood-fair admission.
1787    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1788    /// Worker permits for expensive inbound neighbor-sync requests.
1789    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1790    /// Admission permits bounding sync workers and queued waiters together.
1791    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1792    /// Per-source sync responder counts; capped at one to preserve ordering.
1793    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1794    /// Bounded worker permits for expensive fresh-offer handling.
1795    fresh_offer_worker_semaphore: Arc<Semaphore>,
1796    /// Admission permits bounding offers running on a worker or queued for one.
1797    fresh_offer_admission_semaphore: Arc<Semaphore>,
1798    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1799    /// and turn honest senders' refusals into trust penalties on this node.
1800    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1801    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1802    /// duplicates collapse onto one verification and one write.
1803    fresh_offer_in_flight: FreshOfferInFlight,
1804    /// Bounded worker permits for paid-list notification proof verification.
1805    paid_notify_worker_semaphore: Arc<Semaphore>,
1806    /// Admission permits bounding notifies on a worker or queued for one.
1807    paid_notify_admission_semaphore: Arc<Semaphore>,
1808    /// Per-source paid-notify counts for flood-fair admission.
1809    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1810    /// Resource controls for the HEAVY subtree-audit round 1: its own
1811    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1812    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1813    /// sessions binding a slice challenge to a matching round 1.
1814    subtree_round1: SubtreeRound1Limiter,
1815    /// Receiver for fresh-write events from the chunk PUT handler.
1816    ///
1817    /// When present, `start()` spawns a drainer task that calls
1818    /// `replicate_fresh` for each event.
1819    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1820    /// Pointer replication (ADR-0016), when this node stores pointers.
1821    pointers: Option<Arc<pointer::PointerReplication>>,
1822    /// Receiver for fresh pointer writes, taken by `start()`.
1823    pointer_fresh_rx: Option<mpsc::UnboundedReceiver<pointer::PointerFreshWrite>>,
1824    /// Sender for delayed possession-check events (ADR-0003). The fresh-write
1825    /// drainer pushes the responsible close-group peers here after each fresh
1826    /// replication; the possession-check scheduler drains the paired receiver.
1827    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1828    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1829    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1830    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1831    /// for a deterministic first audit. The matching receiver is drained by
1832    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1833    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1834    /// like launches; a dropped nomination is penalty-free — the peer's
1835    /// gossiped commitments stay lottery-covered and its next settled payment
1836    /// re-nominates the paid pin.
1837    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1838    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1839    /// `start_first_audit_drainer`.
1840    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1841    /// Counters shared with the first-audit drainer task, so the scheduler's
1842    /// decisions (queued / launched / self-target skipped / outcome) stay
1843    /// observable from the engine after the drainer takes the receiver.
1844    first_audit_observability: Arc<FirstAuditObservability>,
1845    /// Shutdown token.
1846    shutdown: CancellationToken,
1847    /// Background task handles.
1848    task_handles: Vec<JoinHandle<()>>,
1849    /// Tracks detached, short-lived work spawned by background producers.
1850    ///
1851    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1852    /// tasks, and delayed possession checks may retain storage or P2P state
1853    /// after their producer exits, so shutdown drains them before those
1854    /// resources may be reopened.
1855    detached_task_tracker: TaskTracker,
1856}
1857
1858impl ReplicationEngine {
1859    /// Create a new replication engine.
1860    ///
1861    /// # Errors
1862    ///
1863    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1864    /// or if the configuration fails validation.
1865    #[allow(clippy::too_many_arguments)]
1866    pub async fn new(
1867        config: ReplicationConfig,
1868        p2p_node: Arc<P2PNode>,
1869        storage: Arc<ChunkStore>,
1870        payment_verifier: Arc<PaymentVerifier>,
1871        identity: Arc<NodeIdentity>,
1872        root_dir: &Path,
1873        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1874        shutdown: CancellationToken,
1875    ) -> Result<Self> {
1876        config.validate().map_err(Error::Config)?;
1877
1878        let paid_list = Arc::new(
1879            PaidList::new(root_dir)
1880                .await
1881                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1882        );
1883
1884        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1885        let config = Arc::new(config);
1886        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1887
1888        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1889        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1890        // now capacity-limited — ingress queue here, pending set (LRU), and
1891        // launch rate (token bucket).
1892        let (monetized_pin_tx, monetized_pin_rx) =
1893            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1894
1895        let engine = Self {
1896            config: Arc::clone(&config),
1897            p2p_node,
1898            storage,
1899            paid_list,
1900            payment_verifier,
1901            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1902            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1903            sync_history: Arc::new(RwLock::new(HashMap::new())),
1904            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1905            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1906            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1907            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1908            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1909            is_bootstrapping: Arc::new(RwLock::new(true)),
1910            sync_trigger: Arc::new(Notify::new()),
1911            bootstrap_complete_notify: Arc::new(Notify::new()),
1912            identity,
1913            commitment_state: Arc::new(ResponderCommitmentState::new()),
1914            retention_path: root_dir.join("commitment_retention.bin"),
1915            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1916            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1917            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1918            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1919            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1920            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1921            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1922            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1923            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1924            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1925                FETCH_RESPONDER_WORKER_LIMIT,
1926            )),
1927            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1928                FETCH_RESPONDER_MAX_OUTSTANDING,
1929            )),
1930            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1931            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1932                VERIFICATION_RESPONDER_WORKER_LIMIT,
1933            )),
1934            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1935                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1936            )),
1937            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1938            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1939                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1940            )),
1941            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1942                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1943            )),
1944            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1945            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1946            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1947            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1948            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1949            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1950            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1951            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1952            subtree_round1: SubtreeRound1Limiter::new(
1953                config.subtree_round1_responder_cooldown,
1954                config.subtree_round1_max_concurrent,
1955            ),
1956            fresh_write_rx: Some(fresh_write_rx),
1957            pointers: None,
1958            pointer_fresh_rx: None,
1959            possession_check_tx,
1960            possession_check_rx: Some(possession_check_rx),
1961            monetized_pin_tx,
1962            monetized_pin_rx: Some(monetized_pin_rx),
1963            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1964            shutdown,
1965            task_handles: Vec::new(),
1966            detached_task_tracker: TaskTracker::new(),
1967        };
1968        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1969        // spawns, so an honest restarted node is answerable for its pre-restart
1970        // pins from the first audit it serves, and the persist loop never races
1971        // an empty snapshot over the good on-disk file.
1972        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1973        Ok(engine)
1974    }
1975
1976    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1977    /// (commitments that backed a payment) for a first audit. Cloneable; the
1978    /// engine drains the matching receiver. Bounded: senders must `try_send`
1979    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1980    #[must_use]
1981    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1982        self.monetized_pin_tx.clone()
1983    }
1984
1985    /// Get a reference to the `PaidList`.
1986    #[must_use]
1987    pub fn paid_list(&self) -> &Arc<PaidList> {
1988        &self.paid_list
1989    }
1990
1991    /// Get a reference to the responder's commitment state. Used by audit
1992    /// handlers to look up commitments by hash; used by the rotation tick
1993    /// to install fresh ones.
1994    #[must_use]
1995    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
1996        &self.commitment_state
1997    }
1998
1999    /// Neighbour-sync state, for the storage migration's possession challenges.
2000    #[must_use]
2001    pub fn sync_state(&self) -> &Arc<RwLock<NeighborSyncState>> {
2002        &self.sync_state
2003    }
2004
2005    /// The audit-challenge coordinator, for the storage migration's possession challenges.
2006    #[must_use]
2007    pub fn audit_challenge_coordinator(&self) -> &Arc<AuditChallengeCoordinator> {
2008        &self.audit_challenge_coordinator
2009    }
2010
2011    /// Replication settings, for the storage migration's possession challenges.
2012    #[must_use]
2013    pub fn config(&self) -> &Arc<ReplicationConfig> {
2014        &self.config
2015    }
2016
2017    /// Get a reference to the auditor's last-commitment-by-peer table.
2018    #[must_use]
2019    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2020        &self.last_commitment_by_peer
2021    }
2022
2023    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2024    /// will be read by quorum / paid-list eligibility checks.
2025    #[must_use]
2026    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2027        &self.recent_provers
2028    }
2029
2030    /// Test-only: rebuild + rotate this node's storage commitment now over its
2031    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2032    /// just stored without waiting for the rotation cadence.
2033    ///
2034    /// # Errors
2035    ///
2036    /// Propagates any error from reading the local key set or building/signing
2037    /// the commitment.
2038    #[cfg(any(test, feature = "test-utils"))]
2039    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2040        rebuild_and_rotate_commitment(
2041            &self.storage,
2042            self.pointers.as_ref().map(|p| p.store()),
2043            &self.identity,
2044            &self.commitment_state,
2045            &self.p2p_node,
2046            &self.config,
2047        )
2048        .await
2049    }
2050
2051    /// Test-only: directly seed this node's cached commitment for `peer`,
2052    /// simulating "we received `peer`'s gossiped commitment" without depending
2053    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2054    /// peer's commitment deterministically.
2055    #[cfg(any(feature = "test-utils", test))]
2056    pub async fn inject_peer_commitment_for_test(
2057        &self,
2058        peer: &PeerId,
2059        commitment: StorageCommitment,
2060    ) {
2061        let now = Instant::now();
2062        self.last_commitment_by_peer
2063            .write()
2064            .await
2065            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2066        self.ever_capable_peers.write().await.insert(*peer);
2067    }
2068
2069    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2070    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2071    /// window and clears any shared cooldown stamped by an earlier gossip
2072    /// launch. The locks follow the production gossip-audit lock order.
2073    #[cfg(any(test, feature = "test-utils"))]
2074    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2075        let now = Instant::now();
2076        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2077        let mut launched = self.audit_on_gossip_cooldown.write().await;
2078        lottery_attempts.insert(*peer, now);
2079        launched.remove(peer);
2080    }
2081
2082    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2083    /// commitment this node has cached for it (from gossip), over the live wire.
2084    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2085    /// in a real two-node setting without waiting for the gossip cadence.
2086    ///
2087    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2088    /// peer yet (gossip hasn't reached us). Gated to test builds.
2089    #[cfg(any(test, feature = "test-utils"))]
2090    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2091        let target = {
2092            let map = self.last_commitment_by_peer.read().await;
2093            map.get(peer)
2094                .and_then(PeerCommitmentRecord::last_commitment)
2095                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2096        };
2097        let Some((pin, key_count)) = target else {
2098            return audit::AuditTickResult::Idle;
2099        };
2100        let credit = storage_commitment_audit::AuditCredit {
2101            recent_provers: &self.recent_provers,
2102        };
2103        storage_commitment_audit::run_subtree_audit(
2104            &self.p2p_node,
2105            &self.config,
2106            peer,
2107            pin,
2108            key_count,
2109            Some(&credit),
2110        )
2111        .await
2112    }
2113
2114    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2115    /// tests assert what the live drainer decided for an injected
2116    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2117    #[cfg(any(test, feature = "test-utils"))]
2118    #[must_use]
2119    pub fn first_audit_stats(&self) -> FirstAuditStats {
2120        let o = &self.first_audit_observability;
2121        FirstAuditStats {
2122            received: o.received.load(Ordering::Relaxed),
2123            queued: o.queued.load(Ordering::Relaxed),
2124            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2125            launched: o.launched.load(Ordering::Relaxed),
2126            passed: o.passed.load(Ordering::Relaxed),
2127            timed_out: o.timed_out.load(Ordering::Relaxed),
2128            failed: o.failed.load(Ordering::Relaxed),
2129        }
2130    }
2131
2132    /// Test-only: run the possession check immediately for `key` against
2133    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2134    ///
2135    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2136    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2137    /// deterministically without waiting for the scheduled check.
2138    #[cfg(any(test, feature = "test-utils"))]
2139    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2140        possession::run_possession_check(
2141            key,
2142            peers,
2143            &self.p2p_node,
2144            &self.storage,
2145            &self.config,
2146            &self.sync_state,
2147            &self.audit_challenge_coordinator,
2148            &self.shutdown,
2149        )
2150        .await;
2151    }
2152
2153    /// Test-only: place `key` directly into the fetch queue as though a
2154    /// verification cycle had just promoted it, with `sources` as its
2155    /// verified holders. Returns whether the key was enqueued.
2156    ///
2157    /// Bypasses admission, verification, and the promotion-time
2158    /// responsibility pre-filter, modelling a promotion decision that has
2159    /// since gone stale (topology churn between promotion and download).
2160    /// The only guard left standing is the per-attempt recheck inside
2161    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2162    /// exercise.
2163    #[cfg(any(test, feature = "test-utils"))]
2164    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2165        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2166        self.queues
2167            .write()
2168            .await
2169            .enqueue_fetch(key, distance, sources)
2170    }
2171
2172    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2173    /// (pending verification, fetch queue, or in-flight fetch).
2174    #[cfg(any(test, feature = "test-utils"))]
2175    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2176        self.queues.read().await.contains_key(key)
2177    }
2178
2179    /// Test-only: place `key` into pending verification as though `hinter` had
2180    /// just advertised it with a replica hint. Returns whether it was admitted.
2181    ///
2182    /// Enters the pipeline one stage earlier than
2183    /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2184    /// decides about the key is observable.
2185    #[cfg(any(test, feature = "test-utils"))]
2186    pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2187        let now = Instant::now();
2188        let entry = VerificationEntry {
2189            state: VerificationState::PendingVerify,
2190            verified_sources: Vec::new(),
2191            tried_sources: HashSet::new(),
2192            created_at: now,
2193            next_verify_at: now,
2194            hint_sources: HashSet::from([hinter]),
2195            replica_hint_sources: HashSet::from([hinter]),
2196            unresolved_retries: 0,
2197            no_holder_reported: false,
2198        };
2199        self.queues
2200            .write()
2201            .await
2202            .add_pending_verify(key, entry)
2203            .admitted()
2204    }
2205
2206    /// Test-only: how far ahead `key`'s next verification round is scheduled,
2207    /// or `None` when the key is not pending verification.
2208    #[cfg(any(test, feature = "test-utils"))]
2209    pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2210        self.queues.read().await.get_pending(key).map(|entry| {
2211            entry
2212                .next_verify_at
2213                .saturating_duration_since(Instant::now())
2214        })
2215    }
2216
2217    /// Replicate pointers too (ADR-0016): the records in `store`, and the
2218    /// fresh writes the pointer PUT handler sends on `fresh_writes`.
2219    ///
2220    /// Call before [`Self::start`].
2221    pub fn with_pointers(
2222        &mut self,
2223        store: PointerStore,
2224        fresh_writes: mpsc::UnboundedReceiver<pointer::PointerFreshWrite>,
2225    ) {
2226        self.pointers = Some(Arc::new(pointer::PointerReplication::new(
2227            store,
2228            Arc::clone(&self.storage),
2229            Arc::clone(&self.p2p_node),
2230            Arc::clone(&self.payment_verifier),
2231            Arc::clone(&self.config),
2232            Arc::clone(&self.is_bootstrapping),
2233            Arc::clone(&self.send_semaphore),
2234            self.shutdown.clone(),
2235            self.detached_task_tracker.clone(),
2236        )));
2237        self.pointer_fresh_rx = Some(fresh_writes);
2238    }
2239
2240    /// The pointer replication, when enabled. Tests use it to drive rounds.
2241    #[cfg(any(test, feature = "test-utils"))]
2242    #[must_use]
2243    pub fn pointer_replication(&self) -> Option<&Arc<pointer::PointerReplication>> {
2244        self.pointers.as_ref()
2245    }
2246
2247    /// Start all background tasks.
2248    ///
2249    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2250    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2251    /// missed by the bootstrap-sync gate.
2252    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2253        if !self.task_handles.is_empty() {
2254            error!("ReplicationEngine::start() called while already running — ignoring");
2255            return;
2256        }
2257        info!("Starting replication engine");
2258
2259        self.start_message_handler();
2260        self.start_neighbor_sync_loop();
2261        self.start_self_lookup_loop();
2262        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2263        // chunks they SHOULD store (responsibility + prior hint).
2264        self.start_audit_loop();
2265        // Audit #1 (storage-commitment) is gossip-triggered in the message
2266        // handler when a peer's commitment is ingested, not on a periodic tick.
2267        self.start_commitment_rotation_loop();
2268        self.start_retention_persist_loop();
2269        self.start_fetch_worker();
2270        self.start_verification_worker();
2271        self.start_bootstrap_sync(dht_events);
2272        self.start_fresh_write_drainer();
2273        self.start_possession_check_scheduler();
2274        if let Some(pointers) = &self.pointers {
2275            self.task_handles.push(pointers.start_verification_loop());
2276            if let Some(writes) = self.pointer_fresh_rx.take() {
2277                self.task_handles.push(pointers.start_fresh_drainer(writes));
2278            }
2279        }
2280        // ADR-0004: deterministic first audit of commitments that backed a
2281        // payment (surfaced by the verifier cross-check).
2282        self.start_first_audit_drainer();
2283        // V2-623: periodic cumulative per-variant traffic accounting.
2284        self.start_traffic_summary_loop();
2285        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2286        #[cfg(feature = "logging")]
2287        self.start_bootstrap_state_snapshot_loop();
2288        #[cfg(feature = "logging")]
2289        self.start_audit_responder_summary_loop();
2290
2291        info!(
2292            "Replication engine started with {} background tasks",
2293            self.task_handles.len()
2294        );
2295    }
2296
2297    /// Returns `true` if the node is still in the replication bootstrap phase.
2298    ///
2299    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2300    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2301    pub async fn is_bootstrapping(&self) -> bool {
2302        *self.is_bootstrapping.read().await
2303    }
2304
2305    /// Wait until the replication bootstrap phase completes.
2306    ///
2307    /// Returns immediately if bootstrap has already completed. Useful for
2308    /// readiness probes, health checks, and test harnesses that need the
2309    /// node to be fully operational before proceeding.
2310    ///
2311    /// Returns `true` if bootstrap completed within the timeout, `false`
2312    /// if the timeout elapsed first.
2313    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2314        // Register the notification future *before* checking the flag so that
2315        // a transition between the read and the await is not missed.
2316        let notified = self.bootstrap_complete_notify.notified();
2317        tokio::pin!(notified);
2318        notified.as_mut().enable();
2319
2320        if !*self.is_bootstrapping.read().await {
2321            return true;
2322        }
2323
2324        tokio::time::timeout(timeout, notified).await.is_ok()
2325    }
2326
2327    /// Cancel all background tasks and wait for them to terminate.
2328    ///
2329    /// This must be awaited before dropping the engine when the caller needs
2330    /// the `Arc<ChunkStore>` references held by background tasks to be
2331    /// released (e.g. before reopening the same LMDB environment).
2332    ///
2333    /// When this returns, no engine-spawned task still holds
2334    /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no LMDB blocking operation
2335    /// (read or write, on either the chunk store or the paid-list
2336    /// environment) is still running.  Engine tasks race their work against
2337    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2338    /// LMDB transaction running detached, so this method additionally waits
2339    /// for both storage layers to go quiescent before returning.
2340    pub async fn shutdown(&mut self) {
2341        self.shutdown.cancel();
2342        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2343            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2344                Ok(Ok(())) => {}
2345                Ok(Err(e)) if e.is_cancelled() => {}
2346                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2347                Err(_) => {
2348                    warn!(
2349                        "Replication task {i} did not stop within {}s, aborting",
2350                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2351                    );
2352                    handle.abort();
2353                    // `abort` only requests cancellation. Await the handle so
2354                    // synchronous sections finish and the task drops every
2355                    // storage/P2P clone before we claim producer quiescence.
2356                    match handle.await {
2357                        Ok(()) => {}
2358                        Err(e) if e.is_cancelled() => {}
2359                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2360                    }
2361                }
2362            }
2363        }
2364
2365        // Close the responder worker pools. Detached tasks still queued for a
2366        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2367        // rather than waiting for a slot that will never free up — without
2368        // this, work admitted just before shutdown would queue behind the last
2369        // in-flight batch and hold the drain below open for its full duration.
2370        self.fresh_offer_worker_semaphore.close();
2371        self.paid_notify_worker_semaphore.close();
2372        self.fetch_responder_worker_semaphore.close();
2373        self.verification_responder_worker_semaphore.close();
2374        self.neighbor_sync_responder_worker_semaphore.close();
2375
2376        // All producers have stopped, so close and drain their detached work.
2377        // A started storage operation must run to completion: dropping an async
2378        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2379        // while an LMDB transaction still owns the environment.
2380        //
2381        // Deliberately unbounded: the LMDB contract requires every worker to
2382        // release its `Arc<ChunkStore>` before the caller may reopen the
2383        // environment, and a timeout here could return with one still held.
2384        // What makes that safe is that every detached task is now guaranteed to
2385        // finish — the pools above are closed, stale work is shed at dequeue,
2386        // and the one genuinely unbounded await (payment verification) races
2387        // `self.shutdown` via `verify_payment_until_shutdown`.
2388        self.detached_task_tracker.close();
2389        self.detached_task_tracker.wait().await;
2390
2391        // Every producer is gone, but a select! racing the shutdown token may
2392        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2393        // (fetch `storage.put`, prune `storage.delete` /
2394        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2395        // detached blocking closure owns a cloned `Env`; wait for both
2396        // environments to go quiescent — bounded by one in-flight transaction
2397        // per op — so the caller may reopen them.
2398        self.storage.wait_idle().await;
2399        self.paid_list.wait_idle().await;
2400    }
2401
2402    /// Trigger an early neighbor sync round.
2403    ///
2404    /// Useful after topology changes (new nodes joining, network heal after
2405    /// partition) when the caller wants replication to converge faster than
2406    /// the regular 10-20 minute cadence.
2407    pub fn trigger_neighbor_sync(&self) {
2408        self.sync_trigger.notify_one();
2409    }
2410
2411    /// Execute fresh replication for a newly stored record, then schedule the
2412    /// delayed possession check for the responsible close-group peers
2413    /// (ADR-0003). The production PUT path schedules via the fresh-write
2414    /// drainer; this direct entry point schedules here so callers (and tests)
2415    /// that drive replication directly still get the possession check.
2416    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2417        let peers = fresh::replicate_fresh(
2418            key,
2419            data,
2420            proof_of_payment,
2421            &self.p2p_node,
2422            &self.paid_list,
2423            &self.config,
2424            &self.send_semaphore,
2425        )
2426        .await;
2427        if !peers.is_empty() {
2428            let _ = self
2429                .possession_check_tx
2430                .send(possession::PossessionCheckEvent { key: *key, peers });
2431        }
2432    }
2433
2434    // =======================================================================
2435    // Background task launchers
2436    // =======================================================================
2437
2438    /// Spawn a task that drains the fresh-write channel and triggers
2439    /// replication for each newly-stored chunk.
2440    fn start_fresh_write_drainer(&mut self) {
2441        let Some(mut rx) = self.fresh_write_rx.take() else {
2442            return;
2443        };
2444        let p2p = Arc::clone(&self.p2p_node);
2445        let paid_list = Arc::clone(&self.paid_list);
2446        let config = Arc::clone(&self.config);
2447        let send_semaphore = Arc::clone(&self.send_semaphore);
2448        let possession_tx = self.possession_check_tx.clone();
2449        let shutdown = self.shutdown.clone();
2450
2451        let handle = tokio::spawn(async move {
2452            loop {
2453                tokio::select! {
2454                    () = shutdown.cancelled() => break,
2455                    event = rx.recv() => {
2456                        let Some(event) = event else { break };
2457                        let peers = fresh::replicate_fresh(
2458                            &event.key,
2459                            &event.data,
2460                            &event.payment_proof,
2461                            &p2p,
2462                            &paid_list,
2463                            &config,
2464                            &send_semaphore,
2465                        )
2466                        .await;
2467                        // Schedule the delayed possession check (ADR-0003) for
2468                        // the responsible close-group peers. A closed receiver
2469                        // (engine shutting down) is ignored.
2470                        if !peers.is_empty() {
2471                            let _ = possession_tx.send(possession::PossessionCheckEvent {
2472                                key: event.key,
2473                                peers,
2474                            });
2475                        }
2476                    }
2477                }
2478            }
2479            debug!("Fresh-write drainer shut down");
2480        });
2481        self.task_handles.push(handle);
2482    }
2483
2484    /// Spawn the possession-check scheduler (ADR-0003).
2485    ///
2486    /// Drains scheduled possession-check events and, for each, waits a
2487    /// randomised 5-15 minute settle delay before probing every responsible
2488    /// peer for actual possession. A peer that fails to prove possession or does
2489    /// not answer is penalised at `AuditChallenge` severity.
2490    fn start_possession_check_scheduler(&mut self) {
2491        let Some(mut rx) = self.possession_check_rx.take() else {
2492            return;
2493        };
2494        let p2p = Arc::clone(&self.p2p_node);
2495        let storage = Arc::clone(&self.storage);
2496        let config = Arc::clone(&self.config);
2497        let sync_state = Arc::clone(&self.sync_state);
2498        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2499        let shutdown = self.shutdown.clone();
2500        let detached_task_tracker = self.detached_task_tracker.clone();
2501
2502        let handle = tokio::spawn(async move {
2503            loop {
2504                tokio::select! {
2505                    () = shutdown.cancelled() => break,
2506                    event = rx.recv() => {
2507                        let Some(event) = event else { break };
2508                        // Spawn a per-chunk delayed check so the drain loop
2509                        // keeps pace with the write rate. Each check sleeps the
2510                        // randomised settle delay, then probes every peer.
2511                        let p2p = Arc::clone(&p2p);
2512                        let storage = Arc::clone(&storage);
2513                        let config = Arc::clone(&config);
2514                        let sync_state = Arc::clone(&sync_state);
2515                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2516                        let shutdown = shutdown.clone();
2517                        let delay_min = config.possession_check_delay_min;
2518                        let delay_max = config.possession_check_delay_max;
2519                        detached_task_tracker.spawn(async move {
2520                            let delay = possession::random_delay(delay_min, delay_max);
2521                            // Race shutdown against the whole settle-then-probe
2522                            // sequence, not just the sleep. Once a check starts it
2523                            // may park on the per-target audit coordinator, which
2524                            // has no deadline of its own: with the settle delay
2525                            // inside the branch BODY the select is already resolved,
2526                            // so those waiters would drain only at the probe timeout
2527                            // (roughly `queued / per-target-limit` probes deep) while
2528                            // `detached_task_tracker.wait()` — deliberately unbounded
2529                            // for the LMDB contract — held shutdown open.
2530                            //
2531                            // Dropping this future mid-probe is safe and is the same
2532                            // shape the neighbor-sync round uses: a parked coordinator
2533                            // acquire releases its counted reference via
2534                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2535                            // covered by the storage-quiescence wait in `shutdown`.
2536                            tokio::select! {
2537                                () = shutdown.cancelled() => {}
2538                                () = async {
2539                                    tokio::time::sleep(delay).await;
2540                                    possession::run_possession_check(
2541                                        event.key,
2542                                        event.peers,
2543                                        &p2p,
2544                                        &storage,
2545                                        &config,
2546                                        &sync_state,
2547                                        &audit_challenge_coordinator,
2548                                        &shutdown,
2549                                    )
2550                                    .await;
2551                                } => {}
2552                            }
2553                        });
2554                    }
2555                }
2556            }
2557            debug!("Possession-check scheduler shut down");
2558        });
2559        self.task_handles.push(handle);
2560    }
2561
2562    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2563    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2564    /// as the gossip path, under the same per-peer cooldown and concurrency
2565    /// caps, but with the probability lottery BYPASSED (the lottery governs
2566    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2567    /// deterministic first audit; a peer minting fresh pins faster than the
2568    /// cooldown forfeits the older ones' coverage, never the newest's (the
2569    /// channel surfaces newest pins as they are monetized).
2570    #[allow(clippy::too_many_lines)]
2571    fn start_first_audit_drainer(&mut self) {
2572        let Some(mut rx) = self.monetized_pin_rx.take() else {
2573            return;
2574        };
2575        let gossip_audit = GossipAuditTrigger {
2576            p2p_node: Arc::clone(&self.p2p_node),
2577            config: Arc::clone(&self.config),
2578            recent_provers: Arc::clone(&self.recent_provers),
2579            sync_state: Arc::clone(&self.sync_state),
2580            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2581            detached_task_tracker: self.detached_task_tracker.clone(),
2582            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2583        };
2584        let shutdown = self.shutdown.clone();
2585        let observability = Arc::clone(&self.first_audit_observability);
2586        let self_peer = *self.p2p_node.peer_id();
2587
2588        let handle = tokio::spawn(async move {
2589            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2590            // scheduler. Payments only NOMINATE pins; the token bucket launches
2591            // them at a fixed per-node rate, and durable suppression is stamped
2592            // only at PROMOTION (after an authoritative post-jitter answerability
2593            // + cooldown check), so a cancelled reservation leaves nothing behind.
2594            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2595            // Periodic retry tick so budget/cooldown-deferred pins get retried
2596            // even when no new nomination arrives. `Skip` collapses a backlog.
2597            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2598            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2599            let mut last_summary = Instant::now();
2600            loop {
2601                // The reservation's jitter deadline is a wake source: if a
2602                // reservation is outstanding, sleep until it is due; otherwise
2603                // a far-future deadline effectively disables that arm and only
2604                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2605                // newly reserved (earlier) deadline is honoured next turn.
2606                let promotion_due = scheduler
2607                    .reserved_ready_at()
2608                    .unwrap_or_else(first_audit_far_future);
2609                tokio::select! {
2610                    () = shutdown.cancelled() => break,
2611                    event = rx.recv() => match event {
2612                        Some(e) => {
2613                            observability.received.fetch_add(1, Ordering::Relaxed);
2614                            // Pre-overflow reservation opportunity: before an
2615                            // arrival may displace a DIFFERENT peer, let the
2616                            // queue launch — a successful reservation frees the
2617                            // slot without eviction. One reservation can be
2618                            // outstanding at a time, so this consumes at most
2619                            // one slot per jitter window; arrivals beyond it
2620                            // fall through to random displacement (ADR-0004
2621                            // Amendment 4).
2622                            if scheduler.would_displace(&e) {
2623                                open_first_audit_reservation(
2624                                    &mut scheduler,
2625                                    &gossip_audit.cooldown,
2626                                    &observability,
2627                                )
2628                                .await;
2629                            }
2630                            scheduler.enqueue(e, &observability);
2631                            // Drain a bounded burst so a flood cannot starve the
2632                            // launch phase.
2633                            let mut drained = 1usize;
2634                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2635                                match rx.try_recv() {
2636                                    Ok(e) => {
2637                                        observability.received.fetch_add(1, Ordering::Relaxed);
2638                                        if scheduler.would_displace(&e) {
2639                                            open_first_audit_reservation(
2640                                                &mut scheduler,
2641                                                &gossip_audit.cooldown,
2642                                                &observability,
2643                                            )
2644                                            .await;
2645                                        }
2646                                        scheduler.enqueue(e, &observability);
2647                                        drained += 1;
2648                                    }
2649                                    Err(_) => break,
2650                                }
2651                            }
2652                        }
2653                        None => break,
2654                    },
2655                    _ = tick.tick() => {}
2656                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2657                }
2658
2659                // 1) Promote a due reservation. Resolved after EVERY wake (not
2660                //    only when the timer arm wins) so a continuously-ready `rx`
2661                //    cannot indefinitely delay a due promotion. The authoritative
2662                //    answerability + cooldown check-and-stamp happens here under
2663                //    the shared cooldown write lock, immediately before the send.
2664                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2665                    let promoted = {
2666                        let mut cooldown = gossip_audit.cooldown.write().await;
2667                        scheduler.resolve(
2668                            reservation,
2669                            SystemTime::now(),
2670                            Instant::now(),
2671                            &mut cooldown,
2672                            &observability,
2673                        )
2674                    };
2675                    if let Some((event, inflight_slot)) = promoted {
2676                        debug!(
2677                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2678                            event.peer, hex::encode(event.pin), event.key_count,
2679                            observability.inflight.load(Ordering::Relaxed)
2680                        );
2681                        let trigger = gossip_audit.clone();
2682                        let audit_observability = Arc::clone(&observability);
2683                        // Track the launch so `shutdown()`'s detached drain
2684                        // covers it. This task outlives the drainer loop that
2685                        // spawned it — the loop breaks on the shutdown token
2686                        // while the audit is still awaiting its response — so a
2687                        // bare spawn would let an in-flight subtree audit keep
2688                        // running, and keep its `Arc<P2PNode>`, past the point
2689                        // `shutdown()` claims every engine task has stopped.
2690                        let tracker = trigger.detached_task_tracker.clone();
2691                        tracker.spawn(async move {
2692                            // The jitter already elapsed as the reservation's
2693                            // timer; the slot is held for the audit's duration
2694                            // and released on drop (panic-safe).
2695                            let inflight_slot = inflight_slot;
2696                            let started = Instant::now();
2697                            let credit = storage_commitment_audit::AuditCredit {
2698                                recent_provers: &trigger.recent_provers,
2699                            };
2700                            let result = storage_commitment_audit::run_subtree_audit(
2701                                &trigger.p2p_node,
2702                                &trigger.config,
2703                                &event.peer,
2704                                event.pin,
2705                                event.key_count,
2706                                Some(&credit),
2707                            )
2708                            .await;
2709                            let outcome = first_audit_terminal_outcome(&result);
2710                            match outcome {
2711                                FirstAuditTerminalOutcome::Passed => {
2712                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2713                                }
2714                                FirstAuditTerminalOutcome::Timeout => {
2715                                    audit_observability
2716                                        .timed_out
2717                                        .fetch_add(1, Ordering::Relaxed);
2718                                }
2719                                FirstAuditTerminalOutcome::Failed => {
2720                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2721                                }
2722                                FirstAuditTerminalOutcome::BootstrapClaim => {
2723                                    audit_observability
2724                                        .bootstrap_claims
2725                                        .fetch_add(1, Ordering::Relaxed);
2726                                }
2727                                FirstAuditTerminalOutcome::Idle => {
2728                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2729                                }
2730                                FirstAuditTerminalOutcome::InsufficientKeys => {
2731                                    audit_observability
2732                                        .insufficient_keys
2733                                        .fetch_add(1, Ordering::Relaxed);
2734                                }
2735                            }
2736                            drop(inflight_slot);
2737                            debug!(
2738                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2739                                outcome.as_str(),
2740                                event.peer, hex::encode(event.pin), event.key_count,
2741                                started.elapsed().as_millis(),
2742                                audit_observability.inflight.load(Ordering::Relaxed)
2743                            );
2744                            handle_subtree_audit_result(
2745                                &result,
2746                                &trigger.p2p_node,
2747                                &trigger.sync_state,
2748                                &trigger.recent_provers,
2749                                &trigger.config,
2750                            )
2751                            .await;
2752                        });
2753                    }
2754                }
2755
2756                // 2) Open the single reservation from the pending queue if none
2757                //    is outstanding (read-only cooldown snapshot; the
2758                //    authoritative stamp is at promotion). Serializing
2759                //    reservations preserves per-launch lane alternation and keeps
2760                //    at most one jitter timer live.
2761                open_first_audit_reservation(
2762                    &mut scheduler,
2763                    &gossip_audit.cooldown,
2764                    &observability,
2765                )
2766                .await;
2767
2768                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2769                    // Token-independent hygiene: collect entries that aged past
2770                    // the answerability horizon while the budget gate kept the
2771                    // reserve scan from running, so the summary below reports
2772                    // only live work.
2773                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2774                    if swept > 0 {
2775                        debug!(
2776                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2777                            scheduler.pending_len()
2778                        );
2779                    }
2780                    info!(
2781                        "First-audit scheduler summary: audit_trigger=first_monetized ingress_dropped={} received={} queued={} coalesced={} suppressed_lower={} duplicates={} capacity_evicted={} self_target_skipped={} cooldown_deferred_attempts={} rate_deferred_attempts={} window_deduped={} launched={} passed={} timeout={} failed={} bootstrap_claims={} idle={} insufficient_keys={} outside_answerability_window={} pending={} pending_cap={} reserved={} oldest_pending_quote_age_ms={} inflight={} tokens={}",
2782                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2783                        observability.received.load(Ordering::Relaxed),
2784                        observability.queued.load(Ordering::Relaxed),
2785                        observability.coalesced.load(Ordering::Relaxed),
2786                        observability.suppressed_lower.load(Ordering::Relaxed),
2787                        observability.duplicates.load(Ordering::Relaxed),
2788                        observability.capacity_evicted.load(Ordering::Relaxed),
2789                        observability.self_target_skipped.load(Ordering::Relaxed),
2790                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2791                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2792                        observability.window_deduped.load(Ordering::Relaxed),
2793                        observability.launched.load(Ordering::Relaxed),
2794                        observability.passed.load(Ordering::Relaxed),
2795                        observability.timed_out.load(Ordering::Relaxed),
2796                        observability.failed.load(Ordering::Relaxed),
2797                        observability.bootstrap_claims.load(Ordering::Relaxed),
2798                        observability.idle.load(Ordering::Relaxed),
2799                        observability.insufficient_keys.load(Ordering::Relaxed),
2800                        observability.outside_answerability_window.load(Ordering::Relaxed),
2801                        scheduler.pending_len(),
2802                        FIRST_AUDIT_PENDING_CAP,
2803                        u8::from(scheduler.has_reservation()),
2804                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2805                        observability.inflight.load(Ordering::Relaxed),
2806                        scheduler.tokens(),
2807                    );
2808                    last_summary = Instant::now();
2809                }
2810            }
2811            debug!("First-audit drainer shut down");
2812        });
2813        self.task_handles.push(handle);
2814    }
2815
2816    #[allow(clippy::too_many_lines)]
2817    fn start_message_handler(&mut self) {
2818        let mut p2p_events = self.p2p_node.subscribe_events();
2819        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
2820        let p2p = Arc::clone(&self.p2p_node);
2821        let storage = Arc::clone(&self.storage);
2822        let paid_list = Arc::clone(&self.paid_list);
2823        let payment_verifier = Arc::clone(&self.payment_verifier);
2824        let queues = Arc::clone(&self.queues);
2825        let config = Arc::clone(&self.config);
2826        let shutdown = self.shutdown.clone();
2827        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
2828        let bootstrap_state = Arc::clone(&self.bootstrap_state);
2829        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
2830        let sync_history = Arc::clone(&self.sync_history);
2831        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
2832        let repair_proofs = Arc::clone(&self.repair_proofs);
2833        let sync_trigger = Arc::clone(&self.sync_trigger);
2834        let my_commitment_state = Arc::clone(&self.commitment_state);
2835        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
2836        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
2837        let recent_provers = Arc::clone(&self.recent_provers);
2838        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
2839        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
2840        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
2841        let sync_state = Arc::clone(&self.sync_state);
2842        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
2843        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
2844        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
2845        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
2846        let fetch_responder_admission_semaphore =
2847            Arc::clone(&self.fetch_responder_admission_semaphore);
2848        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
2849        let verification_responder_worker_semaphore =
2850            Arc::clone(&self.verification_responder_worker_semaphore);
2851        let verification_responder_admission_semaphore =
2852            Arc::clone(&self.verification_responder_admission_semaphore);
2853        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
2854        let neighbor_sync_responder_worker_semaphore =
2855            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
2856        let neighbor_sync_responder_admission_semaphore =
2857            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
2858        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
2859        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
2860        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
2861        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
2862        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
2863        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
2864        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
2865        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
2866        let detached_task_tracker = self.detached_task_tracker.clone();
2867        let subtree_round1 = self.subtree_round1.clone();
2868
2869        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
2870        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
2871        let gossip_audit = GossipAuditTrigger {
2872            p2p_node: Arc::clone(&p2p),
2873            config: Arc::clone(&config),
2874            recent_provers: Arc::clone(&recent_provers),
2875            sync_state: Arc::clone(&sync_state),
2876            cooldown: Arc::clone(&audit_on_gossip_cooldown),
2877            detached_task_tracker: detached_task_tracker.clone(),
2878            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
2879        };
2880
2881        let handler_context = ReplicationMessageHandlerContext {
2882            p2p_node: Arc::clone(&p2p),
2883            storage,
2884            paid_list,
2885            payment_verifier,
2886            queues,
2887            config: Arc::clone(&config),
2888            is_bootstrapping,
2889            bootstrap_state,
2890            sync_history,
2891            sync_cycle_epoch,
2892            repair_proofs: Arc::clone(&repair_proofs),
2893            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
2894            ever_capable_peers,
2895            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
2896            my_commitment_state,
2897            gossip_audit,
2898            audit_responder_semaphore,
2899            audit_responder_inflight,
2900            audit_responder_metrics,
2901            subtree_round1,
2902            fetch_responder_worker_semaphore,
2903            fetch_responder_admission_semaphore,
2904            fetch_responder_inflight,
2905            verification_responder_worker_semaphore,
2906            verification_responder_admission_semaphore,
2907            verification_responder_inflight,
2908            neighbor_sync_responder_worker_semaphore,
2909            neighbor_sync_responder_admission_semaphore,
2910            neighbor_sync_responder_inflight,
2911            fresh_offer_worker_semaphore,
2912            fresh_offer_admission_semaphore,
2913            fresh_offer_responder_inflight,
2914            fresh_offer_in_flight,
2915            paid_notify_worker_semaphore,
2916            paid_notify_admission_semaphore,
2917            paid_notify_responder_inflight,
2918            pointers: self.pointers.clone(),
2919            shutdown: shutdown.clone(),
2920            detached_task_tracker,
2921        };
2922
2923        let (replication_tx, mut replication_rx) =
2924            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
2925        let serial_context = handler_context.clone();
2926        let serial_shutdown = shutdown.clone();
2927        let serial_handle = tokio::spawn(async move {
2928            loop {
2929                tokio::select! {
2930                    () = serial_shutdown.cancelled() => break,
2931                    inbound = replication_rx.recv() => {
2932                        let Some(inbound) = inbound else { break };
2933                        let source = inbound.source;
2934                        match handle_replication_message(
2935                            &source,
2936                            inbound.msg,
2937                            &serial_context,
2938                            inbound.received_at,
2939                            inbound.rr_message_id.as_deref(),
2940                        )
2941                        .await
2942                        {
2943                            Ok(()) => {}
2944                            Err(e) => {
2945                                debug!("Replication message from {source} error: {e}");
2946                            }
2947                        }
2948                    }
2949                }
2950            }
2951            debug!("Replication non-audit serial handler shut down");
2952        });
2953        self.task_handles.push(serial_handle);
2954
2955        let handle = tokio::spawn(async move {
2956            loop {
2957                tokio::select! {
2958                    () = shutdown.cancelled() => break,
2959                    event = p2p_events.recv() => {
2960                        let event = match event {
2961                            Ok(event) => event,
2962                            Err(error) => match handle_replication_event_recv_error(&error) {
2963                                ControlFlow::Continue(()) => continue,
2964                                ControlFlow::Break(()) => break,
2965                            },
2966                        };
2967                        let Some((source, payload, inbound_protocol, rr_message_id)) =
2968                            replication_payload_from_event(event)
2969                        else {
2970                            continue;
2971                        };
2972                        let received_at = Instant::now();
2973                        let msg = match ReplicationMessage::decode(&payload) {
2974                            Ok(msg) => msg,
2975                            Err(e) => {
2976                                debug!("Replication message from {source} decode error: {e}");
2977                                continue;
2978                            }
2979                        };
2980                        if !body_matches_protocol(&msg.body, inbound_protocol) {
2981                            debug!(
2982                                "Dropping replication body (variant {}) on protocol \
2983                                 {inbound_protocol}: wrong id for its family \
2984                                 (cross-version or misrouted)",
2985                                msg.body.variant_index()
2986                            );
2987                            continue;
2988                        }
2989                        if let Some(class) = audit_responder_class(&msg.body) {
2990                            handler_context
2991                                .audit_responder_metrics
2992                                .record_received(source, class);
2993                        }
2994                        let inbound = InboundReplicationMessage {
2995                            source,
2996                            msg,
2997                            rr_message_id,
2998                            received_at,
2999                        };
3000                        if matches!(
3001                            inbound.msg.body,
3002                            ReplicationMessageBody::AuditChallenge(_)
3003                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
3004                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
3005                        ) {
3006                            let source = inbound.source;
3007                            match handle_replication_message(
3008                                &source,
3009                                inbound.msg,
3010                                &handler_context,
3011                                inbound.received_at,
3012                                inbound.rr_message_id.as_deref(),
3013                            )
3014                            .await
3015                            {
3016                                Ok(()) => {}
3017                                Err(e) => {
3018                                    debug!("Replication message from {source} error: {e}");
3019                                }
3020                            }
3021                            continue;
3022                        }
3023                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
3024                            if dropped.audit_responder_class.is_some() {
3025                                handler_context
3026                                    .audit_responder_metrics
3027                                    .record_serial_queue_drop(dropped.source);
3028                            }
3029                            // Every serial-lane class has protocol recovery: syncs rerun,
3030                            // fetches retry, verification re-asks, and a dropped fresh
3031                            // offer is refilled by neighbor sync (the possession check
3032                            // penalises the absence but never re-offers). Responses are
3033                            // covered by their requester's deadline/retry path. Never run
3034                            // a bulk handler here: event receipt must remain non-blocking.
3035                            warn!(
3036                                message_class = dropped.message_class,
3037                                source = %dropped.source,
3038                                queue_depth = dropped.queue_depth,
3039                                reason = dropped.reason.as_str(),
3040                                "Replication serial-queue message dropped"
3041                            );
3042                        }
3043                    }
3044                    // Gap 4: Topology churn handling (Section 13).
3045                    //
3046                    // The DHT routing table emits KClosestPeersChanged when the
3047                    // K-closest peer set actually changes, which is the precise
3048                    // signal for triggering neighbor sync. This replaces the
3049                    // previous approach of checking every PeerConnected /
3050                    // PeerDisconnected event against the close group.
3051                    dht_event = dht_events.recv() => {
3052                        let dht_event = match dht_event {
3053                            Ok(event) => event,
3054                            Err(RecvError::Lagged(missed)) => {
3055                                // Under heavy churn the broadcast buffer can overflow
3056                                // and drop routing-table events — the moment
3057                                // convergence matters most. A dropped
3058                                // KClosestPeersChanged means its entrants were never
3059                                // queued and its departures were never pruned, so
3060                                // draining priority_order cannot recover either.
3061                                // Resync from ground truth instead: snapshot the
3062                                // current close-peer set, prune pending peers that
3063                                // left it during the lost window (retain_sync_peers,
3064                                // as the normal topology-change path does), and queue
3065                                // every member. Dedup (queue_priority_peers) and
3066                                // per-peer cooldown (select_next_sync_peer) drop peers
3067                                // already queued or recently synced, so only genuine
3068                                // entrants surface.
3069                                warn!(
3070                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3071                                );
3072                                let self_id = *p2p.peer_id();
3073                                let neighbors = neighbor_sync::snapshot_close_neighbors(
3074                                    &p2p,
3075                                    &self_id,
3076                                    config.neighbor_sync_scope,
3077                                )
3078                                .await;
3079                                let neighbor_set =
3080                                    neighbors.iter().copied().collect::<HashSet<_>>();
3081                                let (requeued, sync_removals) = {
3082                                    let mut state = sync_state.write().await;
3083                                    let sync_removals =
3084                                        state.retain_sync_peers(&neighbor_set);
3085                                    let requeued = state.queue_priority_peers(neighbors);
3086                                    (requeued, sync_removals)
3087                                };
3088                                if sync_removals > 0 {
3089                                    debug!(
3090                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3091                                    );
3092                                }
3093                                if requeued > 0 {
3094                                    debug!(
3095                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3096                                    );
3097                                    sync_trigger.notify_one();
3098                                }
3099                                continue;
3100                            }
3101                            Err(RecvError::Closed) => {
3102                                // A closed broadcast channel never yields again;
3103                                // continuing would spin the select! loop forever.
3104                                warn!(
3105                                    "DHT event stream closed on replication branch; stopping message handler"
3106                                );
3107                                break;
3108                            }
3109                        };
3110                        match dht_event {
3111                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3112                                let old_peers = old
3113                                    .iter()
3114                                    .take(config.neighbor_sync_scope)
3115                                    .copied()
3116                                    .collect::<HashSet<_>>();
3117                                let new_scoped = new
3118                                    .iter()
3119                                    .take(config.neighbor_sync_scope)
3120                                    .copied()
3121                                    .collect::<Vec<_>>();
3122                                let new_peers =
3123                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3124                                let entrants = new_scoped
3125                                    .iter()
3126                                    .copied()
3127                                    .filter(|peer| !old_peers.contains(peer))
3128                                    .collect::<Vec<_>>();
3129                                let entrant_count = entrants.len();
3130                                let (priority_insertions, sync_removals) = {
3131                                    let mut state = sync_state.write().await;
3132                                    let sync_removals = state.retain_sync_peers(&new_peers);
3133                                    let priority_insertions = state.queue_priority_peers(entrants);
3134                                    (priority_insertions, sync_removals)
3135                                };
3136                                if priority_insertions > 0 {
3137                                    debug!(
3138                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3139                                    );
3140                                } else {
3141                                    debug!(
3142                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3143                                    );
3144                                }
3145                                sync_trigger.notify_one();
3146                            }
3147                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3148                                sync_state.write().await.remove_peer(&peer_id);
3149                                repair_proofs.write().await.remove_peer(&peer_id);
3150                                if let Some(pointers) = &handler_context.pointers {
3151                                    pointers.forget_peer(&peer_id);
3152                                }
3153                                update_bootstrap_after_peer_removed(
3154                                    &peer_id,
3155                                    &handler_context.bootstrap_state,
3156                                    &handler_context.queues,
3157                                    &handler_context.is_bootstrapping,
3158                                    &bootstrap_complete_notify,
3159                                )
3160                                .await;
3161                                // v12: drop the commitment bytes and the
3162                                // recent-prover credit so a churn / sybil
3163                                // attacker cannot leave behind one
3164                                // StorageCommitment per identity in
3165                                // `last_commitment_by_peer`. Also drop the
3166                                // sig-verify rate-limit timestamp.
3167                                last_commitment_by_peer.write().await.remove(&peer_id);
3168                                recent_provers.write().await.forget_peer(&peer_id);
3169                                sig_verify_attempts.write().await.remove(&peer_id);
3170                                // Same for the gossip-audit cooldown (ADR-0002)
3171                                // and the lottery-attempt window.
3172                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3173                                gossip_lottery_attempts.write().await.remove(&peer_id);
3174                                // The sticky `commitment_capable` flag is
3175                                // preserved orthogonally via
3176                                // `ever_capable_peers` — even after this
3177                                // removal, a re-joining peer continues to
3178                                // be treated as v12-capable rather than
3179                                // legacy (§3 shield).
3180                            }
3181                            _ => {}
3182                        }
3183                    }
3184                }
3185            }
3186            debug!("Replication message handler shut down");
3187        });
3188        self.task_handles.push(handle);
3189    }
3190
3191    fn start_neighbor_sync_loop(&mut self) {
3192        let pointers = self.pointers.clone();
3193        let p2p = Arc::clone(&self.p2p_node);
3194        let storage = Arc::clone(&self.storage);
3195        let paid_list = Arc::clone(&self.paid_list);
3196        let queues = Arc::clone(&self.queues);
3197        let config = Arc::clone(&self.config);
3198        let shutdown = self.shutdown.clone();
3199        let sync_state = Arc::clone(&self.sync_state);
3200        let sync_history = Arc::clone(&self.sync_history);
3201        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3202        let repair_proofs = Arc::clone(&self.repair_proofs);
3203        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3204        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3205        let sync_trigger = Arc::clone(&self.sync_trigger);
3206        let commitment_state = Arc::clone(&self.commitment_state);
3207        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3208        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3209        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3210        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3211        let detached_task_tracker = self.detached_task_tracker.clone();
3212        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3213        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3214        // here too so a peer that only ever answers — never initiates sync —
3215        // is still audited; otherwise it could fully evade auditing.
3216        let gossip_audit = GossipAuditTrigger {
3217            p2p_node: Arc::clone(&p2p),
3218            config: Arc::clone(&config),
3219            recent_provers: Arc::clone(&self.recent_provers),
3220            sync_state: Arc::clone(&sync_state),
3221            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3222            detached_task_tracker,
3223            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3224        };
3225
3226        let handle = tokio::spawn(async move {
3227            loop {
3228                // Park for the periodic tick or an explicit trigger ONLY when no
3229                // priority (topology-change) peers are queued. `sync_trigger` is a
3230                // coalescing `Notify`, so a churn burst that queues many entrants
3231                // produces a single wakeup; parking after draining one batch would
3232                // leave the rest waiting up to a full periodic tick. `priority_order`
3233                // is the durable record of pending work, so drain it back-to-back —
3234                // each round removes the peers it selects (`select_next_sync_peer`),
3235                // so the drain terminates once the queue empties.
3236                if !sync_state.read().await.has_priority_peers() {
3237                    let interval = config.random_neighbor_sync_interval();
3238                    tokio::select! {
3239                        () = shutdown.cancelled() => break,
3240                        () = tokio::time::sleep(interval) => {}
3241                        () = sync_trigger.notified() => {
3242                            debug!("Neighbor sync triggered by topology change");
3243                        }
3244                    }
3245                }
3246                // Wrap the sync round in a select so shutdown cancels
3247                // in-progress network operations rather than waiting for
3248                // the full round to complete.
3249                tokio::select! {
3250                    () = shutdown.cancelled() => break,
3251                    () = run_neighbor_sync_round(
3252                        &p2p,
3253                        &storage,
3254                        &paid_list,
3255                        &queues,
3256                        &config,
3257                        &sync_state,
3258                        &sync_history,
3259                        &sync_cycle_epoch,
3260                        &repair_proofs,
3261                        &is_bootstrapping,
3262                        &bootstrap_state,
3263                        &commitment_state,
3264                        &last_commitment_by_peer,
3265                        &ever_capable_peers,
3266                        &sig_verify_attempts,
3267                        &audit_challenge_coordinator,
3268                        &gossip_audit,
3269                        pointers.as_ref(),
3270                    ) => {}
3271                }
3272            }
3273            debug!("Neighbor sync loop shut down");
3274        });
3275        self.task_handles.push(handle);
3276    }
3277
3278    fn start_self_lookup_loop(&mut self) {
3279        let p2p = Arc::clone(&self.p2p_node);
3280        let config = Arc::clone(&self.config);
3281        let shutdown = self.shutdown.clone();
3282
3283        let handle = tokio::spawn(async move {
3284            loop {
3285                let interval = config.random_self_lookup_interval();
3286                tokio::select! {
3287                    () = shutdown.cancelled() => break,
3288                    () = tokio::time::sleep(interval) => {
3289                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3290                            debug!("Self-lookup failed: {e}");
3291                        }
3292                    }
3293                }
3294            }
3295            debug!("Self-lookup loop shut down");
3296        });
3297        self.task_handles.push(handle);
3298    }
3299
3300    /// Periodic responsible-chunk audit loop (audit #2): every
3301    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3302    /// eligible close peer for the chunks it *should* be storing (by
3303    /// responsibility and prior repair hint), independent of the gossip-triggered
3304    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3305    /// immediately and periodically thereafter.
3306    fn start_audit_loop(&mut self) {
3307        let p2p = Arc::clone(&self.p2p_node);
3308        let storage = Arc::clone(&self.storage);
3309        let config = Arc::clone(&self.config);
3310        let shutdown = self.shutdown.clone();
3311        let sync_history = Arc::clone(&self.sync_history);
3312        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3313        let repair_proofs = Arc::clone(&self.repair_proofs);
3314        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3315        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3316        let sync_state = Arc::clone(&self.sync_state);
3317        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3318
3319        let handle = tokio::spawn(async move {
3320            // Invariant 19: wait for bootstrap to drain before starting audits.
3321            loop {
3322                tokio::select! {
3323                    () = shutdown.cancelled() => return,
3324                    () = tokio::time::sleep(
3325                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3326                    ) => {
3327                        if bootstrap_state.read().await.is_drained() {
3328                            break;
3329                        }
3330                    }
3331                }
3332            }
3333
3334            // Run one audit tick immediately after bootstrap drain.
3335            {
3336                let bootstrapping = *is_bootstrapping.read().await;
3337                let result = {
3338                    let history = sync_history.read().await;
3339                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3340                    audit::audit_tick_with_repair_proofs(
3341                        &p2p,
3342                        &storage,
3343                        &config,
3344                        &history,
3345                        &repair_proofs,
3346                        &audit_challenge_coordinator,
3347                        current_sync_epoch,
3348                        bootstrapping,
3349                    )
3350                    .await
3351                };
3352                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3353            }
3354
3355            // Then run periodically.
3356            loop {
3357                let interval = config.random_audit_tick_interval();
3358                tokio::select! {
3359                    () = shutdown.cancelled() => break,
3360                    () = tokio::time::sleep(interval) => {
3361                        let bootstrapping = *is_bootstrapping.read().await;
3362                        let result = {
3363                            let history = sync_history.read().await;
3364                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3365                            audit::audit_tick_with_repair_proofs(
3366                                &p2p,
3367                                &storage,
3368                                &config,
3369                                &history,
3370                                &repair_proofs,
3371                                &audit_challenge_coordinator,
3372                                current_sync_epoch,
3373                                bootstrapping,
3374                            )
3375                            .await
3376                        };
3377                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3378                    }
3379                }
3380            }
3381            debug!("Audit loop shut down");
3382        });
3383        self.task_handles.push(handle);
3384    }
3385
3386    /// Periodically rebuild + sign + rotate the responder's storage
3387    /// commitment.
3388    ///
3389    /// Phase 3 of the v12 storage-bound audit. Once per
3390    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3391    /// current LMDB key set, builds a Merkle tree (for content-addressed
3392    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3393    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3394    /// into `commitment_state`. Old `previous` slot is dropped by the
3395    /// rotate (per `ResponderCommitmentState::rotate`).
3396    ///
3397    /// Skips if the key set is empty (no commitment to make) — the
3398    /// auditor side falls back to the legacy plain-digest path for
3399    /// peers that have never gossiped a commitment.
3400    fn start_commitment_rotation_loop(&mut self) {
3401        let storage = Arc::clone(&self.storage);
3402        let identity = Arc::clone(&self.identity);
3403        let commitment_state = Arc::clone(&self.commitment_state);
3404        let shutdown = self.shutdown.clone();
3405        let p2p = Arc::clone(&self.p2p_node);
3406        let config = Arc::clone(&self.config);
3407        let sync_trigger = Arc::clone(&self.sync_trigger);
3408        let recent_provers = Arc::clone(&self.recent_provers);
3409        let pointer_store = self.pointers.as_ref().map(|p| p.store().clone());
3410
3411        let handle = tokio::spawn(async move {
3412            // Build the first commitment immediately on startup so a
3413            // restarted node can answer commitment-bound audits right
3414            // away — otherwise current() stays None for a full rotation
3415            // interval and audits silently fall back to legacy.
3416            //
3417            // After the first build, trigger an immediate neighbor-sync
3418            // round so the new commitment gossips out within seconds.
3419            // Without this, after a restart remote auditors keep pinning
3420            // the pre-restart (rotated-away) hash until their normal
3421            // sync cadence elapses — up to 1 h in the worst case,
3422            // during which time commitment-bound audits hit "unknown
3423            // commitment hash" -> Idle no-ops.
3424            // ML-DSA signatures are randomized so we cannot reproduce
3425            // the pre-restart hash; the only honest path to recovery
3426            // is fast re-gossip.
3427            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3428            // spawned), so this initial rebuild no-ops when the key set is
3429            // unchanged — preserving the reloaded current pin; otherwise the
3430            // reloaded roots stay answerable as retained slots until their gossip
3431            // TTL lapses. Persistence is handled by the retention-persist loop.
3432            if let Err(e) = rebuild_and_rotate_commitment(
3433                &storage,
3434                pointer_store.as_ref(),
3435                &identity,
3436                &commitment_state,
3437                &p2p,
3438                &config,
3439            )
3440            .await
3441            {
3442                warn!("Initial commitment build failed: {e}");
3443            } else {
3444                sync_trigger.notify_one();
3445            }
3446            loop {
3447                tokio::select! {
3448                    () = shutdown.cancelled() => break,
3449                    () = tokio::time::sleep(
3450                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3451                    ) => {
3452                        if let Err(e) = rebuild_and_rotate_commitment(
3453                            &storage,
3454                            pointer_store.as_ref(),
3455                            &identity,
3456                            &commitment_state,
3457                            &p2p,
3458                            &config,
3459                        ).await {
3460                            warn!("Commitment rotation failed: {e}");
3461                        }
3462                        // Piggyback a sweep of expired recent_provers
3463                        // entries on the rotation tick (same cadence,
3464                        // 1 h). is_credited_holder already honours the
3465                        // TTL on read, but the sweep reclaims memory
3466                        // for entries we'll never re-read.
3467                        let dropped = recent_provers.write().await.sweep_expired(
3468                            std::time::Instant::now()
3469                        );
3470                        if dropped > 0 {
3471                            debug!("recent_provers: swept {dropped} expired entries");
3472                        }
3473                    }
3474                }
3475            }
3476            debug!("Commitment rotation loop shut down");
3477        });
3478        self.task_handles.push(handle);
3479    }
3480
3481    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3482    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3483    /// rotations — survives a restart. Flushes once immediately, then every
3484    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3485    fn start_retention_persist_loop(&mut self) {
3486        let commitment_state = Arc::clone(&self.commitment_state);
3487        let retention_path = self.retention_path.clone();
3488        let shutdown = self.shutdown.clone();
3489        let handle = tokio::spawn(async move {
3490            let mut last: Option<Vec<u8>> = None;
3491            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3492            loop {
3493                tokio::select! {
3494                    () = shutdown.cancelled() => {
3495                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3496                            .await;
3497                        break;
3498                    }
3499                    () = tokio::time::sleep(std::time::Duration::from_secs(
3500                        RETENTION_PERSIST_INTERVAL_SECS,
3501                    )) => {
3502                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3503                            .await;
3504                    }
3505                }
3506            }
3507            debug!("Commitment retention persist loop shut down");
3508        });
3509        self.task_handles.push(handle);
3510    }
3511
3512    /// Periodically emit the cumulative replication traffic summaries: the
3513    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3514    /// (V2-684). Both read process-global counter tables maintained by the
3515    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3516    /// state.
3517    fn start_traffic_summary_loop(&mut self) {
3518        let shutdown = self.shutdown.clone();
3519        let handle = tokio::spawn(async move {
3520            loop {
3521                tokio::select! {
3522                    () = shutdown.cancelled() => break,
3523                    () = tokio::time::sleep(std::time::Duration::from_secs(
3524                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3525                    )) => {
3526                        protocol::log_traffic_summary();
3527                        protocol::log_served_peers_summary();
3528                        protocol::log_audit_outcome_summary();
3529                        audit_metrics::log_responder_admission_summary();
3530                        // V2-834 Part D: chunk RPC, upgrade and EVM RPC attribution
3531                        // ride the same cadence.
3532                        crate::storage::traffic::log_chunk_rpc_traffic_summary();
3533                        crate::upgrade::traffic::log_upgrade_traffic_summary();
3534                        crate::payment::traffic::log_evm_rpc_summary();
3535                    }
3536                }
3537            }
3538            debug!("Replication traffic summary loop shut down");
3539        });
3540        self.task_handles.push(handle);
3541    }
3542
3543    /// Periodically expose the state that gates bootstrap completion and prune
3544    /// admission. The state counts are copied before reading `is_bootstrapping`
3545    /// so this diagnostic path never nests async locks.
3546    #[cfg(feature = "logging")]
3547    fn start_bootstrap_state_snapshot_loop(&mut self) {
3548        let shutdown = self.shutdown.clone();
3549        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3550        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3551        let started_at = Instant::now();
3552        let handle = tokio::spawn(async move {
3553            loop {
3554                tokio::select! {
3555                    () = shutdown.cancelled() => break,
3556                    () = tokio::time::sleep(Duration::from_secs(
3557                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3558                    )) => {
3559                        let (
3560                            drained,
3561                            pending_peer_requests,
3562                            pending_keys,
3563                            capacity_rejected_sources,
3564                        ) = {
3565                            let state = bootstrap_state.read().await;
3566                            (
3567                                state.drained,
3568                                state.pending_peer_requests,
3569                                state.pending_keys.len(),
3570                                state.capacity_rejected_sources.len(),
3571                            )
3572                        };
3573                        let bootstrapping = *is_bootstrapping.read().await;
3574                        let snapshot_state = if drained && !bootstrapping {
3575                            "healthy"
3576                        } else if drained {
3577                            "drained_waiting_for_bootstrap_flag"
3578                        } else {
3579                            "pending"
3580                        };
3581                        info!(
3582                            drained,
3583                            pending_peer_requests,
3584                            pending_keys,
3585                            capacity_rejected_sources,
3586                            is_bootstrapping = bootstrapping,
3587                            snapshot_state,
3588                            uptime_secs = started_at.elapsed().as_secs(),
3589                            "Replication bootstrap state snapshot"
3590                        );
3591                        if drained && !bootstrapping {
3592                            info!(
3593                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3594                            );
3595                            break;
3596                        }
3597                    }
3598                }
3599            }
3600            debug!("Bootstrap state snapshot loop shut down");
3601        });
3602        self.task_handles.push(handle);
3603    }
3604
3605    /// Periodically rank remote peers using the shared audit responder pool and
3606    /// report handler-only versus end-to-end latency. Windowed values make a
3607    /// burst visible even after a long-running node has accumulated traffic.
3608    #[cfg(feature = "logging")]
3609    fn start_audit_responder_summary_loop(&mut self) {
3610        let shutdown = self.shutdown.clone();
3611        let metrics = Arc::clone(&self.audit_responder_metrics);
3612        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3613        let handle = tokio::spawn(async move {
3614            let mut window_started = Instant::now();
3615            loop {
3616                tokio::select! {
3617                    () = shutdown.cancelled() => {
3618                        log_audit_responder_summary(
3619                            &metrics,
3620                            &semaphore,
3621                            window_started.elapsed(),
3622                        );
3623                        break;
3624                    }
3625                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3626                        log_audit_responder_summary(
3627                            &metrics,
3628                            &semaphore,
3629                            window_started.elapsed(),
3630                        );
3631                        window_started = Instant::now();
3632                    }
3633                }
3634            }
3635            debug!("Audit responder summary loop shut down");
3636        });
3637        self.task_handles.push(handle);
3638    }
3639
3640    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3641    fn start_fetch_worker(&mut self) {
3642        let p2p = Arc::clone(&self.p2p_node);
3643        let storage = Arc::clone(&self.storage);
3644        let queues = Arc::clone(&self.queues);
3645        let config = Arc::clone(&self.config);
3646        let shutdown = self.shutdown.clone();
3647        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3648        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3649        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3650        let detached_task_tracker = self.detached_task_tracker.clone();
3651        let concurrency = max_parallel_fetch();
3652
3653        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3654
3655        let handle = tokio::spawn(async move {
3656            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3657            // always recover the key — even if the inner task panics.
3658            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3659
3660            loop {
3661                // Fill up to `concurrency` slots from the queue.
3662                {
3663                    let mut q = queues.write().await;
3664                    while in_flight.len() < concurrency {
3665                        let Some(candidate) = q.dequeue_fetch() else {
3666                            break;
3667                        };
3668                        let fetch_key = candidate.key;
3669                        let Some(&source) = candidate.sources.first() else {
3670                            warn!(
3671                                "Fetch candidate {} has no sources; requeueing for verification",
3672                                hex::encode(fetch_key)
3673                            );
3674                            let _ = q.requeue_candidate_for_verification(
3675                                candidate,
3676                                config.verification_request_timeout,
3677                            );
3678                            continue;
3679                        };
3680                        q.start_dequeued_fetch(candidate, source);
3681
3682                        let p2p = Arc::clone(&p2p);
3683                        let storage = Arc::clone(&storage);
3684                        let config = Arc::clone(&config);
3685                        let token = shutdown.clone();
3686                        let tracker = detached_task_tracker.clone();
3687                        in_flight.push(Box::pin(async move {
3688                            // Tracked so shutdown() still awaits the task if
3689                            // this awaiter is dropped (e.g. the worker is
3690                            // aborted): it holds Arc<ChunkStore> and must
3691                            // not outlive the engine.
3692                            let handle = tracker.spawn(async move {
3693                                // Cancel-aware: abort when the engine shuts down.
3694                                tokio::select! {
3695                                    () = token.cancelled() => FetchOutcome {
3696                                        key: fetch_key,
3697                                        result: FetchResult::SourceFailed,
3698                                    },
3699                                    outcome = execute_single_fetch(
3700                                        p2p, storage, config, fetch_key, source,
3701                                    ) => outcome,
3702                                }
3703                            });
3704                            match handle.await {
3705                                Ok(outcome) => (outcome.key, Some(outcome)),
3706                                Err(e) => {
3707                                    error!(
3708                                        "Fetch task for {} panicked: {e}",
3709                                        hex::encode(fetch_key)
3710                                    );
3711                                    (fetch_key, None)
3712                                }
3713                            }
3714                        }));
3715                    }
3716                } // release queues write lock
3717
3718                if in_flight.is_empty() {
3719                    // No work — wait for new items or shutdown.
3720                    tokio::select! {
3721                        () = shutdown.cancelled() => break,
3722                        () = tokio::time::sleep(
3723                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3724                        ) => continue,
3725                    }
3726                }
3727
3728                // Wait for the next fetch to complete and process the result.
3729                tokio::select! {
3730                    () = shutdown.cancelled() => break,
3731                    Some((key, maybe_outcome)) = in_flight.next() => {
3732                        let mut q = queues.write().await;
3733                        let terminal = if let Some(outcome) = maybe_outcome {
3734                            match apply_fetch_result(
3735                                &mut q,
3736                                &key,
3737                                &outcome.result,
3738                                config.verification_request_timeout,
3739                            ) {
3740                                FetchFollowUp::Terminal => true,
3741                                FetchFollowUp::RequeuedForVerification => false,
3742                                FetchFollowUp::RetryFrom(next_peer) => {
3743                                    // Spawn a new fetch task for the next source.
3744                                    let p2p = Arc::clone(&p2p);
3745                                    let storage = Arc::clone(&storage);
3746                                    let config = Arc::clone(&config);
3747                                    let token = shutdown.clone();
3748                                    let tracker = detached_task_tracker.clone();
3749                                    let fetch_key = key;
3750                                    in_flight.push(Box::pin(async move {
3751                                        // Tracked for the same reason as the
3752                                        // initial fetch spawn above.
3753                                        let handle = tracker.spawn(async move {
3754                                            tokio::select! {
3755                                                () = token.cancelled() => FetchOutcome {
3756                                                    key: fetch_key,
3757                                                    result: FetchResult::SourceFailed,
3758                                                },
3759                                                outcome = execute_single_fetch(
3760                                                    p2p, storage, config, fetch_key, next_peer,
3761                                                ) => outcome,
3762                                            }
3763                                        });
3764                                        match handle.await {
3765                                            Ok(outcome) => (outcome.key, Some(outcome)),
3766                                            Err(e) => {
3767                                                error!(
3768                                                    "Fetch task for {} panicked: {e}",
3769                                                    hex::encode(fetch_key)
3770                                                );
3771                                                (fetch_key, None)
3772                                            }
3773                                        }
3774                                    }));
3775                                    false
3776                                }
3777                            }
3778                        } else {
3779                            // Task panicked — retry verification when this was
3780                            // a verified repair, otherwise reclaim the slot.
3781                            !q.requeue_fetch_for_verification(
3782                                &key,
3783                                config.verification_request_timeout,
3784                            )
3785                        };
3786
3787                        // Shrink bootstrap pending set on terminal exit.
3788                        if terminal {
3789                            drop(q); // release queues lock before acquiring bootstrap_state
3790                            if !bootstrap_state.read().await.is_drained() {
3791                                bootstrap_state.write().await.remove_key(&key);
3792                                let q = queues.read().await;
3793                                if bootstrap::check_bootstrap_drained(
3794                                    &bootstrap_state,
3795                                    &q,
3796                                )
3797                                .await
3798                                {
3799                                    complete_bootstrap(
3800                                        &is_bootstrapping,
3801                                        &bootstrap_complete_notify,
3802                                    ).await;
3803                                }
3804                            }
3805                        }
3806                    }
3807                }
3808            }
3809
3810            // Cancel and drain remaining in-flight fetches on shutdown.
3811            // The CancellationToken is already cancelled by this point, so
3812            // spawned tasks will see cancellation via their select! branches.
3813            while in_flight.next().await.is_some() {}
3814            debug!("Fetch worker shut down");
3815        });
3816        self.task_handles.push(handle);
3817    }
3818
3819    fn start_verification_worker(&mut self) {
3820        let p2p = Arc::clone(&self.p2p_node);
3821        let storage = Arc::clone(&self.storage);
3822        let queues = Arc::clone(&self.queues);
3823        let paid_list = Arc::clone(&self.paid_list);
3824        let config = Arc::clone(&self.config);
3825        let shutdown = self.shutdown.clone();
3826        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3827        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3828        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3829        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3830        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3831        let recent_provers = Arc::clone(&self.recent_provers);
3832
3833        let handle = tokio::spawn(async move {
3834            loop {
3835                tokio::select! {
3836                    () = shutdown.cancelled() => break,
3837                    () = tokio::time::sleep(
3838                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
3839                    ) => {
3840                        let ctx = VerificationCycleContext {
3841                            p2p_node: &p2p,
3842                            paid_list: &paid_list,
3843                            storage: &storage,
3844                            queues: &queues,
3845                            config: &config,
3846                            bootstrap_state: &bootstrap_state,
3847                            is_bootstrapping: &is_bootstrapping,
3848                            bootstrap_complete_notify: &bootstrap_complete_notify,
3849                            last_commitment_by_peer: &last_commitment_by_peer,
3850                            ever_capable_peers: &ever_capable_peers,
3851                            recent_provers: &recent_provers,
3852                        };
3853                        run_verification_cycle(ctx).await;
3854                    }
3855                }
3856            }
3857            debug!("Verification worker shut down");
3858        });
3859        self.task_handles.push(handle);
3860    }
3861
3862    /// Gap 3: Run a one-shot bootstrap sync on startup.
3863    ///
3864    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
3865    /// (indicating the routing table is populated) before snapshotting
3866    /// close neighbors. Falls back after a timeout so bootstrap nodes
3867    /// (which have no peers and therefore never receive the event) still
3868    /// proceed.
3869    ///
3870    /// After the gate, finds close neighbors, syncs with each in
3871    /// round-robin batches, admits returned hints into the verification
3872    /// pipeline, and tracks discovered keys for bootstrap drain detection.
3873    #[allow(clippy::too_many_lines)]
3874    fn start_bootstrap_sync(
3875        &mut self,
3876        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
3877    ) {
3878        let p2p = Arc::clone(&self.p2p_node);
3879        let storage = Arc::clone(&self.storage);
3880        let paid_list = Arc::clone(&self.paid_list);
3881        let queues = Arc::clone(&self.queues);
3882        let config = Arc::clone(&self.config);
3883        let shutdown = self.shutdown.clone();
3884        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3885        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3886        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3887        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3888        let repair_proofs = Arc::clone(&self.repair_proofs);
3889        let my_commitment_state = Arc::clone(&self.commitment_state);
3890        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3891        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3892        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3893
3894        let handle = tokio::spawn(async move {
3895            // Wait for DHT bootstrap to complete before snapshotting
3896            // neighbors. The routing table is empty until saorsa-core
3897            // finishes its FIND_NODE rounds and bucket refreshes.
3898            let gate = bootstrap::wait_for_bootstrap_complete(
3899                dht_events,
3900                config.bootstrap_complete_timeout_secs,
3901                &shutdown,
3902            )
3903            .await;
3904
3905            if gate == bootstrap::BootstrapGateResult::Shutdown {
3906                return;
3907            }
3908
3909            let self_id = *p2p.peer_id();
3910            let neighbors =
3911                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
3912                    .await;
3913
3914            if neighbors.is_empty() {
3915                info!("Bootstrap sync: no close neighbors found, marking drained");
3916                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
3917                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
3918                return;
3919            }
3920
3921            let neighbor_count = neighbors.len();
3922            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
3923
3924            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
3925            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
3926                if shutdown.is_cancelled() {
3927                    break;
3928                }
3929
3930                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
3931                    batch,
3932                    &storage,
3933                    &paid_list,
3934                    &p2p,
3935                    config.close_group_size,
3936                    config.paid_list_close_group_size,
3937                )
3938                .await;
3939
3940                // Keep the batch outstanding until every response has been
3941                // admitted and bootstrap accounting is updated. The verification
3942                // worker uses this counter as a batch barrier, so it cannot race
3943                // the source aggregation below.
3944                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
3945                let bootstrapping = *is_bootstrapping.read().await;
3946
3947                let sync_futures = batch.iter().map(|peer| {
3948                    let peer = *peer;
3949                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
3950                    // Atomically snapshot + mark-gossiped for each emitted
3951                    // bootstrap request so we remain answerable for it.
3952                    let commitment = my_commitment_state
3953                        .current_for_gossip()
3954                        .map(|binding| binding.commitment().clone());
3955                    let p2p = &p2p;
3956                    let config = &config;
3957                    async move {
3958                        let outcome = neighbor_sync::sync_with_peer_with_hints(
3959                            &peer,
3960                            p2p,
3961                            config,
3962                            bootstrapping,
3963                            hints,
3964                            commitment,
3965                        )
3966                        .await;
3967                        (peer, outcome)
3968                    }
3969                });
3970                let completed = join_all(sync_futures).await;
3971
3972                // Process response metadata before exposing any of this batch's
3973                // hints to verification.
3974                for (peer, outcome) in &completed {
3975                    if let Some(outcome) = outcome {
3976                        // Ingest the peer's piggybacked commitment from the
3977                        // response (same verification as the request path).
3978                        // Bootstrap is the FIRST gossip we receive from most
3979                        // peers, so this populates last_commitment_by_peer.
3980                        //
3981                        // We intentionally do NOT trigger a gossip-audit here:
3982                        // during bootstrap this node may itself still be
3983                        // bootstrapping (audits are gated on that), and the
3984                        // close-group/RT view is not yet stable. The peer is
3985                        // audited on the first STEADY-STATE neighbor-sync round
3986                        // after bootstrap drains (request + response paths both
3987                        // trigger), which is within one sync cycle — so caching
3988                        // the commitment here is sufficient and there is no
3989                        // coverage gap (ADR-0002).
3990                        ingest_peer_commitment(
3991                            peer,
3992                            outcome.response.commitment.as_ref(),
3993                            &p2p,
3994                            &last_commitment_by_peer,
3995                            &ever_capable_peers,
3996                            &sig_verify_attempts,
3997                        )
3998                        .await; // sig_verify_attempts in scope from line ~1080
3999
4000                        if !outcome.response.bootstrapping {
4001                            record_sent_replica_hints(
4002                                peer,
4003                                &outcome.sent_replica_hints,
4004                                &repair_proofs,
4005                                &sync_cycle_epoch,
4006                            )
4007                            .await;
4008                        }
4009                    }
4010                }
4011
4012                let pending_keys: HashSet<XorName> = {
4013                    let q = queues.read().await;
4014                    q.pending_keys().into_iter().collect()
4015                };
4016                let admission_futures = completed.iter().map(async |(_, outcome)| match outcome {
4017                    Some(outcome) if !outcome.response.bootstrapping => Some(
4018                        admission::admit_hints(
4019                            &self_id,
4020                            &outcome.response.replica_hints,
4021                            &outcome.response.paid_hints,
4022                            &p2p,
4023                            &config,
4024                            &storage,
4025                            &paid_list,
4026                            &pending_keys,
4027                        )
4028                        .await,
4029                    ),
4030                    _ => None,
4031                });
4032                let admitted = join_all(admission_futures).await;
4033
4034                // Queue every peer's admitted hints under one write lock. Once
4035                // released, source-count ordering sees the complete batch.
4036                let (batch_outcomes, batch_discovered) = {
4037                    let mut q = queues.write().await;
4038                    let outcomes = completed
4039                        .iter()
4040                        .zip(admitted)
4041                        .filter_map(|((peer, _), admitted)| {
4042                            admitted.map(|admitted| {
4043                                (
4044                                    *peer,
4045                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
4046                                )
4047                            })
4048                        })
4049                        .collect::<Vec<_>>();
4050                    let live_discovered = outcomes
4051                        .iter()
4052                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
4053                        .filter(|key| q.contains_key(key))
4054                        .collect::<HashSet<_>>();
4055                    (outcomes, live_discovered)
4056                };
4057
4058                publish_bootstrap_admission_outcomes(
4059                    &bootstrap_state,
4060                    &batch_outcomes,
4061                    &batch_discovered,
4062                )
4063                .await;
4064
4065                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4066            }
4067
4068            // Check drain condition.
4069            {
4070                let q = queues.read().await;
4071                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4072                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4073                }
4074            }
4075
4076            info!("Bootstrap sync completed");
4077        });
4078        self.task_handles.push(handle);
4079    }
4080}
4081
4082// ===========================================================================
4083// Free functions for background tasks
4084// ===========================================================================
4085
4086#[cfg(feature = "logging")]
4087fn log_audit_responder_summary(
4088    metrics: &AuditResponderMetrics,
4089    semaphore: &Semaphore,
4090    window: Duration,
4091) {
4092    let snapshot = metrics.take_snapshot();
4093    if snapshot.origins.is_empty() {
4094        return;
4095    }
4096
4097    let total = snapshot.total;
4098    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4099        total.received_by_class;
4100    let global_inflight =
4101        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4102    info!(
4103        target: "ant_node::replication::audit_responder",
4104        window_ms = window.as_millis(),
4105        source_count = snapshot.origins.len(),
4106        received = total.received(),
4107        digest_received,
4108        subtree_received,
4109        byte_received,
4110        commitment_pin_received,
4111        admitted = total.admitted,
4112        global_pool_drops = total.global_pool_drops,
4113        per_peer_cap_drops = total.per_peer_cap_drops,
4114        serial_queue_drops = total.serial_queue_drops,
4115        completed = total.completed,
4116        send_failures = total.send_failures,
4117        processing_avg_ms = total.processing_avg_ms(),
4118        processing_max_ms = total.processing_max_ms,
4119        total_avg_ms = total.total_avg_ms(),
4120        total_max_ms = total.total_max_ms,
4121        global_inflight,
4122        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4123        peak_global_inflight = total.peak_global_inflight,
4124        "Audit responder summary"
4125    );
4126
4127    for (index, origin) in snapshot
4128        .origins
4129        .iter()
4130        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4131        .enumerate()
4132    {
4133        let Some(source) = origin.source else {
4134            continue;
4135        };
4136        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4137            origin.received_by_class;
4138        info!(
4139            target: "ant_node::replication::audit_responder",
4140            rank = index + 1,
4141            source = %source,
4142            received = origin.received(),
4143            digest_received,
4144            subtree_received,
4145            byte_received,
4146            commitment_pin_received,
4147            admitted = origin.admitted,
4148            global_pool_drops = origin.global_pool_drops,
4149            per_peer_cap_drops = origin.per_peer_cap_drops,
4150            serial_queue_drops = origin.serial_queue_drops,
4151            completed = origin.completed,
4152            send_failures = origin.send_failures,
4153            processing_avg_ms = origin.processing_avg_ms(),
4154            processing_max_ms = origin.processing_max_ms,
4155            total_avg_ms = origin.total_avg_ms(),
4156            total_max_ms = origin.total_max_ms,
4157            peak_global_inflight = origin.peak_global_inflight,
4158            peak_peer_inflight = origin.peak_peer_inflight,
4159            "Audit responder top origin"
4160        );
4161    }
4162}
4163
4164/// Which ceiling rejected an audit-responder admission attempt.
4165///
4166/// Stable, machine-readable so a production log-scrape can bucket drops by
4167/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4168/// single opaque "capacity reached" line; this splits the two distinct causes
4169/// so the next such investigation can tell a global-pool exhaustion (the whole
4170/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4171/// without re-instrumenting.
4172///
4173/// This branch runs a SINGLE shared audit-responder pool for all challenge
4174/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4175/// pool to distinguish here — the `kind=` log field already separates the
4176/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4177/// dedicated slow pool is later split out, add its variants here.
4178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4179enum ResponderRejectReason {
4180    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4181    /// free; the per-peer cap was not the binding constraint.
4182    GlobalPoolFull,
4183    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4184    /// share, so the global permit was never attempted.
4185    PerPeerCapFull,
4186}
4187
4188impl ResponderRejectReason {
4189    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4190    /// frozen — production log tooling greps for them.
4191    fn as_str(self) -> &'static str {
4192        match self {
4193            Self::GlobalPoolFull => "global_pool_full",
4194            Self::PerPeerCapFull => "per_peer_cap_full",
4195        }
4196    }
4197}
4198
4199impl From<ResponderRejectReason> for AuditResponderDropReason {
4200    fn from(reason: ResponderRejectReason) -> Self {
4201        match reason {
4202            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4203            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4204        }
4205    }
4206}
4207
4208impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4209    fn from(reason: ResponderRejectReason) -> Self {
4210        match reason {
4211            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4212            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4213        }
4214    }
4215}
4216
4217/// Cumulative fresh-offer admission refusals in this process.
4218///
4219/// **Expected value in healthy operation is zero.** A node that refuses a
4220/// legitimate fresh offer does not merely shed load: the sender transmits
4221/// offers one-way and never reads the refusal, so the chunk's absence
4222/// resurfaces at the sender's delayed possession check and is charged to the
4223/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4224/// means the node is either under-provisioned for its offered load or its
4225/// admission share is mis-sized — and is accruing unearned trust damage either
4226/// way. Operators should alarm on any sustained non-zero rate.
4227///
4228/// Process-global rather than per-engine, which is exactly right in production
4229/// (one node per process) and adequate in multi-node test harnesses, where the
4230/// useful assertion is that *no* node in the fleet refused.
4231#[must_use]
4232pub fn fresh_offer_admission_refusals() -> u64 {
4233    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4234}
4235
4236/// Cumulative paid-list notification admission refusals in this process.
4237///
4238/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4239/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4240/// paid-list evidence outright rather than pushing work back onto a requester.
4241#[must_use]
4242pub fn paid_notify_admission_refusals() -> u64 {
4243    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4244}
4245
4246/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4247///
4248/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4249/// different things: this one says the node was saturated across all sources
4250/// and is genuinely under-provisioned for its offered load.
4251#[must_use]
4252pub fn fresh_offer_refusals_global_pool() -> u64 {
4253    audit_metrics::responder_admission_drops_by_ceiling(
4254        ReplicationResponderClass::FreshOffer,
4255        ResponderAdmissionCeiling::GlobalPool,
4256    )
4257}
4258
4259/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4260///
4261/// For fresh offers this usually indicts the *share's size* rather than the
4262/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4263/// node handling a client's PUT and fanning it out — so a share sized for
4264/// request/response traffic will refuse ordinary uploads.
4265#[must_use]
4266pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4267    audit_metrics::responder_admission_drops_by_ceiling(
4268        ReplicationResponderClass::FreshOffer,
4269        ResponderAdmissionCeiling::PerPeerShare,
4270    )
4271}
4272
4273/// Why an audit-responder admission attempt failed, with the decision-time
4274/// capacity counters that let a drop be logged with full context.
4275///
4276/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4277/// decision was made (the two ceilings are read under different locks, so they
4278/// are not a single atomic view), but they are exact enough to tell a saturated
4279/// node from a single self-throttling flooder.
4280#[derive(Debug, Clone, Copy)]
4281struct ResponderAdmissionFailure {
4282    reason: ResponderRejectReason,
4283    /// Global permits in use across the whole engine at decision time.
4284    global_inflight: usize,
4285    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4286    global_limit: usize,
4287    /// In-flight audit responders already held for `source` at decision time.
4288    peer_inflight: u32,
4289    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4290    peer_limit: u32,
4291}
4292
4293impl fmt::Display for ResponderAdmissionFailure {
4294    /// Renders the stable `reason=... global_inflight=... global_limit=...
4295    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4296    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4297        write!(
4298            f,
4299            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4300            self.reason.as_str(),
4301            self.global_inflight,
4302            self.global_limit,
4303            self.peer_inflight,
4304            self.peer_limit,
4305        )
4306    }
4307}
4308
4309/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4310/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4311/// spawned task ties both bounds to the task's exact lifetime — no manual
4312/// decrement to forget on an early return or panic.
4313struct ResponderGuard {
4314    _permit: tokio::sync::OwnedSemaphorePermit,
4315    _peer_slot: PeerResponderSlot,
4316    global_inflight: usize,
4317    peer_inflight: u32,
4318}
4319
4320type AuditResponderGuard = ResponderGuard;
4321type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4322
4323/// Provisional or admitted per-peer responder slot.
4324///
4325/// The slot is claimed before the global permit is attempted. Keeping that
4326/// claim under RAII means cancellation while rolling a failed admission back
4327/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4328/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4329struct PeerResponderSlot {
4330    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4331    peer: PeerId,
4332}
4333
4334#[derive(Clone)]
4335struct ReplicationMessageHandlerContext {
4336    p2p_node: Arc<P2PNode>,
4337    storage: Arc<ChunkStore>,
4338    paid_list: Arc<PaidList>,
4339    payment_verifier: Arc<PaymentVerifier>,
4340    queues: Arc<RwLock<ReplicationQueues>>,
4341    config: Arc<ReplicationConfig>,
4342    is_bootstrapping: Arc<RwLock<bool>>,
4343    bootstrap_state: Arc<RwLock<BootstrapState>>,
4344    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4345    sync_cycle_epoch: Arc<RwLock<u64>>,
4346    repair_proofs: Arc<RwLock<RepairProofs>>,
4347    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4348    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4349    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4350    my_commitment_state: Arc<ResponderCommitmentState>,
4351    gossip_audit: GossipAuditTrigger,
4352    audit_responder_semaphore: Arc<Semaphore>,
4353    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4354    audit_responder_metrics: Arc<AuditResponderMetrics>,
4355    subtree_round1: SubtreeRound1Limiter,
4356    fetch_responder_worker_semaphore: Arc<Semaphore>,
4357    fetch_responder_admission_semaphore: Arc<Semaphore>,
4358    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4359    verification_responder_worker_semaphore: Arc<Semaphore>,
4360    verification_responder_admission_semaphore: Arc<Semaphore>,
4361    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4362    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4363    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4364    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4365    fresh_offer_worker_semaphore: Arc<Semaphore>,
4366    fresh_offer_admission_semaphore: Arc<Semaphore>,
4367    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4368    fresh_offer_in_flight: FreshOfferInFlight,
4369    paid_notify_worker_semaphore: Arc<Semaphore>,
4370    paid_notify_admission_semaphore: Arc<Semaphore>,
4371    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4372    /// Pointer replication, when this node stores pointers.
4373    pointers: Option<Arc<pointer::PointerReplication>>,
4374    /// The engine's shutdown token, for detached responder work.
4375    ///
4376    /// Workers on [`Self::detached_task_tracker`] race this around their
4377    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4378    /// where dropping the awaiter would detach a live transaction. This is
4379    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4380    /// terminate: the wait stays safe because it is now guaranteed finite.
4381    shutdown: CancellationToken,
4382    /// Shared tracker for detached work so `shutdown()` can await release of
4383    /// storage and P2P resources after all producer tasks have stopped.
4384    detached_task_tracker: TaskTracker,
4385}
4386
4387struct InboundReplicationMessage {
4388    source: PeerId,
4389    msg: ReplicationMessage,
4390    rr_message_id: Option<String>,
4391    received_at: Instant,
4392}
4393
4394#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4395enum SerialQueueDropReason {
4396    Full,
4397    Closed,
4398}
4399
4400#[cfg(feature = "logging")]
4401impl SerialQueueDropReason {
4402    const fn as_str(self) -> &'static str {
4403        match self {
4404            Self::Full => "full",
4405            Self::Closed => "closed",
4406        }
4407    }
4408}
4409
4410#[derive(Debug, Clone, Copy)]
4411#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4412struct SerialQueueDrop {
4413    source: PeerId,
4414    message_class: &'static str,
4415    audit_responder_class: Option<AuditResponderClass>,
4416    queue_depth: usize,
4417    reason: SerialQueueDropReason,
4418}
4419
4420fn try_enqueue_serial_message(
4421    sender: &mpsc::Sender<InboundReplicationMessage>,
4422    inbound: InboundReplicationMessage,
4423) -> std::result::Result<(), SerialQueueDrop> {
4424    let source = inbound.source;
4425    let message_class = replication_message_class(&inbound.msg.body);
4426    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4427    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4428    sender.try_send(inbound).map_err(|error| {
4429        let (reason, dropped) = match error {
4430            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4431            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4432        };
4433        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4434        SerialQueueDrop {
4435            source,
4436            message_class,
4437            audit_responder_class,
4438            queue_depth,
4439            reason,
4440        }
4441    })
4442}
4443
4444const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4445    match body {
4446        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4447        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4448        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4449        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4450        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4451        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4452        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4453        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4454        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4455        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4456        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4457        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4458        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4459        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4460        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4461        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4462        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4463        ReplicationMessageBody::PointerFreshOffer(_) => "pointer_fresh_offer",
4464        ReplicationMessageBody::PointerHints(_) => "pointer_hints",
4465        ReplicationMessageBody::PointerFetchRequest(_) => "pointer_fetch_request",
4466        ReplicationMessageBody::PointerFetchResponse(_) => "pointer_fetch_response",
4467        ReplicationMessageBody::PointerStateRequest(_) => "pointer_state_request",
4468        ReplicationMessageBody::PointerStateResponse(_) => "pointer_state_response",
4469    }
4470}
4471
4472const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4473    match body {
4474        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4475        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4476        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4477        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4478        _ => None,
4479    }
4480}
4481
4482impl AuditResponderClass {
4483    const fn per_peer_limit(self) -> u32 {
4484        match self {
4485            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4486            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4487        }
4488    }
4489}
4490
4491fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4492    match error {
4493        RecvError::Lagged(missed) => {
4494            audit_metrics::record_replication_event_lagged(*missed);
4495            warn!(
4496                "Missed {missed} P2P events on replication branch (broadcast lag); \
4497                 replication messages may have been dropped before dispatch"
4498            );
4499            ControlFlow::Continue(())
4500        }
4501        RecvError::Closed => {
4502            // A closed broadcast channel never yields again, so the branch
4503            // would otherwise be immediately ready on every select! iteration.
4504            warn!("P2P event stream closed on replication branch; stopping message handler");
4505            ControlFlow::Break(())
4506        }
4507    }
4508}
4509
4510fn replication_payload_from_event(
4511    event: P2PEvent,
4512) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4513    let P2PEvent::Message {
4514        topic,
4515        source: Some(source),
4516        data,
4517        ..
4518    } = event
4519    else {
4520        return None;
4521    };
4522
4523    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4524    if !is_rr {
4525        return Some((source, data, matched_id, None));
4526    }
4527    if is_rr {
4528        return P2PNode::parse_request_envelope(&data)
4529            .filter(|(_, is_resp, _)| !is_resp)
4530            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4531    }
4532    None
4533}
4534
4535impl Drop for PeerResponderSlot {
4536    fn drop(&mut self) {
4537        // Decrement (and prune to keep the map bounded) without blocking the
4538        // async runtime: a short lock on a tiny map.
4539        //
4540        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4541        // with no spawn. Otherwise defer to a task — but only if a runtime is
4542        // actually current, so `Drop` during shutdown (no runtime) can never
4543        // panic. A missed decrement at shutdown is harmless: the whole map is
4544        // being dropped with the engine.
4545        let peer = self.peer;
4546        if let Ok(mut map) = self.inflight.try_write() {
4547            if let Some(n) = map.get_mut(&peer) {
4548                *n = n.saturating_sub(1);
4549                if *n == 0 {
4550                    map.remove(&peer);
4551                }
4552            }
4553            return;
4554        }
4555        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4556            let inflight = Arc::clone(&self.inflight);
4557            handle.spawn(async move {
4558                let mut map = inflight.write().await;
4559                if let Some(n) = map.get_mut(&peer) {
4560                    *n = n.saturating_sub(1);
4561                    if *n == 0 {
4562                        map.remove(&peer);
4563                    }
4564                }
4565            });
4566        }
4567    }
4568}
4569
4570/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4571/// and then a global permit. The limits are parameters so independent responder
4572/// classes can reuse the same flood-fair admission and cancellation semantics.
4573async fn admit_bounded_responder(
4574    semaphore: &Arc<Semaphore>,
4575    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4576    source: &PeerId,
4577    global_limit: usize,
4578    peer_limit: u32,
4579) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4580    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4581
4582    let admitted_peer_inflight = {
4583        let mut map = inflight.write().await;
4584        let entry = map.entry(*source).or_insert(0);
4585        if *entry >= peer_limit {
4586            let peer_inflight = *entry;
4587            drop(map);
4588            return Err(ResponderAdmissionFailure {
4589                reason: ResponderRejectReason::PerPeerCapFull,
4590                global_inflight: global_inflight(semaphore),
4591                global_limit,
4592                peer_inflight,
4593                peer_limit,
4594            });
4595        }
4596        *entry += 1;
4597        *entry
4598    };
4599
4600    let peer_slot = PeerResponderSlot {
4601        inflight: Arc::clone(inflight),
4602        peer: *source,
4603    };
4604    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4605        return Err(ResponderAdmissionFailure {
4606            reason: ResponderRejectReason::GlobalPoolFull,
4607            global_inflight: global_inflight(semaphore),
4608            global_limit,
4609            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4610            peer_limit,
4611        });
4612    };
4613
4614    Ok(ResponderGuard {
4615        _permit: permit,
4616        _peer_slot: peer_slot,
4617        global_inflight: global_inflight(semaphore),
4618        peer_inflight: admitted_peer_inflight,
4619    })
4620}
4621
4622/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4623struct SubtreeSession {
4624    commitment_hash: [u8; 32],
4625    nonce: [u8; 32],
4626    inserted: Instant,
4627}
4628
4629/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4630/// read and hash, refilled continuously at
4631/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4632/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4633///
4634/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4635/// identity may ask, so it is refilled by acquiring more identities; this is
4636/// charged for work done regardless of who asked, so it is not.
4637///
4638/// Charged after the fact, with the bytes the proof actually covered: the cost
4639/// of a request is not known until the pinned commitment has been resolved and
4640/// its subtree selected, both of which happen inside the handler. Admission
4641/// therefore asks only whether the balance is positive, and a proof that costs
4642/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4643/// Carrying the debt is what makes the bound real: without it a maximal proof
4644/// would cost the same as a trivial one, since either way the next request only
4645/// has to wait for the balance to climb back above zero. With it, sustained
4646/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4647/// admitted proportionally less often.
4648struct Round1WorkBudget {
4649    /// Signed, so an over-large proof leaves debt to work off.
4650    balance: i64,
4651    last_refill: Instant,
4652}
4653
4654impl Round1WorkBudget {
4655    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4656    /// for longer than the burst takes to refill.
4657    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4658    /// Nanoseconds per second, for the sub-second part of a refill.
4659    const NANOS_PER_SEC: i64 = 1_000_000_000;
4660
4661    fn new() -> Self {
4662        Self {
4663            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4664            last_refill: Instant::now(),
4665        }
4666    }
4667
4668    /// Add the tokens accrued since the last touch, capped at the burst size.
4669    fn refill(&mut self, now: Instant) {
4670        let elapsed = now.saturating_duration_since(self.last_refill);
4671        self.last_refill = now;
4672        let whole_secs = i64::try_from(elapsed.as_secs())
4673            .unwrap_or(i64::MAX)
4674            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4675        let sub_sec = i64::from(elapsed.subsec_nanos())
4676            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4677            / Self::NANOS_PER_SEC;
4678        self.balance = self
4679            .balance
4680            .saturating_add(whole_secs.saturating_add(sub_sec))
4681            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4682    }
4683
4684    /// Whether budget remains for a new round-1 proof.
4685    fn has_budget(&mut self, now: Instant) -> bool {
4686        self.refill(now);
4687        self.balance > 0
4688    }
4689
4690    /// Charge `bytes` of completed proof work, carrying debt down to
4691    /// [`Self::MAX_DEBT`].
4692    fn charge(&mut self, bytes: i64, now: Instant) {
4693        self.refill(now);
4694        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4695    }
4696}
4697
4698/// Resource controls for the HEAVY subtree-audit round 1: a tight
4699/// admission pool separate from the light responsible/slice audits, a per-peer
4700/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4701/// challenge is only served after a matching round 1.
4702///
4703/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4704/// bounds not keyed by peer identity, and so the only one that bounds sustained
4705/// work rather than concurrency or per-identity frequency.
4706#[derive(Clone)]
4707struct SubtreeRound1Limiter {
4708    semaphore: Arc<Semaphore>,
4709    /// Global ceiling on concurrent round-1 proofs (config-driven;
4710    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4711    /// semaphore because the per-peer admission helper needs the same number.
4712    max_concurrent: usize,
4713    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4714    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4715    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4716    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4717    cooldown_interval: Duration,
4718    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4719    /// Identity-independent ceiling on sustained round-1 work.
4720    work: Arc<RwLock<Round1WorkBudget>>,
4721}
4722
4723impl SubtreeRound1Limiter {
4724    /// `max_concurrent` of 0 would wedge the responder into refusing every
4725    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4726    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4727    /// rather than to off.
4728    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4729        let max_concurrent = max_concurrent.max(1);
4730        Self {
4731            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4732            max_concurrent,
4733            inflight: Arc::new(RwLock::new(HashMap::new())),
4734            cooldown: Arc::new(RwLock::new(HashMap::new())),
4735            cooldown_interval,
4736            sessions: Arc::new(RwLock::new(HashMap::new())),
4737            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4738        }
4739    }
4740
4741    /// Charge completed round-1 proof work against the responder-wide budget.
4742    async fn charge_work(&self, content_bytes: i64) {
4743        self.work
4744            .write()
4745            .await
4746            .charge(content_bytes, Instant::now());
4747    }
4748
4749    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4750    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4751    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4752    /// drops the challenge (the remote auditor applies its own graced-timeout
4753    /// policy).
4754    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4755        let guard = admit_bounded_responder(
4756            &self.semaphore,
4757            &self.inflight,
4758            source,
4759            self.max_concurrent,
4760            MAX_SUBTREE_ROUND1_PER_PEER,
4761        )
4762        .await
4763        .ok()?;
4764        // Checked before the per-peer cooldown is stamped, so a peer refused for
4765        // want of budget is not also charged its next allowance.
4766        if !self.work.write().await.has_budget(Instant::now()) {
4767            return None; // guard drops here, releasing the permit + slot
4768        }
4769        let now = Instant::now();
4770        let mut cooldown = self.cooldown.write().await;
4771        if let Some(&last) = cooldown.get(source) {
4772            if now.duration_since(last) < self.cooldown_interval {
4773                return None; // guard drops here, releasing the permit + slot
4774            }
4775        }
4776        // Evict lapsed entries (their cooldown has expired, so they no longer
4777        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4778        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4779        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4780            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4781                cooldown.remove(&oldest);
4782            }
4783        }
4784        cooldown.insert(*source, now);
4785        Some(guard)
4786    }
4787
4788    /// Record a single-use session once a round-1 proof is built and about to be
4789    /// sent, so the matching round 2 is admitted exactly once.
4790    async fn open_session(
4791        &self,
4792        source: PeerId,
4793        challenge_id: u64,
4794        commitment_hash: [u8; 32],
4795        nonce: [u8; 32],
4796    ) {
4797        let now = Instant::now();
4798        let mut sessions = self.sessions.write().await;
4799        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
4800        if sessions.len() >= MAX_SUBTREE_SESSIONS {
4801            if let Some(oldest) = sessions
4802                .iter()
4803                .min_by_key(|(_, e)| e.inserted)
4804                .map(|(k, _)| *k)
4805            {
4806                sessions.remove(&oldest);
4807            }
4808        }
4809        sessions.insert(
4810            (source, challenge_id),
4811            SubtreeSession {
4812                commitment_hash,
4813                nonce,
4814                inserted: now,
4815            },
4816        );
4817    }
4818
4819    /// Atomically consume the round-2 session for this exchange. `true` iff a
4820    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
4821    /// existed (and is now removed); a miss silently drops round 2 to the graced
4822    /// timeout lane (sessions are ephemeral and can be lost across a restart).
4823    async fn consume_session(
4824        &self,
4825        source: &PeerId,
4826        challenge_id: u64,
4827        commitment_hash: &[u8; 32],
4828        nonce: &[u8; 32],
4829    ) -> bool {
4830        let mut sessions = self.sessions.write().await;
4831        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
4832            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
4833                && &e.commitment_hash == commitment_hash
4834                && &e.nonce == nonce
4835        });
4836        if matches {
4837            sessions.remove(&(*source, challenge_id));
4838        }
4839        matches
4840    }
4841}
4842
4843/// Outcome of admitting a round-2 slice challenge.
4844enum SliceAdmission {
4845    /// Admitted: the guard holds the global permit and the per-peer slot, and
4846    /// the single-use round-1 session has been consumed.
4847    Admitted(AuditResponderGuard),
4848    /// Refused at a responder ceiling. The round-1 session is left INTACT.
4849    Capacity(AuditResponderAdmissionFailure),
4850    /// No live round-1 session matched this challenge.
4851    NoSession,
4852}
4853
4854/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
4855/// the single-use round-1 session.
4856///
4857/// The order is the point: a single-use token must not be spent on work that is
4858/// then refused. Consuming first and testing admission second leaves the session
4859/// destroyed by a purely local capacity drop, so the refusal is not recoverable
4860/// even in principle.
4861///
4862/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
4863/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
4864/// auditor does not currently re-send round 2 within an audit. The preserved
4865/// session is therefore not yet *recovering* an audit — it keeps a refusal
4866/// truthful (temporary means temporary) and keeps the invariant available for a
4867/// retry, rather than baking "capacity drop is permanent" into the state
4868/// machine. If an application-level retry is ruled out for good, this ordering
4869/// still costs nothing over the alternative.
4870///
4871/// Cost of the ordering: the permit and per-peer slot are held across the
4872/// session probe, which is one in-memory map lookup and no chunk work. The
4873/// per-peer cap still bounds a peer sending unsessioned challenges to the same
4874/// share it could already occupy with well-formed ones, so the admission
4875/// surface is unchanged.
4876async fn admit_slice_challenge(
4877    semaphore: &Arc<Semaphore>,
4878    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4879    round1: &SubtreeRound1Limiter,
4880    source: &PeerId,
4881    challenge: &protocol::SubtreeSliceChallenge,
4882) -> SliceAdmission {
4883    let guard =
4884        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
4885            Ok(guard) => guard,
4886            Err(failure) => return SliceAdmission::Capacity(failure),
4887        };
4888    if !round1
4889        .consume_session(
4890            source,
4891            challenge.challenge_id,
4892            &challenge.expected_commitment_hash,
4893            &challenge.nonce,
4894        )
4895        .await
4896    {
4897        // Release the permit and per-peer slot before the caller replies: no
4898        // chunk work follows, so holding them would shrink the pool for nothing.
4899        drop(guard);
4900        return SliceAdmission::NoSession;
4901    }
4902    SliceAdmission::Admitted(guard)
4903}
4904
4905/// Try to admit one audit-responder task for `source`: take a global permit AND
4906/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
4907/// its decision-time counters (caller drops the challenge, leaving the remote
4908/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
4909/// so one flooder can neither exhaust the global pool's effect on others nor
4910/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
4911/// log exactly WHY the drop happened rather than a single opaque "capacity
4912/// reached".
4913async fn admit_audit_responder(
4914    semaphore: &Arc<Semaphore>,
4915    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4916    source: &PeerId,
4917    class: AuditResponderClass,
4918) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
4919    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
4920    let peer_limit = class.per_peer_limit();
4921    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
4922}
4923
4924/// Handle an incoming replication protocol message.
4925///
4926/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
4927/// request-response path and the response must be sent via `send_response`
4928/// so saorsa-core can route it back to the waiting `send_request` caller.
4929#[allow(clippy::too_many_lines)]
4930async fn handle_replication_message(
4931    source: &PeerId,
4932    msg: ReplicationMessage,
4933    ctx: &ReplicationMessageHandlerContext,
4934    received_at: Instant,
4935    rr_message_id: Option<&str>,
4936) -> Result<()> {
4937    match msg.body {
4938        ReplicationMessageBody::FreshReplicationOffer(offer) => {
4939            dispatch_fresh_offer(
4940                *source,
4941                offer,
4942                ctx,
4943                msg.request_id,
4944                received_at,
4945                rr_message_id,
4946            )
4947            .await
4948        }
4949        ReplicationMessageBody::PaidNotify(notify) => {
4950            dispatch_paid_notify(*source, notify, ctx, received_at).await
4951        }
4952        ReplicationMessageBody::NeighborSyncRequest(request) => {
4953            let bootstrapping = *ctx.is_bootstrapping.read().await;
4954            // Phase-3 storage-bound audit: store the sender's
4955            // commitment for use as `expected_commitment_hash` in
4956            // future audits. Verify signature before storing so a peer
4957            // cannot inject a forged commitment for someone else.
4958            if let Some(target) = ingest_peer_commitment(
4959                source,
4960                request.commitment.as_ref(),
4961                &ctx.p2p_node,
4962                &ctx.last_commitment_by_peer,
4963                &ctx.ever_capable_peers,
4964                &ctx.sig_verify_attempts,
4965            )
4966            .await
4967            {
4968                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
4969            }
4970            dispatch_neighbor_sync_request(
4971                *source,
4972                request,
4973                ctx,
4974                bootstrapping,
4975                // Atomically snapshot + mark-gossiped: emitted in the sync
4976                // response, so we must stay answerable for it (ADR-0002).
4977                ctx.my_commitment_state
4978                    .current_for_gossip()
4979                    .map(|b| b.commitment().clone()),
4980                msg.request_id,
4981                received_at,
4982                rr_message_id,
4983            )
4984            .await
4985        }
4986        ReplicationMessageBody::VerificationRequest(request) => {
4987            dispatch_verification_request(
4988                *source,
4989                request,
4990                ctx,
4991                msg.request_id,
4992                received_at,
4993                rr_message_id,
4994            )
4995            .await
4996        }
4997        ReplicationMessageBody::FetchRequest(request) => {
4998            dispatch_fetch_request(
4999                *source,
5000                request,
5001                ctx,
5002                msg.request_id,
5003                received_at,
5004                rr_message_id,
5005            )
5006            .await
5007        }
5008        ReplicationMessageBody::AuditChallenge(challenge) => {
5009            // Responsible-chunk audit (audit #2) responder: answer with per-key
5010            // possession digests. This same handler also answers the
5011            // prune-confirmation audit, which sends the same `AuditChallenge`
5012            // wire message.
5013            //
5014            // Answering digests the stored bytes of every challenged key, so —
5015            // like the subtree/byte audits below — run it on a detached task off
5016            // this serial message loop. Handling it inline lets one challenge
5017            // block all other replication traffic until its digests complete
5018            // (head-of-line blocking). The same flood-fair admission applies: a
5019            // global ceiling AND a per-peer cap, dropping the challenge if either
5020            // is hit. A dropped challenge reads as a penalised timeout to the
5021            // auditor, so the caps must remain high enough for honest audit load;
5022            // the per-peer share still prevents one flooder from starving others.
5023            let class = AuditResponderClass::Digest;
5024            let guard = match admit_audit_responder(
5025                &ctx.audit_responder_semaphore,
5026                &ctx.audit_responder_inflight,
5027                source,
5028                class,
5029            )
5030            .await
5031            {
5032                Ok(guard) => guard,
5033                Err(failure) => {
5034                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
5035                    audit_metrics::record_admission_drop(class);
5036                    ctx.audit_responder_metrics
5037                        .record_drop(*source, failure.reason.into());
5038                    warn!(
5039                        target: "ant_node::replication::audit_responder",
5040                        event = "admission_dropped",
5041                        kind = "responsible",
5042                        responder_class = class.as_str(),
5043                        source = %source,
5044                        challenge_id = challenge.challenge_id,
5045                        key_count = challenge.keys.len(),
5046                        request_response = rr_message_id.is_some(),
5047                        dispatch_ms = received_at.elapsed().as_millis(),
5048                        reason = failure.reason.as_str(),
5049                        global_inflight = failure.global_inflight,
5050                        global_limit = failure.global_limit,
5051                        peer_inflight = failure.peer_inflight,
5052                        peer_limit = failure.peer_limit,
5053                        "Audit responder admission dropped"
5054                    );
5055                    return Ok(());
5056                }
5057            };
5058            let admission_global_inflight = guard.global_inflight;
5059            let admission_peer_inflight = guard.peer_inflight;
5060            ctx.audit_responder_metrics.record_admitted(
5061                *source,
5062                admission_global_inflight,
5063                admission_peer_inflight,
5064            );
5065            info!(
5066                target: "ant_node::replication::audit_responder",
5067                event = "admitted",
5068                kind = "responsible",
5069                responder_class = class.as_str(),
5070                source = %source,
5071                challenge_id = challenge.challenge_id,
5072                key_count = challenge.keys.len(),
5073                request_response = rr_message_id.is_some(),
5074                dispatch_ms = received_at.elapsed().as_millis(),
5075                global_inflight = admission_global_inflight,
5076                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5077                peer_inflight = admission_peer_inflight,
5078                peer_limit = class.per_peer_limit(),
5079                "Audit responder request admitted"
5080            );
5081            let bootstrapping = *ctx.is_bootstrapping.read().await;
5082            let dispatch_latency = received_at.elapsed();
5083            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5084            debug!(
5085                audit_type = "digest_responder",
5086                dispatch_latency_ms = dispatch_latency.as_millis(),
5087                source = %source,
5088                "Audit challenge dispatch latency measured"
5089            );
5090            let storage = Arc::clone(&ctx.storage);
5091            let p2p_node = Arc::clone(&ctx.p2p_node);
5092            let source = *source;
5093            let request_id = msg.request_id;
5094            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5095            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5096            ctx.detached_task_tracker.spawn(async move {
5097                let _guard = guard; // global permit + per-peer slot, held until done
5098                let worker_started = Instant::now();
5099                match handle_audit_challenge_msg(
5100                    &source,
5101                    &challenge,
5102                    &storage,
5103                    &p2p_node,
5104                    bootstrapping,
5105                    ReplyRoute {
5106                        request_id,
5107                        rr_message_id: rr_message_id.as_deref(),
5108                        protocol: REPLICATION_PROTOCOL_ID,
5109                    },
5110                )
5111                .await
5112                {
5113                    Ok(completion) => log_audit_responder_completion(
5114                        &responder_metrics,
5115                        source,
5116                        class,
5117                        "responsible",
5118                        challenge.challenge_id,
5119                        challenge.keys.len(),
5120                        completion.response_kind,
5121                        completion.sent,
5122                        received_at,
5123                        worker_started,
5124                        completion.processing,
5125                        completion.response_send,
5126                    ),
5127                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5128                }
5129            });
5130            Ok(())
5131        }
5132        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5133            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5134            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5135            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5136            // detached task so this serial message loop is never blocked on disk
5137            // I/O — otherwise one audit stalls all replication traffic (§5).
5138            //
5139            // A bounded, flood-fair admission restores backpressure (codex#1 +
5140            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5141            // we drop this challenge. Subtree auditors grace timeout
5142            // non-responses, so capacity drops throttle flooders without turning
5143            // into trust penalties (and one source cannot starve other peers,
5144            // since its share is capped per-peer).
5145            let class = AuditResponderClass::Subtree;
5146            info!(
5147                "Audit challenge received: kind=subtree source={source} request_response={}",
5148                rr_message_id.is_some(),
5149            );
5150            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5151            // so it uses its own tight admission pool + per-peer rate cooldown,
5152            // separate from the light responsible/slice audits, and a miss silently
5153            // drops (subtree auditors grace timeouts).
5154            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5155                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5156                warn!(
5157                    target: "ant_node::replication::audit_responder",
5158                    event = "admission_dropped",
5159                    kind = "subtree",
5160                    responder_class = class.as_str(),
5161                    source = %source,
5162                    challenge_id = challenge.challenge_id,
5163                    request_response = rr_message_id.is_some(),
5164                    dispatch_ms = received_at.elapsed().as_millis(),
5165                    reason = "heavy_pool_cooldown_or_work_budget",
5166                    "Audit responder admission dropped"
5167                );
5168                return Ok(());
5169            };
5170            let admission_global_inflight = guard.global_inflight;
5171            let admission_peer_inflight = guard.peer_inflight;
5172            ctx.audit_responder_metrics.record_admitted(
5173                *source,
5174                admission_global_inflight,
5175                admission_peer_inflight,
5176            );
5177            info!(
5178                target: "ant_node::replication::audit_responder",
5179                event = "admitted",
5180                kind = "subtree",
5181                responder_class = class.as_str(),
5182                source = %source,
5183                challenge_id = challenge.challenge_id,
5184                request_response = rr_message_id.is_some(),
5185                dispatch_ms = received_at.elapsed().as_millis(),
5186                global_inflight = admission_global_inflight,
5187                global_limit = ctx.subtree_round1.max_concurrent,
5188                peer_inflight = admission_peer_inflight,
5189                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5190                "Audit responder request admitted"
5191            );
5192            let bootstrapping = *ctx.is_bootstrapping.read().await;
5193            let storage = Arc::clone(&ctx.storage);
5194            let p2p_node = Arc::clone(&ctx.p2p_node);
5195            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5196            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5197            let source = *source;
5198            let request_id = msg.request_id;
5199            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5200            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5201            let subtree_round1 = ctx.subtree_round1.clone();
5202            ctx.detached_task_tracker.spawn(async move {
5203                let _guard = guard; // global permit + per-peer slot, held until done
5204                let worker_started = Instant::now();
5205                let processing_started = Instant::now();
5206                let storage_commitment_audit::Round1Work {
5207                    response,
5208                    content_bytes,
5209                } = storage_commitment_audit::handle_subtree_challenge_measured_with_pointers(
5210                    &challenge,
5211                    &storage,
5212                    pointer_store.as_ref(),
5213                    p2p_node.peer_id(),
5214                    bootstrapping,
5215                    Some(&my_commitment_state),
5216                )
5217                .await;
5218                let processing = processing_started.elapsed();
5219                // Charge the work actually done, on EVERY outcome.
5220                //
5221                // This used to charge only the `Proof` arm, reasoning that the
5222                // rejecting paths either read nothing or reflected this node's
5223                // own broken storage. The second half of that was wrong: a
5224                // retained commitment containing one unreadable key still costs
5225                // a full run of reads and keyed-BLAKE3 passes over every leaf
5226                // before it, and then rejects. An attacker who finds such a
5227                // commitment could replay subtrees over it indefinitely for
5228                // free. The per-peer cooldown does not catch that either, since
5229                // it is escapable by rotating identity — the responder-wide
5230                // budget is the only bound that applies, so it has to see the
5231                // work. A zero charge is a no-op, so the untouched paths are
5232                // unaffected.
5233                subtree_round1.charge_work(content_bytes).await;
5234                // A round-1 proof authorizes exactly one matching round 2: open a
5235                // single-use session so a slice challenge cannot be served without
5236                // a live round-1 exchange.
5237                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5238                {
5239                    subtree_round1
5240                        .open_session(
5241                            source,
5242                            challenge.challenge_id,
5243                            challenge.expected_commitment_hash,
5244                            challenge.nonce,
5245                        )
5246                        .await;
5247                }
5248                let response_kind = subtree_audit_response_kind(&response);
5249                let work_items = subtree_audit_response_work_items(&response);
5250                let response_send_started = Instant::now();
5251                let sent = send_replication_response_checked(
5252                    &source,
5253                    &p2p_node,
5254                    request_id,
5255                    ReplicationMessageBody::SubtreeAuditResponse(response),
5256                    rr_message_id.as_deref(),
5257                    None,
5258                )
5259                .await;
5260                let response_send = response_send_started.elapsed();
5261                log_audit_responder_completion(
5262                    &responder_metrics,
5263                    source,
5264                    class,
5265                    "subtree",
5266                    challenge.challenge_id,
5267                    work_items,
5268                    response_kind,
5269                    sent,
5270                    received_at,
5271                    worker_started,
5272                    processing,
5273                    response_send,
5274                );
5275            });
5276            Ok(())
5277        }
5278        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5279            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5280            // block of each auditor-selected spot-check key with a Bao verified
5281            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5282            // build the proofs, so it runs off the serial loop under the light
5283            // audit pool's global and per-peer ceilings.
5284            let class = AuditResponderClass::Byte;
5285            info!(
5286                "Audit challenge received: kind=slice source={source} request_response={}",
5287                rr_message_id.is_some(),
5288            );
5289            let guard = match admit_slice_challenge(
5290                &ctx.audit_responder_semaphore,
5291                &ctx.audit_responder_inflight,
5292                &ctx.subtree_round1,
5293                source,
5294                &challenge,
5295            )
5296            .await
5297            {
5298                SliceAdmission::Admitted(guard) => guard,
5299                SliceAdmission::Capacity(failure) => {
5300                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5301                    audit_metrics::record_admission_drop(class);
5302                    ctx.audit_responder_metrics
5303                        .record_drop(*source, failure.reason.into());
5304                    warn!(
5305                        target: "ant_node::replication::audit_responder",
5306                        event = "admission_dropped",
5307                        kind = "byte",
5308                        responder_class = class.as_str(),
5309                        source = %source,
5310                        challenge_id = challenge.challenge_id,
5311                        key_count = challenge.openings.len(),
5312                        request_response = rr_message_id.is_some(),
5313                        dispatch_ms = received_at.elapsed().as_millis(),
5314                        reason = failure.reason.as_str(),
5315                        global_inflight = failure.global_inflight,
5316                        global_limit = failure.global_limit,
5317                        peer_inflight = failure.peer_inflight,
5318                        peer_limit = failure.peer_limit,
5319                        "Audit responder admission dropped"
5320                    );
5321                    return Ok(());
5322                }
5323                // No live round-1 session: reply with a cheap `Transient` rejection
5324                // rather than dropping silently. Sessions are ephemeral (an honest
5325                // responder that restarts between rounds loses its session), and an
5326                // unanswered `send_request` would make saorsa-core record a
5327                // transport trust failure against that honest responder — an
5328                // ongoing effect, not just a rollout-window one. A `Transient`
5329                // reply routes the auditor to the graced timeout lane (no trust
5330                // penalty; the responder re-earns pinned credit on the next audit)
5331                // and does no chunk work, so it is not a DoS lever.
5332                SliceAdmission::NoSession => {
5333                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5334                    debug!(
5335                        "Slice challenge without a live round-1 session source={source} \
5336                         challenge_id={} → Transient reject",
5337                        challenge.challenge_id
5338                    );
5339                    send_replication_response_checked(
5340                        source,
5341                        &ctx.p2p_node,
5342                        msg.request_id,
5343                        ReplicationMessageBody::SubtreeSliceResponse(
5344                            protocol::SubtreeSliceResponse::Rejected {
5345                                challenge_id: challenge.challenge_id,
5346                                kind: protocol::RejectKind::Transient,
5347                                reason: "no live round-1 session".to_string(),
5348                            },
5349                        ),
5350                        rr_message_id,
5351                        None,
5352                    )
5353                    .await;
5354                    return Ok(());
5355                }
5356            };
5357            let admission_global_inflight = guard.global_inflight;
5358            let admission_peer_inflight = guard.peer_inflight;
5359            ctx.audit_responder_metrics.record_admitted(
5360                *source,
5361                admission_global_inflight,
5362                admission_peer_inflight,
5363            );
5364            info!(
5365                target: "ant_node::replication::audit_responder",
5366                event = "admitted",
5367                kind = "byte",
5368                responder_class = class.as_str(),
5369                source = %source,
5370                challenge_id = challenge.challenge_id,
5371                key_count = challenge.openings.len(),
5372                request_response = rr_message_id.is_some(),
5373                dispatch_ms = received_at.elapsed().as_millis(),
5374                global_inflight = admission_global_inflight,
5375                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5376                peer_inflight = admission_peer_inflight,
5377                peer_limit = class.per_peer_limit(),
5378                "Audit responder request admitted"
5379            );
5380            let bootstrapping = *ctx.is_bootstrapping.read().await;
5381            let storage = Arc::clone(&ctx.storage);
5382            let p2p_node = Arc::clone(&ctx.p2p_node);
5383            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5384            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5385            let source = *source;
5386            let request_id = msg.request_id;
5387            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5388            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5389            ctx.detached_task_tracker.spawn(async move {
5390                let _guard = guard; // global permit + per-peer slot, held until done
5391                let worker_started = Instant::now();
5392                let processing_started = Instant::now();
5393                let response =
5394                    storage_commitment_audit::handle_subtree_slice_challenge_with_pointers(
5395                        &challenge,
5396                        &storage,
5397                        pointer_store.as_ref(),
5398                        p2p_node.peer_id(),
5399                        bootstrapping,
5400                        Some(&my_commitment_state),
5401                    )
5402                    .await;
5403                let processing = processing_started.elapsed();
5404                let response_kind = subtree_slice_response_kind(&response);
5405                let response_send_started = Instant::now();
5406                let sent = send_replication_response_checked(
5407                    &source,
5408                    &p2p_node,
5409                    request_id,
5410                    ReplicationMessageBody::SubtreeSliceResponse(response),
5411                    rr_message_id.as_deref(),
5412                    None,
5413                )
5414                .await;
5415                let response_send = response_send_started.elapsed();
5416                log_audit_responder_completion(
5417                    &responder_metrics,
5418                    source,
5419                    class,
5420                    "byte",
5421                    challenge.challenge_id,
5422                    challenge.openings.len(),
5423                    response_kind,
5424                    sent,
5425                    received_at,
5426                    worker_started,
5427                    processing,
5428                    response_send,
5429                );
5430            });
5431            Ok(())
5432        }
5433        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5434            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5435            // only. `lookup_by_hash` is an allocation-light read over the
5436            // bounded slot set; it returns the live current commitment or any
5437            // still-answerable recently-gossiped/quoted one. A miss is reported
5438            // as `NotRetained` (graced, never confirmed) rather than an error,
5439            // so an aged-out pin can never brand an honest node.
5440            //
5441            // Reuse the audit-responder admission guard (global ceiling + per-peer
5442            // cap) so a flood of fetches cannot drive unbounded commitment
5443            // clone/encode/send work; over-limit is dropped, which the fetching
5444            // peer graces exactly like a missed audit response.
5445            let class = AuditResponderClass::CommitmentPin;
5446            let guard = match admit_audit_responder(
5447                &ctx.audit_responder_semaphore,
5448                &ctx.audit_responder_inflight,
5449                source,
5450                class,
5451            )
5452            .await
5453            {
5454                Ok(guard) => guard,
5455                Err(failure) => {
5456                    audit_metrics::record_admission_drop(class);
5457                    ctx.audit_responder_metrics
5458                        .record_drop(*source, failure.reason.into());
5459                    warn!(
5460                        target: "ant_node::replication::audit_responder",
5461                        event = "admission_dropped",
5462                        kind = "commitment_pin",
5463                        responder_class = class.as_str(),
5464                        source = %source,
5465                        challenge_id = msg.request_id,
5466                        request_response = rr_message_id.is_some(),
5467                        dispatch_ms = received_at.elapsed().as_millis(),
5468                        reason = failure.reason.as_str(),
5469                        global_inflight = failure.global_inflight,
5470                        global_limit = failure.global_limit,
5471                        peer_inflight = failure.peer_inflight,
5472                        peer_limit = failure.peer_limit,
5473                        "Audit responder admission dropped"
5474                    );
5475                    return Ok(());
5476                }
5477            };
5478            ctx.audit_responder_metrics.record_admitted(
5479                *source,
5480                guard.global_inflight,
5481                guard.peer_inflight,
5482            );
5483            info!(
5484                target: "ant_node::replication::audit_responder",
5485                event = "admitted",
5486                kind = "commitment_pin",
5487                responder_class = class.as_str(),
5488                source = %source,
5489                challenge_id = msg.request_id,
5490                request_response = rr_message_id.is_some(),
5491                dispatch_ms = received_at.elapsed().as_millis(),
5492                global_inflight = guard.global_inflight,
5493                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5494                peer_inflight = guard.peer_inflight,
5495                peer_limit = class.per_peer_limit(),
5496                "Audit responder request admitted"
5497            );
5498            let worker_started = Instant::now();
5499            let processing_started = Instant::now();
5500            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5501                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5502                |built| protocol::GetCommitmentByPinResponse::Found {
5503                    commitment: built.commitment().clone(),
5504                },
5505            );
5506            let processing = processing_started.elapsed();
5507            let response_kind = commitment_pin_response_kind(&response);
5508            let response_send_started = Instant::now();
5509            let sent = send_replication_response_checked(
5510                source,
5511                &ctx.p2p_node,
5512                msg.request_id,
5513                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5514                rr_message_id,
5515                None,
5516            )
5517            .await;
5518            let response_send = response_send_started.elapsed();
5519            log_audit_responder_completion(
5520                &ctx.audit_responder_metrics,
5521                *source,
5522                class,
5523                "commitment_pin",
5524                msg.request_id,
5525                1,
5526                response_kind,
5527                sent,
5528                received_at,
5529                worker_started,
5530                processing,
5531                response_send,
5532            );
5533            drop(guard);
5534            Ok(())
5535        }
5536        // Pointers (ADR-0016). A node that does not store pointers ignores
5537        // them, and so is never marked capable and never asked anything.
5538        ReplicationMessageBody::PointerFreshOffer(offer) => {
5539            if let Some(pointers) = &ctx.pointers {
5540                pointers.accept_offer_detached(*source, offer);
5541            }
5542            Ok(())
5543        }
5544        ReplicationMessageBody::PointerHints(hints) => {
5545            if let Some(pointers) = &ctx.pointers {
5546                pointers.handle_hints(*source, hints.hints).await;
5547            }
5548            Ok(())
5549        }
5550        ReplicationMessageBody::PointerFetchRequest(request) => {
5551            if let Some(pointers) = &ctx.pointers {
5552                pointers.serve_fetch_detached(
5553                    *source,
5554                    request,
5555                    msg.request_id,
5556                    rr_message_id.map(ToOwned::to_owned),
5557                );
5558            }
5559            Ok(())
5560        }
5561        ReplicationMessageBody::PointerStateRequest(request) => {
5562            if let Some(pointers) = &ctx.pointers {
5563                pointers.serve_state_detached(
5564                    *source,
5565                    request,
5566                    msg.request_id,
5567                    rr_message_id.map(ToOwned::to_owned),
5568                );
5569            }
5570            Ok(())
5571        }
5572        // Response messages are handled by their respective request initiators.
5573        ReplicationMessageBody::FreshReplicationResponse(_)
5574        | ReplicationMessageBody::NeighborSyncResponse(_)
5575        | ReplicationMessageBody::VerificationResponse(_)
5576        | ReplicationMessageBody::FetchResponse(_)
5577        | ReplicationMessageBody::AuditResponse(_)
5578        | ReplicationMessageBody::SubtreeAuditResponse(_)
5579        | ReplicationMessageBody::SubtreeSliceResponse(_)
5580        | ReplicationMessageBody::GetCommitmentByPinResponse(_)
5581        | ReplicationMessageBody::PointerFetchResponse(_)
5582        | ReplicationMessageBody::PointerStateResponse(_) => Ok(()),
5583    }
5584}
5585
5586// ---------------------------------------------------------------------------
5587// Per-message-type handlers
5588// ---------------------------------------------------------------------------
5589
5590/// Verify a payment proof, yielding early if the engine is shutting down.
5591///
5592/// Returns `None` when shutdown won the race, meaning no verdict was reached
5593/// and the caller must abandon the message without storing or penalising.
5594///
5595/// Payment verification is pure network I/O — an EVM round trip and, on the
5596/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5597/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5598/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5599/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5600/// is guaranteed to end.
5601///
5602/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5603/// dropping its awaiter would detach a live LMDB transaction and break the
5604/// very contract the unbounded wait exists to uphold.
5605async fn verify_payment_until_shutdown(
5606    payment_verifier: &Arc<PaymentVerifier>,
5607    key: &XorName,
5608    proof_of_payment: &[u8],
5609    context: VerificationContext,
5610    shutdown: &CancellationToken,
5611) -> Option<Result<crate::payment::PaymentStatus>> {
5612    tokio::select! {
5613        () = shutdown.cancelled() => None,
5614        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5615            Some(result)
5616        }
5617    }
5618}
5619
5620/// A fresh offer rejected on payload shape alone.
5621struct FreshOfferRejection {
5622    /// Wire-visible reason returned to the sender.
5623    reason: String,
5624    /// Whether the sender is charged for it. Reserved for offers no honest
5625    /// node would construct, so an ordinary capacity refusal stays free.
5626    penalise: bool,
5627}
5628
5629/// Reject a fresh offer on payload shape, or return `None` to admit it.
5630///
5631/// Pure and non-blocking by construction: these are the checks answerable from
5632/// the payload alone, run on the serial message loop *before* the in-flight
5633/// claim and the admission permit, so a malformed offer can neither lock an
5634/// honest offer out of its key nor occupy one of the scarce
5635/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5636/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5637/// verification — stays on the worker.
5638///
5639/// The content-address hash is deliberately included despite costing real CPU
5640/// on the loop: it is what makes the entry below *earned* rather than merely
5641/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5642/// arrive at link speed, so a flooder can never make this loop hash faster than
5643/// it can deliver the bytes, and delivering them already cost it more than the
5644/// hash costs us. The receive path has in any case already deserialised the
5645/// same buffer.
5646///
5647/// Every rejection here is penalised. These are the conditions no honest sender
5648/// can produce — an absent, undersized, oversized, or non-matching payload — as
5649/// distinct from a capacity refusal, which is this node's own state and stays
5650/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5651/// proof that fails to verify may simply have been read against a lagging chain
5652/// view, and penalising that would charge honest senders in correlated bursts.
5653fn fresh_offer_structural_rejection(
5654    key: &XorName,
5655    data: &[u8],
5656    proof_of_payment: &[u8],
5657) -> Option<FreshOfferRejection> {
5658    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5659    // and an absent proof is the cheapest possible slot-filler, so this is the
5660    // first thing checked.
5661    if proof_of_payment.is_empty() {
5662        return Some(FreshOfferRejection {
5663            reason: "Missing proof of payment".to_string(),
5664            penalise: true,
5665        });
5666    }
5667
5668    // Bound the proof before it can be queued. The verifier applies the same
5669    // limits, but only once the offer reaches a worker — too late here, because
5670    // an entry retains a proof per queued sender, and a proof is capped on the
5671    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5672    // a byte of data and a 10 MiB "proof" would be admitted, and
5673    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5674    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5675    // admission bound exists to enforce.
5676    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5677        return Some(FreshOfferRejection {
5678            reason: format!(
5679                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5680                proof_of_payment.len(),
5681            ),
5682            penalise: true,
5683        });
5684    }
5685    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5686        return Some(FreshOfferRejection {
5687            reason: format!(
5688                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5689                proof_of_payment.len(),
5690            ),
5691            penalise: true,
5692        });
5693    }
5694
5695    // Enforce chunk size invariant: the normal PUT path rejects data larger
5696    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5697    // prevent peers from pushing oversized records through replication.
5698    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5699        return Some(FreshOfferRejection {
5700            reason: format!(
5701                "Data size {} exceeds maximum chunk size {}",
5702                data.len(),
5703                crate::ant_protocol::MAX_CHUNK_SIZE,
5704            ),
5705            penalise: true,
5706        });
5707    }
5708
5709    // Mirror the normal PUT path: the advertised key must be the content
5710    // address of the supplied bytes. Ordered last so an oversized payload is
5711    // refused without being hashed.
5712    //
5713    // This is the check that makes the entry safe to open, and safe for later
5714    // offers to be folded into. Until it passes, the sender has only *asserted*
5715    // an association between the key and the bytes. Opening an entry on an
5716    // assertion would let any peer that knows a key — every recipient of its
5717    // `PaidNotify`, not just the close group — seize it with junk; folding a
5718    // later offer into an entry on an assertion would be worse still, since the
5719    // handler tries each queued proof against the *opener's* bytes and would be
5720    // storing bytes nobody offered for that proof.
5721    let computed_key = crate::client::compute_address(data);
5722    if computed_key != *key {
5723        return Some(FreshOfferRejection {
5724            reason: format!(
5725                "Content address mismatch: expected {}, computed {}",
5726                hex::encode(key),
5727                hex::encode(computed_key),
5728            ),
5729            penalise: true,
5730        });
5731    }
5732
5733    None
5734}
5735
5736/// Tell `source` its offer for `key` was not taken.
5737///
5738/// Note the sender does not currently read this: `fresh::replicate_fresh` uses
5739/// one-way `send_message`, so the refusal is observed only as a later absence by
5740/// the delayed possession check. Recorded in ADR-0005 as a known gap.
5741async fn refuse_fresh_offer(
5742    source: &PeerId,
5743    key: XorName,
5744    reason: String,
5745    ctx: &ReplicationMessageHandlerContext,
5746    request_id: u64,
5747    rr_message_id: Option<&str>,
5748) {
5749    send_replication_response(
5750        source,
5751        &ctx.p2p_node,
5752        request_id,
5753        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
5754            key,
5755            reason,
5756        }),
5757        rr_message_id,
5758    )
5759    .await;
5760}
5761
5762/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
5763/// the sender when the defect is one no honest node could produce.
5764///
5765/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
5766/// two say opposite things: this is the sender's fault, that one is ours.
5767async fn refuse_malformed_fresh_offer(
5768    source: &PeerId,
5769    key: XorName,
5770    rejection: FreshOfferRejection,
5771    ctx: &ReplicationMessageHandlerContext,
5772    request_id: u64,
5773    rr_message_id: Option<&str>,
5774) {
5775    if rejection.penalise {
5776        warn!(
5777            "Rejecting fresh offer for key {} from {source}: {}",
5778            hex::encode(key),
5779            rejection.reason
5780        );
5781        ctx.p2p_node
5782            .report_trust_event(
5783                source,
5784                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
5785            )
5786            .await;
5787    } else {
5788        debug!(
5789            "Fresh offer for {} from {source} refused before admission: {}",
5790            hex::encode(key),
5791            rejection.reason
5792        );
5793    }
5794    refuse_fresh_offer(
5795        source,
5796        key,
5797        rejection.reason,
5798        ctx,
5799        request_id,
5800        rr_message_id,
5801    )
5802    .await;
5803}
5804
5805/// Tell senders whose proofs joined an entry that was torn down before a handler
5806/// ever ran for it.
5807///
5808/// Only reachable in the window between opening an entry and failing to take an
5809/// admission permit. Their proofs are answered rather than dropped with the
5810/// entry, so the refusal count reflects what actually happened.
5811async fn refuse_stranded_fresh_offers(
5812    key: XorName,
5813    stranded: Vec<FreshOfferAttempt>,
5814    ctx: &ReplicationMessageHandlerContext,
5815) {
5816    for attempt in stranded {
5817        refuse_fresh_offer(
5818            &attempt.source,
5819            key,
5820            "Receiver at fresh-offer capacity".to_string(),
5821            ctx,
5822            attempt.request_id,
5823            attempt.rr_message_id.as_deref(),
5824        )
5825        .await;
5826    }
5827}
5828
5829/// Admit a fresh offer for handling on a worker, or refuse it.
5830///
5831/// This runs on the serial non-audit message loop, so it must stay cheap: every
5832/// path here is a set insert, a permit try, or a small response send. The offer
5833/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
5834/// runs on a tracked worker task, never inline, because stalling this loop backs
5835/// up the inbound queue and ultimately drops replication messages wholesale.
5836///
5837/// Admission is bounded **per source** as well as globally
5838/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
5839/// hold every slot, and since a refusal is later read as absence by the
5840/// sender's delayed possession check, the resulting refusals land as
5841/// audit-severity penalties on this node rather than on the flooder.
5842///
5843/// The structurally-invalid checks run **before** the entry is opened and before
5844/// the permit is taken, so junk can neither seize a key nor occupy a slot for
5845/// the duration of a payment verification.
5846///
5847/// Only the offer that *opens* an entry costs a permit and a worker. Later
5848/// offers for the same key contribute their proof and are answered by whatever
5849/// the opener's handler concludes, which is what keeps the routine
5850/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
5851/// one verification per key.
5852async fn dispatch_fresh_offer(
5853    source: PeerId,
5854    offer: protocol::FreshReplicationOffer,
5855    ctx: &ReplicationMessageHandlerContext,
5856    request_id: u64,
5857    received_at: Instant,
5858    rr_message_id: Option<&str>,
5859) -> Result<()> {
5860    if let Some(rejection) =
5861        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
5862    {
5863        refuse_malformed_fresh_offer(
5864            &source,
5865            offer.key,
5866            rejection,
5867            ctx,
5868            request_id,
5869            rr_message_id,
5870        )
5871        .await;
5872        return Ok(());
5873    }
5874
5875    // Join the work already in flight for this key before taking an admission
5876    // permit, so the duplicates a single client PUT produces cost one permit
5877    // between them rather than one each.
5878    //
5879    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
5880    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
5881    // already held for the key. That is what lets its payload be dropped here
5882    // and only its proof retained: the handler will try that proof against the
5883    // bytes it already has.
5884    let key = offer.key;
5885    let admission_outcome = FreshOfferEntryGuard::admit(
5886        &ctx.fresh_offer_in_flight,
5887        offer,
5888        source,
5889        request_id,
5890        rr_message_id.map(ToOwned::to_owned),
5891        received_at,
5892    );
5893    let mut entry = match admission_outcome {
5894        FreshOfferAdmission::Opened(entry) => entry,
5895        FreshOfferAdmission::Joined => {
5896            // No response yet: this proof has not been judged. The handler that
5897            // owns the key answers every queued sender once it settles.
5898            debug!(
5899                "Fresh offer for {} from {source} queued behind the handler already \
5900                 holding the key",
5901                hex::encode(key)
5902            );
5903            return Ok(());
5904        }
5905        // Surplus, not suspect: the proofs already queued are enough to place
5906        // the record, so neither case is charged as misbehaviour.
5907        surplus => {
5908            debug!(
5909                "Fresh offer for {} from {source} refused: {}",
5910                hex::encode(key),
5911                surplus.surplus_reason()
5912            );
5913            refuse_fresh_offer(
5914                &source,
5915                key,
5916                "Duplicate offer already in flight".to_string(),
5917                ctx,
5918                request_id,
5919                rr_message_id,
5920            )
5921            .await;
5922            return Ok(());
5923        }
5924    };
5925
5926    let admission = match admit_bounded_responder(
5927        &ctx.fresh_offer_admission_semaphore,
5928        &ctx.fresh_offer_responder_inflight,
5929        &source,
5930        FRESH_OFFER_MAX_OUTSTANDING,
5931        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
5932    )
5933    .await
5934    {
5935        Ok(guard) => guard,
5936        Err(failure) => {
5937            audit_metrics::record_responder_admission_drop(
5938                ReplicationResponderClass::FreshOffer,
5939                failure.reason.into(),
5940            );
5941            // WARN, not DEBUG: a healthy node should never refuse a legitimate
5942            // fresh offer. The sender does not read this refusal, so it
5943            // resurfaces as a missing key at the delayed possession check and
5944            // is charged to US at audit severity. Log the binding ceiling
5945            // locally; the wire reason stays generic so a probing peer cannot
5946            // map out this node's live occupancy.
5947            warn!(
5948                responder_class = "fresh_offer",
5949                source = %source,
5950                key = %hex::encode(key),
5951                penalty_suspended = config::close_group_storage_penalty_suspended(),
5952                "Fresh offer refused at admission; the resulting absence is recorded \
5953                 against this node, and penalised unless the release withholds it: \
5954                 {failure}"
5955            );
5956            // Release the key explicitly rather than on drop, so the next offer
5957            // opens a fresh entry rather than queueing behind a handler that was
5958            // never spawned — and so any proof that joined in the window between
5959            // opening the entry and failing here is answered rather than
5960            // discarded with it.
5961            let stranded = entry.release();
5962            refuse_fresh_offer(
5963                &source,
5964                key,
5965                "Receiver at fresh-offer capacity".to_string(),
5966                ctx,
5967                request_id,
5968                rr_message_id,
5969            )
5970            .await;
5971            refuse_stranded_fresh_offers(key, stranded, ctx).await;
5972            return Ok(());
5973        }
5974    };
5975
5976    let ctx = ctx.clone();
5977    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
5978    // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
5979    // those references be released before the caller reopens the environment.
5980    ctx.detached_task_tracker
5981        .clone()
5982        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
5983    Ok(())
5984}
5985
5986/// Body of one tracked fresh-offer worker: drive one key to a verdict.
5987///
5988/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
5989/// A started handler is never cancelled: `storage.put()` awaits
5990/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
5991/// transaction. Shutdown responsiveness comes from the closed worker semaphore
5992/// and from `handle_fresh_offer` racing the token around payment verification.
5993///
5994/// Works down the key's queued proofs rather than judging the key on the first
5995/// one. A proof that fails to establish payment disqualifies its *sender*, not
5996/// the record: the bytes are content-addressed and identical across every offer,
5997/// so the next sender's proof is tried against the copy already in hand — no
5998/// second payload, no second permit, no refetch. Only when a failure is about
5999/// the key itself (not responsible, no capacity, shutting down) does rotating
6000/// become pointless, because every remaining proof would meet the same wall.
6001async fn run_fresh_offer_worker(
6002    key: XorName,
6003    mut entry: Box<FreshOfferEntryGuard>,
6004    ctx: ReplicationMessageHandlerContext,
6005    admission: ResponderGuard,
6006) {
6007    // The admission permit is released on completion, freeing the payload's
6008    // memory budget and the opening source's per-peer share. The entry releases
6009    // the key itself, either as the queue empties or on drop.
6010    let _admission = admission;
6011    let received_at = entry.received_at();
6012    // Wait for a worker slot here rather than in the caller. The worker bound
6013    // caps concurrent EVM and storage pressure; making the message loop wait on
6014    // it is what put that pressure back on the loop.
6015    //
6016    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
6017    // path for offers still queued behind a worker when the engine stops — not
6018    // dead code.
6019    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
6020        .acquire_owned()
6021        .await
6022    else {
6023        debug!(
6024            "Fresh offer for {} dropped: worker pool shut down",
6025            hex::encode(key)
6026        );
6027        return;
6028    };
6029    // Fresh offers are fire-and-forget (`send_message`), so there is no
6030    // requester deadline to honour and a late store is still genuinely useful.
6031    // The threshold is the point past which the offer has already cost us what
6032    // it was going to cost: the possession check (ADR-0003) has run by then and
6033    // charged the absence to this node, and it does not re-offer the key —
6034    // repair comes later from neighbor sync. Shedding here trades a copy that
6035    // would have arrived after the penalty for the multi-MiB payload it is
6036    // holding, and keeps a backlog from outliving its own admission bound.
6037    //
6038    // Note this is a memory-pressure decision, not a redundancy one: the copy
6039    // is late, not useless, so on a node with headroom finishing it would still
6040    // beat waiting for neighbor sync.
6041    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
6042        debug!(
6043            responder_class = "fresh_offer",
6044            key = %hex::encode(key),
6045            request_age_ms = received_at.elapsed().as_millis(),
6046            "Superseded fresh offer shed at dequeue"
6047        );
6048        return;
6049    }
6050
6051    let mut verdict = FreshOfferOutcome::Abandoned;
6052    while let Some(attempt) = entry.next_attempt() {
6053        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
6054            Ok(outcome) => {
6055                verdict = outcome;
6056                match outcome {
6057                    // Settled: the record is down and every remaining sender
6058                    // wanted exactly that. Abandoned: the key cannot be placed
6059                    // by anyone right now, so the proofs behind this one would
6060                    // fail identically. Either way there is nothing left to try.
6061                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
6062                    // This sender's claim to have paid did not hold up. Say so
6063                    // to that sender alone and try the next proof.
6064                    FreshOfferOutcome::ProofRejected => {}
6065                }
6066            }
6067            Err(e) => {
6068                debug!(
6069                    "Fresh replication offer for {} from {} error: {e}",
6070                    hex::encode(key),
6071                    attempt.source
6072                );
6073                verdict = FreshOfferOutcome::Abandoned;
6074                break;
6075            }
6076        }
6077    }
6078
6079    // Answer the senders whose proofs were never reached. A stored record is
6080    // what they were asking for, so it is an acceptance even though their own
6081    // proof went untested.
6082    let unreached = entry.release();
6083    if unreached.is_empty() {
6084        return;
6085    }
6086    let response = match verdict {
6087        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
6088        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
6089            FreshReplicationResponse::Rejected {
6090                key,
6091                reason: "Record could not be stored from any offered proof".to_string(),
6092            }
6093        }
6094    };
6095    for attempt in unreached {
6096        send_replication_response(
6097            &attempt.source,
6098            &ctx.p2p_node,
6099            attempt.request_id,
6100            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
6101            attempt.rr_message_id.as_deref(),
6102        )
6103        .await;
6104    }
6105}
6106
6107/// What one proof concluded, and whether another proof for the same key is worth
6108/// trying.
6109///
6110/// The distinction the worker acts on is *what the failure was about*. A
6111/// rejected proof is a statement about its sender; anything else is a statement
6112/// about the key or this node, which no other sender's proof can change.
6113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6114enum FreshOfferOutcome {
6115    /// The record is stored. The key is done.
6116    Settled,
6117    /// This proof did not establish payment. A different sender's proof for the
6118    /// same bytes may still succeed.
6119    ProofRejected,
6120    /// Nothing about this key can succeed right now — not responsible, no disk,
6121    /// shutting down, or a write that failed. Rotating repeats the failure.
6122    Abandoned,
6123}
6124
6125// A linear sequence of protocol steps — structural recheck, responsibility,
6126// capacity, payment, write — each with its own refusal response. Splitting it
6127// would scatter one decision across several functions.
6128#[allow(clippy::too_many_lines)]
6129async fn handle_fresh_offer(
6130    key: &XorName,
6131    data: &[u8],
6132    attempt: &FreshOfferAttempt,
6133    ctx: &ReplicationMessageHandlerContext,
6134) -> Result<FreshOfferOutcome> {
6135    let source = &attempt.source;
6136    let request_id = attempt.request_id;
6137    let rr_message_id = attempt.rr_message_id.as_deref();
6138    let p2p_node = &ctx.p2p_node;
6139    let config = &ctx.config;
6140    let self_id = *p2p_node.peer_id();
6141
6142    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6143    // proof, bad proof size, oversized payload, content-address mismatch —
6144    // before opening the entry or taking an admission permit, so nothing
6145    // reaching a worker should trip them. Kept so the handler is correct in
6146    // isolation. Note this re-checks the *pairing* actually being used: these
6147    // bytes against this attempt's proof.
6148    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6149    {
6150        if rejection.penalise {
6151            warn!(
6152                "Rejecting fresh offer for key {}: {}",
6153                hex::encode(key),
6154                rejection.reason
6155            );
6156            p2p_node
6157                .report_trust_event(
6158                    source,
6159                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6160                )
6161                .await;
6162        }
6163        send_replication_response(
6164            source,
6165            p2p_node,
6166            request_id,
6167            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6168                key: *key,
6169                reason: rejection.reason,
6170            }),
6171            rr_message_id,
6172        )
6173        .await;
6174        // Structurally invalid is a fact about this attempt, not the key.
6175        return Ok(FreshOfferOutcome::ProofRejected);
6176    }
6177
6178    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6179    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6180    // the same width client PUTs use), not just the close group plus a small
6181    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6182    // table may still list closer full nodes it hasn't evicted yet, ranking it
6183    // outside the narrow window in its own view; the wider accept window absorbs
6184    // that transient skew so the chunk still lands. Retention (pruning) stays at
6185    // `storage_admission_width`, so steady-state replication is unchanged.
6186    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6187    {
6188        send_replication_response(
6189            source,
6190            p2p_node,
6191            request_id,
6192            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6193                key: *key,
6194                reason: "Not in storage-admission range for this key".to_string(),
6195            }),
6196            rr_message_id,
6197        )
6198        .await;
6199        // About the key and this node's place in the routing table, not about
6200        // the sender: every queued proof would be refused identically.
6201        return Ok(FreshOfferOutcome::Abandoned);
6202    }
6203
6204    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6205    // never store this record, so reject it before the expensive payment
6206    // verification (EVM on-chain query / merkle pool work) rather than verifying
6207    // and only then failing at `storage.put` below. Reuses the cached capacity
6208    // check (passing results only, so freed space is detected promptly), and the
6209    // store path keeps its own check as defence-in-depth.
6210    if let Err(e) = ctx.storage.check_capacity() {
6211        info!(
6212            target: "ant_node::storage::disk_precheck",
6213            key = %hex::encode(key),
6214            "Rejecting fresh replication offer before payment verification: {e}"
6215        );
6216        send_replication_response(
6217            source,
6218            p2p_node,
6219            request_id,
6220            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6221                key: *key,
6222                reason: e.to_string(),
6223            }),
6224            rr_message_id,
6225        )
6226        .await;
6227        // A full disk is this node's condition, not the sender's.
6228        return Ok(FreshOfferOutcome::Abandoned);
6229    }
6230
6231    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6232    // part of the immediate write fan-out: this receiver is about to store the
6233    // record as if the client had PUT it here directly. Storage admission
6234    // was checked above before proof work. FreshReplication verification is
6235    // identical to ClientPut — store-strength cache semantics, paid-quote
6236    // issuer K-closeness checks for single-node proofs, merkle candidate
6237    // closeness for merkle proofs, and the same price-floor policy — the
6238    // distinct context only labels price-floor telemetry.
6239    let Some(verification) = verify_payment_until_shutdown(
6240        &ctx.payment_verifier,
6241        key,
6242        &attempt.proof_of_payment,
6243        fresh_offer_payment_context(),
6244        &ctx.shutdown,
6245    )
6246    .await
6247    else {
6248        debug!(
6249            "Fresh offer for {} from {source} abandoned: engine shutting down \
6250             during payment verification",
6251            hex::encode(key)
6252        );
6253        return Ok(FreshOfferOutcome::Abandoned);
6254    };
6255    match verification {
6256        Ok(status) if status.can_store() => {
6257            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6258        }
6259        // The chain has no record of this payment. That is a statement about
6260        // *this sender's* proof, so the key rotates to the next one rather than
6261        // being written off — the whole point of queueing them.
6262        //
6263        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6264        // not "definitively unpaid", so a lagging or reorganising chain view
6265        // renders honest senders indistinguishable from forgers, and penalising
6266        // would land on the entire close group at once. The structural checks in
6267        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6268        // because those cannot be produced by an honest sender at all.
6269        Ok(_) => {
6270            debug!(
6271                "Fresh offer for {} from {source}: no payment found for this proof",
6272                hex::encode(key)
6273            );
6274            send_replication_response(
6275                source,
6276                p2p_node,
6277                request_id,
6278                ReplicationMessageBody::FreshReplicationResponse(
6279                    FreshReplicationResponse::Rejected {
6280                        key: *key,
6281                        reason: "Payment verification failed: payment required".to_string(),
6282                    },
6283                ),
6284                rr_message_id,
6285            )
6286            .await;
6287            return Ok(FreshOfferOutcome::ProofRejected);
6288        }
6289        // A verification *error* is usually ours — an unreachable or failing EVM
6290        // endpoint — so it is neither penalised nor treated as this sender's
6291        // fault. Another proof still gets its turn, since the next call may well
6292        // succeed against a recovered endpoint.
6293        Err(e) => {
6294            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6295            send_replication_response(
6296                source,
6297                p2p_node,
6298                request_id,
6299                ReplicationMessageBody::FreshReplicationResponse(
6300                    FreshReplicationResponse::Rejected {
6301                        key: *key,
6302                        reason: format!("Payment verification error: {e}"),
6303                    },
6304                ),
6305                rr_message_id,
6306            )
6307            .await;
6308            return Ok(FreshOfferOutcome::ProofRejected);
6309        }
6310    }
6311
6312    // Rule 6: add to PaidForList.
6313    if let Err(e) = ctx.paid_list.insert(key).await {
6314        warn!("Failed to add key to PaidForList: {e}");
6315    }
6316
6317    // Store the record.
6318    match ctx.storage.put(key, data).await {
6319        Ok(_) => {
6320            send_replication_response(
6321                source,
6322                p2p_node,
6323                request_id,
6324                ReplicationMessageBody::FreshReplicationResponse(
6325                    FreshReplicationResponse::Accepted { key: *key },
6326                ),
6327                rr_message_id,
6328            )
6329            .await;
6330            Ok(FreshOfferOutcome::Settled)
6331        }
6332        Err(e) => {
6333            send_replication_response(
6334                source,
6335                p2p_node,
6336                request_id,
6337                ReplicationMessageBody::FreshReplicationResponse(
6338                    FreshReplicationResponse::Rejected {
6339                        key: *key,
6340                        reason: e.to_string(),
6341                    },
6342                ),
6343                rr_message_id,
6344            )
6345            .await;
6346            // The payment was good and the write still failed, so this is local
6347            // storage trouble that another proof cannot get around.
6348            Ok(FreshOfferOutcome::Abandoned)
6349        }
6350    }
6351}
6352
6353/// Admit a paid-list notification for handling on a worker, or drop it.
6354///
6355/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6356/// meant one message could park every other non-audit message behind a full
6357/// payment verification. That verification is not a bounded local computation:
6358/// on the merkle path it performs an iterative Kademlia lookup capped only by
6359/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6360/// the loop for minutes while the bounded inbound queue behind it overflowed
6361/// and dropped unrelated replication traffic wholesale.
6362///
6363/// It now follows the same detached-responder pattern as neighbor sync and
6364/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6365/// when stale, and run on a tracked worker.
6366///
6367/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6368/// refused notify is simply dropped. The sender's own paid-list convergence
6369/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6370/// the recovery path, exactly as for a notify lost in transit.
6371async fn dispatch_paid_notify(
6372    source: PeerId,
6373    notify: protocol::PaidNotify,
6374    ctx: &ReplicationMessageHandlerContext,
6375    received_at: Instant,
6376) -> Result<()> {
6377    let admission = match admit_bounded_responder(
6378        &ctx.paid_notify_admission_semaphore,
6379        &ctx.paid_notify_responder_inflight,
6380        &source,
6381        PAID_NOTIFY_MAX_OUTSTANDING,
6382        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6383    )
6384    .await
6385    {
6386        Ok(guard) => guard,
6387        Err(failure) => {
6388            audit_metrics::record_responder_admission_drop(
6389                ReplicationResponderClass::PaidNotify,
6390                failure.reason.into(),
6391            );
6392            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6393            // so a refusal discards durable paid-list evidence outright rather
6394            // than pushing work back onto a requester.
6395            warn!(
6396                responder_class = "paid_notify",
6397                source = %source,
6398                key = %hex::encode(notify.key),
6399                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6400            );
6401            return Ok(());
6402        }
6403    };
6404
6405    let ctx = ctx.clone();
6406    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6407    // Deliberately NOT the verification request deadline used by the
6408    // request/response responders. Nobody is waiting on a notify, and shedding
6409    // one discards durable paid-list evidence rather than a reply a requester
6410    // has already given up on. The threshold is instead the point at which the
6411    // pull path would have learned the same fact anyway: one slow-cadence
6412    // neighbor-sync interval, after which the verification cycle's paid-list
6413    // quorum makes this notify genuinely redundant.
6414    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6415    ctx.detached_task_tracker.clone().spawn(async move {
6416        let _admission = admission;
6417        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6418        // still queued behind a worker when the engine stops.
6419        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6420            debug!("Paid notify from {source} dropped: worker pool shut down");
6421            return;
6422        };
6423        if request_is_stale(received_at, queue_max_age) {
6424            debug!(
6425                responder_class = "paid_notify",
6426                source = %source,
6427                request_age_ms = received_at.elapsed().as_millis(),
6428                "Redundant paid notify shed at dequeue"
6429            );
6430            return;
6431        }
6432        if let Err(e) = handle_paid_notify(
6433            &source,
6434            &notify,
6435            &ctx.paid_list,
6436            &ctx.payment_verifier,
6437            &ctx.p2p_node,
6438            &ctx.config,
6439            &ctx.shutdown,
6440        )
6441        .await
6442        {
6443            debug!("Paid notify from {source} error: {e}");
6444        }
6445    });
6446
6447    Ok(())
6448}
6449
6450async fn handle_paid_notify(
6451    _source: &PeerId,
6452    notify: &protocol::PaidNotify,
6453    paid_list: &Arc<PaidList>,
6454    payment_verifier: &Arc<PaymentVerifier>,
6455    p2p_node: &Arc<P2PNode>,
6456    config: &ReplicationConfig,
6457    shutdown: &CancellationToken,
6458) -> Result<()> {
6459    let self_id = *p2p_node.peer_id();
6460
6461    // Rule 3: validate PoP presence before adding.
6462    if notify.proof_of_payment.is_empty() {
6463        return Ok(());
6464    }
6465
6466    // Check if we're in PaidCloseGroup for this key.
6467    if !admission::is_in_paid_close_group(
6468        &self_id,
6469        &notify.key,
6470        p2p_node,
6471        config.paid_list_close_group_size,
6472    )
6473    .await
6474    {
6475        return Ok(());
6476    }
6477
6478    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6479    // paid-list metadata, so local paid-list close-group membership was checked
6480    // above before proof work. The verifier then runs the same payment proof
6481    // checks as ClientPut while writing a paid-list-strength cache entry.
6482    let Some(verification) = verify_payment_until_shutdown(
6483        payment_verifier,
6484        &notify.key,
6485        &notify.proof_of_payment,
6486        paid_notify_payment_context(),
6487        shutdown,
6488    )
6489    .await
6490    else {
6491        debug!(
6492            "Paid notify for {} abandoned: engine shutting down during payment \
6493             verification",
6494            hex::encode(notify.key)
6495        );
6496        return Ok(());
6497    };
6498    match verification {
6499        Ok(status) if status.can_store() => {
6500            debug!(
6501                "PoP validated for paid notify key {}",
6502                hex::encode(notify.key)
6503            );
6504        }
6505        Ok(_) => {
6506            warn!(
6507                "Paid notify rejected: payment required for key {}",
6508                hex::encode(notify.key)
6509            );
6510            return Ok(());
6511        }
6512        Err(e) => {
6513            warn!(
6514                "PoP verification error for paid notify key {}: {e}",
6515                hex::encode(notify.key)
6516            );
6517            return Ok(());
6518        }
6519    }
6520
6521    if let Err(e) = paid_list.insert(&notify.key).await {
6522        warn!("Failed to add paid notify key to PaidForList: {e}");
6523    }
6524
6525    Ok(())
6526}
6527
6528#[allow(clippy::too_many_arguments)]
6529async fn dispatch_neighbor_sync_request(
6530    source: PeerId,
6531    request: protocol::NeighborSyncRequest,
6532    ctx: &ReplicationMessageHandlerContext,
6533    is_bootstrapping: bool,
6534    my_commitment: Option<StorageCommitment>,
6535    request_id: u64,
6536    received_at: Instant,
6537    rr_message_id: Option<&str>,
6538) -> Result<()> {
6539    // A peer syncing with us gets our pointer hints as well — including a
6540    // node that is bootstrapping, which is how it learns the pointers it
6541    // should hold.
6542    if let Some(pointers) = &ctx.pointers {
6543        pointers.push_hints_detached(vec![source]);
6544    }
6545    let guard = match admit_bounded_responder(
6546        &ctx.neighbor_sync_responder_admission_semaphore,
6547        &ctx.neighbor_sync_responder_inflight,
6548        &source,
6549        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6550        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6551    )
6552    .await
6553    {
6554        Ok(guard) => guard,
6555        Err(failure) => {
6556            audit_metrics::record_responder_admission_drop(
6557                ReplicationResponderClass::NeighborSync,
6558                failure.reason.into(),
6559            );
6560            warn!(
6561                responder_class = "neighbor_sync",
6562                source = %source,
6563                "Neighbor-sync response dropped at admission: {failure}"
6564            );
6565            return Ok(());
6566        }
6567    };
6568
6569    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6570    let p2p_node = Arc::clone(&ctx.p2p_node);
6571    let storage = Arc::clone(&ctx.storage);
6572    let paid_list = Arc::clone(&ctx.paid_list);
6573    let queues = Arc::clone(&ctx.queues);
6574    let config = Arc::clone(&ctx.config);
6575    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6576    let sync_history = Arc::clone(&ctx.sync_history);
6577    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6578    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6579    let request_timeout = ctx.config.verification_request_timeout;
6580    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6581    ctx.detached_task_tracker.spawn(async move {
6582        let _guard = guard;
6583        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6584            debug!(
6585                responder_class = "neighbor_sync",
6586                source = %source,
6587                "Neighbor-sync responder worker pool closed before dequeue"
6588            );
6589            return;
6590        };
6591        if request_is_stale(received_at, request_timeout) {
6592            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6593            debug!(
6594                responder_class = "neighbor_sync",
6595                source = %source,
6596                request_age_ms = received_at.elapsed().as_millis(),
6597                "Stale neighbor-sync request shed at dequeue"
6598            );
6599            return;
6600        }
6601        if let Err(e) = handle_neighbor_sync_request(
6602            &source,
6603            &request,
6604            &p2p_node,
6605            &storage,
6606            &paid_list,
6607            &queues,
6608            &config,
6609            is_bootstrapping,
6610            &bootstrap_state,
6611            &sync_history,
6612            &sync_cycle_epoch,
6613            &repair_proofs,
6614            my_commitment,
6615            request_id,
6616            rr_message_id.as_deref(),
6617        )
6618        .await
6619        {
6620            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6621        }
6622    });
6623
6624    Ok(())
6625}
6626
6627#[allow(clippy::too_many_arguments)]
6628async fn handle_neighbor_sync_request(
6629    source: &PeerId,
6630    request: &protocol::NeighborSyncRequest,
6631    p2p_node: &Arc<P2PNode>,
6632    storage: &Arc<ChunkStore>,
6633    paid_list: &Arc<PaidList>,
6634    queues: &Arc<RwLock<ReplicationQueues>>,
6635    config: &ReplicationConfig,
6636    is_bootstrapping: bool,
6637    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6638    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6639    sync_cycle_epoch: &Arc<RwLock<u64>>,
6640    repair_proofs: &Arc<RwLock<RepairProofs>>,
6641    my_commitment: Option<StorageCommitment>,
6642    request_id: u64,
6643    rr_message_id: Option<&str>,
6644) -> Result<()> {
6645    let self_id = *p2p_node.peer_id();
6646
6647    // No per-request hint count limit: the wire message size limit
6648    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6649    // challenges, sync hints don't drive expensive computation — they just
6650    // enter the verification queue. A per-request limit here would break
6651    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6652
6653    // Build response (outbound hints).
6654    let (response, sent_replica_hints, sender_in_rt) =
6655        neighbor_sync::handle_sync_request_with_proofs(
6656            source,
6657            request,
6658            p2p_node,
6659            storage,
6660            paid_list,
6661            config,
6662            is_bootstrapping,
6663            my_commitment.clone(),
6664        )
6665        .await;
6666
6667    // Send response.
6668    let response_sent = send_replication_response_checked(
6669        source,
6670        p2p_node,
6671        request_id,
6672        ReplicationMessageBody::NeighborSyncResponse(response),
6673        rr_message_id,
6674        None,
6675    )
6676    .await;
6677
6678    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6679    if !sender_in_rt {
6680        return Ok(());
6681    }
6682
6683    // Update sync history for this peer before recording repair proofs so a
6684    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6685    {
6686        let mut history = sync_history.write().await;
6687        let record = history.entry(*source).or_insert(PeerSyncRecord {
6688            last_sync: None,
6689            cycles_since_sync: 0,
6690        });
6691        record.last_sync = Some(Instant::now());
6692        record.cycles_since_sync = 0;
6693    }
6694
6695    if response_sent && !request.bootstrapping {
6696        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6697            .await;
6698    }
6699
6700    // Admit inbound hints and queue for verification.
6701    let outcome = admit_and_queue_hints(
6702        &self_id,
6703        source,
6704        &request.replica_hints,
6705        &request.paid_hints,
6706        p2p_node,
6707        config,
6708        storage,
6709        paid_list,
6710        queues,
6711    )
6712    .await;
6713
6714    // Track discovered keys for bootstrap drain detection so that hints
6715    // admitted via inbound sync requests are not missed. Capacity-rejected
6716    // hints keep this source on the "not yet drained" list until its next
6717    // sync re-admits them; a clean cycle clears the source.
6718    if is_bootstrapping {
6719        let live_discovered = outcome.discovered.clone();
6720        let outcomes = [(*source, outcome)];
6721        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6722    }
6723
6724    Ok(())
6725}
6726
6727/// Test-only record of who *sent* a verification request covering a watched key.
6728///
6729/// The capacity gate's entire effect is a request that is never sent, and a
6730/// request that was not sent leaves no production counter anywhere — not on the
6731/// sender, whose traffic counters are process-global and so cannot separate one
6732/// node of a single-process testnet from another, and not on the responder,
6733/// which simply never hears from it. Recording who asked is what lets a test
6734/// tell "held the key back" apart from "probed the close group, was refused at
6735/// the dial, and then held the key back", which are otherwise identical from the
6736/// queue's point of view.
6737///
6738/// Arming replaces the previous watch, so the outer map holds exactly the keys
6739/// the current test named, and each inner map holds at most one entry per node
6740/// in the process. Nothing is recorded until a test arms it, and the armed path
6741/// costs one read lock on the sending side.
6742///
6743/// Counting is per key because a node that cannot write legitimately keeps
6744/// sending verification requests for keys it has not yet authorized — that is
6745/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
6746/// would assert something untrue.
6747///
6748/// It counts *send attempts*, deliberately, recorded immediately before the wire
6749/// call. A responder sheds requests at admission and as stale, so a
6750/// receiver-side count would report zero for probes that were really sent, and
6751/// an assertion that this node asked nobody would pass on the strength of the
6752/// receiver dropping the question. It is not proof of delivery: a send that
6753/// fails immediately, with no route or during shutdown, is still counted.
6754///
6755/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
6756/// MSRV.
6757#[cfg(any(test, feature = "test-utils"))]
6758type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
6759
6760#[cfg(any(test, feature = "test-utils"))]
6761static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
6762    std::sync::OnceLock::new();
6763
6764#[cfg(any(test, feature = "test-utils"))]
6765fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
6766    VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
6767}
6768
6769/// Test-only: start counting verification requests for `keys`, from zero.
6770///
6771/// Replaces any previous watch rather than adding to it, so the map is bounded
6772/// by the keys of the test that armed it last and nothing accumulates across a
6773/// process running many tests.
6774#[cfg(any(test, feature = "test-utils"))]
6775pub fn watch_verification_requests_for_test(keys: &[XorName]) {
6776    if let Ok(mut watch) = verification_watch().write() {
6777        watch.clear();
6778        for key in keys {
6779            watch.insert(*key, HashMap::new());
6780        }
6781    }
6782}
6783
6784/// Record that `requester` sent a verification request covering `keys`, for
6785/// whichever of them are watched. A poisoned lock is ignored rather than
6786/// propagated: this is observation for tests and must never change behaviour.
6787#[cfg(any(test, feature = "test-utils"))]
6788pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
6789    // Fast path under a read lock: with nothing watched — every production
6790    // build, and every test that did not ask — this is all the sender pays.
6791    match verification_watch().read() {
6792        Ok(watch) if watch.is_empty() => return,
6793        Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
6794        Ok(_) => {}
6795        Err(_) => return,
6796    }
6797    if let Ok(mut watch) = verification_watch().write() {
6798        for key in keys {
6799            if let Some(by_peer) = watch.get_mut(key) {
6800                *by_peer.entry(*requester).or_insert(0) += 1;
6801            }
6802        }
6803    }
6804}
6805
6806/// Test-only: how many times `requester` has asked this process about `key`.
6807/// Zero unless the key was registered with `watch_verification_requests_for_test`.
6808#[cfg(any(test, feature = "test-utils"))]
6809#[must_use]
6810pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
6811    verification_watch().read().map_or(0, |watch| {
6812        watch
6813            .get(key)
6814            .and_then(|by_peer| by_peer.get(requester))
6815            .copied()
6816            .unwrap_or(0)
6817    })
6818}
6819
6820async fn handle_verification_request(
6821    source: &PeerId,
6822    request: &protocol::VerificationRequest,
6823    storage: &Arc<ChunkStore>,
6824    paid_list: &Arc<PaidList>,
6825    p2p_node: &Arc<P2PNode>,
6826    request_id: u64,
6827    rr_message_id: Option<&str>,
6828) -> Result<()> {
6829    #[derive(Clone, Copy)]
6830    enum CachedPaidLookup {
6831        NotChecked,
6832        Checked(Option<bool>),
6833    }
6834
6835    #[derive(Clone, Copy)]
6836    struct CachedVerificationLookup {
6837        present: Option<bool>,
6838        paid: CachedPaidLookup,
6839    }
6840
6841    if verification_request_exceeds_limit(request.keys.len()) {
6842        warn!(
6843            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
6844            request.keys.len(),
6845        );
6846        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6847        return Ok(());
6848    }
6849
6850    let requested_keys = request.keys.as_slice();
6851
6852    if request.paid_list_check_indices.len() > request.keys.len() {
6853        warn!(
6854            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
6855            request.paid_list_check_indices.len(),
6856            request.keys.len(),
6857        );
6858        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
6859        return Ok(());
6860    }
6861
6862    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
6863    let paid_check_set: HashSet<u32> = request
6864        .paid_list_check_indices
6865        .iter()
6866        .copied()
6867        .filter(|&idx| {
6868            if idx >= keys_len {
6869                warn!(
6870                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
6871                    requested_keys.len(),
6872                );
6873                false
6874            } else {
6875                true
6876            }
6877        })
6878        .collect();
6879
6880    let mut results = Vec::with_capacity(requested_keys.len());
6881    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
6882    for (i, key) in requested_keys.iter().enumerate() {
6883        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
6884        let cached = lookup_cache.entry(*key).or_insert_with(|| {
6885            let present = match storage.exists(key) {
6886                Ok(present) => Some(present),
6887                Err(e) => {
6888                    warn!(
6889                        "Verification request from {source}: failed to check storage for {}: {e}",
6890                        hex::encode(key)
6891                    );
6892                    None
6893                }
6894            };
6895            CachedVerificationLookup {
6896                present,
6897                paid: CachedPaidLookup::NotChecked,
6898            }
6899        });
6900
6901        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
6902            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
6903                Ok(paid) => Some(paid),
6904                Err(e) => {
6905                    warn!(
6906                        "Verification request from {source}: failed to check paid-list for {}: {e}",
6907                        hex::encode(key)
6908                    );
6909                    None
6910                }
6911            });
6912        }
6913
6914        let paid = if needs_paid {
6915            match cached.paid {
6916                CachedPaidLookup::Checked(paid) => paid,
6917                CachedPaidLookup::NotChecked => None,
6918            }
6919        } else {
6920            None
6921        };
6922
6923        if cached.present.is_none() && paid.is_none() {
6924            continue;
6925        }
6926
6927        results.push(protocol::KeyVerificationResult {
6928            key: *key,
6929            present: cached.present.unwrap_or(false),
6930            paid,
6931        });
6932    }
6933
6934    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
6935
6936    Ok(())
6937}
6938
6939async fn dispatch_verification_request(
6940    source: PeerId,
6941    request: protocol::VerificationRequest,
6942    ctx: &ReplicationMessageHandlerContext,
6943    request_id: u64,
6944    received_at: Instant,
6945    rr_message_id: Option<&str>,
6946) -> Result<()> {
6947    let guard = match admit_bounded_responder(
6948        &ctx.verification_responder_admission_semaphore,
6949        &ctx.verification_responder_inflight,
6950        &source,
6951        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
6952        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6953    )
6954    .await
6955    {
6956        Ok(guard) => guard,
6957        Err(failure) => {
6958            audit_metrics::record_responder_admission_drop(
6959                ReplicationResponderClass::Verification,
6960                failure.reason.into(),
6961            );
6962            warn!(
6963                responder_class = "verification",
6964                source = %source,
6965                "Verification response dropped at admission: {failure}"
6966            );
6967            return Ok(());
6968        }
6969    };
6970
6971    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
6972    let storage = Arc::clone(&ctx.storage);
6973    let paid_list = Arc::clone(&ctx.paid_list);
6974    let p2p_node = Arc::clone(&ctx.p2p_node);
6975    let request_timeout = ctx.config.verification_request_timeout;
6976    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6977    ctx.detached_task_tracker.spawn(async move {
6978        let _guard = guard;
6979        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6980            debug!(
6981                responder_class = "verification",
6982                source = %source,
6983                "Verification responder worker pool closed before dequeue"
6984            );
6985            return;
6986        };
6987        if request_is_stale(received_at, request_timeout) {
6988            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
6989            debug!(
6990                responder_class = "verification",
6991                source = %source,
6992                request_age_ms = received_at.elapsed().as_millis(),
6993                "Stale verification request shed at dequeue"
6994            );
6995            return;
6996        }
6997        if let Err(e) = handle_verification_request(
6998            &source,
6999            &request,
7000            &storage,
7001            &paid_list,
7002            &p2p_node,
7003            request_id,
7004            rr_message_id.as_deref(),
7005        )
7006        .await
7007        {
7008            debug!(source = %source, "Verification request handling failed: {e}");
7009        }
7010    });
7011
7012    Ok(())
7013}
7014
7015const fn verification_request_exceeds_limit(key_count: usize) -> bool {
7016    key_count > MAX_INCOMING_VERIFICATION_KEYS
7017}
7018
7019async fn send_verification_results(
7020    source: &PeerId,
7021    p2p_node: &Arc<P2PNode>,
7022    request_id: u64,
7023    results: Vec<protocol::KeyVerificationResult>,
7024    rr_message_id: Option<&str>,
7025) {
7026    send_replication_response(
7027        source,
7028        p2p_node,
7029        request_id,
7030        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
7031        rr_message_id,
7032    )
7033    .await;
7034}
7035
7036async fn dispatch_fetch_request(
7037    source: PeerId,
7038    request: protocol::FetchRequest,
7039    ctx: &ReplicationMessageHandlerContext,
7040    request_id: u64,
7041    received_at: Instant,
7042    rr_message_id: Option<&str>,
7043) -> Result<()> {
7044    let guard = match admit_bounded_responder(
7045        &ctx.fetch_responder_admission_semaphore,
7046        &ctx.fetch_responder_inflight,
7047        &source,
7048        FETCH_RESPONDER_MAX_OUTSTANDING,
7049        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7050    )
7051    .await
7052    {
7053        Ok(guard) => guard,
7054        Err(failure) => {
7055            audit_metrics::record_responder_admission_drop(
7056                ReplicationResponderClass::Fetch,
7057                failure.reason.into(),
7058            );
7059            warn!(
7060                responder_class = "fetch",
7061                source = %source,
7062                "Fetch response dropped at admission: {failure}"
7063            );
7064            return Ok(());
7065        }
7066    };
7067
7068    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
7069    let storage = Arc::clone(&ctx.storage);
7070    let p2p_node = Arc::clone(&ctx.p2p_node);
7071    let request_timeout = ctx.config.fetch_request_timeout;
7072    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7073    ctx.detached_task_tracker.spawn(async move {
7074        let _guard = guard;
7075        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7076            debug!(
7077                responder_class = "fetch",
7078                source = %source,
7079                "Fetch responder worker pool closed before dequeue"
7080            );
7081            return;
7082        };
7083        if request_is_stale(received_at, request_timeout) {
7084            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
7085            debug!(
7086                responder_class = "fetch",
7087                source = %source,
7088                request_age_ms = received_at.elapsed().as_millis(),
7089                "Stale fetch request shed at dequeue"
7090            );
7091            return;
7092        }
7093        if let Err(e) = handle_fetch_request(
7094            &source,
7095            &request,
7096            &storage,
7097            &p2p_node,
7098            request_id,
7099            rr_message_id.as_deref(),
7100        )
7101        .await
7102        {
7103            debug!(source = %source, "Fetch request handling failed: {e}");
7104        }
7105    });
7106
7107    Ok(())
7108}
7109
7110fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
7111    received_at.elapsed() >= timeout
7112}
7113
7114/// How a fetch responder's answer is charged against its reputation.
7115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7116enum FetchFault {
7117    /// The peer does not hold a chunk it was expected to hold.
7118    ///
7119    /// This is the lane the release withholds, because a node part-way through moving
7120    /// off the legacy store answers exactly this way about chunks it has legitimately
7121    /// given up.
7122    UnheldChunk,
7123    /// The peer's own storage failed, or served bytes that no longer hash to their
7124    /// address.
7125    ///
7126    /// Never withheld. `FetchResponse::Error` has one producer, and it is the responder's
7127    /// storage read returning an error: an I/O fault, an exhausted descriptor table, or a
7128    /// failed integrity check. A peer that merely does not hold the chunk answers
7129    /// `NotFound` instead, so nothing about the migration produces this.
7130    ResponderFault,
7131}
7132
7133/// Classify a fetch response that did not carry the chunk.
7134///
7135/// `Success` yields `None`. Every other answer is a fault of one kind or the other, and
7136/// which kind decides whether this release charges for it.
7137fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
7138    match response {
7139        protocol::FetchResponse::Success { .. } => None,
7140        protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
7141        protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
7142    }
7143}
7144
7145/// Charge a fetch fault to the responder.
7146///
7147/// The only place the two kinds are treated differently. An unheld chunk goes through the
7148/// release switch, which is currently withholding it; a responder fault is charged
7149/// directly and is not affected by the switch at all.
7150async fn charge_fetch_fault(
7151    p2p_node: &Arc<P2PNode>,
7152    source: &PeerId,
7153    fault: FetchFault,
7154    lane: &'static str,
7155) {
7156    match fault {
7157        FetchFault::UnheldChunk => {
7158            config::penalise_unheld_close_group_chunk(
7159                p2p_node,
7160                source,
7161                lane,
7162                REPLICATION_TRUST_WEIGHT,
7163            )
7164            .await;
7165        }
7166        FetchFault::ResponderFault => {
7167            p2p_node
7168                .report_trust_event(
7169                    source,
7170                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7171                )
7172                .await;
7173        }
7174    }
7175}
7176
7177/// Turn the responder's storage read into the answer it sends back.
7178///
7179/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7180/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7181/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7182/// Nothing about a node giving chunks up produces the second.
7183fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7184    match read {
7185        Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7186        Ok(None) => protocol::FetchResponse::NotFound { key },
7187        Err(e) => protocol::FetchResponse::Error {
7188            key,
7189            reason: format!("{e}"),
7190        },
7191    }
7192}
7193
7194async fn handle_fetch_request(
7195    source: &PeerId,
7196    request: &protocol::FetchRequest,
7197    storage: &Arc<ChunkStore>,
7198    p2p_node: &Arc<P2PNode>,
7199    request_id: u64,
7200    rr_message_id: Option<&str>,
7201) -> Result<()> {
7202    let response = fetch_response_for(request.key, storage.get(&request.key).await);
7203
7204    send_replication_response(
7205        source,
7206        p2p_node,
7207        request_id,
7208        ReplicationMessageBody::FetchResponse(response),
7209        rr_message_id,
7210    )
7211    .await;
7212
7213    Ok(())
7214}
7215
7216/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7217/// the prune-confirmation audit, which reuses the same wire message): reply with
7218/// per-key possession digests.
7219struct AuditResponderCompletion {
7220    response_kind: &'static str,
7221    sent: bool,
7222    processing: Duration,
7223    response_send: Duration,
7224}
7225
7226async fn handle_audit_challenge_msg(
7227    source: &PeerId,
7228    challenge: &protocol::AuditChallenge,
7229    storage: &Arc<ChunkStore>,
7230    p2p_node: &Arc<P2PNode>,
7231    is_bootstrapping: bool,
7232    reply: ReplyRoute<'_>,
7233) -> Result<AuditResponderCompletion> {
7234    #[allow(clippy::cast_possible_truncation)]
7235    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7236    info!(
7237        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7238        challenge.keys.len(),
7239        is_bootstrapping,
7240        reply.rr_message_id.is_some(),
7241    );
7242
7243    let processing_started = Instant::now();
7244    let response = audit::handle_audit_challenge(
7245        challenge,
7246        storage,
7247        p2p_node.peer_id(),
7248        is_bootstrapping,
7249        stored_chunks,
7250    )
7251    .await;
7252    let processing = processing_started.elapsed();
7253    let response_kind = audit_response_kind(&response);
7254
7255    let response_send_started = Instant::now();
7256    let sent = send_replication_response_checked(
7257        source,
7258        p2p_node,
7259        reply.request_id,
7260        ReplicationMessageBody::AuditResponse(response),
7261        reply.rr_message_id,
7262        Some(reply.protocol),
7263    )
7264    .await;
7265    let response_send = response_send_started.elapsed();
7266
7267    Ok(AuditResponderCompletion {
7268        response_kind,
7269        sent,
7270        processing,
7271        response_send,
7272    })
7273}
7274
7275#[allow(clippy::too_many_arguments)]
7276fn log_audit_responder_completion(
7277    metrics: &AuditResponderMetrics,
7278    source: PeerId,
7279    class: AuditResponderClass,
7280    kind: &'static str,
7281    challenge_id: u64,
7282    work_items: usize,
7283    response_kind: &'static str,
7284    sent: bool,
7285    received_at: Instant,
7286    worker_started: Instant,
7287    processing: Duration,
7288    response_send: Duration,
7289) {
7290    let dispatch = worker_started.saturating_duration_since(received_at);
7291    let total = received_at.elapsed();
7292    metrics.record_completed(source, processing, total, sent);
7293    if sent {
7294        info!(
7295            target: "ant_node::replication::audit_responder",
7296            event = "completed",
7297            kind,
7298            responder_class = class.as_str(),
7299            source = %source,
7300            challenge_id,
7301            work_items,
7302            response = response_kind,
7303            sent,
7304            dispatch_ms = dispatch.as_millis(),
7305            processing_ms = processing.as_millis(),
7306            response_send_ms = response_send.as_millis(),
7307            total_ms = total.as_millis(),
7308            "Audit responder request completed"
7309        );
7310    } else {
7311        warn!(
7312            target: "ant_node::replication::audit_responder",
7313            event = "completed",
7314            kind,
7315            responder_class = class.as_str(),
7316            source = %source,
7317            challenge_id,
7318            work_items,
7319            response = response_kind,
7320            sent,
7321            dispatch_ms = dispatch.as_millis(),
7322            processing_ms = processing.as_millis(),
7323            response_send_ms = response_send.as_millis(),
7324            total_ms = total.as_millis(),
7325            "Audit responder request completed without sending a reply"
7326        );
7327    }
7328}
7329
7330/// Where a reply goes and how it is addressed.
7331///
7332/// Grouped because the audit responder needs all three together and one of them
7333/// is not derivable from the body: during the rollout window a possession reply
7334/// may have to go out on the core id rather than its family's own (see
7335/// [`is_legacy_possession_challenge`]).
7336struct ReplyRoute<'a> {
7337    /// Correlates the reply with the challenge, at the replication layer.
7338    request_id: u64,
7339    /// Present when the challenge arrived over request-response, in which case
7340    /// the reply rides the same exchange back.
7341    rr_message_id: Option<&'a str>,
7342    /// The protocol id to answer on.
7343    protocol: &'static str,
7344}
7345
7346fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7347    match response {
7348        protocol::AuditResponse::Digests { .. } => "digests",
7349        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7350        protocol::AuditResponse::Rejected { .. } => "rejected",
7351    }
7352}
7353
7354fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7355    match response {
7356        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7357        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7358        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7359    }
7360}
7361
7362fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7363    match response {
7364        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7365        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7366        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7367    }
7368}
7369
7370fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7371    match response {
7372        protocol::SubtreeSliceResponse::Items { .. } => "items",
7373        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7374        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7375    }
7376}
7377
7378fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7379    match response {
7380        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7381        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7382    }
7383}
7384
7385// ---------------------------------------------------------------------------
7386// Message sending helper
7387// ---------------------------------------------------------------------------
7388
7389/// Send a replication response message as a best-effort reply.
7390///
7391/// Encode and send failures are logged by the checked helper. Most response
7392/// paths do not need to branch on send success, so this wrapper keeps those
7393/// call sites explicit about their best-effort behavior.
7394async fn send_replication_response(
7395    peer: &PeerId,
7396    p2p_node: &Arc<P2PNode>,
7397    request_id: u64,
7398    body: ReplicationMessageBody,
7399    rr_message_id: Option<&str>,
7400) {
7401    let _ =
7402        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7403            .await;
7404}
7405
7406/// Send a replication response message and report whether it was accepted.
7407///
7408/// Returns `true` after the message is encoded and accepted by the P2P send
7409/// path. Returns `false` after logging an encode or send failure. Repair-proof
7410/// recording uses this to avoid trusting hints that were not actually sent.
7411///
7412/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7413/// request-response path so saorsa-core can route it back to the caller's
7414/// `send_request` future. Otherwise it is sent as a plain message.
7415///
7416/// `protocol` overrides the id the body would route on by family. Exactly one
7417/// caller needs it: a possession challenge from a peer that predates the family
7418/// split has to be answered where it was asked (see
7419/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7420/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7421async fn send_replication_response_checked(
7422    peer: &PeerId,
7423    p2p_node: &Arc<P2PNode>,
7424    request_id: u64,
7425    body: ReplicationMessageBody,
7426    rr_message_id: Option<&str>,
7427    protocol: Option<&'static str>,
7428) -> bool {
7429    let msg = ReplicationMessage { request_id, body };
7430    let encoded = match msg.encode() {
7431        Ok(data) => data,
7432        Err(e) => {
7433            warn!("Failed to encode replication response: {e}");
7434            return false;
7435        }
7436    };
7437    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7438    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7439    // included for completeness. Other response variants (verification/audit/
7440    // commitment) are intentionally excluded — the round-2 audit reply is now a
7441    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7442    if matches!(
7443        msg.body,
7444        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7445    ) {
7446        protocol::record_served(peer, encoded.len());
7447    }
7448    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7449    let result = if let Some(msg_id) = rr_message_id {
7450        p2p_node
7451            .send_response(peer, protocol, msg_id, encoded)
7452            .await
7453    } else {
7454        p2p_node.send_message(peer, protocol, encoded, &[]).await
7455    };
7456    if let Err(e) = result {
7457        debug!("Failed to send replication response to {peer}: {e}");
7458        return false;
7459    }
7460    true
7461}
7462
7463async fn record_sent_replica_hints(
7464    peer: &PeerId,
7465    hints: &[neighbor_sync::SentReplicaHint],
7466    repair_proofs: &Arc<RwLock<RepairProofs>>,
7467    sync_cycle_epoch: &Arc<RwLock<u64>>,
7468) {
7469    if hints.is_empty() {
7470        return;
7471    }
7472
7473    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7474    let mut proofs = repair_proofs.write().await;
7475    for hint in hints {
7476        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7477            debug!(
7478                "Recorded repair hint proof for peer {peer} and key {}",
7479                hex::encode(hint.key)
7480            );
7481        }
7482    }
7483}
7484
7485// ---------------------------------------------------------------------------
7486// Neighbor sync round
7487// ---------------------------------------------------------------------------
7488
7489/// Run one neighbor sync round.
7490#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7491async fn run_neighbor_sync_round(
7492    p2p_node: &Arc<P2PNode>,
7493    storage: &Arc<ChunkStore>,
7494    paid_list: &Arc<PaidList>,
7495    queues: &Arc<RwLock<ReplicationQueues>>,
7496    config: &ReplicationConfig,
7497    sync_state: &Arc<RwLock<NeighborSyncState>>,
7498    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7499    sync_cycle_epoch: &Arc<RwLock<u64>>,
7500    repair_proofs: &Arc<RwLock<RepairProofs>>,
7501    is_bootstrapping: &Arc<RwLock<bool>>,
7502    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7503    commitment_state: &Arc<ResponderCommitmentState>,
7504    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7505    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7506    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7507    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7508    gossip_audit: &GossipAuditTrigger,
7509    pointers: Option<&Arc<pointer::PointerReplication>>,
7510) {
7511    let self_id = *p2p_node.peer_id();
7512    let bootstrapping = *is_bootstrapping.read().await;
7513
7514    // Check if cycle is complete; start new one if needed.
7515    // We check under a read lock, then release it before the expensive
7516    // prune pass and DHT snapshot so other tasks are not starved.
7517    let cycle_complete = sync_state.read().await.is_cycle_complete();
7518    if cycle_complete {
7519        // A completed local neighbor-sync cycle advances the epoch component
7520        // of repair-proof maturity. The per-key wall-clock minimum age is
7521        // checked when audits are selected.
7522        {
7523            let mut history = sync_history.write().await;
7524            for record in history.values_mut() {
7525                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7526            }
7527        }
7528        {
7529            let mut epoch = sync_cycle_epoch.write().await;
7530            *epoch = epoch.saturating_add(1);
7531        }
7532
7533        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7534        // Prune candidacy is unconditional once the hysteresis elapses;
7535        // bootstrap state only defers the remote prune-confirmation audits
7536        // until bootstrap has drained.
7537        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7538        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7539            self_id: &self_id,
7540            storage,
7541            paid_list,
7542            p2p_node,
7543            config,
7544            sync_state,
7545            repair_proofs,
7546            allow_remote_prune_audits,
7547            commitment_state: Some(commitment_state),
7548            audit_challenge_coordinator,
7549        })
7550        .await;
7551        if let Some(pointers) = pointers {
7552            pointers
7553                .prune_pass(allow_remote_prune_audits, Some(commitment_state))
7554                .await;
7555        }
7556
7557        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7558        let neighbors =
7559            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7560                .await;
7561
7562        // Now re-acquire write lock and re-check before swapping cycle.
7563        let mut state = sync_state.write().await;
7564        if state.is_cycle_complete() {
7565            // Preserve cooldown and bootstrap-claim tracking across cycles.
7566            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7567            // would reset the abuse detection timer every cycle.
7568            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7569            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7570            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7571            let old_prune_cursor = state.prune_cursor;
7572            *state = NeighborSyncState::new_cycle(neighbors);
7573            state.last_sync_times = old_sync_times;
7574            state.bootstrap_claims = old_bootstrap_claims;
7575            state.bootstrap_claim_history = old_bootstrap_claim_history;
7576            state.prune_cursor = old_prune_cursor;
7577        }
7578    }
7579
7580    // Select batch of peers.
7581    let batch = {
7582        let mut state = sync_state.write().await;
7583        neighbor_sync::select_sync_batch(
7584            &mut state,
7585            config.neighbor_sync_peer_count,
7586            config.neighbor_sync_cooldown,
7587        )
7588    };
7589
7590    if batch.is_empty() {
7591        return;
7592    }
7593
7594    debug!("Neighbor sync: syncing with {} peers", batch.len());
7595    if let Some(pointers) = pointers {
7596        pointers.push_hints_detached(batch.clone());
7597    }
7598
7599    // Snapshot our current commitment once per round so all peers in
7600    // this batch see the same thing (gossip is the responder's attestation;
7601    // same value across the batch is fine and reduces RwLock churn). Atomically
7602    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7603    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7604    let gossiped = commitment_state.current_for_gossip();
7605    // The hash actually put on the wire, captured with the payload. A rotation later in
7606    // the round must not let a reply be credited to a root the peer never saw.
7607    let gossiped_hash = gossiped.as_ref().map(|b| b.hash());
7608    let my_commitment = gossiped.map(|b| b.commitment().clone());
7609
7610    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7611        &batch,
7612        storage,
7613        paid_list,
7614        p2p_node,
7615        config.close_group_size,
7616        config.paid_list_close_group_size,
7617    )
7618    .await;
7619
7620    // Sync with each peer in the batch.
7621    for peer in &batch {
7622        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7623        let outcome = neighbor_sync::sync_with_peer_with_hints(
7624            peer,
7625            p2p_node,
7626            config,
7627            bootstrapping,
7628            hints,
7629            my_commitment.clone(),
7630        )
7631        .await;
7632
7633        if let Some(outcome) = outcome {
7634            // The peer answered, so the request that carried our commitment root arrived.
7635            // That is proof of delivery rather than proof of emission, and the storage
7636            // migration will not let a node give anything up until its close group has
7637            // actually seen the reduced root.
7638            if let Some(hash) = gossiped_hash {
7639                commitment_state.note_commitment_delivered(*peer, hash);
7640            }
7641            handle_sync_response(
7642                &self_id,
7643                peer,
7644                &outcome.response,
7645                &outcome.sent_replica_hints,
7646                p2p_node,
7647                config,
7648                bootstrapping,
7649                bootstrap_state,
7650                storage,
7651                paid_list,
7652                queues,
7653                sync_state,
7654                sync_history,
7655                sync_cycle_epoch,
7656                repair_proofs,
7657                last_commitment_by_peer,
7658                ever_capable_peers,
7659                sig_verify_attempts,
7660                gossip_audit,
7661            )
7662            .await;
7663        } else {
7664            // Sync failed -- remove peer and try to fill slot.
7665            let replacement = {
7666                let mut state = sync_state.write().await;
7667                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7668            };
7669
7670            // Attempt sync with the replacement peer (if one was found).
7671            if let Some(replacement_peer) = replacement {
7672                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7673                    std::slice::from_ref(&replacement_peer),
7674                    storage,
7675                    paid_list,
7676                    p2p_node,
7677                    config.close_group_size,
7678                    config.paid_list_close_group_size,
7679                )
7680                .await;
7681                let hints = replacement_hints
7682                    .remove(&replacement_peer)
7683                    .unwrap_or_default();
7684                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7685                    &replacement_peer,
7686                    p2p_node,
7687                    config,
7688                    bootstrapping,
7689                    hints,
7690                    my_commitment.clone(),
7691                )
7692                .await;
7693
7694                if let Some(outcome) = replacement_outcome {
7695                    // Same payload, same round trip, same proof: a reply can only come
7696                    // back if the request carrying the root reached this peer. Omitting it
7697                    // here made the counter under-report on any node whose primary syncs
7698                    // often fall through to a replacement, which is exactly the node most
7699                    // likely to be short of disk, and stalled its migration indefinitely.
7700                    if let Some(hash) = gossiped_hash {
7701                        commitment_state.note_commitment_delivered(replacement_peer, hash);
7702                    }
7703                    handle_sync_response(
7704                        &self_id,
7705                        &replacement_peer,
7706                        &outcome.response,
7707                        &outcome.sent_replica_hints,
7708                        p2p_node,
7709                        config,
7710                        bootstrapping,
7711                        bootstrap_state,
7712                        storage,
7713                        paid_list,
7714                        queues,
7715                        sync_state,
7716                        sync_history,
7717                        sync_cycle_epoch,
7718                        repair_proofs,
7719                        last_commitment_by_peer,
7720                        ever_capable_peers,
7721                        sig_verify_attempts,
7722                        gossip_audit,
7723                    )
7724                    .await;
7725                }
7726            }
7727        }
7728    }
7729}
7730
7731/// Process a successful neighbor sync response: record the sync, check for
7732/// bootstrap claim abuse, and admit inbound hints.
7733#[allow(clippy::too_many_arguments)]
7734async fn handle_sync_response(
7735    self_id: &PeerId,
7736    peer: &PeerId,
7737    resp: &NeighborSyncResponse,
7738    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7739    p2p_node: &Arc<P2PNode>,
7740    config: &ReplicationConfig,
7741    bootstrapping: bool,
7742    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7743    storage: &Arc<ChunkStore>,
7744    paid_list: &Arc<PaidList>,
7745    queues: &Arc<RwLock<ReplicationQueues>>,
7746    sync_state: &Arc<RwLock<NeighborSyncState>>,
7747    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7748    sync_cycle_epoch: &Arc<RwLock<u64>>,
7749    repair_proofs: &Arc<RwLock<RepairProofs>>,
7750    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7751    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7752    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7753    gossip_audit: &GossipAuditTrigger,
7754) {
7755    // Ingest the peer's commitment if they piggybacked one on the response.
7756    // Same verification as the request path (peer-id binding + signature);
7757    // forged commitments are dropped at the edge. A *changed* commitment here
7758    // is a gossip-audit trigger just like on the request path — so a peer that
7759    // only ever answers sync (never initiates) is still audited (ADR-0002).
7760    if let Some(target) = ingest_peer_commitment(
7761        peer,
7762        resp.commitment.as_ref(),
7763        p2p_node,
7764        last_commitment_by_peer,
7765        ever_capable_peers,
7766        sig_verify_attempts,
7767    )
7768    .await
7769    {
7770        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7771    }
7772
7773    // Record successful sync.
7774    {
7775        let mut state = sync_state.write().await;
7776        neighbor_sync::record_successful_sync(&mut state, peer);
7777    }
7778    {
7779        let mut history = sync_history.write().await;
7780        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7781            last_sync: None,
7782            cycles_since_sync: 0,
7783        });
7784        record.last_sync = Some(Instant::now());
7785        record.cycles_since_sync = 0;
7786    }
7787
7788    // Process inbound hints from response (skip if peer is bootstrapping).
7789    if resp.bootstrapping {
7790        // Gap 6: BootstrapClaimAbuse grace period enforcement.
7791        // Separate state mutation from network I/O to avoid holding the
7792        // write lock across report_trust_event.
7793        let should_report = {
7794            let now = Instant::now();
7795            let mut state = sync_state.write().await;
7796            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
7797                BootstrapClaimObservation::WithinGrace { .. } => false,
7798                BootstrapClaimObservation::PastGrace { first_seen } => {
7799                    warn!(
7800                        "Peer {peer} has been claiming bootstrap for {:?}, \
7801                         exceeding grace period of {:?} — reporting abuse",
7802                        now.duration_since(first_seen),
7803                        config.bootstrap_claim_grace_period,
7804                    );
7805                    true
7806                }
7807                BootstrapClaimObservation::Repeated { first_seen } => {
7808                    warn!(
7809                        "Peer {peer} repeated bootstrap claim after previously stopping; \
7810                         first claim was {:?} ago — reporting abuse",
7811                        now.duration_since(first_seen),
7812                    );
7813                    true
7814                }
7815            }
7816        };
7817        if should_report {
7818            p2p_node
7819                .report_trust_event(
7820                    peer,
7821                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7822                )
7823                .await;
7824        }
7825    } else {
7826        // Peer is not claiming bootstrap; clear active claim while retaining
7827        // history so the peer cannot start a second grace window later.
7828        {
7829            let mut state = sync_state.write().await;
7830            state.clear_active_bootstrap_claim(peer);
7831        }
7832        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
7833        let outcome = admit_and_queue_hints(
7834            self_id,
7835            peer,
7836            &resp.replica_hints,
7837            &resp.paid_hints,
7838            p2p_node,
7839            config,
7840            storage,
7841            paid_list,
7842            queues,
7843        )
7844        .await;
7845
7846        // Track discovered keys for bootstrap drain detection so that hints
7847        // admitted via regular neighbor sync are not missed. Capacity-
7848        // rejected hints keep this source on the "not yet drained" list
7849        // until its next sync replays them; a clean cycle clears it.
7850        if bootstrapping {
7851            let live_discovered = outcome.discovered.clone();
7852            let outcomes = [(*peer, outcome)];
7853            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
7854                .await;
7855        }
7856    }
7857}
7858
7859/// Admit hints and queue them for verification, returning newly-discovered keys.
7860///
7861/// Shared by neighbor-sync request handling, response handling, and bootstrap
7862/// sync so that admission + queueing logic lives in one place.
7863#[allow(clippy::too_many_arguments)]
7864/// Outcome of [`admit_and_queue_hints`].
7865///
7866/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
7867/// available; that source is kept outstanding until it re-hints. `displaced`
7868/// tracks older borrowed hints reclaimed for another sender; only the key is
7869/// dropped from bootstrap tracking — the former owner's standing is untouched
7870/// (see [`publish_bootstrap_admission_outcomes`]).
7871struct AdmissionOutcome {
7872    discovered: HashSet<XorName>,
7873    capacity_rejected_count: usize,
7874    displaced: Vec<CapacityDisplacement>,
7875}
7876
7877/// Publish one atomic admission unit into bootstrap drain accounting.
7878///
7879/// Only sources that were themselves capacity-rejected are kept outstanding.
7880/// A fairness displacement forfeits the displaced *key* but never stamps its
7881/// former owner: reclaiming a borrowed slot is this node's own fairness
7882/// decision, so charging it to the victim would let a sustained flooder wedge
7883/// our bootstrap drain open through an unrelated honest peer. Clean sources
7884/// are cleared only after every outcome in the unit is known, so peer
7885/// iteration order cannot falsely clear a rejection recorded later in the same
7886/// bootstrap batch.
7887async fn publish_bootstrap_admission_outcomes(
7888    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7889    outcomes: &[(PeerId, AdmissionOutcome)],
7890    live_discovered: &HashSet<XorName>,
7891) {
7892    let mut rejected_sources = HashSet::new();
7893    let mut clean_sources = HashSet::new();
7894    let mut displaced_keys = HashSet::new();
7895
7896    for (source, outcome) in outcomes {
7897        if outcome.capacity_rejected_count > 0 {
7898            rejected_sources.insert(*source);
7899        } else {
7900            clean_sources.insert(*source);
7901        }
7902        // Only the *key* of a fairness displacement is forfeited here, never
7903        // its owner's standing. Reclaiming a borrowed slot is our own fairness
7904        // decision, not a failure by the peer that held it: stamping the victim
7905        // would let a sustained flooder block our bootstrap drain through an
7906        // unrelated honest peer that never overflowed us. The displaced key
7907        // falls to the same post-bootstrap neighbor-sync and audit/repair
7908        // recovery path that TTL expiry already relies on.
7909        for displacement in &outcome.displaced {
7910            displaced_keys.insert(displacement.key);
7911        }
7912    }
7913    clean_sources.retain(|source| !rejected_sources.contains(source));
7914
7915    let now = Instant::now();
7916    let mut state = bootstrap_state.write().await;
7917    for key in displaced_keys {
7918        state.remove_key(&key);
7919    }
7920    state.pending_keys.extend(live_discovered);
7921    for source in clean_sources {
7922        state.capacity_rejected_sources.remove(&source);
7923    }
7924    for source in rejected_sources {
7925        // First-seen: a source that keeps overflowing us must not keep its own
7926        // record fresh, or bootstrap never drains and auditing stays off.
7927        state.note_capacity_rejected(source, now);
7928    }
7929}
7930
7931#[allow(clippy::too_many_arguments)]
7932async fn admit_and_queue_hints(
7933    self_id: &PeerId,
7934    source_peer: &PeerId,
7935    replica_hints: &[XorName],
7936    paid_hints: &[XorName],
7937    p2p_node: &Arc<P2PNode>,
7938    config: &ReplicationConfig,
7939    storage: &Arc<ChunkStore>,
7940    paid_list: &Arc<PaidList>,
7941    queues: &Arc<RwLock<ReplicationQueues>>,
7942) -> AdmissionOutcome {
7943    let pending_keys: HashSet<XorName> = {
7944        let q = queues.read().await;
7945        q.pending_keys().into_iter().collect()
7946    };
7947
7948    let admitted = admission::admit_hints(
7949        self_id,
7950        replica_hints,
7951        paid_hints,
7952        p2p_node,
7953        config,
7954        storage,
7955        paid_list,
7956        &pending_keys,
7957    )
7958    .await;
7959
7960    let mut q = queues.write().await;
7961    queue_admitted_hints(source_peer, admitted, storage, &mut q)
7962}
7963
7964fn queue_admitted_hints(
7965    source_peer: &PeerId,
7966    admitted: admission::AdmissionResult,
7967    storage: &ChunkStore,
7968    q: &mut ReplicationQueues,
7969) -> AdmissionOutcome {
7970    let mut discovered = HashSet::new();
7971    let mut capacity_rejected_count: usize = 0;
7972    let mut displaced = Vec::new();
7973    let now = Instant::now();
7974
7975    for key in admitted.replica_keys {
7976        if !storage.exists(&key).unwrap_or(false) {
7977            let result = q.add_pending_verify(
7978                key,
7979                VerificationEntry {
7980                    state: VerificationState::PendingVerify,
7981                    verified_sources: Vec::new(),
7982                    tried_sources: HashSet::new(),
7983                    created_at: now,
7984                    next_verify_at: now,
7985                    hint_sources: HashSet::from([*source_peer]),
7986                    // Non-empty: this peer claimed possession, so it is a
7987                    // fetch-source candidate. Derives HintPipeline::Replica.
7988                    replica_hint_sources: HashSet::from([*source_peer]),
7989                    unresolved_retries: 0,
7990                    no_holder_reported: false,
7991                },
7992            );
7993            match result {
7994                crate::replication::scheduling::AdmissionResult::Admitted => {
7995                    discovered.insert(key);
7996                }
7997                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
7998                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
7999                    capacity_rejected_count += 1;
8000                }
8001            }
8002        }
8003    }
8004
8005    for key in admitted.paid_only_keys {
8006        let result = q.add_pending_verify(
8007            key,
8008            VerificationEntry {
8009                state: VerificationState::PendingVerify,
8010                verified_sources: Vec::new(),
8011                tried_sources: HashSet::new(),
8012                created_at: now,
8013                next_verify_at: now,
8014                hint_sources: HashSet::from([*source_peer]),
8015                // Empty: a paid hint makes no possession claim, so this peer is
8016                // not a fetch source. Derives HintPipeline::PaidOnly.
8017                replica_hint_sources: HashSet::new(),
8018                unresolved_retries: 0,
8019                no_holder_reported: false,
8020            },
8021        );
8022        match result {
8023            crate::replication::scheduling::AdmissionResult::Admitted => {
8024                discovered.insert(key);
8025            }
8026            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8027            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8028                capacity_rejected_count += 1;
8029            }
8030        }
8031    }
8032
8033    if capacity_rejected_count > 0 {
8034        debug!(
8035            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
8036             rejected at queue capacity; source will need to re-hint after pending_verify drains"
8037        );
8038    }
8039
8040    displaced.extend(q.take_capacity_displacements());
8041
8042    AdmissionOutcome {
8043        discovered,
8044        capacity_rejected_count,
8045        displaced,
8046    }
8047}
8048
8049// ---------------------------------------------------------------------------
8050// Verification cycle
8051// ---------------------------------------------------------------------------
8052
8053/// Run one verification cycle: process pending keys through quorum checks.
8054#[allow(clippy::too_many_lines)]
8055async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
8056    let cycle_started = Instant::now();
8057    let VerificationCycleContext {
8058        p2p_node,
8059        paid_list,
8060        storage,
8061        queues,
8062        config,
8063        bootstrap_state,
8064        is_bootstrapping,
8065        bootstrap_complete_notify,
8066        last_commitment_by_peer,
8067        ever_capable_peers,
8068        recent_provers,
8069    } = ctx;
8070
8071    // Self-heal the bootstrap drain before any early-return below: abandoned
8072    // capacity-rejection records must expire, and a drain condition that
8073    // became true without a triggering event must still be observed. Pending
8074    // peer requests legitimately block the drain check itself, but not this.
8075    expire_and_recheck_bootstrap_drain(
8076        bootstrap_state,
8077        queues,
8078        is_bootstrapping,
8079        bootstrap_complete_notify,
8080        config.capacity_rejected_max_age(),
8081    )
8082    .await;
8083
8084    // Bootstrap admits one concurrent neighbor batch as an atomic source
8085    // aggregation unit. Do not select newly queued keys until that batch's
8086    // hints and drain accounting have both been published.
8087    if bootstrap_state.read().await.pending_peer_requests > 0 {
8088        return;
8089    }
8090
8091    // Evict stale entries that have been pending too long (e.g. unreachable
8092    // verification targets during a network partition).
8093    let stale_pending_keys = {
8094        let mut q = queues.write().await;
8095        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
8096    };
8097    if !stale_pending_keys.is_empty() {
8098        update_bootstrap_after_verification(
8099            &stale_pending_keys,
8100            bootstrap_state,
8101            queues,
8102            is_bootstrapping,
8103            bootstrap_complete_notify,
8104        )
8105        .await;
8106    }
8107
8108    let pending_keys = {
8109        let mut q = queues.write().await;
8110        // Re-check while holding the queue write lock used by fair selection.
8111        // This closes the race
8112        // where a bootstrap batch starts after the early check: the batch
8113        // cannot publish its hints under the queue write lock until this
8114        // selection either returns or declines to run.
8115        if bootstrap_state.read().await.pending_peer_requests > 0 {
8116            return;
8117        }
8118        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
8119    };
8120
8121    if pending_keys.is_empty() {
8122        return;
8123    }
8124    let initial_pending_count = pending_keys.len();
8125
8126    // Capacity verdict for this cycle — the same pre-check the PUT handler and
8127    // the fresh-offer path already run (V2-411), read once and reused below.
8128    //
8129    // It gates only the two steps that exist to enable a fetch: the presence
8130    // probe that discovers holders, and the promotion that queues the download.
8131    // Everything a cycle does that does not need a local write still runs on a
8132    // full node — the local paid-list fast path, `PaidForList` convergence
8133    // through the quorum round, and the terminal checks that retire a key this
8134    // node already holds or is no longer admitted for. Gating earlier than this
8135    // would stop a full node learning which of its keys were paid for, and
8136    // would strand keys that should have retired, which keeps bootstrap drain
8137    // pending and audits disabled until stale eviction.
8138    // Only a *full* disk is a standing condition worth minutes of backoff. A
8139    // failed `statvfs` says nothing about available space and may have cleared
8140    // by the next cycle, so it is treated as writable here and left to the
8141    // pre-check at the dial, which queries again and may well permit the write.
8142    let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8143    // Counted per gate rather than combined. `local_paid_probe` below counts
8144    // probes actually sent, so it reads zero once the first gate fires; keeping
8145    // the two deferral counts apart is what lets an operator see which branch a
8146    // full node's keys are taking without adding a code path to find out.
8147    let mut capacity_deferred_probe = 0usize;
8148    let mut capacity_deferred_promote = 0usize;
8149
8150    let self_id = *p2p_node.peer_id();
8151
8152    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8153    // step 4). Paid-list membership settles *validity* — the key is known-paid,
8154    // so no quorum round is needed. It says nothing about whether we must hold
8155    // the bytes; that is decided below.
8156    let mut local_paid_keys = Vec::new();
8157    let mut keys_needing_network = Vec::new();
8158    let mut terminal_keys: Vec<XorName> = Vec::new();
8159    {
8160        let mut q = queues.write().await;
8161        for key in &pending_keys {
8162            if paid_list.contains(key).unwrap_or(false) {
8163                if q.set_pending_state(key, VerificationState::PaidListVerified) {
8164                    local_paid_keys.push(*key);
8165                }
8166            } else {
8167                keys_needing_network.push(*key);
8168            }
8169        }
8170    }
8171
8172    // Storage responsibility is a live routing question, decided identically
8173    // for every known-paid key regardless of how the advertising peer labelled
8174    // its hint — a replica hint is a possession *claim* by the sender, never
8175    // permission for us to store. Held outside the queue lock: `is_responsible`
8176    // awaits into the DHT manager.
8177    let mut local_paid_presence_probe_keys = Vec::new();
8178    if !local_paid_keys.is_empty() {
8179        let mut terminal_paid = Vec::new();
8180        for key in local_paid_keys {
8181            if storage.exists(&key).unwrap_or(false) {
8182                terminal_paid.push(key);
8183            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8184                // We carry storage responsibility and lack the bytes. The
8185                // presence probe below discovers holders to fetch from; it is
8186                // source discovery, not re-verification.
8187                local_paid_presence_probe_keys.push(key);
8188            } else {
8189                terminal_paid.push(key);
8190            }
8191        }
8192
8193        if !terminal_paid.is_empty() {
8194            let mut q = queues.write().await;
8195            for key in terminal_paid {
8196                q.remove_pending(&key);
8197                terminal_keys.push(key);
8198            }
8199        }
8200
8201        // Capacity gate, first of two. Everything above this point has already
8202        // run: authorization succeeded via the local `PaidForList` hit, and the
8203        // keys that should retire (already held, or no longer storage-admitted)
8204        // have retired. What is left is a probe whose only purpose is finding a
8205        // holder to download from, and this node cannot write what it would
8206        // download.
8207        if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8208            let mut q = queues.write().await;
8209            for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8210                if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8211                    capacity_deferred_probe += 1;
8212                }
8213            }
8214        }
8215    }
8216
8217    let local_paid_probe_count = local_paid_presence_probe_keys.len();
8218    let keys_needing_network_count = keys_needing_network.len();
8219    // Keys this cycle put back because no peer claimed possession. Reported in
8220    // aggregate below; the per-key line is warned once per entry, not per retry.
8221    let mut no_holder_deferrals = 0usize;
8222
8223    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8224    // step 4, authorization succeeds immediately; run a presence-only probe
8225    // to find any holder we can fetch from.
8226    if !local_paid_presence_probe_keys.is_empty() {
8227        let targets = quorum::compute_presence_targets(
8228            &local_paid_presence_probe_keys,
8229            p2p_node,
8230            config,
8231            &self_id,
8232        )
8233        .await;
8234        let evidence = quorum::run_verification_round(
8235            &local_paid_presence_probe_keys,
8236            &targets,
8237            p2p_node,
8238            config,
8239        )
8240        .await;
8241
8242        let mut q = queues.write().await;
8243        for key in local_paid_presence_probe_keys {
8244            if storage.exists(&key).unwrap_or(false) {
8245                q.remove_pending(&key);
8246                terminal_keys.push(key);
8247                continue;
8248            }
8249            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8250                quorum::present_sources_for_key(&key, ev, &targets)
8251            });
8252            if let Some(entry) = q.get_pending(&key) {
8253                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8254            }
8255            if sources.is_empty() {
8256                no_holder_deferrals += 1;
8257                let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8258                let first_report = q.claim_no_holder_report(&key);
8259                report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8260            } else {
8261                // A holder answered, so whatever came before is not a run of
8262                // consecutive failures any more. Clear before promoting: if the
8263                // fetch queue is full the entry stays pending, and it must not
8264                // carry the old backoff.
8265                q.clear_unresolved(&key);
8266                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8267                // Atomic remove+enqueue: if fetch_queue is at capacity, the
8268                // pending entry is preserved and retried next cycle (no
8269                // silent drop of verified replica-repair work).
8270                let _ = q.promote_pending_to_fetch(key, distance, sources);
8271            }
8272        }
8273    }
8274
8275    // Steps 2-5: Network verification (skipped if all keys resolved locally).
8276    if !keys_needing_network.is_empty() {
8277        // Step 2: Compute targets and run network verification round.
8278        let targets =
8279            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8280                .await;
8281
8282        let evidence =
8283            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8284
8285        // Step 3: Evaluate results — collect outcomes without holding the write
8286        // lock across paid-list I/O.
8287        //
8288        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8289        // table and recent_provers cache up front so the synchronous
8290        // evaluate_key_evidence_with_holder_check predicate can consult
8291        // them without awaiting. The predicate downgrades a Present
8292        // claim to Unresolved unless the peer is credited for that key.
8293        // Snapshot per-peer commitment data. We need two views:
8294        //   - `commitment_by_peer_snapshot`: peers that currently have
8295        //     a verified commitment record on file (used to look up
8296        //     their current hash).
8297        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
8298        //     set. Sourced from a separate set rather than the
8299        //     commitment map so eviction (PeerRemoved cleanup, sybil
8300        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8301        //     a previously-v12 peer to "legacy" credit-unconditionally.
8302        //     Legacy / pre-v12 peers that have never sent a commitment
8303        //     remain absent from the set and are credited via the
8304        //     legacy path so mixed-version networks stay live.
8305        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8306            let map = last_commitment_by_peer.read().await;
8307            map.iter()
8308                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8309                // of every peer's ~5 KiB commitment.
8310                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8311                .collect()
8312        };
8313        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8314        // Take a full snapshot of recent_provers under the read lock,
8315        // then release. The cache is bounded (16/key × keys), so the
8316        // clone is cheap.
8317        let provers_snapshot = recent_provers.read().await.clone();
8318        // For the replica-fetch path, we need to know whether THIS
8319        // node already holds the key being verified. The v12 §6
8320        // holder-credit gate is meant to prevent uncredited Present
8321        // claims from contributing to paid-list / reward quorum for
8322        // keys we DO hold (and could audit ourselves). For keys we
8323        // are trying to FETCH (i.e. not in local storage), there is
8324        // no possible local audit credit, and gating the presence
8325        // quorum on credit would deadlock replica-repair in a
8326        // fully v12-capable close group.
8327        let mut locally_held: HashSet<XorName> = HashSet::new();
8328        for key in &keys_needing_network {
8329            if storage.exists(key).unwrap_or(false) {
8330                locally_held.insert(*key);
8331            }
8332        }
8333        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8334            if !locally_held.contains(key) {
8335                // Replica-fetch path: we don't hold this key, so we
8336                // cannot have collected audit credit for it. Trust
8337                // Present claims to drive fetch-source promotion;
8338                // chunk-PUT payment_verifier is the security backstop
8339                // when the bytes actually arrive.
8340                return true;
8341            }
8342            if !capable_peer_snapshot.contains(peer) {
8343                // Pre-v12 / legacy peer that has never gossiped a
8344                // commitment. The v12 §6 holder-eligibility check
8345                // doesn't apply: their Present evidence comes through
8346                // the legacy path and we credit it unconditionally
8347                // so a mixed-version network stays live during
8348                // transition.
8349                return true;
8350            }
8351            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8352                // Peer is commitment_capable (sticky) but currently
8353                // has no live commitment record on file (e.g. their
8354                // last gossip was evicted from the LRU cache, or it
8355                // failed verification). Withhold credit until they
8356                // re-prove storage under a fresh commitment.
8357                return false;
8358            };
8359            provers_snapshot.is_credited_holder(key, peer, hash)
8360        };
8361
8362        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8363        {
8364            let q = queues.read().await;
8365            for key in &keys_needing_network {
8366                let Some(ev) = evidence.get(key) else {
8367                    continue;
8368                };
8369                if q.get_pending(key).is_none() {
8370                    continue;
8371                }
8372                let outcome = quorum::evaluate_key_evidence_with_holder_check(
8373                    key,
8374                    ev,
8375                    &targets,
8376                    config,
8377                    holder_credit,
8378                );
8379                evaluated.push((*key, outcome));
8380            }
8381        } // read lock released
8382
8383        // Step 4: Insert verified keys into PaidForList (no lock held).
8384        let mut paid_insert_keys: Vec<XorName> = Vec::new();
8385        for (key, outcome) in &evaluated {
8386            if matches!(
8387                outcome,
8388                KeyVerificationOutcome::QuorumVerified { .. }
8389                    | KeyVerificationOutcome::PaidListVerified { .. }
8390            ) {
8391                paid_insert_keys.push(*key);
8392            }
8393        }
8394        for key in &paid_insert_keys {
8395            if let Err(e) = paid_list.insert(key).await {
8396                warn!("Failed to add verified key to PaidForList: {e}");
8397            }
8398        }
8399
8400        // Verification established validity; the paid-list insert above records
8401        // it. Downloading the bytes is a separate duty, owed only by the
8402        // storage-admission group, asked on the same terms for every verified
8403        // key — the advertising peer's replica/paid labelling is a claim about
8404        // itself and carries no authority over what we store. This check is a
8405        // cheap pre-filter that keeps never-responsible keys out of the fetch
8406        // queue entirely; the authoritative gate is the per-attempt recheck in
8407        // `execute_single_fetch`, because a key can wait in the nearest-first
8408        // fetch queue long enough for this promotion-time answer to go stale.
8409        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8410        for (key, outcome) in &evaluated {
8411            if matches!(
8412                outcome,
8413                KeyVerificationOutcome::QuorumVerified { .. }
8414                    | KeyVerificationOutcome::PaidListVerified { .. }
8415            ) && !storage.exists(key).unwrap_or(false)
8416                && is_storage_admitted(&self_id, key, p2p_node, config).await
8417            {
8418                fetch_allowed_keys.insert(*key);
8419            }
8420        }
8421
8422        // Step 5: Update queues with the evaluated outcomes.
8423        let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
8424        let mut q = queues.write().await;
8425        for (key, outcome) in evaluated {
8426            let replica_hint_sources = q
8427                .get_pending(&key)
8428                .map(|entry| entry.replica_hint_sources.clone())
8429                .unwrap_or_default();
8430            if let Some(ev) = evidence.get(&key) {
8431                if let Some(source) =
8432                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8433                {
8434                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8435                }
8436            }
8437            match outcome {
8438                KeyVerificationOutcome::QuorumVerified { sources }
8439                | KeyVerificationOutcome::PaidListVerified { sources } => {
8440                    let mut fetch_sources = sources;
8441                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8442                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8443                    if fetch_eligible && write_blocked {
8444                        // Capacity gate, second of two, and deliberately after
8445                        // Step 4: the key is now recorded in `PaidForList` and
8446                        // its verification stands. Only the download is held,
8447                        // because `execute_single_fetch` would refuse it and
8448                        // hand the key straight back here.
8449                        if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8450                            capacity_deferred_promote += 1;
8451                        }
8452                    } else if fetch_eligible && !fetch_sources.is_empty() {
8453                        // A holder answered; see the matching clear on the
8454                        // local-paid path.
8455                        q.clear_unresolved(&key);
8456                        let distance =
8457                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8458                        // Atomic remove+enqueue: on fetch_queue capacity miss
8459                        // the pending entry is preserved so this verified key
8460                        // is retried on the next cycle (no silent drop).
8461                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8462                        // Not terminal — either moved to fetch queue, or
8463                        // retained as pending until queue drains.
8464                    } else if fetch_eligible && fetch_sources.is_empty() {
8465                        no_holder_deferrals += 1;
8466                        let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8467                        let first_report = q.claim_no_holder_report(&key);
8468                        report_unresolved_deferral(
8469                            "Verified storage-admitted key",
8470                            &key,
8471                            outcome,
8472                            first_report,
8473                        );
8474                    } else {
8475                        q.remove_pending(&key);
8476                        terminal_keys.push(key);
8477                    }
8478                }
8479                KeyVerificationOutcome::QuorumFailed => {
8480                    q.remove_pending(&key);
8481                    terminal_keys.push(key);
8482                }
8483                KeyVerificationOutcome::QuorumInconclusive => {
8484                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8485                    // Backed off like any other unresolved round, but it does
8486                    // NOT claim the no-holder report: nothing yet says this key
8487                    // has no holder, so the first round that does say so must
8488                    // still be the one that warns.
8489                    let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8490                }
8491            }
8492        }
8493        drop(q);
8494
8495        for ((peer, fault), bad_hint_count) in bad_singleton_hints {
8496            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8497            warn!(
8498                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8499                 sole-source replica hints ({fault:?}); \
8500                 reporting {reports} bounded trust failure(s)"
8501            );
8502            for _ in 0..reports {
8503                match fault {
8504                    // A claim about a key that does not exist. Punishable whatever the
8505                    // sender's disk is doing.
8506                    SingletonHintFault::RejectedByCloseGroup => {
8507                        p2p_node
8508                            .report_trust_event(
8509                                &peer,
8510                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8511                            )
8512                            .await;
8513                    }
8514                    // "I advertised it and no longer have it." That is the one statement a
8515                    // node short of disk cannot avoid making while it moves its chunks, so
8516                    // it goes through the release switch.
8517                    SingletonHintFault::DeniedPossession => {
8518                        config::penalise_unheld_close_group_chunk(
8519                            p2p_node,
8520                            &peer,
8521                            "replica_hint_denied_possession",
8522                            REPLICATION_TRUST_WEIGHT,
8523                        )
8524                        .await;
8525                    }
8526                }
8527            }
8528        }
8529    }
8530
8531    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8532    // the drain condition.
8533    update_bootstrap_after_verification(
8534        &terminal_keys,
8535        bootstrap_state,
8536        queues,
8537        is_bootstrapping,
8538        bootstrap_complete_notify,
8539    )
8540    .await;
8541
8542    let (pending_after, fetch_after, in_flight_after) = {
8543        let q = queues.read().await;
8544        (
8545            q.pending_count(),
8546            q.fetch_queue_count(),
8547            q.in_flight_count(),
8548        )
8549    };
8550    let terminal_key_count = terminal_keys.len();
8551    let elapsed_ms = cycle_started.elapsed().as_millis();
8552
8553    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8554        info!(
8555            target: "ant_node::replication::verification",
8556            "Slow replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8557        );
8558    } else {
8559        debug!(
8560            target: "ant_node::replication::verification",
8561            "Replication verification cycle: pending_start={initial_pending_count}, capacity_deferred_probe={capacity_deferred_probe}, capacity_deferred_promote={capacity_deferred_promote}, local_paid_probe={local_paid_probe_count}, network_verify={keys_needing_network_count}, terminal={terminal_key_count}, no_holders={no_holder_deferrals}, pending_after={pending_after}, fetch_after={fetch_after}, in_flight_after={in_flight_after}, elapsed_ms={elapsed_ms}",
8562        );
8563    }
8564}
8565
8566/// Report a verification round that left a key without a usable holder.
8567///
8568/// Warns once per entry — the first failure is news, and by the hundredth the
8569/// node is re-asking peers it has already exhausted. Later failures stay at
8570/// `debug`, and the per-cycle count is carried in the cycle summary so the
8571/// scale of a backlog is still visible without a line per key per retry.
8572///
8573/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8574/// number: a round may advance the count without producing a no-holder result,
8575/// and such a round must not consume the warning.
8576///
8577/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8578/// a holder clears it, so a later relapse warns again: "once per episode", not
8579/// "once ever".
8580fn report_unresolved_deferral(
8581    what: &str,
8582    key: &XorName,
8583    outcome: Option<DeferralOutcome>,
8584    first_report: bool,
8585) {
8586    let Some(outcome) = outcome else {
8587        // The entry left `pending_verify` under the same lock; nothing deferred.
8588        return;
8589    };
8590    if first_report {
8591        warn!(
8592            "{what} {} has no responding holders yet; deferring retry",
8593            hex::encode(key)
8594        );
8595    } else {
8596        debug!(
8597            "{what} {} still has no responding holders after {} attempts; \
8598             retrying in {}s",
8599            hex::encode(key),
8600            outcome.attempt,
8601            outcome.retry_after.as_secs()
8602        );
8603    }
8604}
8605
8606/// Add peers that claimed possession as fallback fetch sources.
8607///
8608/// Paid-only advertisers make no possession claim and are absent from
8609/// `replica_hint_sources` by construction, so they are never added.
8610fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8611    for source in replica_hint_sources {
8612        if !sources.contains(source) {
8613            sources.push(*source);
8614        }
8615    }
8616}
8617
8618/// Why a sole-source replica hint is punishable.
8619///
8620/// The two cases look alike and are not. A hint the close group rejects outright is a
8621/// claim about a key that does not exist, which is a bad hint however the sender's disk is
8622/// doing. A sender that advertised a key and then answers `Absent` for it is making a
8623/// statement about its own storage, and that is the one thing a node short of disk cannot
8624/// avoid saying while it moves its chunks out of a store that will not give the space back.
8625#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8626enum SingletonHintFault {
8627    /// The close group says the key does not exist.
8628    RejectedByCloseGroup,
8629    /// The sender advertised the key and then denied holding it.
8630    DeniedPossession,
8631}
8632
8633/// Return the sole replica advertiser when either the close group definitively
8634/// rejects the key or the advertiser explicitly denies possessing it, and say which.
8635/// Paid-only advertisements, corroborated replica hints, and inconclusive
8636/// rounds without that direct contradiction are deliberately non-penalizing.
8637fn punishable_singleton_replica_hint_source(
8638    replica_hint_sources: &HashSet<PeerId>,
8639    outcome: &KeyVerificationOutcome,
8640    evidence: &crate::replication::types::KeyVerificationEvidence,
8641) -> Option<(PeerId, SingletonHintFault)> {
8642    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8643    // reserved for peers that actually claimed possession.
8644    if replica_hint_sources.len() != 1 {
8645        return None;
8646    }
8647    let source = *replica_hint_sources.iter().next()?;
8648    if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
8649        return Some((source, SingletonHintFault::RejectedByCloseGroup));
8650    }
8651    if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
8652        return Some((source, SingletonHintFault::DeniedPossession));
8653    }
8654    None
8655}
8656
8657/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8658/// bootstrap pending set and transition out of bootstrapping when drained.
8659async fn update_bootstrap_after_verification(
8660    terminal_keys: &[XorName],
8661    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8662    queues: &Arc<RwLock<ReplicationQueues>>,
8663    is_bootstrapping: &Arc<RwLock<bool>>,
8664    bootstrap_complete_notify: &Arc<Notify>,
8665) {
8666    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8667        return;
8668    }
8669    {
8670        let mut bs = bootstrap_state.write().await;
8671        for key in terminal_keys {
8672            bs.remove_key(key);
8673        }
8674    }
8675    let q = queues.read().await;
8676    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8677        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8678    }
8679}
8680
8681/// Retire bootstrap work owed by a peer that permanently left the routing
8682/// table, then immediately re-check drain so this removal can complete
8683/// bootstrap without waiting for an unrelated pipeline event.
8684async fn update_bootstrap_after_peer_removed(
8685    peer: &PeerId,
8686    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8687    queues: &Arc<RwLock<ReplicationQueues>>,
8688    is_bootstrapping: &Arc<RwLock<bool>>,
8689    bootstrap_complete_notify: &Arc<Notify>,
8690) {
8691    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8692    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8693
8694    if !orphaned_keys.is_empty() {
8695        let mut state = bootstrap_state.write().await;
8696        for key in &orphaned_keys {
8697            state.remove_key(key);
8698        }
8699    }
8700
8701    if orphaned_keys.is_empty() && !cleared_rejection {
8702        return;
8703    }
8704    let q = queues.read().await;
8705    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8706        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8707    }
8708}
8709
8710/// Periodic bootstrap-drain self-healing, run on every verification worker
8711/// tick until bootstrap drains.
8712///
8713/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8714/// recording of a capacity rejection leaves an entry no future event can
8715/// clear — `max_age` expiry is its only exit. And a clean-cycle
8716/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8717/// quiet node the drain condition can become true with nothing left to
8718/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8719/// drain itself, so this is invoked before `run_verification_cycle`'s
8720/// early-returns.
8721async fn expire_and_recheck_bootstrap_drain(
8722    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8723    queues: &Arc<RwLock<ReplicationQueues>>,
8724    is_bootstrapping: &Arc<RwLock<bool>>,
8725    bootstrap_complete_notify: &Arc<Notify>,
8726    max_age: Duration,
8727) {
8728    if bootstrap_state.read().await.is_drained() {
8729        return;
8730    }
8731    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8732    let q = queues.read().await;
8733    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8734        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8735    }
8736}
8737
8738/// Set `is_bootstrapping` to `false` and wake all waiters.
8739async fn complete_bootstrap(
8740    is_bootstrapping: &Arc<RwLock<bool>>,
8741    bootstrap_complete_notify: &Arc<Notify>,
8742) {
8743    *is_bootstrapping.write().await = false;
8744    bootstrap_complete_notify.notify_waiters();
8745    info!("Replication bootstrap complete");
8746}
8747
8748// ---------------------------------------------------------------------------
8749// Fetch types and single-fetch executor
8750// ---------------------------------------------------------------------------
8751
8752/// Result classification for a single fetch attempt.
8753enum FetchResult {
8754    /// Data fetched, integrity-checked, and stored successfully.
8755    Stored,
8756    /// Content-address integrity check failed — do not retry.
8757    IntegrityFailed,
8758    /// Source failed (network error or non-success response) — retryable.
8759    SourceFailed,
8760    /// This node could not write the chunk locally: the capacity pre-check
8761    /// refused before the dial, or `put` failed after the bytes arrived.
8762    ///
8763    /// Distinct from [`Self::SourceFailed`] because nothing about the source
8764    /// is implicated, and because the remedy is the opposite one. A source
8765    /// failure should move on to the next holder; a local write failure must
8766    /// not — every remaining source would send the same chunk into the same
8767    /// full disk. The key returns to verification instead, so a later cycle
8768    /// retries it once local capacity allows. That is a retry path, not a
8769    /// liveness guarantee: `evict_stale` still expires the entry at
8770    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8771    /// which re-acquisition depends on a fresh hint.
8772    LocalWriteFailed,
8773    /// This node already holds the key, so there is nothing to fetch —
8774    /// terminal, exactly like [`Self::Stored`], because the duty is already
8775    /// discharged.
8776    ///
8777    /// Responsibility is rechecked at download time; possession has to be too.
8778    /// The earlier gates already drop held keys out of the fetch pipeline —
8779    /// `queue_admitted_hints` skips them, and the promotion-time
8780    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8781    /// them. (`is_relevant` is not one of them: possession there makes a key
8782    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8783    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8784    /// client PUT, or another source landing first. The nearest-first fetch
8785    /// queue is deep enough for that window to be real.
8786    ///
8787    /// This check must also precede the capacity pre-check below, because
8788    /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
8789    /// it, a full node would decline a key it already holds, which `put` would
8790    /// have accepted as a duplicate.
8791    AlreadyHeld,
8792    /// Live routing state no longer places this node in the storage-admission
8793    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8794    /// the fetch was serving has lapsed, so no alternate source is tried and
8795    /// no trust event is reported: the source did nothing wrong.
8796    NoLongerResponsible,
8797}
8798
8799/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8800/// worker loop to update queue state.
8801struct FetchOutcome {
8802    key: XorName,
8803    result: FetchResult,
8804}
8805
8806/// What the fetch worker must do next for a key whose fetch attempt resolved.
8807#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8808enum FetchFollowUp {
8809    /// The key terminally left the fetch pipeline (its in-flight entry is
8810    /// removed and any verification retry-slot reservation released); the
8811    /// caller must run bootstrap accounting for it.
8812    Terminal,
8813    /// The key returned to `pending_verify` for a later verification round.
8814    RequeuedForVerification,
8815    /// Retry immediately from this next untried verified source.
8816    RetryFrom(PeerId),
8817}
8818
8819/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8820///
8821/// Split out of the fetch-worker loop so the per-variant queue transitions
8822/// are unit-testable without a live network. The caller holds the queues
8823/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
8824/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
8825/// retry-slot reservation, and the caller's terminal handling shrinks the
8826/// bootstrap pending set — dropping the key without that accounting would
8827/// stall bootstrap drain forever.
8828///
8829/// The nursery `option_if_let_else` rewrite is impossible here: both
8830/// `map_or_else` closures would need `&mut *q` simultaneously.
8831#[allow(clippy::option_if_let_else)]
8832fn apply_fetch_result(
8833    q: &mut ReplicationQueues,
8834    key: &XorName,
8835    result: &FetchResult,
8836    verification_retry_after: Duration,
8837) -> FetchFollowUp {
8838    match result {
8839        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
8840            q.complete_fetch(key);
8841            FetchFollowUp::Terminal
8842        }
8843        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
8844            if let Some(next_peer) = q.retry_fetch(key) {
8845                FetchFollowUp::RetryFrom(next_peer)
8846            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
8847                FetchFollowUp::RequeuedForVerification
8848            } else {
8849                FetchFollowUp::Terminal
8850            }
8851        }
8852        // No `retry_fetch`: the local write is what failed, so every other
8853        // source would be asked to send the same chunk into the same full
8854        // disk. Requeueing for verification is what keeps the key from being
8855        // stranded — it comes back once capacity allows — and the fallthrough
8856        // to `Terminal` when there is no retry metadata is what keeps
8857        // bootstrap drain accounting correct, exactly as for a source failure.
8858        //
8859        // The ordinary requeue delay, deliberately. A standing capacity block
8860        // does not need a longer one here: the key returns to pending, and the
8861        // gate at the head of the next cycle defers it for minutes. A separate
8862        // backoff on this path would duplicate that to save one 15 s round, on
8863        // a race the gate already makes rare.
8864        FetchResult::LocalWriteFailed => {
8865            if q.requeue_fetch_for_verification(key, verification_retry_after) {
8866                FetchFollowUp::RequeuedForVerification
8867            } else {
8868                FetchFollowUp::Terminal
8869            }
8870        }
8871    }
8872}
8873
8874/// Whether this node currently sits inside the storage-admission group for
8875/// `key`, per live local routing state.
8876///
8877/// This is the one question every storage decision in this module asks; see
8878/// [`admission::is_responsible`]. A purely local routing-table lookup — no
8879/// network I/O — but it awaits into the DHT manager, so callers must not
8880/// hold the queues lock across it.
8881async fn is_storage_admitted(
8882    self_id: &PeerId,
8883    key: &XorName,
8884    p2p_node: &Arc<P2PNode>,
8885    config: &ReplicationConfig,
8886) -> bool {
8887    admission::is_responsible(
8888        self_id,
8889        key,
8890        p2p_node,
8891        storage_admission_width(config.close_group_size),
8892    )
8893    .await
8894}
8895
8896#[allow(clippy::too_many_lines)]
8897/// Execute a single fetch request against `source` for `key`.
8898///
8899/// Handles encoding, network I/O, integrity checking, storage, and trust
8900/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
8901/// queue state without holding any locks during the network round-trip.
8902///
8903/// This is the authoritative storage-responsibility gate: each attempt —
8904/// including every per-source retry, which re-enters here — rechecks live
8905/// routing state before spending bandwidth, and once more before writing
8906/// bytes that arrived after a round-trip. The verification-time check that
8907/// promoted the key into the fetch queue is only a pre-filter; the queue is
8908/// nearest-first and deep, so a promotion decision can go stale under
8909/// topology churn before the key is ever dequeued.
8910async fn execute_single_fetch(
8911    p2p_node: Arc<P2PNode>,
8912    storage: Arc<ChunkStore>,
8913    config: Arc<ReplicationConfig>,
8914    key: XorName,
8915    source: PeerId,
8916) -> FetchOutcome {
8917    let self_id = *p2p_node.peer_id();
8918    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
8919        debug!(
8920            "Skipping fetch for {}: no longer in the storage-admission group",
8921            hex::encode(key)
8922        );
8923        return FetchOutcome {
8924            key,
8925            result: FetchResult::NoLongerResponsible,
8926        };
8927    }
8928
8929    // Possession, then capacity — both before the dial, and in that order.
8930    //
8931    // `ChunkStore::put` tests `exists` before it tests disk space, so a full
8932    // node still accepts a key it already holds. Checking possession first is
8933    // what keeps this pair of gates from declining work `put` would have
8934    // taken.
8935    if storage.exists(&key).unwrap_or(false) {
8936        debug!(
8937            "Skipping fetch for {}: already held locally",
8938            hex::encode(key)
8939        );
8940        return FetchOutcome {
8941            key,
8942            result: FetchResult::AlreadyHeld,
8943        };
8944    }
8945
8946    // Capacity is checked before the dial rather than after the bytes arrive.
8947    // `put` runs this same check on every write of a key it does not already
8948    // hold, so this reaches the same verdict `put` would reach *at this
8949    // instant*. It is not a guarantee about the later write: both answers can
8950    // change across the round trip. Space freed in between would have let a
8951    // post-download `put` succeed, so a refusal here can cost a fleeting
8952    // acquisition and one retry cycle of delay; space lost in between is why
8953    // the check inside `put` still has to stay.
8954    //
8955    // What it buys is that the refusal costs no bandwidth. Without it a
8956    // disk-full node pulls the whole chunk over the network first, and the
8957    // failure is then classified as the source's — no trust event, but the
8958    // worker walks to every remaining holder, and each re-uploads the same
8959    // chunk into the same full disk.
8960    if let Err(e) = storage.check_capacity() {
8961        debug!(
8962            "Skipping fetch for {}: local storage cannot accept a write: {e}",
8963            hex::encode(key)
8964        );
8965        return FetchOutcome {
8966            key,
8967            result: FetchResult::LocalWriteFailed,
8968        };
8969    }
8970
8971    let request = protocol::FetchRequest { key };
8972    let msg = ReplicationMessage {
8973        request_id: rand::thread_rng().gen::<u64>(),
8974        body: ReplicationMessageBody::FetchRequest(request),
8975    };
8976
8977    let encoded = match msg.encode() {
8978        Ok(data) => data,
8979        Err(e) => {
8980            warn!("Failed to encode fetch request: {e}");
8981            return FetchOutcome {
8982                key,
8983                result: FetchResult::SourceFailed,
8984            };
8985        }
8986    };
8987
8988    let result = p2p_node
8989        .send_request(
8990            &source,
8991            REPLICATION_PROTOCOL_ID,
8992            encoded,
8993            config.fetch_request_timeout,
8994        )
8995        .await;
8996
8997    match result {
8998        Ok(response) => {
8999            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
9000                p2p_node
9001                    .report_trust_event(
9002                        &source,
9003                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9004                    )
9005                    .await;
9006                return FetchOutcome {
9007                    key,
9008                    result: FetchResult::SourceFailed,
9009                };
9010            };
9011
9012            match resp_msg.body {
9013                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
9014                    key: resp_key,
9015                    data,
9016                }) => {
9017                    // Validate the response key matches the requested key.
9018                    // A malicious peer could serve valid data for a different
9019                    // key, passing integrity checks while the requested key
9020                    // is falsely marked as fetched.
9021                    if resp_key != key {
9022                        warn!(
9023                            "Fetch response key mismatch: requested {}, got {}",
9024                            hex::encode(key),
9025                            hex::encode(resp_key)
9026                        );
9027                        p2p_node
9028                            .report_trust_event(
9029                                &source,
9030                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9031                            )
9032                            .await;
9033                        return FetchOutcome {
9034                            key,
9035                            result: FetchResult::IntegrityFailed,
9036                        };
9037                    }
9038
9039                    // Enforce chunk size invariant on fetched data.
9040                    // Checked before the content-address hash to avoid
9041                    // hashing up to 10 MiB of oversized junk data.
9042                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
9043                        warn!(
9044                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
9045                            hex::encode(resp_key),
9046                            data.len(),
9047                            crate::ant_protocol::MAX_CHUNK_SIZE,
9048                        );
9049                        p2p_node
9050                            .report_trust_event(
9051                                &source,
9052                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9053                            )
9054                            .await;
9055                        return FetchOutcome {
9056                            key,
9057                            result: FetchResult::IntegrityFailed,
9058                        };
9059                    }
9060
9061                    // Content-address integrity check.
9062                    let computed = crate::client::compute_address(&data);
9063                    if computed != resp_key {
9064                        warn!(
9065                            "Fetched record integrity check failed: expected {}, got {}",
9066                            hex::encode(resp_key),
9067                            hex::encode(computed)
9068                        );
9069                        p2p_node
9070                            .report_trust_event(
9071                                &source,
9072                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9073                            )
9074                            .await;
9075                        return FetchOutcome {
9076                            key,
9077                            result: FetchResult::IntegrityFailed,
9078                        };
9079                    }
9080
9081                    // Responsibility can lapse during the network round-trip.
9082                    // The bandwidth is already spent; declining the write is
9083                    // what still avoids the disk write and the later
9084                    // fetch→store→prune churn. Edge flapping is dampened by
9085                    // the margin `storage_admission_width` adds over
9086                    // `close_group_size`.
9087                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9088                        debug!(
9089                            "Fetched {} but responsibility lapsed in transit; not storing",
9090                            hex::encode(key)
9091                        );
9092                        return FetchOutcome {
9093                            key,
9094                            result: FetchResult::NoLongerResponsible,
9095                        };
9096                    }
9097
9098                    if let Err(e) = storage.put(&resp_key, &data).await {
9099                        // The bytes arrived and passed the content-address
9100                        // check, so the source did its job; the failure is
9101                        // entirely local (disk-full, or an LMDB error). Any
9102                        // valid source must serve identical content, so trying
9103                        // the next one cannot cure a local error — it only
9104                        // re-downloads the same chunk into the same store.
9105                        warn!(
9106                            "Failed to store fetched record {}: {e}",
9107                            hex::encode(resp_key)
9108                        );
9109                        return FetchOutcome {
9110                            key,
9111                            result: FetchResult::LocalWriteFailed,
9112                        };
9113                    }
9114
9115                    FetchOutcome {
9116                        key,
9117                        result: FetchResult::Stored,
9118                    }
9119                }
9120                ReplicationMessageBody::FetchResponse(
9121                    ref response @ (protocol::FetchResponse::NotFound { .. }
9122                    | protocol::FetchResponse::Error { .. }),
9123                ) => {
9124                    // This peer was selected as a fetch source because it recently
9125                    // answered `Present` during verification, so either answer is
9126                    // evidence of something. Which one decides what it is charged: a peer
9127                    // that does not hold the chunk is the lane this release withholds, a
9128                    // peer whose own read failed is not.
9129                    if let protocol::FetchResponse::Error { reason, .. } = response {
9130                        warn!(
9131                            "Fetch: peer {source} returned error for {}: {reason}",
9132                            hex::encode(key)
9133                        );
9134                    } else {
9135                        warn!(
9136                            "Fetch: verified source {source} returned NotFound for {}",
9137                            hex::encode(key)
9138                        );
9139                    }
9140                    if let Some(fault) = fetch_fault_for(response) {
9141                        let lane = match fault {
9142                            FetchFault::UnheldChunk => "fetch_not_found",
9143                            FetchFault::ResponderFault => "fetch_error",
9144                        };
9145                        charge_fetch_fault(&p2p_node, &source, fault, lane).await;
9146                    }
9147                    FetchOutcome {
9148                        key,
9149                        result: FetchResult::SourceFailed,
9150                    }
9151                }
9152                _ => {
9153                    // Unexpected message type — treat as malformed.
9154                    p2p_node
9155                        .report_trust_event(
9156                            &source,
9157                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9158                        )
9159                        .await;
9160                    FetchOutcome {
9161                        key,
9162                        result: FetchResult::SourceFailed,
9163                    }
9164                }
9165            }
9166        }
9167        Err(e) => {
9168            debug!("Fetch request to {source} failed: {e}");
9169            // No ApplicationFailure here — P2PNode::send_request() already
9170            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9171            FetchOutcome {
9172                key,
9173                result: FetchResult::SourceFailed,
9174            }
9175        }
9176    }
9177}
9178
9179// ---------------------------------------------------------------------------
9180// Audit result handler
9181// ---------------------------------------------------------------------------
9182
9183/// Format the first confirmed-failed key as a 16-hex-char label.
9184///
9185/// Pairs with `challenged_peer` to form a stable cross-host correlation
9186/// handle in the audit-failure log line, e.g.
9187///
9188/// ```text
9189/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9190/// ```
9191///
9192/// Falls back to `"0x"` when the list is empty so the log line never
9193/// contains a misleading default.
9194fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9195    confirmed_failed_keys.first().map_or_else(
9196        || "0x".to_string(),
9197        |k| format!("0x{}", hex::encode(&k[..8])),
9198    )
9199}
9200
9201/// Execute the side effects for a subtree storage-commitment audit failure.
9202///
9203/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9204/// legitimately time out on slow or loaded honest peers, so it never touches the
9205/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9206/// failures still penalise immediately and revoke holder credit.
9207async fn handle_subtree_failed_audit(
9208    challenged_peer: &PeerId,
9209    confirmed_failed_key_count: usize,
9210    reason: &AuditFailureReason,
9211    p2p_node: &Arc<P2PNode>,
9212    sync_state: &Arc<RwLock<NeighborSyncState>>,
9213    recent_provers: &Arc<RwLock<RecentProvers>>,
9214) {
9215    if matches!(reason, AuditFailureReason::Timeout) {
9216        debug!(
9217            "Audit timeout for {challenged_peer} fully graced \
9218             (subtree audit does not evict on timeout)"
9219        );
9220        return;
9221    }
9222
9223    // The caller already logged the rich failure line with reason + per-category
9224    // summary; avoid a redundant second error log here.
9225    let _ = confirmed_failed_key_count;
9226    {
9227        let mut state = sync_state.write().await;
9228        state.clear_active_bootstrap_claim(challenged_peer);
9229    }
9230    {
9231        let mut provers_guard = recent_provers.write().await;
9232        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9233    }
9234    // Deliberately NOT routed through the release switch. This is the commitment-bound
9235    // subtree audit: the peer published a signed claim to hold these keys and could not
9236    // answer for them. That contract is enforced in every release, including the one that
9237    // withholds the penalty for merely not holding a close-group chunk, because the whole
9238    // migration depends on a node's reduced commitment still meaning something.
9239    p2p_node
9240        .report_trust_event(
9241            challenged_peer,
9242            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9243        )
9244        .await;
9245}
9246
9247/// Handle audit result: log findings and emit trust events.
9248async fn handle_subtree_audit_result(
9249    result: &AuditTickResult,
9250    p2p_node: &Arc<P2PNode>,
9251    sync_state: &Arc<RwLock<NeighborSyncState>>,
9252    recent_provers: &Arc<RwLock<RecentProvers>>,
9253    config: &ReplicationConfig,
9254) {
9255    match result {
9256        AuditTickResult::Passed {
9257            challenged_peer,
9258            keys_checked,
9259        } => {
9260            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9261            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9262            // Peer responded normally — clear the active bootstrap claim while
9263            // retaining history so a later claim is treated as repeated abuse.
9264            {
9265                let mut state = sync_state.write().await;
9266                state.clear_active_bootstrap_claim(challenged_peer);
9267            }
9268            p2p_node
9269                .report_trust_event(
9270                    challenged_peer,
9271                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9272                )
9273                .await;
9274        }
9275        AuditTickResult::Failed {
9276            evidence,
9277            no_response_class,
9278        } => {
9279            if let FailureEvidence::AuditFailure {
9280                challenged_peer,
9281                confirmed_failed_keys,
9282                summary,
9283                reason,
9284                ..
9285            } = evidence
9286            {
9287                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9288                // Rich diagnostics (from main's audit-failure logging) + the
9289                // first-failed-key correlation handle.
9290                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9291                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9292                error!(
9293                    "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
9294                    audit_failure_class,
9295                    confirmed_failed_keys.len(),
9296                    summary.challenged_keys,
9297                    summary.absent_keys,
9298                    summary.digest_mismatch_keys,
9299                );
9300                // Route the side effects through the subtree-only failure path.
9301                // Responsible-chunk `AuditChallenge` handling intentionally uses
9302                // its own old immediate-penalty handler below.
9303                handle_subtree_failed_audit(
9304                    challenged_peer,
9305                    confirmed_failed_keys.len(),
9306                    reason,
9307                    p2p_node,
9308                    sync_state,
9309                    recent_provers,
9310                )
9311                .await;
9312            }
9313        }
9314        AuditTickResult::BootstrapClaim { peer } => {
9315            // Gap 6: BootstrapClaimAbuse grace period in audit path.
9316            // Separate state mutation from network I/O to avoid holding the
9317            // write lock across report_trust_event.
9318            let should_report = {
9319                let now = Instant::now();
9320                let mut state = sync_state.write().await;
9321                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9322                {
9323                    BootstrapClaimObservation::WithinGrace { .. } => {
9324                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9325                        false
9326                    }
9327                    BootstrapClaimObservation::PastGrace { first_seen } => {
9328                        warn!(
9329                            "Audit: peer {peer} claiming bootstrap past grace period \
9330                             ({:?} > {:?}), reporting abuse",
9331                            now.duration_since(first_seen),
9332                            config.bootstrap_claim_grace_period,
9333                        );
9334                        true
9335                    }
9336                    BootstrapClaimObservation::Repeated { first_seen } => {
9337                        warn!(
9338                            "Audit: peer {peer} repeated bootstrap claim after previously \
9339                             stopping; first claim was {:?} ago, reporting abuse",
9340                            now.duration_since(first_seen),
9341                        );
9342                        true
9343                    }
9344                }
9345            };
9346            if should_report {
9347                p2p_node
9348                    .report_trust_event(
9349                        peer,
9350                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9351                    )
9352                    .await;
9353            }
9354        }
9355        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9356    }
9357}
9358
9359/// Whether a confirmed audit failure with this reason clears the peer's active
9360/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9361/// bootstrapping); every confirmed storage-integrity reason does.
9362///
9363/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9364/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9365/// still reports the normal audit trust penalty.
9366fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9367    !matches!(reason, AuditFailureReason::Timeout)
9368}
9369
9370/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9371/// events and manage bootstrap-claim state.
9372///
9373/// This is intentionally separate from the subtree audit result handler. A
9374/// responsible-chunk `AuditChallenge` `Failed` result reports
9375/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9376/// restoring the pre-ADR-0002 behaviour.
9377#[allow(clippy::too_many_lines)]
9378async fn handle_audit_result(
9379    result: &AuditTickResult,
9380    p2p_node: &Arc<P2PNode>,
9381    sync_state: &Arc<RwLock<NeighborSyncState>>,
9382    config: &ReplicationConfig,
9383) {
9384    match result {
9385        AuditTickResult::Passed {
9386            challenged_peer,
9387            keys_checked,
9388        } => {
9389            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9390            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9391            {
9392                let mut state = sync_state.write().await;
9393                state.clear_active_bootstrap_claim(challenged_peer);
9394            }
9395            p2p_node
9396                .report_trust_event(
9397                    challenged_peer,
9398                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9399                )
9400                .await;
9401        }
9402        AuditTickResult::Failed {
9403            evidence,
9404            no_response_class,
9405        } => {
9406            if let FailureEvidence::AuditFailure {
9407                challenged_peer,
9408                confirmed_failed_keys,
9409                summary,
9410                reason,
9411                ..
9412            } = evidence
9413            {
9414                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9415                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9416                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9417                error!(
9418                    "Audit failure for {challenged_peer}: reason={reason:?}, audit_failure_class={}, confirmed_failed_keys={}, challenged_keys={}, absent_keys={}, digest_mismatch_keys={}, first_failed_key={first_failed_key}",
9419                    audit_failure_class,
9420                    confirmed_failed_keys.len(),
9421                    summary.challenged_keys,
9422                    summary.absent_keys,
9423                    summary.digest_mismatch_keys,
9424                );
9425                if audit_failure_clears_bootstrap_claim(reason) {
9426                    let mut state = sync_state.write().await;
9427                    state.clear_active_bootstrap_claim(challenged_peer);
9428                } else {
9429                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9430                }
9431                config::penalise_unheld_close_group_chunk(
9432                    p2p_node,
9433                    challenged_peer,
9434                    crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
9435                    config::AUDIT_FAILURE_TRUST_WEIGHT,
9436                )
9437                .await;
9438            }
9439        }
9440        AuditTickResult::BootstrapClaim { peer } => {
9441            let should_report = {
9442                let now = Instant::now();
9443                let mut state = sync_state.write().await;
9444                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9445                {
9446                    BootstrapClaimObservation::WithinGrace { .. } => {
9447                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9448                        false
9449                    }
9450                    BootstrapClaimObservation::PastGrace { first_seen } => {
9451                        warn!(
9452                            "Audit: peer {peer} claiming bootstrap past grace period \
9453                             ({:?} > {:?}), reporting abuse",
9454                            now.duration_since(first_seen),
9455                            config.bootstrap_claim_grace_period,
9456                        );
9457                        true
9458                    }
9459                    BootstrapClaimObservation::Repeated { first_seen } => {
9460                        warn!(
9461                            "Audit: peer {peer} repeated bootstrap claim after previously \
9462                             stopping; first claim was {:?} ago, reporting abuse",
9463                            now.duration_since(first_seen),
9464                        );
9465                        true
9466                    }
9467                }
9468            };
9469            if should_report {
9470                p2p_node
9471                    .report_trust_event(
9472                        peer,
9473                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9474                    )
9475                    .await;
9476            }
9477        }
9478        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9479    }
9480}
9481
9482/// Whether a confirmed audit failure with this reason should revoke the
9483/// peer's `recent_provers` holder credit immediately (v12 §6).
9484///
9485/// `true` for any reason where the peer actually answered (or admitted
9486/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9487/// bytes for committed key"), `MalformedResponse` — these prove the
9488/// peer no longer holds what it committed to, so it must not keep
9489/// holder credit for the proof TTL. `false` for `Timeout`: a single
9490/// dropped packet must not strip an honest peer; the 40-min TTL is the
9491/// deliberate liveness cushion there.
9492fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9493    !matches!(reason, AuditFailureReason::Timeout)
9494}
9495
9496/// Apply the holder-credit revocation decision for a confirmed audit
9497/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9498/// testable without a live `P2PNode`: the production `Failed` arm of
9499/// `handle_subtree_audit_result` calls exactly this.
9500fn apply_audit_failure_credit_revocation(
9501    provers: &mut RecentProvers,
9502    challenged_peer: &PeerId,
9503    reason: &AuditFailureReason,
9504) {
9505    if audit_failure_revokes_holder_credit(reason) {
9506        provers.forget_peer(challenged_peer);
9507    }
9508}
9509
9510// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9511
9512// ---------------------------------------------------------------------------
9513// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9514// ---------------------------------------------------------------------------
9515
9516/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9517/// message handler passes one value instead of a long argument list; all
9518/// fields are cheap `Arc` clones.
9519#[derive(Clone)]
9520struct GossipAuditTrigger {
9521    p2p_node: Arc<P2PNode>,
9522    config: Arc<ReplicationConfig>,
9523    recent_provers: Arc<RwLock<RecentProvers>>,
9524    sync_state: Arc<RwLock<NeighborSyncState>>,
9525    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9526    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9527    /// only when a real audit is about to be sent — never by a losing lottery
9528    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9529    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9530    detached_task_tracker: TaskTracker,
9531    /// Gossip-private lottery attempt window: stamped on every roll (win or
9532    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9533    /// The first-audit scheduler never reads this map.
9534    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9535}
9536
9537/// What a gossip ingest yields for the audit trigger: the commitment hash to
9538/// pin and the `key_count` needed to size the response deadline from the actual
9539/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9540/// or not) so a stable-keyset node stays auditable — not just on its first
9541/// commitment.
9542#[derive(Debug, Clone, Copy)]
9543struct AuditTarget {
9544    pin_hash: [u8; 32],
9545    key_count: u32,
9546}
9547
9548/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9549/// verifier's cross-check so it can receive a **deterministic first audit**.
9550///
9551/// Sent from the verifier to the replication engine's first-audit drainer. The
9552/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9553/// audits of the same peer revert to the gossip lottery), orders most-recently-
9554/// monetized first, and runs the same `run_subtree_audit` under the same
9555/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9556#[derive(Debug, Clone, Copy)]
9557pub struct MonetizedPinEvent {
9558    /// The peer whose commitment backed the payment.
9559    pub peer: PeerId,
9560    /// The pinned commitment hash.
9561    pub pin: [u8; 32],
9562    /// The committed key count (sizes the audit deadline).
9563    pub key_count: u32,
9564    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9565    /// pin whose quote is older than the answerability window (ADR-0004 A1
9566    /// guardrail A): with grace removed, challenging an aged-out pin would
9567    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9568    pub quote_ts: SystemTime,
9569}
9570
9571/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9572/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9573/// stamps `now`), `false` if it was audited within
9574/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9575/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9576/// without a live node: a burst of gossips from one peer yields at most one
9577/// `true` per cooldown window.
9578fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9579    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9580    let known = match map.get(peer) {
9581        Some(&last) => {
9582            if now.saturating_duration_since(last) < cooldown {
9583                return false;
9584            }
9585            true
9586        }
9587        None => false,
9588    };
9589    // Bound the map under churn like its siblings (drop the oldest stamp) before
9590    // admitting a brand-new peer.
9591    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9592        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9593            map.remove(&victim);
9594        }
9595    }
9596    map.insert(*peer, now);
9597    true
9598}
9599
9600/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9601/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9602/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9603/// already covered; the authoritative check-and-stamp still runs at promotion,
9604/// so this is only an optimization and never the security boundary.
9605fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9606    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9607    map.get(peer)
9608        .is_none_or(|&last| now.saturating_duration_since(last) >= cooldown)
9609}
9610
9611/// The gossip-audit launch decision in ONE place so the ordering is shared
9612/// between production and its test (ADR-0002 "occasional surprise exams").
9613///
9614/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9615/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9616/// sampled first, a gossip flood would re-roll it on every message until one
9617/// won, multiplying audits, so each peer gets at most one lottery roll per
9618/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9619/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9620/// also consults — only after a WIN, i.e. only when a real audit is about to be
9621/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9622/// wire, so it must not defer a paid first audit (repeatable losses could
9623/// otherwise hold a monetized pin past its answerability window). Production
9624/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9625/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9626/// here fails the test.
9627fn audit_launch_decision(
9628    attempts: &mut HashMap<PeerId, Instant>,
9629    launched: &mut HashMap<PeerId, Instant>,
9630    peer: &PeerId,
9631    now: Instant,
9632    lottery_wins: bool,
9633) -> bool {
9634    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9635    // window even on a loss; private to the gossip path).
9636    if !cooldown_allows_audit(attempts, peer, now) {
9637        return false;
9638    }
9639    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9640    // shared.
9641    if !lottery_wins {
9642        return false;
9643    }
9644    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9645    // either path still suppresses this launch), stamped only on launch.
9646    cooldown_allows_audit(launched, peer, now)
9647}
9648
9649/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9650/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9651/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9652/// handling is never blocked on a network round-trip.
9653async fn maybe_trigger_gossip_audit(
9654    trigger: &GossipAuditTrigger,
9655    peer: &PeerId,
9656    target: AuditTarget,
9657) {
9658    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9659    // lives in the pure `audit_launch_decision` so the ordering is shared with
9660    // its test. Sample the lottery here, then let the helper apply the gates.
9661    let now = Instant::now();
9662    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9663    {
9664        // Lock order: attempts before the shared cooldown; this is the only
9665        // place both are held together.
9666        let mut attempts = trigger.lottery_attempts.write().await;
9667        let mut launched = trigger.cooldown.write().await;
9668        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9669            return;
9670        }
9671    }
9672
9673    let detached_task_tracker = trigger.detached_task_tracker.clone();
9674    let trigger = trigger.clone();
9675    let peer = *peer;
9676    detached_task_tracker.spawn(async move {
9677        let credit = storage_commitment_audit::AuditCredit {
9678            recent_provers: &trigger.recent_provers,
9679        };
9680        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9681            &trigger.p2p_node,
9682            &trigger.config,
9683            &peer,
9684            target.pin_hash,
9685            target.key_count,
9686            Some(&credit),
9687            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9688        )
9689        .await;
9690        handle_subtree_audit_result(
9691            &result,
9692            &trigger.p2p_node,
9693            &trigger.sync_state,
9694            &trigger.recent_provers,
9695            &trigger.config,
9696        )
9697        .await;
9698    });
9699}
9700
9701/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9702///
9703/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9704/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9705/// of its last attempt. Holds one write lock across the decision so two
9706/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9707/// caller's expensive verify so a slow/failed verify still rate-limits the next
9708/// message. Bounds the map under a flood of distinct peer ids.
9709async fn sig_verify_rate_limit_ok(
9710    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9711    source: &PeerId,
9712    now: Instant,
9713) -> bool {
9714    let mut attempts = sig_verify_attempts.write().await;
9715    if let Some(&last) = attempts.get(source) {
9716        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9717            return false;
9718        }
9719    }
9720    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9721        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9722            attempts.remove(&victim);
9723        }
9724    }
9725    attempts.insert(*source, now);
9726    true
9727}
9728
9729/// Verify + store an inbound commitment from a gossip peer.
9730///
9731/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9732/// the bootstrap-sync loop. Drops the commitment unless all five gates
9733/// pass:
9734///   1. `source` is in our DHT routing table (sybil/churn cap).
9735///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9736///      binding to the authenticated transport peer).
9737///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9738///      (the embedded pubkey actually belongs to the claimed identity —
9739///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9740///   4. `verify_commitment_signature(commitment)` succeeds against the
9741///      embedded public key. The signed payload binds the pubkey, so an
9742///      adversary cannot swap the key while keeping the body.
9743///   5. The cache has room or this is an update for an existing entry
9744///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9745///
9746/// On all-pass, the commitment is stored as the auditor's per-peer
9747/// "last known commitment" for use as `expected_commitment_hash` in
9748/// future audits.
9749///
9750/// Failures (no commitment / mismatched peer id / bad signature) are
9751/// silent drops — gossip is best-effort and a malformed commitment from
9752/// one peer should not affect anything else.
9753///
9754/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9755/// or not its root changed), so the caller can run a probabilistic,
9756/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9757/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9758/// being auditable, so it cannot pass one audit and then delete data while
9759/// re-gossiping the same root forever. The cooldown + probability bound the
9760/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9761/// gate) or there is nothing to pin.
9762///
9763/// Handle a capable peer gossiping `None` (a commitment downgrade).
9764///
9765/// A capable peer that previously gossiped a commitment but now gossips `None`
9766/// is trying to drop off the audit path. Within the answerability window we keep
9767/// the cached commitment pinned AND return it as an audit target so this gossip
9768/// still schedules a subtree audit against the peer's last known commitment — if
9769/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9770/// the trigger MUST fire here or the downgrade is never re-challenged).
9771///
9772/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9773/// honours for its own retired commitment: once that elapses since we last
9774/// received the peer's commitment, an honest peer has legitimately retired that
9775/// root (its responder side `retire_current`s and lets it age out) and can no
9776/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9777/// failure, so we then forget the cached commitment (keeping the sticky
9778/// `commitment_capable` bit) and stop pinning it.
9779async fn handle_commitment_downgrade(
9780    source: &PeerId,
9781    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9782) -> Option<AuditTarget> {
9783    let now = Instant::now();
9784    let cached = {
9785        let map = last_commitment_by_peer.read().await;
9786        map.get(source).and_then(|rec| {
9787            if !rec.commitment_capable {
9788                return None;
9789            }
9790            let last = rec.last_commitment()?;
9791            let pin = rec.commitment_hash()?;
9792            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9793            Some((pin, last.key_count, fresh))
9794        })
9795    };
9796    match cached {
9797        Some((pin, key_count, true)) => {
9798            warn!(
9799                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9800                 (downgrade attempt); auditing against its last cached commitment"
9801            );
9802            Some(AuditTarget {
9803                pin_hash: pin,
9804                key_count,
9805            })
9806        }
9807        Some((_, _, false)) => {
9808            // Cached commitment has aged past the answerability window — forget
9809            // it so we stop pinning a root the peer is no longer obliged to
9810            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9811            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9812            // from this peer may have refreshed `received_at` in the gap between
9813            // our read and write locks; if so, leave its fresh commitment intact.
9814            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9815                let still_stale =
9816                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9817                if still_stale {
9818                    rec.clear_commitment();
9819                    debug!(
9820                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9821                         commitment aged past the answerability TTL; forgetting it"
9822                    );
9823                }
9824            }
9825            None
9826        }
9827        None => None,
9828    }
9829}
9830
9831async fn ingest_peer_commitment(
9832    source: &PeerId,
9833    commitment: Option<&StorageCommitment>,
9834    p2p_node: &Arc<P2PNode>,
9835    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9836    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
9837    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9838) -> Option<AuditTarget> {
9839    let Some(c) = commitment else {
9840        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
9841    };
9842    // RT-membership gate: only accept commitments from peers in our
9843    // routing table. Off-RT senders (sybils, drive-by relays) cannot
9844    // populate the cache, which closes the hole where a flood of
9845    // off-RT identities could fill the cap and evict honest
9846    // peers. The neighbor-sync request handler applies the same gate
9847    // before admitting inbound replication hints (see neighbor_sync.rs
9848    // `sender_in_rt`); we mirror that policy here for the commitment
9849    // piggyback.
9850    if !p2p_node.dht_manager().is_in_routing_table(source).await {
9851        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
9852        return None;
9853    }
9854    // Peer-id binding: the commitment's claimed sender must match the
9855    // authenticated transport peer (`source`). Defeats relay/replay
9856    // and also pins which embedded public key we are about to verify
9857    // against — the verify itself trusts the embedded key, so the
9858    // peer-id binding is the link to a real identity.
9859    if &c.sender_peer_id != source.as_bytes() {
9860        warn!(
9861            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
9862             (dropped, possible relay attempt)"
9863        );
9864        return None;
9865    }
9866    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
9867    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
9868    // with a throwaway key they own and lie about which identity it
9869    // belongs to (the embedded-key signature would verify trivially).
9870    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
9871    if derived_peer_id != c.sender_peer_id {
9872        warn!(
9873            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
9874             {source} (dropped, throwaway-key attack)"
9875        );
9876        return None;
9877    }
9878    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
9879    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
9880    // sybil/RT-membership-bypassing peer that flooded valid-looking
9881    // gossip would otherwise burn CPU on every message. The rate
9882    // limit is checked AFTER cheap structural gates (RT, peer-id
9883    // binding, pubkey-binding) and BEFORE the expensive sig verify.
9884    //
9885    // Tracked in `sig_verify_attempts` (separate from
9886    // last_commitment_by_peer) so EVERY attempt — successful or not —
9887    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
9888    // would skip the cap for peers we've never successfully verified,
9889    // letting a flood of invalid-but-structurally-plausible gossips
9890    // burn CPU.
9891    let now = Instant::now();
9892    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
9893        debug!(
9894            "ingest_peer_commitment: rate-limited sig verify from {source} \
9895             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
9896        );
9897        return None;
9898    }
9899    // Signature verify, using the public key embedded in the commitment
9900    // itself. The pubkey is bound by the signature payload (see
9901    // commitment_signed_payload) so an adversary cannot keep the body
9902    // and swap the key to one they hold the secret for.
9903    if !crate::replication::commitment::verify_commitment_signature(c) {
9904        warn!(
9905            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
9906             (dropped, forged commitment)"
9907        );
9908        return None;
9909    }
9910    // The new commitment's hash, used to store and to pin for the audit target.
9911    let new_hash = commitment_hash(c);
9912    let mut map = last_commitment_by_peer.write().await;
9913    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
9914    // evict an arbitrary existing entry to make room. Updates for peers
9915    // already in the map are always accepted (they replace, not grow).
9916    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
9917        // Drop one arbitrary entry. HashMap iter order is random which
9918        // is fine — over time PeerRemoved cleanup keeps the working set
9919        // anchored on the real RT membership; this cap only fires under
9920        // active flooding attempts.
9921        if let Some(victim) = map.keys().next().copied() {
9922            map.remove(&victim);
9923            warn!(
9924                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
9925                 evicted {victim} to admit {source}"
9926            );
9927        }
9928    }
9929    // Preserve sticky commitment_capable across updates — once true,
9930    // always true. New entries start with capable = true (we just
9931    // verified a valid commitment from this peer).
9932    map.entry(*source)
9933        .and_modify(|r| {
9934            // set_commitment refreshes the cached hash (§13) alongside the
9935            // commitment + received_at so they never drift.
9936            r.set_commitment(c.clone(), now);
9937            r.last_sig_verify_at = now;
9938            r.commitment_capable = true; // sticky-redundant but explicit
9939        })
9940        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
9941    drop(map);
9942    // Record the sticky "ever v12-capable" bit in a set independent of
9943    // `last_commitment_by_peer` (whose entries can be evicted by
9944    // `PeerRemoved` and the sybil cap). This is what the §3 audit
9945    // shield and the §6 holder-eligibility closure consult to decide
9946    // whether the peer is expected to speak v12.
9947    //
9948    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
9949    // identity-rotation attacks: once full, new entries are refused.
9950    // Refusal degrades over-cap peers to the behaviour before this set
9951    // existed (treated as legacy on rejoin), which is not a security
9952    // regression and preserves the historic set stable.
9953    {
9954        let mut set = ever_capable_peers.write().await;
9955        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
9956            set.insert(*source);
9957        } else {
9958            warn!(
9959                "ingest_peer_commitment: ever_capable_peers at cap \
9960                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
9961            );
9962        }
9963    }
9964    // Return an audit target for EVERY valid stored commitment (changed or
9965    // not), so the caller's cooldown+probability-gated trigger keeps a
9966    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
9967    // failure (new_hash == None, unreachable for a real commitment) yields None.
9968    new_hash.map(|pin_hash| AuditTarget {
9969        pin_hash,
9970        key_count: c.key_count,
9971    })
9972}
9973
9974// ---------------------------------------------------------------------------
9975// Storage-bound audit (v12) — responder commitment rotation
9976// ---------------------------------------------------------------------------
9977
9978/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
9979/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
9980/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
9981async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
9982    let bytes = match tokio::fs::read(path).await {
9983        Ok(b) => b,
9984        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
9985            debug!(
9986                "Commitment retention: no snapshot at {} (fresh start)",
9987                path.display()
9988            );
9989            return;
9990        }
9991        Err(e) => {
9992            warn!(
9993                "Commitment retention: failed to read {}: {e}",
9994                path.display()
9995            );
9996            return;
9997        }
9998    };
9999    if let Some(mut persisted) = PersistedRetention::from_bytes(&bytes) {
10000        let sidecar = pointer_leaves_path(path);
10001        match tokio::fs::read(&sidecar).await {
10002            Ok(leaves) => {
10003                if !persisted.attach_pointer_leaves(&leaves) {
10004                    warn!(
10005                        "Commitment retention: corrupt pointer leaves at {}; \
10006                         commitments holding pointers will not be restored",
10007                        sidecar.display()
10008                    );
10009                }
10010            }
10011            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
10012            Err(e) => warn!(
10013                "Commitment retention: failed to read {}: {e}",
10014                sidecar.display()
10015            ),
10016        }
10017        state.restore(&persisted);
10018        info!(
10019            "Commitment retention: reloaded {} slot(s) from {}",
10020            state.retained_slot_count(),
10021            path.display()
10022        );
10023    } else {
10024        warn!(
10025            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
10026            path.display()
10027        );
10028    }
10029}
10030
10031/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
10032/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
10033/// needless disk writes on idle nodes. On success updates `last` to the bytes
10034/// written; on a serialization/write error the existing on-disk snapshot is left
10035/// intact (never truncated).
10036///
10037/// The pointer leaves go to a sidecar written first (ADR-0016), so the
10038/// retention file never names a commitment whose pointer leaves are not yet
10039/// on disk. A crash between the two leaves a sidecar ahead of the file, which
10040/// is harmless: it is keyed by commitment hash.
10041async fn persist_retention_if_changed(
10042    state: &ResponderCommitmentState,
10043    path: &Path,
10044    last: &mut Option<Vec<u8>>,
10045) {
10046    let snapshot = state.snapshot();
10047    let (Some(bytes), Some(leaves)) = (snapshot.to_bytes(), snapshot.pointer_leaves_bytes()) else {
10048        warn!("Commitment retention: serialization failed; keeping previous snapshot");
10049        return;
10050    };
10051    let mut combined = leaves.clone();
10052    combined.extend_from_slice(&bytes);
10053    if last.as_deref() == Some(combined.as_slice()) {
10054        return;
10055    }
10056    if write_retention_atomic(&pointer_leaves_path(path), leaves).await
10057        && write_retention_atomic(path, bytes).await
10058    {
10059        *last = Some(combined);
10060    }
10061}
10062
10063/// Where the pointer leaves of the retention at `path` are kept.
10064fn pointer_leaves_path(path: &Path) -> PathBuf {
10065    path.with_file_name("commitment_retention_pointers.bin")
10066}
10067
10068/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
10069/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
10070/// success. Only the retention-persist loop writes this path, so a fixed temp
10071/// name is safe.
10072async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
10073    let path = path.to_path_buf();
10074    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
10075        let tmp = path.with_extension("tmp");
10076        std::fs::write(&tmp, &bytes)?;
10077        std::fs::File::open(&tmp)?.sync_all()?;
10078        std::fs::rename(&tmp, &path)?;
10079        // Fsync the directory so the rename (the durable-commit point) is not
10080        // lost on a crash right after it. An empty parent (relative filename)
10081        // means the current directory.
10082        let dir = path
10083            .parent()
10084            .filter(|p| !p.as_os_str().is_empty())
10085            .unwrap_or_else(|| Path::new("."));
10086        std::fs::File::open(dir)?.sync_all()?;
10087        Ok(())
10088    })
10089    .await;
10090    match res {
10091        Ok(Ok(())) => true,
10092        Ok(Err(e)) => {
10093            warn!("Commitment retention: persist failed: {e}");
10094            false
10095        }
10096        Err(e) => {
10097            warn!("Commitment retention: persist task join failed: {e}");
10098            false
10099        }
10100    }
10101}
10102
10103/// Read the current LMDB key set, build + sign a fresh
10104/// `StorageCommitment`, and rotate it into `state` as the new `current`.
10105/// The prior `current` is demoted to `previous`; the prior `previous` is
10106/// dropped (per `ResponderCommitmentState::rotate`).
10107///
10108/// For content-addressed chunks (Autonomi's chunk store), `address ==
10109/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
10110/// re-read each chunk's bytes to compute the leaf hash.
10111///
10112/// The pointers this node is responsible for are committed alongside, each as
10113/// `(address, pointer_leaf_hash(address))` (ADR-0016), so they are audited and
10114/// priced exactly as chunks are.
10115///
10116/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
10117/// rotate. The auditor side handles "no commitment for this peer" by
10118/// falling back to the legacy plain-digest audit path.
10119async fn rebuild_and_rotate_commitment(
10120    storage: &Arc<ChunkStore>,
10121    pointers: Option<&PointerStore>,
10122    identity: &Arc<NodeIdentity>,
10123    state: &Arc<ResponderCommitmentState>,
10124    p2p: &Arc<P2PNode>,
10125    config: &Arc<ReplicationConfig>,
10126) -> Result<()> {
10127    // Not `all_keys()`. While the node is bridging off the legacy store these are the
10128    // same thing, but once it has settled on what it can hold this narrows to the
10129    // file-backed set, which is what stops it claiming keys it is about to give up. It is
10130    // also what lets `is_held` eventually go false for those keys, which is the gate on
10131    // removing the legacy environment at all.
10132    let stored_keys = storage
10133        .committable_keys()
10134        .await
10135        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
10136
10137    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
10138    // everything currently on disk ("hold"). This is the half of the retention
10139    // contract that lets out-of-range chunks age out: a key that has left our
10140    // close group is excluded from the NEXT commitment, so once its last gossip
10141    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
10142    // set, `ResponderCommitmentState::is_held` goes false,
10143    // and the pruner (which until then vetoes its deletion) reclaims it. Without
10144    // this filter the pruner's reprieve would keep re-committing stale keys
10145    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
10146    // re-committed and re-gossiped every rotation — a permanent pin).
10147    let self_id = *p2p.peer_id();
10148    let mut keys = Vec::with_capacity(stored_keys.len());
10149    for k in stored_keys {
10150        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
10151            keys.push(k);
10152        }
10153    }
10154    // The same rule for pointers: an out-of-range pointer leaves the next
10155    // commitment, and the pruner reclaims it once no retained slot holds it.
10156    let mut pointer_keys = Vec::new();
10157    for state in pointers.map(PointerStore::held_states).unwrap_or_default() {
10158        if admission::is_responsible(&self_id, &state.address, p2p, config.close_group_size).await {
10159            pointer_keys.push(state.address);
10160        }
10161    }
10162
10163    if keys.is_empty() && pointer_keys.is_empty() {
10164        // There used to be a second branch here that dropped every retained root outright
10165        // when the node looked empty. It is gone, and the reason is worth keeping.
10166        //
10167        // "Empty" was decided from key counts, and every version of that test was wrong in
10168        // the same direction. It read the committable set, which narrows to the file-backed
10169        // keys once the migration settles, so a node whose disk filled before it could copy
10170        // anything looked empty with a full legacy store beside it. Adding the raw file index
10171        // still missed a file dropped from the index by a failed read while its legacy copy
10172        // was being put back. Adding the legacy environment still missed a files-only node
10173        // that had published bytes to disk but not yet indexed them, because a file is
10174        // published before it is indexed. Each fix closed one window and left another.
10175        //
10176        // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10177        // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10178        // lane, which is enforced in every release and is not the lane the migration holds
10179        // off — so a node that still holds the bytes is slashed for holding them. Retiring
10180        // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10181        // instead of vanishing now. Both set `has_current = false`; they differ only in
10182        // whether the node goes on being answerable in the meantime. A genuinely empty node
10183        // cannot answer either way, so retiring costs it nothing it had.
10184        //
10185        // So there is one branch, and no emptiness question to get wrong.
10186        //
10187        // A peer may still be pinning a root we gossiped
10188        // moments ago and could demand its bytes in a round-2 challenge, which
10189        // we can still answer (the bytes are present). But we must STOP
10190        // advertising the stale commitment: retire it so `current()` returns
10191        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10192        // The retired slot then ages out by its gossip-answerability TTL while
10193        // remaining answerable for in-flight pins until then. Once it ages out,
10194        // `is_held` flips false and the pruner reclaims the now-uncommitted,
10195        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10196        // pointing at the stale root, which the gossip loop would keep
10197        // re-stamping — pinning its keys forever.)
10198        debug!(
10199            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10200             (stays answerable until its gossip TTL lapses, bytes still on disk)"
10201        );
10202        state.retire_current();
10203        storage.note_commitment_rebuilt();
10204        return Ok(());
10205    }
10206
10207    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10208    // to more than the protocol limit; auditor would reject the
10209    // commitment otherwise).
10210    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10211    let total = keys.len().saturating_add(pointer_keys.len());
10212    if total > cap {
10213        warn!(
10214            "Commitment rotation: key set ({total}) exceeds MAX_COMMITMENT_KEY_COUNT ({cap}); \
10215             truncating — investigate as this likely means a misconfiguration"
10216        );
10217    }
10218
10219    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10220    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10221    // full chunk re-read per rotation.
10222    //
10223    // Consequence to be precise about: because the leaf is `(key, key)`,
10224    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10225    // commitment therefore binds "which keys I claim to hold"; it does NOT
10226    // by itself prove byte possession. Byte possession is enforced by the
10227    // round-2 slice audit: a Bao verified slice decoded against the chunk
10228    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10229    // nonce, so a responder that holds the key list but dropped the bytes
10230    // cannot answer. This is sound ONLY while keys are content addresses;
10231    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10232    // (`evaluate_subtree_structure`), so a non-content-addressed
10233    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10234    // earn credit for `key`. If this module is ever reused for
10235    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10236    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10237    //
10238    // Pointers are that case, and are handled by being told apart rather than
10239    // hashed: a pointer leaf is `(address, pointer_leaf_hash(address))`, which
10240    // the verifier accepts only for a leaf of exactly a pointer's size, and
10241    // round 2 then demands the whole signed record in place of a Bao slice.
10242    // The root binds which pointers are held, never their current state, so an
10243    // update does not move it.
10244    //
10245    // A pointer address that is also a chunk key would need a BLAKE3 preimage;
10246    // the dedup only keeps such a collision from failing the whole build.
10247    let mut entries: Vec<_> = keys
10248        .into_iter()
10249        .map(|k| (k, k))
10250        .chain(
10251            pointer_keys
10252                .into_iter()
10253                .map(|address| (address, commitment::pointer_leaf_hash(&address))),
10254        )
10255        .collect();
10256    entries.sort_by_key(|(k, _)| *k);
10257    entries.dedup_by_key(|(k, _)| *k);
10258    entries.truncate(cap);
10259
10260    // No-op-rotation guard: compute just the Merkle root from `entries`
10261    // and compare against the currently-advertised commitment's root.
10262    // If they match, the key set is unchanged and a new rotation would
10263    // only swap a randomized ML-DSA signature for a fresh one — same
10264    // content, different commitment_hash. That invalidates every
10265    // outstanding `recent_provers` credit on this node across the
10266    // close group with no security benefit, breaking steady-state
10267    // quorum liveness on large nodes that can't re-audit every key
10268    // every rotation interval. Skip the rotation entirely when the
10269    // tree is unchanged.
10270    // Build the tree ONCE here (moving `entries`): it serves both the no-op
10271    // root check below and, if we proceed, the signed commitment via
10272    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10273    // inside `BuiltCommitment::build`).
10274    let candidate_tree = commitment::MerkleTree::build(entries)
10275        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10276    let candidate_root = candidate_tree.root();
10277    if let Some(current) = state.current() {
10278        if current.commitment().root == candidate_root {
10279            debug!(
10280                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10281                hex::encode(candidate_root)
10282            );
10283            // Even though we skip re-signing (to avoid invalidating holder
10284            // credit), retention must still advance on the wall clock: a
10285            // previously-gossiped commitment that holds a now-out-of-range key
10286            // must be able to age out of the answerability window even when the
10287            // committed key set is frozen here for many rotations. Without this,
10288            // the no-op guard would pin a stale slot — and its key — forever.
10289            state.age_out();
10290            // The advertised commitment already equals the committable set, which is
10291            // exactly what the retirement gate is counting.
10292            storage.note_commitment_rebuilt();
10293            return Ok(());
10294        }
10295    }
10296
10297    let sk_bytes = identity.secret_key_bytes().to_vec();
10298    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10299        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10300    let pk_bytes = identity.public_key().as_bytes().to_vec();
10301    let peer_id_bytes = *p2p.peer_id().as_bytes();
10302
10303    let built = commitment_state::BuiltCommitment::build_from_tree(
10304        candidate_tree,
10305        &peer_id_bytes,
10306        &sk,
10307        &pk_bytes,
10308    )
10309    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10310
10311    let hash = hex::encode(built.hash());
10312    let key_count = built.commitment().key_count;
10313    let pointer_count = built.tree().pointer_count();
10314    state.rotate(built);
10315    info!("Storage commitment rotated: hash={hash} key_count={key_count} pointers={pointer_count}");
10316    // Counted only on the paths where the advertised commitment now genuinely reflects
10317    // the committable set, never merely on having read it. The retirement gate is what
10318    // consumes this, and it authorises deleting the legacy store.
10319    storage.note_commitment_rebuilt();
10320    Ok(())
10321}
10322
10323#[cfg(test)]
10324#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10325mod tests {
10326
10327    /// The two fetch failures mean different things and must be charged differently.
10328    ///
10329    /// `NotFound` is a peer saying it does not hold the chunk, which is what a node
10330    /// part-way through the migration says about chunks it has legitimately given up, so
10331    /// it is the lane this release withholds. `Error` has a single producer, the
10332    /// responder's own storage read failing, and that is never about the migration.
10333    #[test]
10334    fn a_missing_chunk_and_a_failed_read_are_different_faults() {
10335        let key = [7u8; 32];
10336        assert_eq!(
10337            fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
10338            Some(FetchFault::UnheldChunk)
10339        );
10340        assert_eq!(
10341            fetch_fault_for(&protocol::FetchResponse::Error {
10342                key,
10343                reason: "read failed".to_string(),
10344            }),
10345            Some(FetchFault::ResponderFault)
10346        );
10347        assert_eq!(
10348            fetch_fault_for(&protocol::FetchResponse::Success {
10349                key,
10350                data: vec![1, 2, 3],
10351            }),
10352            None
10353        );
10354    }
10355
10356    /// The responder's answer says which fault it is, so the mapping from a storage read
10357    /// to a response is what the classification above rests on.
10358    ///
10359    /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10360    /// an I/O fault or a failed integrity check, reads as `Err`. Nothing in the migration
10361    /// turns the first into the second.
10362    #[tokio::test]
10363    async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10364        let dir = tempfile::tempdir().expect("temp dir");
10365        let storage = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
10366            root_dir: dir.path().to_path_buf(),
10367            verify_on_read: true,
10368            max_map_size: 0,
10369            disk_reserve: 0,
10370        })
10371        .await
10372        .expect("open store");
10373
10374        let absent = [9u8; 32];
10375        assert!(
10376            matches!(storage.get(&absent).await, Ok(None)),
10377            "a chunk this node does not hold must read as a plain miss, not a fault"
10378        );
10379
10380        // And the answer each read produces. A miss is `NotFound`, which is the withheld
10381        // lane; a failed read is `Error`, which is not.
10382        assert!(matches!(
10383            fetch_response_for(absent, Ok(None)),
10384            protocol::FetchResponse::NotFound { .. }
10385        ));
10386        assert!(matches!(
10387            fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10388            protocol::FetchResponse::Success { .. }
10389        ));
10390        assert!(matches!(
10391            fetch_response_for(
10392                absent,
10393                Err(crate::error::Error::Storage("read failed".into()))
10394            ),
10395            protocol::FetchResponse::Error { .. }
10396        ));
10397    }
10398    use super::*;
10399    use super::{
10400        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10401        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10402        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10403        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10404        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10405        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10406        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10407        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10408    };
10409    use crate::payment::VerificationContext;
10410    use crate::replication::audit::AuditTickResult;
10411    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10412    use crate::replication::recent_provers::RecentProvers;
10413    use crate::replication::types::{AuditFailureReason, FailureEvidence};
10414    use lru::LruCache;
10415    use saorsa_core::identity::PeerId;
10416    use std::collections::HashMap;
10417    use std::num::NonZeroUsize;
10418    use std::sync::atomic::Ordering;
10419    use std::sync::Arc;
10420    use std::time::Duration;
10421    use std::time::Instant;
10422    use std::time::SystemTime;
10423
10424    #[test]
10425    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10426        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10427            assert_eq!(match_replication_protocol(id), Some((id, false)));
10428            assert_eq!(
10429                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10430                Some((id, true))
10431            );
10432        }
10433        assert_eq!(
10434            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10435            None
10436        );
10437        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10438        assert_eq!(match_replication_protocol(RR_PREFIX), None);
10439    }
10440
10441    #[test]
10442    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10443        use crate::replication::protocol::{
10444            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10445            SubtreeSliceChallenge,
10446        };
10447
10448        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10449            challenge_id: 1,
10450            nonce: [0u8; 32],
10451            challenged_peer_id: [0u8; 32],
10452            expected_commitment_hash: [0u8; 32],
10453            openings: vec![],
10454        });
10455        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10456            challenge_id: 1,
10457            nonce: [0u8; 32],
10458            challenged_peer_id: [0u8; 32],
10459            keys: vec![[0u8; 32]],
10460        });
10461        let digest_response =
10462            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10463        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10464            key: [0u8; 32],
10465            data: vec![],
10466            proof_of_payment: vec![],
10467        });
10468
10469        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10470        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10471
10472        for body in [&digest_challenge, &digest_response, &core] {
10473            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10474            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10475        }
10476
10477        for body in [&subtree, &digest_challenge, &digest_response, &core] {
10478            assert!(body_matches_protocol(body, response_protocol_for(body)));
10479        }
10480    }
10481
10482    fn test_peer(b: u8) -> PeerId {
10483        let mut bytes = [0u8; 32];
10484        bytes[0] = b;
10485        PeerId::from_bytes(bytes)
10486    }
10487
10488    /// A structurally valid offer for `data`: real content address, a proof of
10489    /// the minimum accepted size, distinguished by `proof_marker` so a test can
10490    /// tell whose proof came back out of the queue.
10491    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10492        protocol::FreshReplicationOffer {
10493            key: crate::client::compute_address(&data),
10494            data,
10495            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10496        }
10497    }
10498
10499    fn admit_test_offer(
10500        in_flight: &FreshOfferInFlight,
10501        offer: protocol::FreshReplicationOffer,
10502        source: PeerId,
10503    ) -> FreshOfferAdmission {
10504        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10505    }
10506
10507    #[test]
10508    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10509        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10510        let data = vec![0x11u8; 64];
10511
10512        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10513        let FreshOfferAdmission::Opened(entry) = opened else {
10514            panic!("first offer for a key should open the entry")
10515        };
10516
10517        // A second sender contributes its proof instead of being turned away:
10518        // its bytes are provably the same, so only the proof is worth keeping.
10519        assert!(
10520            matches!(
10521                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10522                FreshOfferAdmission::Joined
10523            ),
10524            "a duplicate from a new source should queue its proof"
10525        );
10526        // The same peer twice is not extra evidence, just extra work.
10527        assert!(
10528            matches!(
10529                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10530                FreshOfferAdmission::DuplicateSource
10531            ),
10532            "one source should hold at most one queued proof per key"
10533        );
10534
10535        // An entry that outlived its handler would bar the key forever.
10536        drop(entry);
10537        assert!(
10538            matches!(
10539                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10540                FreshOfferAdmission::Opened(_)
10541            ),
10542            "a released key should be openable again"
10543        );
10544    }
10545
10546    #[test]
10547    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10548        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10549
10550        // A node only receives offers for keys close to its own ID, so accepted
10551        // keys share a long prefix. Any prefix-derived shard index would have
10552        // funnelled these two onto one lock and serialized them.
10553        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10554        assert!(
10555            matches!(
10556                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10557                FreshOfferAdmission::Opened(_)
10558            ),
10559            "distinct keys should never block each other"
10560        );
10561    }
10562
10563    /// The regression that motivated queueing proofs at all.
10564    ///
10565    /// A sender whose proof does not verify must cost the network its own
10566    /// attempt and nothing more. Refusing every later offer outright made the
10567    /// first arrival the only arrival, so one bad proof lost the record — and
10568    /// the delayed possession check then charged that absence to this node.
10569    #[test]
10570    fn a_failing_proof_hands_the_key_to_the_next_sender() {
10571        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10572        let data = vec![0x5Au8; 128];
10573        let forger = test_peer(0xF0);
10574        let genuine = test_peer(0x0F);
10575
10576        let FreshOfferAdmission::Opened(mut entry) =
10577            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10578        else {
10579            panic!("the first offer should open the entry");
10580        };
10581        assert!(
10582            matches!(
10583                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10584                FreshOfferAdmission::Joined
10585            ),
10586            "the genuine sender must not be turned away by the forger"
10587        );
10588
10589        let first = entry
10590            .next_attempt()
10591            .expect("the opener's proof comes first");
10592        assert_eq!(first.source, forger);
10593
10594        // Treat the forger's proof as failed: the next one is still reachable,
10595        // and it is tried against the bytes already held rather than a refetch.
10596        let second = entry
10597            .next_attempt()
10598            .expect("a failed proof must not consume the key");
10599        assert_eq!(second.source, genuine);
10600        assert_eq!(
10601            second.proof_of_payment,
10602            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10603        );
10604        assert_eq!(
10605            entry.data(),
10606            data.as_slice(),
10607            "every proof is tried against the one copy of the bytes"
10608        );
10609
10610        // Draining the queue releases the key rather than stranding it.
10611        assert!(entry.next_attempt().is_none());
10612        assert!(
10613            matches!(
10614                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10615                FreshOfferAdmission::Opened(_)
10616            ),
10617            "an exhausted entry should release its key"
10618        );
10619    }
10620
10621    /// The cap has to be a lifetime budget, not a queue depth.
10622    ///
10623    /// The handler pops a proof before verifying it, so gating admission on the
10624    /// *instantaneous* queue length lets a fresh source refill the slot that pop
10625    /// just freed. Each refill is another on-chain payment verification, run
10626    /// sequentially while the entry holds its admission permit and a worker
10627    /// slot, so a stream of distinct sources could keep one key's handler — and
10628    /// one of only four workers — busy indefinitely.
10629    #[test]
10630    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10631        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10632        let data = vec![0x3Du8; 32];
10633
10634        let FreshOfferAdmission::Opened(mut entry) =
10635            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10636        else {
10637            panic!("the first offer should open the entry")
10638        };
10639
10640        // Drive pop-then-admit with a fresh source every time, exactly as a
10641        // sybil stream would. The budget must be spent by admissions, not
10642        // returned by pops.
10643        let mut admitted = 1;
10644        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10645            let _ = entry.next_attempt();
10646            if matches!(
10647                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10648                FreshOfferAdmission::Joined
10649            ) {
10650                admitted += 1;
10651            }
10652        }
10653
10654        assert!(
10655            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10656            "a key accepted {admitted} proofs over its lifetime, but the budget is \
10657             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10658        );
10659    }
10660
10661    #[test]
10662    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10663        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10664        let data = vec![0x2Cu8; 32];
10665
10666        // The opener occupies the first slot, so the cap is reached after
10667        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10668        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10669        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10670            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10671            assert!(
10672                matches!(
10673                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10674                    FreshOfferAdmission::Joined
10675                ),
10676                "sender {i} is within the legitimate close-group fan-out"
10677            );
10678        }
10679
10680        let surplus = test_peer(0xEE);
10681        assert!(
10682            matches!(
10683                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10684                FreshOfferAdmission::Full
10685            ),
10686            "past the cap a proof is surplus: enough are already queued to place the record"
10687        );
10688    }
10689
10690    #[test]
10691    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10692        assert!(!verification_request_exceeds_limit(
10693            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10694        ));
10695        assert!(verification_request_exceeds_limit(
10696            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10697        ));
10698    }
10699
10700    // The heavy round-1 limiter enforces the per-peer rate cooldown
10701    // and single-use round-1 → round-2 sessions.
10702    #[tokio::test]
10703    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10704        let limiter = SubtreeRound1Limiter::new(
10705            Duration::from_hours(1),
10706            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10707        );
10708        let peer = test_peer(1);
10709
10710        // First round-1 is admitted; drop the guard so concurrency is free again.
10711        let guard = limiter.admit(&peer).await;
10712        assert!(guard.is_some(), "first round-1 admitted");
10713        drop(guard);
10714        // A second round-1 within the cooldown is dropped even though the heavy
10715        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10716        assert!(
10717            limiter.admit(&peer).await.is_none(),
10718            "second round-1 within cooldown is rate-dropped"
10719        );
10720        // A different peer has its own cooldown.
10721        assert!(limiter.admit(&test_peer(2)).await.is_some());
10722
10723        // Session: opened by round 1, consumed exactly once by the matching round 2.
10724        let hash = [7u8; 32];
10725        let nonce = [9u8; 32];
10726        limiter.open_session(peer, 42, hash, nonce).await;
10727        // Wrong nonce / commitment does not match.
10728        assert!(!limiter.consume_session(&peer, 42, &hash, &[0u8; 32]).await);
10729        assert!(!limiter.consume_session(&peer, 42, &[0u8; 32], &nonce).await);
10730        // A round 2 with no prior round 1 (wrong challenge_id) misses.
10731        assert!(!limiter.consume_session(&peer, 99, &hash, &nonce).await);
10732        // The matching round 2 consumes it — and only once (single-use).
10733        assert!(limiter.consume_session(&peer, 42, &hash, &nonce).await);
10734        assert!(!limiter.consume_session(&peer, 42, &hash, &nonce).await);
10735    }
10736
10737    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
10738    // so a party holding several identities refills its allowance by rotating
10739    // between them and can keep the heavy pool busy indefinitely. The work
10740    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
10741    // so a fresh identity is refused exactly like a repeat caller once it is
10742    // spent. That is the difference between bounding concurrency and bounding
10743    // sustained work.
10744    #[tokio::test]
10745    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
10746        // Cooldown disabled so only the work budget can refuse anything.
10747        let limiter =
10748            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10749        assert!(
10750            limiter.admit(&test_peer(1)).await.is_some(),
10751            "a node starts with budget in hand so it can serve audits at once"
10752        );
10753
10754        // Serve enough proof work to run the balance into debt. Charging exactly
10755        // the burst would leave it at zero, which the next nanosecond of refill
10756        // lifts back above the line — the debt is the point.
10757        limiter
10758            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
10759            .await;
10760
10761        for id in 2..8u8 {
10762            assert!(
10763                limiter.admit(&test_peer(id)).await.is_none(),
10764                "a never-seen peer must still be refused while the budget is spent"
10765            );
10766        }
10767    }
10768
10769    // The budget is a rate, not a quota: it comes back on its own, so an honest
10770    // auditor blocked by a flood is only delayed. Carrying the debt is what
10771    // prices an expensive proof above a cheap one — without it, a proof reading
10772    // a maximal subtree would cost no more of the next caller's wait than a
10773    // one-leaf proof.
10774    #[test]
10775    fn round1_work_budget_carries_debt_and_refills_over_time() {
10776        let now = Instant::now();
10777        let at = |secs: u64| {
10778            now.checked_add(Duration::from_secs(secs))
10779                .unwrap_or_else(Instant::now)
10780        };
10781        let mut budget = Round1WorkBudget {
10782            balance: 0,
10783            last_refill: now,
10784        };
10785        assert!(!budget.has_budget(now), "empty means empty");
10786
10787        // A proof costing four seconds' worth of refill leaves four seconds of
10788        // debt, so the wait scales with what was actually served.
10789        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
10790        assert!(
10791            !budget.has_budget(at(3)),
10792            "still in debt three seconds after an over-large proof"
10793        );
10794        assert!(
10795            budget.has_budget(at(5)),
10796            "the debt is worked off at the refill rate"
10797        );
10798
10799        // Idle time does not bank unbounded credit for a later flood.
10800        budget.refill(at(24 * 60 * 60));
10801        assert_eq!(
10802            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
10803            "refill is capped at the burst size"
10804        );
10805    }
10806
10807    // The heavy round-1 pool size is the tightest bound the responder applies and
10808    // the one least backed by fleet measurement, so it is read from config rather
10809    // than baked into the binary: a fleet that lands on the wrong number retunes
10810    // instead of waiting for a release. These pin that the configured value is
10811    // what actually gates admission, and that a 0 degrades to slow, not to off —
10812    // a wedged-shut responder would read on every auditor as a graced timeout,
10813    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
10814    #[tokio::test]
10815    async fn round1_pool_size_comes_from_config() {
10816        // Cooldown disabled so only concurrency can refuse anything.
10817        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10818        let held = limiter.admit(&test_peer(1)).await;
10819        assert!(held.is_some(), "the single configured slot is admitted");
10820        assert!(
10821            limiter.admit(&test_peer(2)).await.is_none(),
10822            "a second concurrent round 1 is refused at a configured pool of 1, \
10823             proving admission follows config rather than the compiled-in default"
10824        );
10825        drop(held);
10826        assert!(
10827            limiter.admit(&test_peer(2)).await.is_some(),
10828            "the slot is reusable once the first proof completes"
10829        );
10830    }
10831
10832    #[tokio::test]
10833    async fn round1_pool_size_of_zero_is_clamped_to_one() {
10834        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
10835        assert!(
10836            limiter.admit(&test_peer(1)).await.is_some(),
10837            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
10838        );
10839    }
10840
10841    fn test_key(b: u8) -> crate::ant_protocol::XorName {
10842        let mut k = [0u8; 32];
10843        k[0] = b;
10844        k
10845    }
10846
10847    #[test]
10848    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
10849        let source = test_peer(0x91);
10850        let corroborator = test_peer(0x92);
10851        let mut evidence = types::KeyVerificationEvidence {
10852            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
10853            paid_list: HashMap::new(),
10854        };
10855        let failed = KeyVerificationOutcome::QuorumFailed;
10856
10857        assert_eq!(
10858            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10859            Some((source, SingletonHintFault::RejectedByCloseGroup)),
10860            "a close-group rejection outranks the denial: the key does not exist, which is \
10861             a bad hint however the sender's own disk is doing"
10862        );
10863        assert_eq!(
10864            punishable_singleton_replica_hint_source(
10865                &HashSet::from([source, corroborator]),
10866                &failed,
10867                &evidence,
10868            ),
10869            None,
10870            "corroborated hints must not use the sole-source penalty lane"
10871        );
10872        assert_eq!(
10873            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
10874            None,
10875            "paid-list advertisements do not claim possession, so they leave the \
10876             replica-hint source set empty and cannot be penalized"
10877        );
10878
10879        evidence
10880            .presence
10881            .insert(source, PresenceEvidence::Unresolved);
10882        assert_eq!(
10883            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
10884            Some((source, SingletonHintFault::RejectedByCloseGroup)),
10885            "definitive close-group rejection is punishable without direct contradiction"
10886        );
10887        assert_eq!(
10888            punishable_singleton_replica_hint_source(
10889                &HashSet::from([source]),
10890                &KeyVerificationOutcome::QuorumInconclusive,
10891                &evidence,
10892            ),
10893            None,
10894            "timeouts and inconclusive evidence are neutral"
10895        );
10896
10897        evidence.presence.insert(source, PresenceEvidence::Absent);
10898        assert_eq!(
10899            punishable_singleton_replica_hint_source(
10900                &HashSet::from([source]),
10901                &KeyVerificationOutcome::QuorumVerified {
10902                    sources: vec![corroborator],
10903                },
10904                &evidence,
10905            ),
10906            Some((source, SingletonHintFault::DeniedPossession)),
10907            "an explicit denial is punishable regardless of the overall outcome, and is \
10908             classified separately because it is a statement about the sender's own \
10909             storage rather than about the key"
10910        );
10911    }
10912
10913    /// Build a round-2 slice challenge matching an open session. `openings` is
10914    /// empty: these tests exercise admission and session handling only, which
10915    /// run before any block is opened.
10916    fn slice_challenge(
10917        challenge_id: u64,
10918        commitment_hash: [u8; 32],
10919        nonce: [u8; 32],
10920    ) -> protocol::SubtreeSliceChallenge {
10921        protocol::SubtreeSliceChallenge {
10922            challenge_id,
10923            nonce,
10924            challenged_peer_id: [0u8; 32],
10925            expected_commitment_hash: commitment_hash,
10926            openings: Vec::new(),
10927        }
10928    }
10929
10930    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
10931    // responder caps MUST NOT burn the single-use round-1 session.
10932    //
10933    // The handler used to consume the session first and admit second, so a
10934    // transient local capacity drop permanently destroyed that audit exchange —
10935    // every retry hit the `no live round-1 session` path and got `Transient`,
10936    // even after load cleared. Turning momentary local load into a deterministic
10937    // round-2 miss costs the responder its whole-slice credit for that round.
10938    #[tokio::test]
10939    async fn capacity_refused_slice_challenge_preserves_round1_session() {
10940        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10941        let inflight = Arc::new(RwLock::new(HashMap::new()));
10942        let round1 =
10943            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10944        let peer = test_peer(0xB1);
10945        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
10946        let challenge = slice_challenge(id, hash, nonce);
10947
10948        round1.open_session(peer, id, hash, nonce).await;
10949
10950        // Saturate this peer's share so the next admission must be refused.
10951        let mut hold = Vec::new();
10952        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
10953            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
10954                .await
10955            {
10956                Ok(guard) => hold.push(guard),
10957                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
10958            }
10959        }
10960
10961        let refused =
10962            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10963        assert!(
10964            matches!(refused, SliceAdmission::Capacity(_)),
10965            "a saturated peer share must refuse on capacity, not on session"
10966        );
10967
10968        // Load clears. The session must have survived the refusal.
10969        drop(hold);
10970        let retried =
10971            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10972        assert!(
10973            matches!(retried, SliceAdmission::Admitted(_)),
10974            "the round-1 session must survive a capacity refusal so the retry succeeds"
10975        );
10976
10977        // Still single-use: the successful admission consumed it exactly once.
10978        drop(retried);
10979        let replayed =
10980            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
10981        assert!(
10982            matches!(replayed, SliceAdmission::NoSession),
10983            "a consumed session must not be replayable"
10984        );
10985    }
10986
10987    // The permit taken for the session probe is released when the probe misses,
10988    // so an unsessioned flood cannot pin the responder pool shut.
10989    #[tokio::test]
10990    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
10991        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
10992        let inflight = Arc::new(RwLock::new(HashMap::new()));
10993        let round1 =
10994            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
10995        let peer = test_peer(0xB2);
10996        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
10997
10998        // Far more unsessioned challenges than the per-peer cap would allow if
10999        // the slot leaked on the miss path.
11000        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
11001            let outcome =
11002                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11003            assert!(
11004                matches!(outcome, SliceAdmission::NoSession),
11005                "no session was ever opened, so every attempt must miss"
11006            );
11007        }
11008
11009        assert_eq!(
11010            semaphore.available_permits(),
11011            MAX_CONCURRENT_AUDIT_RESPONSES,
11012            "every global permit must be returned"
11013        );
11014        assert!(
11015            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
11016            "no per-peer slot may be left occupied"
11017        );
11018    }
11019
11020    #[test]
11021    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
11022        assert!(!audit_failure_revokes_holder_credit(
11023            &AuditFailureReason::Timeout
11024        ));
11025        assert!(audit_failure_revokes_holder_credit(
11026            &AuditFailureReason::DigestMismatch
11027        ));
11028    }
11029
11030    #[tokio::test]
11031    async fn audit_responder_admission_reports_per_peer_cap_full() {
11032        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11033        let inflight = Arc::new(RwLock::new(HashMap::new()));
11034        let peer = test_peer(0xA1);
11035
11036        let mut guards = Vec::new();
11037        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11038            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
11039                .await
11040            {
11041                Ok(guard) => guards.push(guard),
11042                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
11043            }
11044        }
11045
11046        let Err(err) =
11047            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11048        else {
11049            panic!("admission should fail once per-peer cap is full");
11050        };
11051        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
11052        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
11053        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11054        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11055
11056        drop(guards);
11057    }
11058
11059    #[tokio::test]
11060    async fn audit_responder_admission_reports_global_pool_full() {
11061        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11062        let inflight = Arc::new(RwLock::new(HashMap::new()));
11063        let peer = test_peer(0xA2);
11064
11065        let mut held_global_permits = Vec::new();
11066        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
11067            held_global_permits.push(
11068                Arc::clone(&semaphore)
11069                    .try_acquire_owned()
11070                    .expect("test should be able to exhaust the global pool"),
11071            );
11072        }
11073
11074        let Err(err) =
11075            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11076        else {
11077            panic!("admission should fail once global pool is full");
11078        };
11079        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
11080        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
11081        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11082        assert_eq!(err.peer_inflight, 0);
11083        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11084
11085        drop(held_global_permits);
11086    }
11087
11088    #[tokio::test]
11089    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
11090        let semaphore = Arc::new(Semaphore::new(1));
11091        let inflight = Arc::new(RwLock::new(HashMap::new()));
11092        let peer = test_peer(0xA3);
11093
11094        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
11095            .await
11096            .expect("first responder should be admitted");
11097        assert_eq!(semaphore.available_permits(), 0);
11098        assert_eq!(inflight.read().await.get(&peer), Some(&1));
11099
11100        drop(guard);
11101        assert_eq!(semaphore.available_permits(), 1);
11102        assert!(!inflight.read().await.contains_key(&peer));
11103    }
11104
11105    #[tokio::test]
11106    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
11107        let semaphore = Arc::new(Semaphore::new(1));
11108        let inflight = Arc::new(RwLock::new(HashMap::new()));
11109        let peer = test_peer(0xA4);
11110        let held_map = inflight.write().await;
11111
11112        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
11113        assert!(
11114            tokio::time::timeout(Duration::from_millis(10), waiting)
11115                .await
11116                .is_err(),
11117            "admission should still be waiting for the peer map"
11118        );
11119
11120        drop(held_map);
11121        assert_eq!(semaphore.available_permits(), 1);
11122        assert!(!inflight.read().await.contains_key(&peer));
11123    }
11124
11125    #[test]
11126    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
11127        let timeout = Duration::from_secs(1);
11128        let old_received_at = Instant::now()
11129            .checked_sub(timeout)
11130            .unwrap_or_else(Instant::now);
11131
11132        assert!(request_is_stale(old_received_at, timeout));
11133        assert!(!request_is_stale(Instant::now(), timeout));
11134    }
11135
11136    #[tokio::test]
11137    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
11138        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
11139        let inflight = Arc::new(RwLock::new(HashMap::new()));
11140        let first_peer = test_peer(0xB3);
11141        let second_peer = test_peer(0xB4);
11142
11143        let first_guard = admit_bounded_responder(
11144            &semaphore,
11145            &inflight,
11146            &first_peer,
11147            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11148            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11149        )
11150        .await
11151        .expect("first sync from a peer should be admitted");
11152        let duplicate = admit_bounded_responder(
11153            &semaphore,
11154            &inflight,
11155            &first_peer,
11156            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11157            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11158        )
11159        .await;
11160        let other_peer = admit_bounded_responder(
11161            &semaphore,
11162            &inflight,
11163            &second_peer,
11164            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11165            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11166        )
11167        .await;
11168
11169        assert!(matches!(
11170            duplicate,
11171            Err(ResponderAdmissionFailure {
11172                reason: ResponderRejectReason::PerPeerCapFull,
11173                ..
11174            })
11175        ));
11176        assert!(other_peer.is_ok());
11177        drop(first_guard);
11178        drop(other_peer);
11179    }
11180
11181    /// One flooding peer must not be able to hold every fresh-offer slot.
11182    ///
11183    /// This is the eviction primitive the per-peer share closes: with only a
11184    /// global bound, a single source occupies the pool, every honest offer in
11185    /// that window is refused, and because a refusal reads as absence to the
11186    /// sender's delayed possession check those refusals land as
11187    /// audit-severity penalties on *this* node.
11188    #[tokio::test]
11189    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
11190        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
11191        let inflight = Arc::new(RwLock::new(HashMap::new()));
11192        let flooder = test_peer(0xC1);
11193        let honest = test_peer(0xC2);
11194
11195        let mut held = Vec::new();
11196        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11197            held.push(
11198                admit_bounded_responder(
11199                    &semaphore,
11200                    &inflight,
11201                    &flooder,
11202                    FRESH_OFFER_MAX_OUTSTANDING,
11203                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11204                )
11205                .await
11206                .expect("offers within the per-peer share are admitted"),
11207            );
11208        }
11209
11210        let flooder_excess = admit_bounded_responder(
11211            &semaphore,
11212            &inflight,
11213            &flooder,
11214            FRESH_OFFER_MAX_OUTSTANDING,
11215            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11216        )
11217        .await;
11218        assert!(
11219            matches!(
11220                flooder_excess,
11221                Err(ResponderAdmissionFailure {
11222                    reason: ResponderRejectReason::PerPeerCapFull,
11223                    ..
11224                })
11225            ),
11226            "one source must not exceed its fresh-offer share"
11227        );
11228
11229        let honest_offer = admit_bounded_responder(
11230            &semaphore,
11231            &inflight,
11232            &honest,
11233            FRESH_OFFER_MAX_OUTSTANDING,
11234            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11235        )
11236        .await;
11237        assert!(
11238            honest_offer.is_ok(),
11239            "an honest sender must still be admitted while another peer floods"
11240        );
11241
11242        assert!(
11243            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11244                < FRESH_OFFER_MAX_OUTSTANDING,
11245            "the per-peer share must leave room for other sources"
11246        );
11247
11248        drop(held);
11249        drop(honest_offer);
11250    }
11251
11252    /// Paid notifies get the same per-source treatment as every other class.
11253    #[tokio::test]
11254    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11255        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11256        let inflight = Arc::new(RwLock::new(HashMap::new()));
11257        let flooder = test_peer(0xC3);
11258        let honest = test_peer(0xC4);
11259
11260        let mut held = Vec::new();
11261        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11262            held.push(
11263                admit_bounded_responder(
11264                    &semaphore,
11265                    &inflight,
11266                    &flooder,
11267                    PAID_NOTIFY_MAX_OUTSTANDING,
11268                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11269                )
11270                .await
11271                .expect("notifies within the per-peer share are admitted"),
11272            );
11273        }
11274
11275        assert!(
11276            matches!(
11277                admit_bounded_responder(
11278                    &semaphore,
11279                    &inflight,
11280                    &flooder,
11281                    PAID_NOTIFY_MAX_OUTSTANDING,
11282                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11283                )
11284                .await,
11285                Err(ResponderAdmissionFailure {
11286                    reason: ResponderRejectReason::PerPeerCapFull,
11287                    ..
11288                })
11289            ),
11290            "one source must not exceed its paid-notify share"
11291        );
11292        assert!(
11293            admit_bounded_responder(
11294                &semaphore,
11295                &inflight,
11296                &honest,
11297                PAID_NOTIFY_MAX_OUTSTANDING,
11298                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11299            )
11300            .await
11301            .is_ok(),
11302            "an honest sender must still be admitted while another peer floods"
11303        );
11304
11305        drop(held);
11306    }
11307
11308    /// The fresh-offer per-source bound must guarantee headroom for a peer
11309    /// holding nothing, without throttling a single legitimate fan-out.
11310    ///
11311    /// Sized as a quota rather than a reserve, this bound refused offers during
11312    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11313    /// refusal is charged to THIS node at audit severity because the sender
11314    /// never reads it.
11315    #[test]
11316    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11317        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11318
11319        assert_eq!(
11320            FRESH_OFFER_MAX_OUTSTANDING - share,
11321            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11322            "a source holding none must always find a free slot"
11323        );
11324        assert!(
11325            share < FRESH_OFFER_MAX_OUTSTANDING,
11326            "one peer must not be able to take the whole pool"
11327        );
11328        // The failure this pins: a share sized like the request/response
11329        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11330        // one-way bulk traffic.
11331        assert!(
11332            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11333            "fresh offers are one-way bulk, not request/response — their share \
11334             must not be sized like the request classes'"
11335        );
11336    }
11337
11338    /// A malformed offer must be refused before it can occupy an admission
11339    /// slot, so junk cannot hold capacity for the length of a verification.
11340    #[test]
11341    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11342        let key = test_key(0xC5);
11343
11344        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11345
11346        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11347            .expect("an offer with no proof must be refused");
11348        assert!(
11349            rejection.penalise,
11350            "an honest sender always attaches a proof"
11351        );
11352
11353        // A proof is retained per queued sender, so its size has to be bounded
11354        // here rather than at the verifier, which only sees it on a worker.
11355        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11356        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11357            .expect("an undersized proof must be refused");
11358        assert!(
11359            rejection.penalise,
11360            "no honest sender constructs an undersized proof"
11361        );
11362        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11363        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11364            .expect("an oversized proof must be refused");
11365        assert!(
11366            rejection.penalise,
11367            "no honest sender constructs an oversized proof"
11368        );
11369
11370        let rejection = fresh_offer_structural_rejection(
11371            &key,
11372            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11373            &valid_proof,
11374        )
11375        .expect("an oversized offer must be refused");
11376        assert!(
11377            rejection.penalise,
11378            "no honest sender constructs an oversized offer"
11379        );
11380
11381        let data = vec![0u8; 1];
11382        assert!(
11383            fresh_offer_structural_rejection(
11384                &crate::client::compute_address(&data),
11385                &data,
11386                &valid_proof
11387            )
11388            .is_none(),
11389            "a well-formed offer must reach admission"
11390        );
11391    }
11392
11393    /// Knowing a key must not be enough to enter its entry.
11394    ///
11395    /// Opening an entry on an unverified key/bytes association would let a peer
11396    /// that has only *learned* the key — every recipient of its `PaidNotify`,
11397    /// not just the close group that gets the chunk — seize it with junk.
11398    /// Joining one would be worse: the handler tries each queued proof against
11399    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11400    /// on bytes it never offered.
11401    #[test]
11402    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11403        let genuine_data = vec![0x5Au8; 128];
11404        let key = crate::client::compute_address(&genuine_data);
11405        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11406
11407        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11408            .expect("bytes that do not hash to the advertised key must be refused");
11409        assert!(
11410            rejection.penalise,
11411            "no honest sender offers bytes that do not hash to the advertised key"
11412        );
11413
11414        // Dispatch reaches the entry only past that rejection, so the forged
11415        // offer never touched the key and the genuine one still opens it.
11416        assert!(
11417            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11418            "the offer that actually carries the key's bytes must reach the entry"
11419        );
11420
11421        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11422        assert!(
11423            matches!(
11424                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11425                FreshOfferAdmission::Opened(_)
11426            ),
11427            "an offer refused on payload shape must leave the key openable"
11428        );
11429    }
11430
11431    #[tokio::test]
11432    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11433        let peer = test_peer(0xA5);
11434        let key = test_key(0xA5);
11435        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11436        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11437        let is_bootstrapping = Arc::new(RwLock::new(true));
11438        let bootstrap_complete_notify = Arc::new(Notify::new());
11439
11440        let now = Instant::now();
11441        queues.write().await.add_pending_verify(
11442            key,
11443            VerificationEntry {
11444                state: VerificationState::PendingVerify,
11445                verified_sources: Vec::new(),
11446                tried_sources: HashSet::new(),
11447                created_at: now,
11448                next_verify_at: now,
11449                hint_sources: HashSet::from([peer]),
11450                replica_hint_sources: HashSet::from([peer]),
11451                unresolved_retries: 0,
11452                no_holder_reported: false,
11453            },
11454        );
11455        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11456        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11457        {
11458            let q = queues.read().await;
11459            assert!(
11460                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11461                "capacity rejection should initially block bootstrap drain"
11462            );
11463        }
11464
11465        update_bootstrap_after_peer_removed(
11466            &peer,
11467            &bootstrap_state,
11468            &queues,
11469            &is_bootstrapping,
11470            &bootstrap_complete_notify,
11471        )
11472        .await;
11473
11474        let state = bootstrap_state.read().await;
11475        assert!(state.capacity_rejected_sources.is_empty());
11476        assert!(state.pending_keys.is_empty());
11477        assert!(state.is_drained());
11478        drop(state);
11479        assert!(!*is_bootstrapping.read().await);
11480    }
11481
11482    /// A fairness displacement forfeits the key but must not stamp its former
11483    /// owner: the owner did nothing wrong, and stamping it lets a flooding
11484    /// source block bootstrap drain through an unrelated honest peer.
11485    #[tokio::test]
11486    async fn fairness_displacement_does_not_stamp_its_victim() {
11487        let displaced_owner = test_peer(0xB1);
11488        let incoming_source = test_peer(0xB2);
11489        let displaced_key = test_key(0xB1);
11490        let admitted_key = test_key(0xB2);
11491        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11492        {
11493            let mut state = bootstrap_state.write().await;
11494            state.pending_keys.insert(displaced_key);
11495            state
11496                .capacity_rejected_sources
11497                .insert(incoming_source, Instant::now());
11498        }
11499        let outcomes = [(
11500            incoming_source,
11501            AdmissionOutcome {
11502                discovered: HashSet::from([admitted_key]),
11503                capacity_rejected_count: 0,
11504                displaced: vec![CapacityDisplacement {
11505                    key: displaced_key,
11506                    owner: displaced_owner,
11507                }],
11508            },
11509        )];
11510
11511        publish_bootstrap_admission_outcomes(
11512            &bootstrap_state,
11513            &outcomes,
11514            &HashSet::from([admitted_key]),
11515        )
11516        .await;
11517
11518        let state = bootstrap_state.read().await;
11519        assert!(!state.pending_keys.contains(&displaced_key));
11520        assert!(state.pending_keys.contains(&admitted_key));
11521        assert!(
11522            !state
11523                .capacity_rejected_sources
11524                .contains_key(&displaced_owner),
11525            "the displaced owner must not be charged for our own fairness reclaim"
11526        );
11527        assert!(!state
11528            .capacity_rejected_sources
11529            .contains_key(&incoming_source));
11530    }
11531
11532    /// A source that keeps overflowing us must not keep its own record fresh.
11533    ///
11534    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11535    /// rejection the debt could never age out, so `check_bootstrap_drained`
11536    /// stayed false forever and auditing never started (Invariant 19).
11537    #[tokio::test]
11538    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11539        const REJECTION_ROUNDS: usize = 5;
11540
11541        let source = test_peer(0xB3);
11542        let key = test_key(0xB3);
11543        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11544
11545        let first_seen = {
11546            let outcomes = [(
11547                source,
11548                AdmissionOutcome {
11549                    discovered: HashSet::new(),
11550                    capacity_rejected_count: 1,
11551                    displaced: Vec::new(),
11552                },
11553            )];
11554            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11555                .await;
11556            bootstrap_state
11557                .read()
11558                .await
11559                .capacity_rejected_sources
11560                .get(&source)
11561                .copied()
11562                .expect("first rejection recorded")
11563        };
11564
11565        for _ in 0..REJECTION_ROUNDS {
11566            let outcomes = [(
11567                source,
11568                AdmissionOutcome {
11569                    discovered: HashSet::from([key]),
11570                    capacity_rejected_count: 1,
11571                    displaced: Vec::new(),
11572                },
11573            )];
11574            publish_bootstrap_admission_outcomes(
11575                &bootstrap_state,
11576                &outcomes,
11577                &HashSet::from([key]),
11578            )
11579            .await;
11580        }
11581
11582        let recorded = bootstrap_state
11583            .read()
11584            .await
11585            .capacity_rejected_sources
11586            .get(&source)
11587            .copied()
11588            .expect("debt still outstanding");
11589        assert_eq!(
11590            recorded, first_seen,
11591            "repeat rejections must not restart the expiry clock"
11592        );
11593    }
11594
11595    /// The verification-worker tick's self-heal path: a capacity rejection
11596    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11597    /// blocks drain until the TTL expires it, at which point the same tick
11598    /// completes bootstrap without any external event.
11599    #[tokio::test]
11600    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11601        let peer = test_peer(0xA6);
11602        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11603        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11604        let is_bootstrapping = Arc::new(RwLock::new(true));
11605        let bootstrap_complete_notify = Arc::new(Notify::new());
11606
11607        // PeerRemoved was fully processed before the rejection landed, so no
11608        // future event will ever clear this entry.
11609        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11610
11611        // Within the TTL the tick keeps waiting for re-delivery.
11612        expire_and_recheck_bootstrap_drain(
11613            &bootstrap_state,
11614            &queues,
11615            &is_bootstrapping,
11616            &bootstrap_complete_notify,
11617            ReplicationConfig::default().capacity_rejected_max_age(),
11618        )
11619        .await;
11620        assert!(!bootstrap_state.read().await.is_drained());
11621        assert!(*is_bootstrapping.read().await);
11622
11623        // Past the TTL the tick expires the orphan and completes bootstrap.
11624        expire_and_recheck_bootstrap_drain(
11625            &bootstrap_state,
11626            &queues,
11627            &is_bootstrapping,
11628            &bootstrap_complete_notify,
11629            Duration::ZERO,
11630        )
11631        .await;
11632        assert!(bootstrap_state.read().await.is_drained());
11633        assert!(!*is_bootstrapping.read().await);
11634    }
11635
11636    #[test]
11637    fn first_audit_terminal_outcomes_are_stable() {
11638        let peer = test_peer(1);
11639        let passed = AuditTickResult::Passed {
11640            challenged_peer: peer,
11641            keys_checked: 1,
11642        };
11643        let timed_out = AuditTickResult::Failed {
11644            evidence: FailureEvidence::AuditFailure {
11645                challenge_id: 1,
11646                challenged_peer: peer,
11647                confirmed_failed_keys: vec![test_key(1)],
11648                summary: crate::replication::types::AuditFailureSummary::default(),
11649                reason: AuditFailureReason::Timeout,
11650            },
11651            no_response_class: Some("timeout"),
11652        };
11653
11654        assert_eq!(
11655            first_audit_terminal_outcome(&passed),
11656            FirstAuditTerminalOutcome::Passed
11657        );
11658        assert_eq!(
11659            first_audit_terminal_outcome(&timed_out),
11660            FirstAuditTerminalOutcome::Timeout
11661        );
11662        assert_eq!(
11663            first_audit_terminal_outcome(&AuditTickResult::Idle),
11664            FirstAuditTerminalOutcome::Idle
11665        );
11666        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11667        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11668        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11669        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11670        assert_eq!(
11671            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11672            "insufficient_keys"
11673        );
11674        assert_eq!(
11675            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11676            "bootstrap_claim"
11677        );
11678    }
11679
11680    #[test]
11681    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11682        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11683        let mut rng = StdRng::seed_from_u64(7);
11684        let peer = test_peer(1);
11685        let base = MonetizedPinEvent {
11686            peer,
11687            pin: [1; 32],
11688            key_count: 100,
11689            quote_ts: SystemTime::now(),
11690        };
11691
11692        // First insert into an empty slot: Queued.
11693        assert_eq!(
11694            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11695            FirstAuditQueueOutcome::Queued
11696        );
11697
11698        // A strictly LOWER-count same-peer nomination must NOT displace it.
11699        let lower = MonetizedPinEvent {
11700            pin: [2; 32],
11701            key_count: 50,
11702            ..base
11703        };
11704        assert_eq!(
11705            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11706            FirstAuditQueueOutcome::SuppressedLower
11707        );
11708        assert_eq!(
11709            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11710            Some(([1; 32], 100)),
11711            "the higher-count pin is retained"
11712        );
11713
11714        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11715        let higher = MonetizedPinEvent {
11716            pin: [3; 32],
11717            key_count: 400,
11718            ..base
11719        };
11720        assert_eq!(
11721            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11722            FirstAuditQueueOutcome::Coalesced
11723        );
11724        assert_eq!(
11725            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11726            Some(([3; 32], 400))
11727        );
11728
11729        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11730        let equal_newer = MonetizedPinEvent {
11731            pin: [4; 32],
11732            key_count: 400,
11733            ..base
11734        };
11735        assert_eq!(
11736            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
11737            FirstAuditQueueOutcome::Coalesced
11738        );
11739        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11740        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
11741        let equal_older = MonetizedPinEvent {
11742            pin: [5; 32],
11743            key_count: 400,
11744            ..base
11745        };
11746        assert_eq!(
11747            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
11748            FirstAuditQueueOutcome::RetainedOnTie
11749        );
11750        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
11751
11752        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
11753        let other_peer = MonetizedPinEvent {
11754            peer: test_peer(2),
11755            pin: [6; 32],
11756            key_count: 100,
11757            ..base
11758        };
11759        assert_eq!(
11760            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
11761            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
11762        );
11763        assert_eq!(pending.len(), 1);
11764        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
11765    }
11766
11767    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
11768
11769    #[test]
11770    fn first_audit_limiter_enforces_burst_then_refills() {
11771        let base = Instant::now();
11772        let mut limiter = FirstAuditLimiter::new(base);
11773        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11774
11775        // The full burst is admitted back-to-back (distinct peers).
11776        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11777            let peer = test_peer(u8::try_from(i).expect("small burst"));
11778            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11779            limiter.commit_launch(peer, 10, base);
11780        }
11781        // Bucket empty: the next distinct peer is deferred, never dropped.
11782        let extra = test_peer(0xEE);
11783        assert_eq!(
11784            limiter.assess(&extra, 10, base, 0),
11785            LimiterVerdict::RateDeferred
11786        );
11787
11788        // One full interval later exactly one token is available again.
11789        let later = base + interval;
11790        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
11791        limiter.commit_launch(extra, 10, later);
11792        let extra2 = test_peer(0xEF);
11793        assert_eq!(
11794            limiter.assess(&extra2, 10, later, 0),
11795            LimiterVerdict::RateDeferred
11796        );
11797    }
11798
11799    #[test]
11800    fn first_audit_limiter_refill_keeps_fractional_remainder() {
11801        let base = Instant::now();
11802        let mut limiter = FirstAuditLimiter::new(base);
11803        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
11804        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11805            let peer = test_peer(u8::try_from(i).expect("small burst"));
11806            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
11807            limiter.commit_launch(peer, 1, base);
11808        }
11809        // 1.5 intervals later one token is earned and the half interval is
11810        // NOT lost to drift...
11811        let at_1_5 = base + interval + interval / 2;
11812        let p = test_peer(0xAA);
11813        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
11814        limiter.commit_launch(p, 1, at_1_5);
11815        // ...so the next token arrives at 2.0 intervals, not 2.5.
11816        let at_2_0 = base + interval * 2;
11817        let q = test_peer(0xAB);
11818        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
11819    }
11820
11821    #[test]
11822    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
11823        let base = Instant::now();
11824        let mut limiter = FirstAuditLimiter::new(base);
11825        let peer = test_peer(1);
11826        assert_eq!(
11827            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
11828            LimiterVerdict::RateDeferred
11829        );
11830        // A freed slot admits without any clock movement.
11831        assert_eq!(
11832            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
11833            LimiterVerdict::Admit
11834        );
11835    }
11836
11837    #[test]
11838    fn first_audit_limiter_assess_consumes_nothing() {
11839        let base = Instant::now();
11840        let mut limiter = FirstAuditLimiter::new(base);
11841        let peer = test_peer(3);
11842        // Repeated assessment must not burn budget or stamp the window: only
11843        // `commit_launch` consumes (the cooldown gate between assess and
11844        // commit can defer, and that deferral must be free).
11845        for _ in 0..10 {
11846            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
11847        }
11848        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
11849            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
11850            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
11851            limiter.commit_launch(p, 5, base);
11852        }
11853    }
11854
11855    #[test]
11856    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
11857        let base = Instant::now();
11858        let mut limiter = FirstAuditLimiter::new(base);
11859        let peer = test_peer(7);
11860        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
11861        limiter.commit_launch(peer, 100, base);
11862
11863        // A rotated pin with a similar count inside the window is dropped...
11864        let soon = base + Duration::from_mins(1);
11865        assert_eq!(
11866            limiter.assess(&peer, 100, soon, 0),
11867            LimiterVerdict::WindowDeduped
11868        );
11869        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
11870        assert_eq!(
11871            limiter.assess(&peer, 150, soon, 0),
11872            LimiterVerdict::WindowDeduped
11873        );
11874        // ...but a >1.5x committed-count jump re-nominates immediately (an
11875        // inflated sidecar-only pin is invisible to the gossip lottery, so
11876        // the window must not shield it).
11877        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
11878
11879        // Window expiry re-admits an unchanged count.
11880        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
11881        assert_eq!(
11882            limiter.assess(&peer, 100, expired, 0),
11883            LimiterVerdict::Admit
11884        );
11885    }
11886
11887    #[test]
11888    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
11889        // A window-deduped nomination must be DROPPED, not kept pending as
11890        // rate-deferred, even when the bucket is also empty: re-queuing a
11891        // suppressed rotation would hold a pending slot for two hours.
11892        let base = Instant::now();
11893        let mut limiter = FirstAuditLimiter::new(base);
11894        let peer = test_peer(9);
11895        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
11896        limiter.commit_launch(peer, 10, base);
11897        let other = test_peer(10);
11898        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
11899        limiter.commit_launch(other, 10, base);
11900        assert_eq!(
11901            limiter.assess(&peer, 10, base, 0),
11902            LimiterVerdict::WindowDeduped
11903        );
11904    }
11905
11906    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
11907    /// is answerable now but would age out of the answerability window during
11908    /// the launch jitter, so scheduling state is only ever committed for a pin
11909    /// that can still be challenged when it actually sends.
11910    #[test]
11911    fn first_audit_horizon_prefilter_boundary() {
11912        let now = SystemTime::now();
11913        // C = the too-old cutoff; H = the worst-case send horizon.
11914        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
11915        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
11916        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
11917        let boundary = now
11918            .checked_add(h)
11919            .and_then(|t| t.checked_sub(c))
11920            .expect("boundary time");
11921
11922        // In window at `now` (age = C - H < C)...
11923        assert!(quote_within_audit_window(boundary, now));
11924        // ...but the horizon prefilter rejects it (age == C at now + H).
11925        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
11926
11927        // A hair newer stays answerable through the horizon; a hair older does
11928        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
11929        // a nanosecond step would round to the same instant there.
11930        let newer = boundary
11931            .checked_add(Duration::from_micros(1))
11932            .expect("newer");
11933        let older = boundary
11934            .checked_sub(Duration::from_micros(1))
11935            .expect("older");
11936        assert!(quote_answerable_through_nominal_jitter(newer, now));
11937        assert!(!quote_answerable_through_nominal_jitter(older, now));
11938
11939        // A quote too far in the FUTURE is rejected at `now`, independent of the
11940        // horizon.
11941        let future = now
11942            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
11943            .and_then(|t| t.checked_add(Duration::from_mins(1)))
11944            .expect("future");
11945        assert!(!quote_answerable_through_nominal_jitter(future, now));
11946    }
11947
11948    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
11949    /// answerability check fails at promotion is fully state-neutral — it stamps
11950    /// no `first_audited`, no per-peer window, refunds its token, releases its
11951    /// in-flight slot, does not flip the lane, and does not count a launch — and
11952    /// a same-peer, same-count successor enqueued DURING the reservation is
11953    /// retained and becomes the next reservation after the cancel. This is the
11954    /// exact hole the reviewer flagged: suppression must never outlive a launch
11955    /// that did not send.
11956    /// A pending pin that has aged past the answerability horizon must not
11957    /// suppress a live lower-count nomination for the same peer: under token
11958    /// starvation no reserve scan ever collects the dead entry, so without the
11959    /// enqueue-time check the peer would stay unauditable through this path
11960    /// indefinitely (e.g. after a prune legitimately lowered its key count).
11961    #[test]
11962    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
11963        let obs = Arc::new(FirstAuditObservability::default());
11964        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
11965        let peer = test_peer(1);
11966
11967        let dead_quote = SystemTime::now()
11968            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
11969            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
11970            .expect("past wall time");
11971        let stale_high = MonetizedPinEvent {
11972            peer,
11973            pin: [1; 32],
11974            key_count: 400,
11975            quote_ts: dead_quote,
11976        };
11977        scheduler.enqueue(stale_high, &obs);
11978        assert_eq!(scheduler.pending_len(), 1);
11979
11980        // A fresh, lower-count nomination (a post-prune commitment).
11981        let fresh_lower = MonetizedPinEvent {
11982            peer,
11983            pin: [2; 32],
11984            key_count: 100,
11985            quote_ts: SystemTime::now(),
11986        };
11987        scheduler.enqueue(fresh_lower, &obs);
11988
11989        assert_eq!(scheduler.pending_len(), 1);
11990        assert_eq!(
11991            scheduler.pending.peek(&peer).map(|e| e.pin),
11992            Some([2; 32]),
11993            "the live nomination replaced the dead incumbent"
11994        );
11995        assert_eq!(
11996            obs.suppressed_lower.load(Ordering::Relaxed),
11997            0,
11998            "no self-erasure signal for displacing a dead pin"
11999        );
12000        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
12001        assert_eq!(
12002            obs.outside_answerability_window.load(Ordering::Relaxed),
12003            1,
12004            "the dead incumbent is accounted as an expiry"
12005        );
12006    }
12007
12008    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
12009    /// nomination still loses to an answerable higher-count pending pin.
12010    #[test]
12011    fn first_audit_live_incumbent_still_suppresses_lower_count() {
12012        let obs = Arc::new(FirstAuditObservability::default());
12013        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12014        let peer = test_peer(1);
12015
12016        let live_high = MonetizedPinEvent {
12017            peer,
12018            pin: [1; 32],
12019            key_count: 400,
12020            quote_ts: SystemTime::now(),
12021        };
12022        scheduler.enqueue(live_high, &obs);
12023        let cheaper = MonetizedPinEvent {
12024            peer,
12025            pin: [2; 32],
12026            key_count: 100,
12027            quote_ts: SystemTime::now(),
12028        };
12029        scheduler.enqueue(cheaper, &obs);
12030
12031        assert_eq!(scheduler.pending_len(), 1);
12032        assert_eq!(
12033            scheduler.pending.peek(&peer).map(|e| e.pin),
12034            Some([1; 32]),
12035            "the higher-count live pin is retained"
12036        );
12037        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
12038        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
12039    }
12040
12041    /// A fresh nomination for peer `b` (distinct pin per peer).
12042    fn live_nomination(b: u8) -> MonetizedPinEvent {
12043        MonetizedPinEvent {
12044            peer: test_peer(b),
12045            pin: [b; 32],
12046            key_count: 100,
12047            quote_ts: SystemTime::now(),
12048        }
12049    }
12050
12051    /// The pending admission cap must equal the number of usable launches the
12052    /// token budget can perform inside one answerability window, counted by
12053    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
12054    /// tokens at age zero, one refill per launch interval), not by repeating
12055    /// the derivation formula. Any larger and admitted work is guaranteed to
12056    /// expire unlaunched; any smaller and the budget idles while nominations
12057    /// are displaced.
12058    #[test]
12059    fn first_audit_pending_cap_matches_strict_launch_horizon() {
12060        let quote_ts = SystemTime::now();
12061        // Burst launches fire at age zero and must pass the reserve predicate.
12062        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
12063        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
12064        let mut refill = 1u32;
12065        loop {
12066            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
12067            let at = quote_ts + age;
12068            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
12069                break;
12070            }
12071            usable += 1;
12072            refill += 1;
12073            assert!(refill < 10_000, "runaway horizon simulation");
12074        }
12075        assert_eq!(
12076            FIRST_AUDIT_PENDING_CAP, usable,
12077            "cap must match the simulated strict launch horizon"
12078        );
12079    }
12080
12081    /// The pending queue is sized to the launch budget while the dedup set
12082    /// keeps the commitment-cache bound: shrinking `first_audited` would
12083    /// forget audited pins and re-admit duplicates.
12084    #[test]
12085    fn first_audit_pending_cap_independent_of_dedup_cap() {
12086        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12087        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
12088        assert_eq!(
12089            scheduler.first_audited.cap().get(),
12090            MAX_LAST_COMMITMENT_BY_PEER
12091        );
12092    }
12093
12094    /// Admission beyond the cap displaces exactly one incumbent per overflow
12095    /// and every displacement is accounted as `capacity_evicted` — the steady
12096    /// overload signal — never silent loss, and never an admission refusal.
12097    #[test]
12098    fn first_audit_admission_beyond_cap_displaces_and_counts() {
12099        let obs = Arc::new(FirstAuditObservability::default());
12100        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12101        let overflow: usize = 5;
12102        let total = FIRST_AUDIT_PENDING_CAP + overflow;
12103
12104        for i in 0..total {
12105            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12106            scheduler.enqueue(live_nomination(b), &obs);
12107        }
12108
12109        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12110        assert_eq!(
12111            obs.capacity_evicted.load(Ordering::Relaxed),
12112            u64::try_from(overflow).expect("overflow fits u64"),
12113            "each admission past the cap displaces exactly one entry"
12114        );
12115        assert_eq!(
12116            obs.queued.load(Ordering::Relaxed),
12117            u64::try_from(total).expect("total fits u64"),
12118            "displacement is not an admission refusal"
12119        );
12120        // Every arrival was admitted (the newest always enters the sample).
12121        let last = u8::try_from(total).expect("test peer count fits u8");
12122        assert!(
12123            scheduler.pending.peek(&test_peer(last)).is_some(),
12124            "the newest arrival always enters the sample"
12125        );
12126    }
12127
12128    /// The reviewer-demonstrated suppression route: a target followed by an
12129    /// ordered batch of distinct-peer nominations, all inside one ingress
12130    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
12131    /// the token bucket EMPTY so no reservation can intervene. Under the old
12132    /// keep-newest LRU the target was evicted with certainty; under random
12133    /// displacement its per-overflow eviction probability is `1/cap`, so
12134    /// across repeated trials the target must survive some runs and be
12135    /// displaced in others — never deterministically flushed, and every
12136    /// displacement accounted.
12137    #[test]
12138    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
12139        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
12140        assert!(FIRST_AUDIT_PENDING_CAP < flood);
12141        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
12142
12143        let trials = 100u64;
12144        let mut survived = 0u32;
12145        let mut evicted = 0u32;
12146        for trial in 0..trials {
12147            let obs = Arc::new(FirstAuditObservability::default());
12148            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12149            // Deterministic per-trial seed: the run is fully reproducible (no
12150            // flake budget at all) while still exercising 100 distinct
12151            // eviction sequences.
12152            scheduler.rng = StdRng::seed_from_u64(trial);
12153            // Drain the burst tokens so the pre-overflow reservation
12154            // opportunity cannot fire: this isolates pure retention.
12155            scheduler.limiter.reserve_token();
12156            scheduler.limiter.reserve_token();
12157
12158            let target = test_peer(200);
12159            scheduler.enqueue(live_nomination(200), &obs);
12160            for i in 0..flood {
12161                let b = u8::try_from(i + 1).expect("flood peer fits u8");
12162                scheduler.enqueue(live_nomination(b), &obs);
12163            }
12164
12165            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12166            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
12167                .expect("overflow count fits u64");
12168            assert_eq!(
12169                obs.capacity_evicted.load(Ordering::Relaxed),
12170                overflows,
12171                "every overflow past the cap is accounted, none silent"
12172            );
12173            if scheduler.pending.peek(&target).is_some() {
12174                survived += 1;
12175            } else {
12176                evicted += 1;
12177            }
12178        }
12179        // With eviction probability 1/cap per overflow, P(target survives one
12180        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
12181        // 100 seeded trials — and the seeds make the split exactly
12182        // reproducible rather than a (vanishingly small) flake budget.
12183        assert!(
12184            survived > 0,
12185            "target must survive some ordered floods — deterministic eviction \
12186             would mean keep-newest retention regressed"
12187        );
12188        assert!(
12189            evicted > 0,
12190            "target must also be displaceable — otherwise overflow is refusing \
12191             admissions instead of sampling"
12192        );
12193    }
12194
12195    /// With a token AVAILABLE, an overflowing arrival must first give pending
12196    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12197    /// one entry out of the queue, so admission proceeds without any eviction.
12198    #[test]
12199    fn first_audit_overflow_reserves_before_destructive_eviction() {
12200        let obs = Arc::new(FirstAuditObservability::default());
12201        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12202        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12203
12204        for i in 0..FIRST_AUDIT_PENDING_CAP {
12205            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12206            scheduler.enqueue(live_nomination(b), &obs);
12207        }
12208        let overflowing = live_nomination(250);
12209        assert!(scheduler.would_displace(&overflowing));
12210
12211        // The drainer's pre-overflow sequence: reserve, then enqueue.
12212        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12213        assert!(
12214            !scheduler.would_displace(&overflowing),
12215            "a successful reservation frees the slot"
12216        );
12217        scheduler.enqueue(overflowing, &obs);
12218
12219        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12220        assert_eq!(
12221            obs.capacity_evicted.load(Ordering::Relaxed),
12222            0,
12223            "no destructive eviction when a launch opportunity existed"
12224        );
12225    }
12226
12227    /// Displacement stamps no suppression state: a displaced peer's next
12228    /// nomination re-enters like any newcomer (it is NOT window-deduped or
12229    /// treated as a duplicate), so under overload every peer keeps an
12230    /// unpredictable chance of prompt first audit.
12231    #[test]
12232    fn first_audit_displaced_peer_may_be_renominated() {
12233        let obs = Arc::new(FirstAuditObservability::default());
12234        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12235        let total = FIRST_AUDIT_PENDING_CAP + 1;
12236
12237        for i in 0..total {
12238            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12239            scheduler.enqueue(live_nomination(b), &obs);
12240        }
12241        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12242        // Find whichever peer the random displacement removed.
12243        let displaced = (1..=total)
12244            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12245            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12246            .expect("exactly one admitted peer was displaced");
12247
12248        scheduler.enqueue(live_nomination(displaced), &obs);
12249
12250        assert!(
12251            scheduler.pending.peek(&test_peer(displaced)).is_some(),
12252            "the displaced peer re-enters the sample"
12253        );
12254        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12255        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12256        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12257        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12258    }
12259
12260    /// The periodic sweep collects expired pending entries even when the token
12261    /// bucket is empty — the reserve path returns at the budget gate and never
12262    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12263    /// honest under fleet-wide starvation.
12264    #[test]
12265    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12266        let obs = Arc::new(FirstAuditObservability::default());
12267        let mono = Instant::now();
12268        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12269
12270        let dead_quote = SystemTime::now()
12271            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12272            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12273            .expect("past wall time");
12274        scheduler.enqueue(
12275            MonetizedPinEvent {
12276                peer: test_peer(1),
12277                pin: [1; 32],
12278                key_count: 100,
12279                quote_ts: dead_quote,
12280            },
12281            &obs,
12282        );
12283        scheduler.enqueue(
12284            MonetizedPinEvent {
12285                peer: test_peer(2),
12286                pin: [2; 32],
12287                key_count: 100,
12288                quote_ts: SystemTime::now(),
12289            },
12290            &obs,
12291        );
12292        assert_eq!(scheduler.pending_len(), 2);
12293
12294        // Empty the bucket so the reserve path is budget-gated (fleet-wide
12295        // starvation) and cannot collect the dead entry itself.
12296        scheduler.limiter.tokens = 0;
12297        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12298        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12299        assert_eq!(
12300            scheduler.pending_len(),
12301            2,
12302            "budget-gated reserve scans nothing"
12303        );
12304
12305        let wall_now = SystemTime::now();
12306        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12307        assert_eq!(scheduler.pending_len(), 1);
12308        assert!(
12309            scheduler.pending.peek(&test_peer(2)).is_some(),
12310            "the live entry survives the sweep"
12311        );
12312        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12313        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12314        assert!(
12315            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12316            "the age gauge reflects only live work after the sweep"
12317        );
12318    }
12319
12320    #[test]
12321    #[allow(clippy::too_many_lines)]
12322    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12323        let obs = Arc::new(FirstAuditObservability::default());
12324        let mono = Instant::now();
12325        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12326
12327        // A pre-existing window sentinel for an UNRELATED peer must survive the
12328        // cancel byte-for-byte (cancel never touches `recent`).
12329        let sentinel_peer = test_peer(0xAA);
12330        scheduler.limiter.promote(sentinel_peer, 500, mono);
12331        let sentinel_before = scheduler
12332            .limiter
12333            .recent
12334            .peek(&sentinel_peer)
12335            .copied()
12336            .expect("sentinel present");
12337
12338        let peer = test_peer(1);
12339        let a = MonetizedPinEvent {
12340            peer,
12341            pin: [1; 32],
12342            key_count: 100,
12343            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12344        };
12345        scheduler.enqueue(a, &obs);
12346
12347        let tokens_before = scheduler.tokens();
12348        let lane_before = scheduler.oldest_first_lane;
12349        let launched_before = obs.launched.load(Ordering::Relaxed);
12350        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12351
12352        // Reserve A (jitter 0 so it is immediately due).
12353        let inflight0 = obs.inflight.load(Ordering::Relaxed);
12354        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12355        assert_eq!(scheduler.reserved_peer(), Some(peer));
12356        assert_eq!(
12357            scheduler.tokens(),
12358            tokens_before - 1,
12359            "reserve consumes a token"
12360        );
12361        assert_eq!(
12362            obs.inflight.load(Ordering::Relaxed),
12363            1,
12364            "reserve holds a slot"
12365        );
12366
12367        // A same-peer, same-count successor arrives DURING the reservation. It
12368        // must be retained (bypasses the window for the reserved peer) and must
12369        // NOT create a second reservation.
12370        let b = MonetizedPinEvent {
12371            peer,
12372            pin: [2; 32],
12373            key_count: 100,
12374            quote_ts: SystemTime::now(),
12375        };
12376        scheduler.enqueue(b, &obs);
12377        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12378        assert!(
12379            !scheduler.try_reserve(
12380                mono,
12381                obs.inflight.load(Ordering::Relaxed),
12382                Duration::ZERO,
12383                &cooldown,
12384                &obs
12385            ),
12386            "no second reservation while one is outstanding"
12387        );
12388
12389        // Resolve A with an injected wall time PAST A's answerability cutoff.
12390        let reservation = scheduler
12391            .take_due_reservation(mono)
12392            .expect("A is due at jitter 0");
12393        let wall_fail = a
12394            .quote_ts
12395            .checked_add(GOSSIP_ANSWERABILITY_TTL)
12396            .and_then(|t| t.checked_add(Duration::from_secs(1)))
12397            .expect("past-cutoff wall time");
12398        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12399        assert!(
12400            promoted.is_none(),
12401            "answerability lapsed -> cancelled, not promoted"
12402        );
12403
12404        // State-neutral cancel.
12405        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12406        assert!(
12407            scheduler.limiter.recent.peek(&peer).is_none(),
12408            "cancel stamps no per-peer window"
12409        );
12410        assert_eq!(
12411            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12412            Some(sentinel_before),
12413            "unrelated window sentinel untouched"
12414        );
12415        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12416        assert_eq!(
12417            scheduler.tokens(),
12418            tokens_before,
12419            "token refunded on cancel"
12420        );
12421        assert_eq!(
12422            obs.inflight.load(Ordering::Relaxed),
12423            0,
12424            "in-flight slot released"
12425        );
12426        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12427        assert_eq!(
12428            obs.launched.load(Ordering::Relaxed),
12429            launched_before,
12430            "no launch counted"
12431        );
12432        assert_eq!(
12433            obs.outside_answerability_window.load(Ordering::Relaxed),
12434            1,
12435            "the cancel reason is recorded"
12436        );
12437
12438        // The successor is still pending and is now fully schedulable: a fresh
12439        // reserve makes B the next reservation (proving eligibility, not merely
12440        // that the limiter would admit it).
12441        assert_eq!(
12442            scheduler.pending_len(),
12443            1,
12444            "successor still pending after cancel"
12445        );
12446        assert!(scheduler.reserved.is_none());
12447        assert!(scheduler.try_reserve(
12448            mono,
12449            obs.inflight.load(Ordering::Relaxed),
12450            Duration::ZERO,
12451            &cooldown,
12452            &obs
12453        ));
12454        assert_eq!(
12455            scheduler.reserved_peer(),
12456            Some(peer),
12457            "the retained successor becomes the next reservation"
12458        );
12459    }
12460
12461    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12462    /// race, the reserved event is requeued ONLY if no same-peer successor is
12463    /// already pending. A successor arrived after the reservation, so it is the
12464    /// newer nomination (e.g. a count jump) and must not be overwritten by the
12465    /// older reserved event.
12466    #[test]
12467    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12468        let obs = Arc::new(FirstAuditObservability::default());
12469        let mono = Instant::now();
12470        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12471        let peer = test_peer(1);
12472
12473        // Reserve A.
12474        let a = MonetizedPinEvent {
12475            peer,
12476            pin: [1; 32],
12477            key_count: 100,
12478            quote_ts: SystemTime::now(),
12479        };
12480        scheduler.enqueue(a, &obs);
12481        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12482        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12483
12484        // A newer same-peer successor B (a count jump) arrives during the
12485        // reservation and is retained.
12486        let b = MonetizedPinEvent {
12487            peer,
12488            pin: [2; 32],
12489            key_count: 400,
12490            quote_ts: SystemTime::now(),
12491        };
12492        scheduler.enqueue(b, &obs);
12493        assert_eq!(scheduler.pending_len(), 1);
12494
12495        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12496        // is already stamped for the peer, so promotion loses the race.
12497        let reservation = scheduler.take_due_reservation(mono).expect("due");
12498        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12499        cooldown.insert(peer, mono); // freshly on cooldown
12500        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12501        assert!(promoted.is_none(), "cooldown race -> not promoted");
12502
12503        // B (newer) is preserved; A did NOT overwrite it.
12504        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12505        assert_eq!(
12506            scheduler.pending.peek(&peer).map(|e| e.pin),
12507            Some([2; 32]),
12508            "the newer successor B is retained, not the older reserved A"
12509        );
12510        assert!(scheduler.first_audited.is_empty());
12511        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12512    }
12513
12514    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12515    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12516    /// and saturates to `0` for a future-dated quote (clock skew) without
12517    /// panicking. A climbing value is the pending-work-aging-out signal.
12518    #[test]
12519    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12520        let now = SystemTime::now();
12521        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12522        assert_eq!(
12523            scheduler.oldest_pending_quote_age_ms(now),
12524            0,
12525            "empty pending -> zero"
12526        );
12527
12528        // Two peers: quotes 10s and 2s old. The gauge must track the older.
12529        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12530            let _ = coalesce_first_audit_event(
12531                &mut scheduler.pending,
12532                MonetizedPinEvent {
12533                    peer: test_peer(peer_id),
12534                    pin,
12535                    key_count: 100,
12536                    quote_ts: now - Duration::from_secs(secs),
12537                },
12538                true,
12539                &mut scheduler.rng,
12540            );
12541        }
12542        assert_eq!(
12543            scheduler.oldest_pending_quote_age_ms(now),
12544            10_000,
12545            "tracks the oldest (10s), not the newest (2s)"
12546        );
12547
12548        // A future-dated quote (clock skew) saturates to zero, never panics.
12549        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12550        let _ = coalesce_first_audit_event(
12551            &mut skewed.pending,
12552            MonetizedPinEvent {
12553                peer: test_peer(3),
12554                pin: [3; 32],
12555                key_count: 100,
12556                quote_ts: now + Duration::from_secs(5),
12557            },
12558            true,
12559            &mut skewed.rng,
12560        );
12561        assert_eq!(
12562            skewed.oldest_pending_quote_age_ms(now),
12563            0,
12564            "future quote_ts saturates to zero"
12565        );
12566    }
12567
12568    /// A flood of strictly-lower-count same-peer nominations must neither
12569    /// displace the retained higher pin NOR disturb its recency position (each
12570    /// is suppressed via `peek`, no `push`), and each must be counted as
12571    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12572    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12573    /// (the documented `lru` contract that also drives the reserve scan's lane
12574    /// ordering), deliberately independent of the overflow policy: eviction is
12575    /// random-victim, so no assertion may require a particular peer to be
12576    /// displaced.
12577    #[test]
12578    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12579        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12580            LruCache::new(NonZeroUsize::new(2).unwrap());
12581        let mut rng = StdRng::seed_from_u64(11);
12582        let victim = test_peer(1);
12583        let other = test_peer(2);
12584        // Victim (high count) inserted first (older), then `other` (newer/MRU).
12585        let _ = coalesce_first_audit_event(
12586            &mut pending,
12587            MonetizedPinEvent {
12588                peer: victim,
12589                pin: [1; 32],
12590                key_count: 400,
12591                quote_ts: SystemTime::now(),
12592            },
12593            true,
12594            &mut rng,
12595        );
12596        let _ = coalesce_first_audit_event(
12597            &mut pending,
12598            MonetizedPinEvent {
12599                peer: other,
12600                pin: [9; 32],
12601                key_count: 100,
12602                quote_ts: SystemTime::now(),
12603            },
12604            true,
12605            &mut rng,
12606        );
12607        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12608        assert_eq!(
12609            order_before,
12610            vec![other, victim],
12611            "sanity: `other` is MRU, the victim is LRU"
12612        );
12613
12614        // Flood the victim with cheaper nominations.
12615        let mut suppressed = 0u64;
12616        for i in 0..8u8 {
12617            let out = coalesce_first_audit_event(
12618                &mut pending,
12619                MonetizedPinEvent {
12620                    peer: victim,
12621                    pin: [i; 32],
12622                    key_count: 50,
12623                    quote_ts: SystemTime::now(),
12624                },
12625                true,
12626                &mut rng,
12627            );
12628            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12629            suppressed += 1;
12630        }
12631        assert_eq!(suppressed, 8);
12632        // Victim pin/count unchanged.
12633        assert_eq!(
12634            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12635            Some(([1; 32], 400))
12636        );
12637        // Recency untouched: the iteration order (which the reserve lanes
12638        // consume) is byte-for-byte what it was before the flood.
12639        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12640        assert_eq!(
12641            order_after, order_before,
12642            "the suppressed-lower flood must not have changed any recency position"
12643        );
12644    }
12645
12646    /// The cooldown-race requeue counts a genuine different-peer capacity
12647    /// eviction (the ADR promises capacity loss is observable).
12648    #[test]
12649    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12650        let obs = Arc::new(FirstAuditObservability::default());
12651        let mono = Instant::now();
12652        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12653        // Pending capacity 1 so a requeue of a different peer must evict.
12654        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12655        let reserved_peer = test_peer(1);
12656        let other_peer = test_peer(2);
12657
12658        // Reserve peer 1.
12659        scheduler.enqueue(
12660            MonetizedPinEvent {
12661                peer: reserved_peer,
12662                pin: [1; 32],
12663                key_count: 100,
12664                quote_ts: SystemTime::now(),
12665            },
12666            &obs,
12667        );
12668        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12669        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12670
12671        // A DIFFERENT peer fills the single pending slot during the reservation.
12672        scheduler.enqueue(
12673            MonetizedPinEvent {
12674                peer: other_peer,
12675                pin: [2; 32],
12676                key_count: 100,
12677                quote_ts: SystemTime::now(),
12678            },
12679            &obs,
12680        );
12681        assert_eq!(scheduler.pending_len(), 1);
12682
12683        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12684        let reservation = scheduler.take_due_reservation(mono).expect("due");
12685        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12686        cooldown.insert(reserved_peer, mono);
12687        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12688        assert!(scheduler
12689            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12690            .is_none());
12691        assert_eq!(
12692            obs.capacity_evicted.load(Ordering::Relaxed),
12693            cap_before + 1,
12694            "the requeue eviction of a different peer is counted"
12695        );
12696        assert_eq!(
12697            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12698            Some([1; 32])
12699        );
12700    }
12701
12702    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12703    /// nomination arriving while an inflated pin is PENDING must not displace it.
12704    /// The inflated pin stays and is the one launched.
12705    #[test]
12706    fn first_audit_pending_lower_count_does_not_replace_higher() {
12707        let obs = Arc::new(FirstAuditObservability::default());
12708        let mono = Instant::now();
12709        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12710        let peer = test_peer(1);
12711
12712        // Inflated (high-count) sidecar pin lands in pending.
12713        scheduler.enqueue(
12714            MonetizedPinEvent {
12715                peer,
12716                pin: [1; 32],
12717                key_count: 400,
12718                quote_ts: SystemTime::now(),
12719            },
12720            &obs,
12721        );
12722        // A cheaper same-peer settlement arrives right after.
12723        scheduler.enqueue(
12724            MonetizedPinEvent {
12725                peer,
12726                pin: [2; 32],
12727                key_count: 100,
12728                quote_ts: SystemTime::now(),
12729            },
12730            &obs,
12731        );
12732
12733        assert_eq!(scheduler.pending_len(), 1);
12734        assert_eq!(
12735            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12736            Some(([1; 32], 400)),
12737            "the inflated pin must not be erased by the cheaper successor"
12738        );
12739        // The dropped cheaper nomination is counted through the enqueue path.
12740        assert_eq!(
12741            obs.suppressed_lower.load(Ordering::Relaxed),
12742            1,
12743            "the attempted cheaper-pin self-erasure is observable"
12744        );
12745
12746        // It reserves and promotes as the inflated pin/count.
12747        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12748        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12749        let reservation = scheduler.take_due_reservation(mono).expect("due");
12750        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12751        let (event, _slot) = scheduler
12752            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12753            .expect("promotes");
12754        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12755    }
12756
12757    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
12758    /// loses the cooldown race must be requeued OVER a lower-count same-peer
12759    /// successor that arrived during its jitter, and must remain launchable once
12760    /// the shared cooldown expires — the cheaper successor cannot suppress it.
12761    #[test]
12762    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
12763        let obs = Arc::new(FirstAuditObservability::default());
12764        let mono = Instant::now();
12765        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12766        let peer = test_peer(1);
12767
12768        // Reserve the inflated pin.
12769        scheduler.enqueue(
12770            MonetizedPinEvent {
12771                peer,
12772                pin: [1; 32],
12773                key_count: 400,
12774                quote_ts: SystemTime::now(),
12775            },
12776            &obs,
12777        );
12778        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12779        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12780
12781        // A cheaper successor arrives during the reservation (bypasses the
12782        // window as the reserved peer) and sits in pending.
12783        scheduler.enqueue(
12784            MonetizedPinEvent {
12785                peer,
12786                pin: [2; 32],
12787                key_count: 100,
12788                quote_ts: SystemTime::now(),
12789            },
12790            &obs,
12791        );
12792        assert_eq!(scheduler.pending_len(), 1);
12793
12794        // Resolve: answerability passes but the shared cooldown is already
12795        // stamped, so the reservation loses the race and requeues.
12796        let reservation = scheduler.take_due_reservation(mono).expect("due");
12797        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12798        cooldown.insert(peer, mono);
12799        assert!(scheduler
12800            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12801            .is_none());
12802
12803        // The inflated pin (400) replaced the cheaper successor (100).
12804        assert_eq!(scheduler.pending_len(), 1);
12805        assert_eq!(
12806            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12807            Some(([1; 32], 400)),
12808            "the inflated reserved pin must survive the requeue over the cheaper successor"
12809        );
12810        assert!(scheduler.first_audited.is_empty());
12811        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12812
12813        // Once the shared cooldown expires, the inflated pin reserves and
12814        // promotes with its intended pin/count.
12815        let later = mono
12816            .checked_add(Duration::from_secs(
12817                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
12818            ))
12819            .expect("later");
12820        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
12821        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
12822        let reservation = scheduler.take_due_reservation(later).expect("due");
12823        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
12824        let (event, _slot) = scheduler
12825            .resolve(
12826                reservation,
12827                SystemTime::now(),
12828                later,
12829                &mut cooldown_later,
12830                &obs,
12831            )
12832            .expect("promotes after cooldown");
12833        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
12834    }
12835
12836    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
12837    /// launch lane, driven through the real scheduler (reserve -> resolve ->
12838    /// promote), so a stream of fresh nominations cannot keep every launch on
12839    /// the newest lane and starve the oldest.
12840    #[test]
12841    fn first_audit_lane_alternates_across_promotions() {
12842        let obs = Arc::new(FirstAuditObservability::default());
12843        let mono = Instant::now();
12844        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12845        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12846
12847        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
12848        let oldest_peer = test_peer(1);
12849        let newest_peer = test_peer(2);
12850        scheduler.enqueue(
12851            MonetizedPinEvent {
12852                peer: oldest_peer,
12853                pin: [1; 32],
12854                key_count: 100,
12855                quote_ts: SystemTime::now(),
12856            },
12857            &obs,
12858        );
12859        scheduler.enqueue(
12860            MonetizedPinEvent {
12861                peer: newest_peer,
12862                pin: [2; 32],
12863                key_count: 100,
12864                quote_ts: SystemTime::now(),
12865            },
12866            &obs,
12867        );
12868
12869        let mut launched_peers = Vec::new();
12870        for _ in 0..2 {
12871            assert!(scheduler.try_reserve(
12872                mono,
12873                obs.inflight.load(Ordering::Relaxed),
12874                Duration::ZERO,
12875                &cooldown,
12876                &obs
12877            ));
12878            let reservation = scheduler.take_due_reservation(mono).expect("due");
12879            // Answerable wall time == the quote's own time (age 0).
12880            let (event, _slot) = scheduler
12881                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12882                .expect("fresh in-window quote promotes");
12883            launched_peers.push(event.peer);
12884        }
12885
12886        // First launch takes the newest lane (lane starts false = newest), the
12887        // second takes the oldest lane: strict alternation.
12888        assert_eq!(
12889            launched_peers,
12890            vec![newest_peer, oldest_peer],
12891            "consecutive promotions alternate newest-then-oldest lane"
12892        );
12893    }
12894
12895    #[test]
12896    fn first_audit_count_jump_boundaries() {
12897        // Exactly 1.5x is NOT a jump; strictly above is.
12898        assert!(!first_audit_count_jump(100, 150));
12899        assert!(first_audit_count_jump(100, 151));
12900        // Anything beats an audited zero; zero never jumps.
12901        assert!(first_audit_count_jump(0, 1));
12902        assert!(!first_audit_count_jump(0, 0));
12903        // Equal max counts must not jump (and must not overflow).
12904        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
12905    }
12906
12907    /// A verified payment's quote list includes the local node's own quote, so
12908    /// the verifier emits a monetized-pin event for the local peer on every
12909    /// payment it verifies. The node cannot network-audit itself, so the
12910    /// scheduler must drop such an event at ingress: never queued, and hence
12911    /// never launched nor marked first-audited.
12912    #[test]
12913    fn first_audit_queue_drops_self_targeting_events() {
12914        let obs = Arc::new(FirstAuditObservability::default());
12915        let self_peer = test_peer(1);
12916        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
12917        let self_event = MonetizedPinEvent {
12918            peer: self_peer,
12919            pin: [7; 32],
12920            key_count: 1,
12921            quote_ts: SystemTime::now(),
12922        };
12923
12924        scheduler.enqueue(self_event, &obs);
12925        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
12926        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
12927        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
12928
12929        // A remote peer's event still queues normally under the same filter.
12930        let remote_event = MonetizedPinEvent {
12931            peer: test_peer(2),
12932            pin: [8; 32],
12933            ..self_event
12934        };
12935        scheduler.enqueue(remote_event, &obs);
12936        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
12937        assert_eq!(scheduler.pending_len(), 1);
12938        assert_eq!(
12939            obs.self_target_skipped.load(Ordering::Relaxed),
12940            1,
12941            "remote event must not count as a self-target skip"
12942        );
12943    }
12944
12945    #[test]
12946    fn fresh_offer_runs_store_admission_payment_checks() {
12947        let context = fresh_offer_payment_context();
12948        assert_eq!(context, VerificationContext::FreshReplication);
12949        // Fresh replication must keep verifying exactly like a direct client
12950        // PUT (store-strength cache, same live checks); the variant only
12951        // exists so price-floor telemetry can tell the two paths apart.
12952        assert!(context.is_store_admission());
12953    }
12954
12955    #[test]
12956    fn paid_notify_uses_paid_list_admission_payment_checks() {
12957        assert_eq!(
12958            paid_notify_payment_context(),
12959            VerificationContext::PaidListAdmission
12960        );
12961    }
12962
12963    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
12964    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
12965    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
12966    #[test]
12967    fn monetized_quote_audit_window_fails_closed_both_ends() {
12968        let now = SystemTime::now();
12969        // Fresh (just quoted) and small future/past skew -> audited.
12970        assert!(quote_within_audit_window(now, now));
12971        assert!(quote_within_audit_window(now + Duration::from_mins(1), now));
12972        assert!(quote_within_audit_window(
12973            now - Duration::from_hours(1),
12974            now
12975        ));
12976        // Far future (badly-skewed / replayed) -> skipped.
12977        assert!(!quote_within_audit_window(
12978            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_mins(1),
12979            now
12980        ));
12981        // Older than the window -> skipped (pin may have aged out).
12982        assert!(!quote_within_audit_window(
12983            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
12984            now
12985        ));
12986    }
12987
12988    #[tokio::test]
12989    async fn replication_branch_lagged_events_are_counted() {
12990        let before = audit_metrics::replication_event_lagged_total();
12991        let flow = handle_replication_event_recv_error(
12992            &tokio::sync::broadcast::error::RecvError::Lagged(3),
12993        );
12994        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
12995        let after = audit_metrics::replication_event_lagged_total();
12996        assert_eq!(after.saturating_sub(before), 3);
12997    }
12998
12999    #[tokio::test]
13000    async fn replication_branch_closed_events_stop_the_loop() {
13001        let flow =
13002            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
13003        assert_eq!(flow, std::ops::ControlFlow::Break(()));
13004    }
13005
13006    #[tokio::test]
13007    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
13008        let (sender, mut receiver) = mpsc::channel(1);
13009        let dropped_body =
13010            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
13011                keys: Vec::new(),
13012                paid_list_check_indices: Vec::new(),
13013            });
13014        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13015        let first = InboundReplicationMessage {
13016            source: test_peer(0xC1),
13017            msg: ReplicationMessage {
13018                request_id: 1,
13019                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
13020                    key: test_key(1),
13021                }),
13022            },
13023            rr_message_id: None,
13024            received_at: Instant::now(),
13025        };
13026        let second = InboundReplicationMessage {
13027            source: test_peer(0xC2),
13028            msg: ReplicationMessage {
13029                request_id: 2,
13030                body: dropped_body.clone(),
13031            },
13032            rr_message_id: None,
13033            received_at: Instant::now(),
13034        };
13035
13036        assert!(try_enqueue_serial_message(&sender, first).is_ok());
13037        let dropped = try_enqueue_serial_message(&sender, second)
13038            .expect_err("a full serial queue must refuse the second message");
13039        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
13040        assert_eq!(dropped.message_class, "verification_request");
13041        assert_eq!(dropped.queue_depth, 1);
13042        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13043        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
13044
13045        let queued = receiver
13046            .recv()
13047            .await
13048            .expect("first message should remain queued");
13049        assert_eq!(queued.msg.request_id, 1);
13050        assert!(receiver.try_recv().is_err());
13051    }
13052
13053    #[tokio::test]
13054    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
13055        let peer = test_peer(0x44);
13056        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
13057
13058        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
13059        let mut digest_guards = Vec::new();
13060        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
13061            let guard = admit_audit_responder(
13062                &semaphore,
13063                &digest_inflight,
13064                &peer,
13065                AuditResponderClass::Digest,
13066            )
13067            .await;
13068            assert!(guard.is_ok());
13069            digest_guards.push(guard);
13070        }
13071        assert!(
13072            admit_audit_responder(
13073                &semaphore,
13074                &digest_inflight,
13075                &peer,
13076                AuditResponderClass::Digest,
13077            )
13078            .await
13079            .is_err(),
13080            "digest class must stop at its documented per-source cap"
13081        );
13082        drop(digest_guards);
13083
13084        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
13085        let mut subtree_guards = Vec::new();
13086        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
13087            let guard = admit_audit_responder(
13088                &semaphore,
13089                &subtree_inflight,
13090                &peer,
13091                AuditResponderClass::Subtree,
13092            )
13093            .await;
13094            assert!(guard.is_ok());
13095            subtree_guards.push(guard);
13096        }
13097        assert!(
13098            admit_audit_responder(
13099                &semaphore,
13100                &subtree_inflight,
13101                &peer,
13102                AuditResponderClass::Subtree,
13103            )
13104            .await
13105            .is_err(),
13106            "subtree class must retain the deployed cap of two"
13107        );
13108        drop(subtree_guards);
13109    }
13110
13111    #[test]
13112    fn in_scope_audit_deadlines_share_one_formula() {
13113        let config = config::ReplicationConfig::default();
13114        for key_count in [1, 4, 16] {
13115            assert_eq!(
13116                audit::responsible_audit_response_timeout(&config, key_count),
13117                config.audit_response_timeout(key_count)
13118            );
13119            assert_eq!(
13120                pruning::prune_audit_response_timeout(&config, key_count),
13121                config.audit_response_timeout(key_count)
13122            );
13123        }
13124        assert_eq!(
13125            possession::possession_probe_response_timeout(&config),
13126            config.audit_response_timeout(1)
13127        );
13128    }
13129
13130    #[test]
13131    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
13132        const EXISTING_SOURCE_ID: u8 = 1;
13133        const HINT_SENDER_ID: u8 = 2;
13134
13135        let existing_source = test_peer(EXISTING_SOURCE_ID);
13136        let hint_sender = test_peer(HINT_SENDER_ID);
13137        let mut sources = vec![existing_source];
13138
13139        let hint_sources = HashSet::from([hint_sender]);
13140        add_replica_hint_sources(&mut sources, &hint_sources);
13141        add_replica_hint_sources(&mut sources, &hint_sources);
13142
13143        // A paid-only advertiser leaves the claim set empty (see
13144        // `queue_admitted_hints`), so it contributes no fetch source.
13145        add_replica_hint_sources(&mut sources, &HashSet::new());
13146
13147        assert_eq!(sources, vec![existing_source, hint_sender]);
13148    }
13149
13150    #[test]
13151    fn audit_timeout_preserves_active_bootstrap_claim() {
13152        assert!(!audit_failure_clears_bootstrap_claim(
13153            &AuditFailureReason::Timeout
13154        ));
13155    }
13156
13157    fn strike_peer(b: u8) -> PeerId {
13158        let mut bytes = [0u8; 32];
13159        bytes[0] = b;
13160        PeerId::from_bytes(bytes)
13161    }
13162
13163    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
13164    // cooldown must collapse a gossip flood into at most one audit per window.
13165
13166    #[test]
13167    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
13168        let peer = strike_peer(1);
13169        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13170        let t0 = Instant::now();
13171        // First gossip in the window passes; a burst of further gossips at the
13172        // same instant are all suppressed.
13173        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13174        let mut passed = 1;
13175        for _ in 0..100 {
13176            if cooldown_allows_audit(&mut map, &peer, t0) {
13177                passed += 1;
13178            }
13179        }
13180        assert_eq!(
13181            passed, 1,
13182            "a flood at one instant must trigger exactly one audit"
13183        );
13184    }
13185
13186    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
13187    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
13188    // consumes the window. This is the property the isolated cooldown tests above
13189    // cannot see: they never sample the lottery, so a regression that reordered
13190    // the gates (sample probability first, only stamp the cooldown on a win)
13191    // would still pass them while breaking flood-resistance: a flood would then
13192    // re-roll the lottery on EVERY message until one won, multiplying audits.
13193    //
13194    // We model the exact production gate order (attempt-window, lottery,
13195    // shared cooldown) with a lottery driven by a fixed outcome instead of
13196    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13197    // messages all WIN. With the production order, the losing first ticket
13198    // burns the ATTEMPT window and every later winner in the same window is
13199    // blocked, so there are 0 audits this window. If the gates were flipped,
13200    // the second message's winning ticket would slip through. The window only
13201    // reopens after it elapses.
13202    //
13203    // FLIPS IF: the lottery is sampled before the attempt-window
13204    // check-and-stamp (a losing ticket no longer consumes the window),
13205    // re-enabling a flood-amplified audit storm.
13206    #[test]
13207    fn losing_lottery_still_consumes_attempt_window() {
13208        // Calls the SHIPPED `audit_launch_decision` (the same function
13209        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13210        // production fails this test — not a local reimplementation.
13211        let peer = strike_peer(3);
13212        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13213        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13214        let t0 = Instant::now();
13215
13216        // First flooded message at t0 LOSES the lottery, but the attempt window
13217        // is stamped BEFORE the lottery is consulted, so the window is consumed.
13218        assert!(
13219            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13220            "a losing ticket launches no audit"
13221        );
13222
13223        // 99 more flooded messages at the same instant would all WIN the lottery,
13224        // yet every one must be blocked by the attempt window the loser stamped.
13225        // (If production sampled the lottery FIRST, these would each get a fresh
13226        // roll and audits would multiply — this assertion catches that reorder.)
13227        let mut audits = 0;
13228        for _ in 0..99 {
13229            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13230                audits += 1;
13231            }
13232        }
13233        assert_eq!(
13234            audits, 0,
13235            "a losing first ticket must consume the attempt window so no later \
13236             flooded message in the same window can audit"
13237        );
13238
13239        // The window only reopens after it elapses; the next winning ticket
13240        // then launches exactly one audit and stamps the SHARED cooldown.
13241        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13242        assert!(
13243            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13244            "after the window a winning ticket audits again"
13245        );
13246        assert!(
13247            launched.contains_key(&peer),
13248            "a real launch stamps the shared cooldown"
13249        );
13250    }
13251
13252    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13253    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13254    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13255    /// first audit deferred until its answerability window expires.
13256    ///
13257    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13258    /// loss (the pre-split behavior, where both paths shared one map).
13259    #[test]
13260    fn losing_lottery_does_not_suppress_monetized_first_audit() {
13261        let peer = strike_peer(4);
13262        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13263        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13264        let t0 = Instant::now();
13265
13266        // A losing ticket consumes the gossip attempt window...
13267        assert!(!audit_launch_decision(
13268            &mut attempts,
13269            &mut launched,
13270            &peer,
13271            t0,
13272            false
13273        ));
13274        // ...but leaves the shared map untouched, so the first-audit reserve
13275        // gate (read-only) and the authoritative promotion check-and-stamp both
13276        // still allow the paid audit to launch immediately.
13277        assert!(
13278            cooldown_would_allow(&launched, &peer, t0),
13279            "reserve gate must not see a losing ticket as audit coverage"
13280        );
13281        assert!(
13282            cooldown_allows_audit(&mut launched, &peer, t0),
13283            "promotion must not be deferred by a losing ticket"
13284        );
13285
13286        // Conversely a WINNING ticket (real audit sent) does suppress the
13287        // first audit for the window, which is the intended shared semantics.
13288        let peer_won = strike_peer(5);
13289        assert!(audit_launch_decision(
13290            &mut attempts,
13291            &mut launched,
13292            &peer_won,
13293            t0,
13294            true
13295        ));
13296        assert!(
13297            !cooldown_would_allow(&launched, &peer_won, t0),
13298            "a real gossip audit still covers the peer for the window"
13299        );
13300    }
13301
13302    #[test]
13303    fn cooldown_lets_audit_through_after_the_window() {
13304        let peer = strike_peer(2);
13305        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13306        let t0 = Instant::now();
13307        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13308        // Within the window: suppressed.
13309        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13310        assert!(!cooldown_allows_audit(&mut map, &peer, within));
13311        // Past the window: allowed again.
13312        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13313        assert!(cooldown_allows_audit(&mut map, &peer, after));
13314    }
13315
13316    #[test]
13317    fn cooldown_is_per_peer_independent() {
13318        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13319        let t0 = Instant::now();
13320        // Different peers each get their own first-audit pass at the same instant.
13321        for i in 0..20u8 {
13322            assert!(
13323                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13324                "peer {i} should be auditable independently"
13325            );
13326        }
13327    }
13328
13329    #[test]
13330    fn audit_on_gossip_constants_match_adr() {
13331        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13332        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13333        // values above 5 would silently never be requested).
13334        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13335        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13336        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13337    }
13338
13339    // (d) A confirmed storage-integrity failure penalizes immediately and
13340    // revokes credit; it is not a timeout.
13341    #[test]
13342    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13343        assert!(audit_failure_clears_bootstrap_claim(
13344            &AuditFailureReason::DigestMismatch
13345        ));
13346        assert!(audit_failure_revokes_holder_credit(
13347            &AuditFailureReason::DigestMismatch
13348        ));
13349    }
13350
13351    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13352    /// uses: confirmed failures revoke credit, `Timeout` does not.
13353    #[test]
13354    fn confirmed_failures_revoke_credit_timeout_does_not() {
13355        for reason in [
13356            AuditFailureReason::MalformedResponse,
13357            AuditFailureReason::DigestMismatch,
13358            AuditFailureReason::KeyAbsent,
13359            AuditFailureReason::Rejected,
13360        ] {
13361            assert!(
13362                audit_failure_revokes_holder_credit(&reason),
13363                "confirmed failure {reason:?} must revoke holder credit"
13364            );
13365        }
13366        assert!(
13367            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13368            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13369        );
13370    }
13371
13372    /// Wiring test for the security fix: the helper the handler calls
13373    /// actually strips a credited peer on a confirmed failure
13374    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13375    /// Records genuine credit first so neither assertion is vacuous;
13376    /// this fails if `forget_peer` stops being called, or if the
13377    /// `Timeout` exclusion is dropped (both verified by mutation).
13378    #[test]
13379    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13380        let peer = test_peer(0xAB);
13381        let key = test_key(1);
13382        let hash = [0xCD; 32];
13383
13384        // Confirmed failure -> credit revoked.
13385        let mut provers = RecentProvers::new();
13386        provers.record_proof(key, peer, hash, Instant::now());
13387        assert!(
13388            provers.is_credited_holder(&key, &peer, &hash),
13389            "precondition: peer credited before failure"
13390        );
13391        apply_audit_failure_credit_revocation(
13392            &mut provers,
13393            &peer,
13394            &AuditFailureReason::DigestMismatch,
13395        );
13396        assert!(
13397            !provers.is_credited_holder(&key, &peer, &hash),
13398            "DigestMismatch must strip the peer's holder credit"
13399        );
13400
13401        // Timeout -> credit retained.
13402        let mut provers_timeout = RecentProvers::new();
13403        provers_timeout.record_proof(key, peer, hash, Instant::now());
13404        apply_audit_failure_credit_revocation(
13405            &mut provers_timeout,
13406            &peer,
13407            &AuditFailureReason::Timeout,
13408        );
13409        assert!(
13410            provers_timeout.is_credited_holder(&key, &peer, &hash),
13411            "Timeout must retain holder credit (deliberate liveness cushion)"
13412        );
13413    }
13414
13415    #[test]
13416    fn decoded_audit_failures_clear_active_bootstrap_claim() {
13417        for reason in [
13418            AuditFailureReason::MalformedResponse,
13419            AuditFailureReason::DigestMismatch,
13420            AuditFailureReason::KeyAbsent,
13421            AuditFailureReason::Rejected,
13422        ] {
13423            assert!(
13424                audit_failure_clears_bootstrap_claim(&reason),
13425                "decoded non-bootstrap failure {reason:?} should clear active claim"
13426            );
13427        }
13428    }
13429
13430    #[test]
13431    fn first_failed_key_label_truncates_to_16_hex_chars() {
13432        // The high-order 8 bytes of the XorName determine the label so an
13433        // operator can group audit-failures on the same chunk prefix.
13434        let mut key = [0u8; 32];
13435        key[0] = 0x18;
13436        key[7] = 0xff;
13437        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13438        // to verify they are NOT included in the label.
13439        for byte in &mut key[8..] {
13440            *byte = 0xAA;
13441        }
13442        let label = first_failed_key_label(&[key]);
13443        // Only the first 8 bytes are encoded, low-order bytes are dropped.
13444        assert_eq!(label, "0x18000000000000ff");
13445        assert_eq!(label.len(), "0x".len() + 16);
13446    }
13447
13448    #[test]
13449    fn first_failed_key_label_falls_back_when_empty() {
13450        // Should never happen in production (audit failure handling rejects
13451        // empty sets), but the formatter must still produce a valid label
13452        // so the log line doesn't contain a misleading default.
13453        assert_eq!(first_failed_key_label(&[]), "0x");
13454    }
13455
13456    #[test]
13457    fn first_failed_key_label_uses_first_key_only() {
13458        let first = [0x11u8; 32];
13459        let second = [0x22u8; 32];
13460        assert_eq!(
13461            first_failed_key_label(&[first, second]),
13462            format!("0x{}", hex::encode(&first[..8]))
13463        );
13464    }
13465
13466    // -- apply_fetch_result --------------------------------------------------
13467    //
13468    // The worker's disposition of a fetch outcome. Note there is no trust
13469    // handle in `apply_fetch_result`'s signature: the worker cannot report a
13470    // trust event for ANY outcome, and `execute_single_fetch` returns
13471    // `NoLongerResponsible` before its trust-reporting paths — the source did
13472    // nothing wrong when this node's own responsibility lapsed.
13473
13474    /// Route `key` through the real pipeline stages (pending → promoted →
13475    /// dequeued → in-flight) so it carries a verification retry-slot
13476    /// reservation, exactly as a worker-dequeued key does. Returns the
13477    /// in-flight source.
13478    fn drive_key_in_flight(
13479        q: &mut ReplicationQueues,
13480        key: XorName,
13481        sources: Vec<PeerId>,
13482    ) -> PeerId {
13483        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13484        let now = Instant::now();
13485        let entry = VerificationEntry {
13486            state: VerificationState::PendingVerify,
13487            verified_sources: Vec::new(),
13488            tried_sources: HashSet::new(),
13489            created_at: now,
13490            next_verify_at: now,
13491            hint_sources: HashSet::from([hinter]),
13492            replica_hint_sources: HashSet::from([hinter]),
13493            unresolved_retries: 0,
13494            no_holder_reported: false,
13495        };
13496        assert!(q.add_pending_verify(key, entry).admitted());
13497        assert!(q.promote_pending_to_fetch(key, key, sources));
13498        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13499        let source = *candidate.sources.first().expect("candidate has a source");
13500        q.start_dequeued_fetch(candidate, source);
13501        source
13502    }
13503
13504    #[test]
13505    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13506        const RETRY_AFTER: Duration = Duration::from_mins(1);
13507
13508        let mut q = ReplicationQueues::new();
13509        let key = test_key(0xAB);
13510        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13511        assert_eq!(q.retry_reserved_slot_count(), 1);
13512
13513        let follow_up =
13514            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13515
13516        assert_eq!(
13517            follow_up,
13518            FetchFollowUp::Terminal,
13519            "lapsed responsibility must run the caller's terminal bootstrap accounting"
13520        );
13521        assert!(
13522            !q.contains_key(&key),
13523            "the key must leave every pipeline stage — alternate sources included"
13524        );
13525        assert_eq!(
13526            q.pending_count(),
13527            0,
13528            "a lapsed-responsibility key must not be requeued for verification"
13529        );
13530        assert_eq!(
13531            q.retry_reserved_slot_count(),
13532            0,
13533            "terminal exit must release the verification retry-slot reservation"
13534        );
13535    }
13536
13537    #[test]
13538    fn no_longer_responsible_shares_the_stored_terminal_path() {
13539        const RETRY_AFTER: Duration = Duration::from_mins(1);
13540
13541        // Both variants must walk the identical terminal gate so the
13542        // battle-tested Stored accounting (retry-slot release + bootstrap
13543        // pending-set shrink in the caller) covers lapsed responsibility too.
13544        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13545            let mut q = ReplicationQueues::new();
13546            let key = test_key(0xCD);
13547            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13548
13549            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13550
13551            assert_eq!(follow_up, FetchFollowUp::Terminal);
13552            assert!(!q.contains_key(&key));
13553            assert_eq!(q.retry_reserved_slot_count(), 0);
13554        }
13555    }
13556
13557    #[test]
13558    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13559        const RETRY_AFTER: Duration = Duration::from_mins(1);
13560
13561        let mut q = ReplicationQueues::new();
13562        let key = test_key(0xEF);
13563        let first = test_peer(0x04);
13564        let second = test_peer(0x05);
13565        drive_key_in_flight(&mut q, key, vec![first, second]);
13566
13567        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13568        assert_eq!(
13569            follow_up,
13570            FetchFollowUp::RetryFrom(second),
13571            "a failed source must not abandon the remaining verified sources"
13572        );
13573        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13574
13575        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13576        assert_eq!(
13577            follow_up,
13578            FetchFollowUp::RequeuedForVerification,
13579            "exhausted sources must restore the reserved verification entry"
13580        );
13581        assert_eq!(q.pending_count(), 1);
13582        assert_eq!(
13583            q.retry_reserved_slot_count(),
13584            0,
13585            "the reservation converts back into the pending entry itself"
13586        );
13587    }
13588
13589    #[test]
13590    fn source_failure_without_retry_metadata_is_terminal() {
13591        const RETRY_AFTER: Duration = Duration::from_mins(1);
13592
13593        // Direct enqueue (no pending entry) models a fetch with no
13594        // verification retry reservation to restore.
13595        let mut q = ReplicationQueues::new();
13596        let key = test_key(0x1F);
13597        let source = test_peer(0x06);
13598        assert!(q.enqueue_fetch(key, key, vec![source]));
13599        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13600        q.start_dequeued_fetch(candidate, source);
13601
13602        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13603
13604        assert_eq!(follow_up, FetchFollowUp::Terminal);
13605        assert!(!q.contains_key(&key));
13606    }
13607
13608    #[test]
13609    fn already_held_key_leaves_the_pipeline_terminally() {
13610        const RETRY_AFTER: Duration = Duration::from_mins(1);
13611
13612        let mut q = ReplicationQueues::new();
13613        let key = test_key(0x4C);
13614        let source = test_peer(0x0B);
13615        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13616
13617        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13618
13619        assert_eq!(
13620            follow_up,
13621            FetchFollowUp::Terminal,
13622            "holding the key already discharges the duty, so the key must leave \
13623             the pipeline exactly as a completed fetch does — requeueing it \
13624             would re-verify a key that needs nothing"
13625        );
13626        assert!(!q.contains_key(&key));
13627        assert_eq!(
13628            q.retry_reserved_slot_count(),
13629            0,
13630            "the terminal path must release the retry-slot reservation, or the \
13631             owner's verification budget leaks"
13632        );
13633    }
13634
13635    #[test]
13636    fn local_write_failure_does_not_conscript_the_remaining_sources() {
13637        const RETRY_AFTER: Duration = Duration::from_mins(1);
13638
13639        let mut q = ReplicationQueues::new();
13640        let key = test_key(0x2A);
13641        let first = test_peer(0x07);
13642        let second = test_peer(0x08);
13643        let third = test_peer(0x09);
13644        drive_key_in_flight(&mut q, key, vec![first, second, third]);
13645
13646        let follow_up =
13647            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13648
13649        assert_eq!(
13650            follow_up,
13651            FetchFollowUp::RequeuedForVerification,
13652            "a local write failure must go straight back to verification: the two \
13653             untried sources would each re-upload the same chunk into the same \
13654             full disk, and neither of them did anything wrong"
13655        );
13656        assert_eq!(q.in_flight_count(), 0);
13657        assert_eq!(
13658            q.pending_count(),
13659            1,
13660            "the key must come back — capacity frees up, and a stranded key is \
13661             a replica this node silently stops owing"
13662        );
13663        assert_eq!(q.retry_reserved_slot_count(), 0);
13664    }
13665
13666    #[test]
13667    fn local_write_failure_without_retry_metadata_is_terminal() {
13668        const RETRY_AFTER: Duration = Duration::from_mins(1);
13669
13670        // No pending entry to restore, so the only way not to strand the key
13671        // in `in_flight_fetch` forever — which would also stall bootstrap
13672        // drain — is the terminal path.
13673        let mut q = ReplicationQueues::new();
13674        let key = test_key(0x3B);
13675        let source = test_peer(0x0A);
13676        assert!(q.enqueue_fetch(key, key, vec![source]));
13677        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13678        q.start_dequeued_fetch(candidate, source);
13679
13680        let follow_up =
13681            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13682
13683        assert_eq!(follow_up, FetchFollowUp::Terminal);
13684        assert!(!q.contains_key(&key));
13685        assert_eq!(q.retry_reserved_slot_count(), 0);
13686    }
13687}