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::pointer::{FinalStateWitness, PointerService};
72use crate::replication::audit::AuditTickResult;
73use crate::replication::audit_coordinator::AuditChallengeCoordinator;
74use crate::replication::audit_metrics::{
75    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
76    ReplicationResponderClass, ResponderAdmissionCeiling,
77};
78use crate::replication::commitment::{commitment_hash, StorageCommitment};
79use crate::replication::commitment_state::{
80    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
81};
82use crate::replication::config::{
83    fresh_read_retry_delay, max_parallel_fetch, storage_admission_width, ReplicationConfig,
84    MAX_AUDIT_RESPONSES_PER_PEER, MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
85    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_FRESH_READ_ATTEMPTS, MAX_INCOMING_VERIFICATION_KEYS,
86    MAX_PENDING_FRESH_OFFERS, MAX_SESSION_POINTER_BINDINGS, MAX_SUBTREE_ROUND1_PER_PEER,
87    MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE, REPLICATION_PROTOCOL_ID,
88    SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
89    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
90};
91use crate::replication::paid_list::PaidList;
92use crate::replication::protocol::{
93    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
94    VerificationResponse,
95};
96use crate::replication::quorum::KeyVerificationOutcome;
97use crate::replication::recent_provers::RecentProvers;
98use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
99use crate::replication::storage_commitment_audit::PointerBindings;
100use crate::replication::types::{
101    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
102    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
103    VerificationState,
104};
105use crate::storage::{CapacityVerdict, ChunkStore};
106use saorsa_core::identity::{NodeIdentity, PeerId};
107use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
108use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
109
110/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
111/// because it was full (Amendment 2). Process-global because the producer is
112/// the payment verifier (a different module) and the drop happens before the
113/// per-drainer `received` counter. A non-zero value is the rollout signal that
114/// nomination ingress is saturating — benign (penalty-free, lottery/next-
115/// payment covered) but worth watching. `Closed` (engine shut down) is not
116/// counted: it is not a saturation signal.
117static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
118
119/// Record one ingress-full drop. Called by the payment verifier's `try_send`
120/// sites; read by the drainer's periodic summary.
121pub(crate) fn note_monetized_ingress_drop() {
122    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
123}
124
125#[derive(Default)]
126struct FirstAuditObservability {
127    received: AtomicU64,
128    queued: AtomicU64,
129    coalesced: AtomicU64,
130    duplicates: AtomicU64,
131    capacity_evicted: AtomicU64,
132    /// An event targeting the local peer itself, dropped at ingress: the node
133    /// cannot network-audit itself (no dialable address for the local peer).
134    self_target_skipped: AtomicU64,
135    /// A strictly-lower-count same-peer nomination that was dropped so a
136    /// higher-count pending pin survived. A sustained rise is the signal of an
137    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
138    suppressed_lower: AtomicU64,
139    cooldown_deferred_attempts: AtomicU64,
140    rate_deferred_attempts: AtomicU64,
141    window_deduped: AtomicU64,
142    launched: AtomicU64,
143    passed: AtomicU64,
144    timed_out: AtomicU64,
145    failed: AtomicU64,
146    bootstrap_claims: AtomicU64,
147    idle: AtomicU64,
148    insufficient_keys: AtomicU64,
149    outside_answerability_window: AtomicU64,
150    inflight: AtomicU64,
151}
152
153/// Test-only snapshot of the first-audit scheduler counters.
154///
155/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
156/// self-targeting monetized pin was dropped and never launched) instead of
157/// scraping log lines.
158#[cfg(any(test, feature = "test-utils"))]
159#[derive(Debug, Clone, Copy)]
160pub struct FirstAuditStats {
161    /// Events ingested from the monetized-pin channel.
162    pub received: u64,
163    /// Events accepted into the pending first-audit queue.
164    pub queued: u64,
165    /// Events dropped because they targeted the local peer.
166    pub self_target_skipped: u64,
167    /// Audits launched.
168    pub launched: u64,
169    /// Launched audits that passed.
170    pub passed: u64,
171    /// Launched audits that timed out (non-response lane).
172    pub timed_out: u64,
173    /// Launched audits that ended in a confirmed failure.
174    pub failed: u64,
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq)]
178enum FirstAuditTerminalOutcome {
179    Passed,
180    Timeout,
181    Failed,
182    BootstrapClaim,
183    Idle,
184    InsufficientKeys,
185}
186
187impl FirstAuditTerminalOutcome {
188    #[cfg(any(feature = "logging", test))]
189    const fn as_str(self) -> &'static str {
190        match self {
191            Self::Passed => "passed",
192            Self::Timeout => "timeout",
193            Self::Failed => "failed",
194            Self::BootstrapClaim => "bootstrap_claim",
195            Self::Idle => "idle",
196            Self::InsufficientKeys => "insufficient_keys",
197        }
198    }
199}
200
201fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
202    match result {
203        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
204        AuditTickResult::Failed {
205            evidence:
206                FailureEvidence::AuditFailure {
207                    reason: AuditFailureReason::Timeout,
208                    ..
209                },
210            ..
211        } => FirstAuditTerminalOutcome::Timeout,
212        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
213        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
214        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
215        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
216    }
217}
218
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220enum FirstAuditQueueOutcome {
221    /// New peer inserted with free capacity.
222    Queued,
223    /// Collapsed with an existing same-peer entry; the incoming won (higher
224    /// count, or equal count and newer) and replaced it.
225    Coalesced,
226    /// Collapsed with an existing same-peer entry; the incoming LOST because it
227    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
228    /// in place. This is the attempted cheaper-pin self-erasure signal.
229    SuppressedLower,
230    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
231    /// lost the freshness tie (it was not the newer of the two) and the
232    /// existing entry was retained. Benign, not an attack signal.
233    RetainedOnTie,
234    /// A DIFFERENT peer's entry was displaced from the capped pending queue
235    /// (random victim) to make room.
236    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
237}
238
239/// Coalesce a monetized nomination into the per-peer pending queue with a
240/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
241/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
242///
243/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
244/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
245/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
246/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
247/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
248/// cannot promote the retained pin's lane position.
249///
250/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
251/// last, so it wins an equal-count tie for freshness) from a cooldown-race
252/// requeue of an older reserved event (the pending successor is newer, so it
253/// wins the tie).
254fn coalesce_first_audit_event(
255    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
256    incoming: MonetizedPinEvent,
257    incoming_is_newer: bool,
258    rng: &mut StdRng,
259) -> FirstAuditQueueOutcome {
260    if let Some(existing) = pending.peek(&incoming.peer) {
261        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
262        // the retained pin's recency (the security-relevant self-erasure case).
263        if incoming.key_count < existing.key_count {
264            return FirstAuditQueueOutcome::SuppressedLower;
265        }
266        // Equal count -> keep the fresher; an older incoming loses a benign tie.
267        if incoming.key_count == existing.key_count && !incoming_is_newer {
268            return FirstAuditQueueOutcome::RetainedOnTie;
269        }
270        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
271        // the value and bumps MRU; replacing an existing key never evicts a
272        // different peer.
273        let _ = pending.push(incoming.peer, incoming);
274        return FirstAuditQueueOutcome::Coalesced;
275    }
276    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
277    // never the LRU: deterministic keep-newest would let an ordered batch of
278    // `cap` distinct-peer nominations flush a chosen target before any launch
279    // lane sees it, cutting the eviction cost from probabilistic to exact. A
280    // random victim caps an attacker's per-nomination eviction probability at
281    // `1/cap` regardless of arrival order or timing, so suppressing a specific
282    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
283    // nominations and is never certain (ADR-0004 Amendment 4).
284    if pending.len() >= pending.cap().get() {
285        let victim = {
286            let idx = rng.gen_range(0..pending.len());
287            pending.iter().nth(idx).map(|(p, _)| *p)
288        };
289        if let Some(victim_peer) = victim {
290            if let Some(evicted) = pending.pop(&victim_peer) {
291                let _ = pending.push(incoming.peer, incoming);
292                return FirstAuditQueueOutcome::CapacityEvicted {
293                    peer: victim_peer,
294                    pin: evicted.pin,
295                };
296            }
297        }
298    }
299    match pending.push(incoming.peer, incoming) {
300        None => FirstAuditQueueOutcome::Queued,
301        // Unreachable: the random-displacement branch above guarantees
302        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
303        // exists). Kept so any future logic error surfaces as an ACCOUNTED
304        // eviction rather than silent loss — but note this arm would be
305        // LRU-order, not random, so it must stay unreachable.
306        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
307            peer: evicted_peer,
308            pin: evicted.pin,
309        },
310    }
311}
312
313/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
314/// prefiltering a nomination's answerability at schedule time, covering the
315/// spawn/dispatch latency between the timer firing and the wire challenge so a
316/// jitter==MAX pin is not admitted only to fail the authoritative check by a
317/// few milliseconds. Tiny against the multi-hour answerability window.
318const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
319
320/// A first audit the limiter recently launched at a peer: when, and the
321/// committed key count that was audited (for the count-jump override).
322#[derive(Debug, Clone, Copy, PartialEq, Eq)]
323struct RecentFirstAudit {
324    launched_at: Instant,
325    key_count: u32,
326}
327
328/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
329/// panicking or cancelled audit task can never leak a slot and wedge the
330/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
331struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
332
333impl FirstAuditInflightSlot {
334    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
335        observability.inflight.fetch_add(1, Ordering::Relaxed);
336        Self(Arc::clone(observability))
337    }
338}
339
340impl Drop for FirstAuditInflightSlot {
341    fn drop(&mut self) {
342        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
343    }
344}
345
346/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
347/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
348/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
349/// overflow-free integer math). A jump re-nominates a peer despite a recent
350/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
351/// only, so no gossip-lottery audit can ever cover it.
352const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
353    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
354        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
355}
356
357/// The launch limiter's verdict for one pending monetized pin.
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359enum LimiterVerdict {
360    /// Within budget and window: the caller may reserve a launch (and consumes
361    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
362    Admit,
363    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
364    /// pin pending and retry on a later tick.
365    RateDeferred,
366    /// The peer had a first audit within
367    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
368    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
369    /// gossip-lottery re-audit path is unaffected).
370    WindowDeduped,
371}
372
373/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
374/// (launch rate), an in-flight cap, and a per-peer re-audit window that
375/// survives pin rotation.
376///
377/// This is the load-bearing aggregate bound the original scheduler lacked:
378/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
379/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
380/// `now`/`inflight` values so every decision is unit-testable without a
381/// runtime.
382struct FirstAuditLimiter {
383    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
384    tokens: u32,
385    /// Refill anchor. While the bucket is full this tracks `now` (a full
386    /// bucket accrues nothing); while below capacity it advances only by
387    /// whole refill intervals so fractional elapsed time is never lost.
388    last_refill: Instant,
389    /// Peers given a first audit recently, with the audited key count.
390    /// Bounded like the drainer's other per-peer maps.
391    recent: LruCache<PeerId, RecentFirstAudit>,
392}
393
394impl FirstAuditLimiter {
395    fn new(now: Instant) -> Self {
396        Self {
397            tokens: config::FIRST_AUDIT_BUDGET_BURST,
398            last_refill: now,
399            recent: LruCache::new(
400                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
401            ),
402        }
403    }
404
405    /// Whether the per-peer re-audit window admits a nomination for `peer`
406    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
407    /// call at ENQUEUE time — suppressed nominations never occupy pending
408    /// slots — without disturbing LRU recency.
409    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
410        self.recent.peek(peer).is_none_or(|prev| {
411            now.saturating_duration_since(prev.launched_at)
412                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
413                || first_audit_count_jump(prev.key_count, key_count)
414        })
415    }
416
417    /// Refill the token bucket for the time elapsed up to `now`.
418    fn refill(&mut self, now: Instant) {
419        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
420            // Full bucket accrues nothing; keep the anchor current so the
421            // next consumption starts its interval from here.
422            self.last_refill = now;
423            return;
424        }
425        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
426        let elapsed = now.saturating_duration_since(self.last_refill);
427        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
428        if earned == 0 {
429            return;
430        }
431        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
432        if earned >= capacity_gap {
433            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
434            self.last_refill = now;
435        } else {
436            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
437            self.tokens = self
438                .tokens
439                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
440            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
441            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
442        }
443    }
444
445    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
446    /// caller runs the remaining (per-peer cooldown) gate and calls
447    /// [`Self::commit_launch`] only for a launch that actually happens, so a
448    /// deferral elsewhere never burns budget or stamps the window.
449    fn assess(
450        &mut self,
451        peer: &PeerId,
452        key_count: u32,
453        now: Instant,
454        inflight: u64,
455    ) -> LimiterVerdict {
456        if !self.window_allows(peer, key_count, now) {
457            return LimiterVerdict::WindowDeduped;
458        }
459        self.refill(now);
460        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
461            return LimiterVerdict::RateDeferred;
462        }
463        LimiterVerdict::Admit
464    }
465
466    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
467    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
468    /// only at [`Self::promote`], after the authoritative post-jitter
469    /// answerability check, so a reservation that is later cancelled leaves no
470    /// suppression behind.
471    fn reserve_token(&mut self) {
472        self.tokens = self.tokens.saturating_sub(1);
473    }
474
475    /// Return a token consumed by a reservation that was cancelled before it
476    /// launched (answerability lapsed or a concurrent gossip audit won the
477    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
478    /// the bucket.
479    fn refund_token(&mut self) {
480        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
481    }
482
483    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
484    /// (promotion). Separated from token consumption so suppression is only
485    /// ever recorded for a real send.
486    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
487        self.recent.put(
488            peer,
489            RecentFirstAudit {
490                launched_at: now,
491                key_count,
492            },
493        );
494    }
495
496    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
497    /// and stamp the window in one call. Production splits these across
498    /// reservation and promotion; the limiter's own budget/window unit tests do
499    /// not model the jitter reservation and use this shorthand.
500    #[cfg(test)]
501    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
502        self.reserve_token();
503        self.promote(peer, key_count, now);
504    }
505}
506
507/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
508/// across the ENTIRE launch-jitter window ending at
509/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
510/// for it cannot later require aborting an out-of-window challenge. The
511/// too-future bound is enforced at `now` (a jitter delay only ages a pin
512/// forward, never toward the future); the too-old bound is enforced at the
513/// latest possible send time. This is a conservative admission prefilter; the
514/// authoritative answerability check still runs at promotion against the real
515/// send-time wall clock, so A1 (no false conviction) holds regardless of how
516/// jitter and the answerability margin are sized. `checked_add` overflow fails
517/// closed (skip the pin).
518fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
519    let Some(latest_send) = now
520        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
521        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
522    else {
523        return false;
524    };
525    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
526}
527
528/// Open the single first-audit reservation from `pending` if none is
529/// outstanding: samples the launch jitter, snapshots the shared cooldown
530/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
531/// shared implementation for both drainer call sites — the per-wake launch
532/// phase and the pre-overflow opportunity inside the ingress batch — so the
533/// two cannot drift.
534async fn open_first_audit_reservation(
535    scheduler: &mut FirstAuditScheduler,
536    cooldown: &RwLock<HashMap<PeerId, Instant>>,
537    observability: &Arc<FirstAuditObservability>,
538) {
539    if scheduler.has_reservation() {
540        return;
541    }
542    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
543        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
544    ));
545    let inflight = observability.inflight.load(Ordering::Relaxed);
546    let reserved = {
547        let cooldown = cooldown.read().await;
548        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
549    };
550    if reserved {
551        if let Some(peer) = scheduler.reserved_peer() {
552            debug!(
553                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
554                scheduler.pending_len()
555            );
556        }
557    }
558}
559
560/// A far-future `Instant` used to effectively DISABLE the promotion-timer
561/// select arm when no reservation is outstanding. The drainer still wakes at
562/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
563/// needs to be comfortably past the next tick.
564fn first_audit_far_future() -> Instant {
565    Instant::now()
566        .checked_add(Duration::from_hours(1))
567        .unwrap_or_else(Instant::now)
568}
569
570/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
571/// its in-flight slot and launch token from schedule time until the jitter
572/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
573/// only if the authoritative post-jitter answerability + cooldown checks pass at
574/// promotion, so a cancelled reservation leaves NO suppression behind.
575struct FirstAuditReservation {
576    event: MonetizedPinEvent,
577    ready_at: Instant,
578    inflight: FirstAuditInflightSlot,
579}
580
581/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
582/// pending queue, the dedup set, the launch limiter, the alternating lane, and
583/// the single outstanding reservation. All mutation is single-threaded in the
584/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
585/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
586/// state machine is unit-testable with injected clocks.
587struct FirstAuditScheduler {
588    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
589    /// (a real send), never at reservation, so a cancelled reservation can be
590    /// re-nominated.
591    first_audited: LruCache<[u8; 32], ()>,
592    /// Highest-count-per-peer pending nominations not yet launched. Capped at
593    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
594    /// one effective answerability window); at capacity a uniformly RANDOM
595    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
596    /// of a specific entry can never be forced deterministically. One further
597    /// entry may be held in `reserved` outside this queue — a deliberate
598    /// one-entry guard slot, so total schedulable occupancy is at most
599    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
600    pending: LruCache<PeerId, MonetizedPinEvent>,
601    /// Token bucket + per-peer re-audit window.
602    limiter: FirstAuditLimiter,
603    /// The single outstanding reservation (E′ serializes reservations so the
604    /// per-launch lane alternation is preserved and at most one jitter timer is
605    /// live).
606    reserved: Option<FirstAuditReservation>,
607    /// Alternating launch lane, flipped on every PROMOTION (real launch).
608    oldest_first_lane: bool,
609    /// The local node's own peer ID. A verified payment's quote list includes
610    /// the node's own quote, so the verifier emits a monetized-pin event for
611    /// the local peer on every payment it verifies. The node cannot
612    /// network-audit itself (there is no dialable address for the local peer,
613    /// so the challenge fails instantly and is miscounted as a timeout), while
614    /// any other payee that verifies the same payment schedules its own first
615    /// audit of this node's pin — a self-dial adds no coverage either way.
616    /// Such an event is dropped at ingress: never queued, and hence never
617    /// launched nor marked first-audited.
618    self_peer: PeerId,
619    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
620    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
621    /// production seeds from OS entropy at construction.
622    rng: StdRng,
623}
624
625impl FirstAuditScheduler {
626    fn new(now: Instant, self_peer: PeerId) -> Self {
627        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
628        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
629        Self {
630            first_audited: LruCache::new(dedup_cap),
631            pending: LruCache::new(pending_cap),
632            limiter: FirstAuditLimiter::new(now),
633            reserved: None,
634            oldest_first_lane: false,
635            self_peer,
636            rng: StdRng::from_entropy(),
637        }
638    }
639
640    /// Observability getter: used by the scheduler summary log and unit tests,
641    /// both absent from a release `--no-default-features` build, so it is dead
642    /// only in that configuration.
643    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
644    fn pending_len(&self) -> usize {
645        self.pending.len()
646    }
647
648    /// Observability getter (see [`Self::pending_len`]).
649    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
650    fn tokens(&self) -> u32 {
651        self.limiter.tokens
652    }
653
654    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
655    /// signed quote timestamp of the oldest pin still awaiting a first audit:
656    /// how close the longest-waiting pending pin is to aging out of the
657    /// answerability window. A value climbing toward the window means pending
658    /// work is expiring unaudited instead of launching; a small, steady value
659    /// means the queue is draining promptly. Returns `0` when `pending` is empty
660    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
661    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
662    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
663        self.pending
664            .iter()
665            .map(|(_, e)| e.quote_ts)
666            .min()
667            .and_then(|oldest| now.duration_since(oldest).ok())
668            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
669    }
670
671    /// Drop every pending nomination that has aged past the answerability
672    /// horizon. `try_reserve` collects expired entries only while it can scan —
673    /// under token starvation it returns at the budget gate first — so without
674    /// a periodic sweep dead entries squat the capped pending queue (displacing
675    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
676    /// telemetry. Each removal is accounted as `outside_answerability_window`,
677    /// exactly like a scan-time expiry. Returns how many entries were dropped;
678    /// survivor recency is untouched.
679    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
680        let expired: Vec<PeerId> = self
681            .pending
682            .iter()
683            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
684            .map(|(peer, _)| *peer)
685            .collect();
686        for peer in &expired {
687            self.pending.pop(peer);
688        }
689        if !expired.is_empty() {
690            obs.outside_answerability_window.fetch_add(
691                u64::try_from(expired.len()).unwrap_or(u64::MAX),
692                Ordering::Relaxed,
693            );
694        }
695        expired.len()
696    }
697
698    fn has_reservation(&self) -> bool {
699        self.reserved.is_some()
700    }
701
702    /// Whether admitting `event` would displace a DIFFERENT peer's pending
703    /// entry: the queue is at capacity and `event.peer` has no incumbent to
704    /// coalesce into. The drainer checks this before enqueueing so pending
705    /// work gets a reservation opportunity BEFORE destructive overflow
706    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
707    /// of `pending`, freeing the slot without any eviction.
708    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
709        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
710    }
711
712    /// When the outstanding reservation becomes eligible for promotion.
713    fn reserved_ready_at(&self) -> Option<Instant> {
714        self.reserved.as_ref().map(|r| r.ready_at)
715    }
716
717    /// The peer of the outstanding reservation, if any.
718    fn reserved_peer(&self) -> Option<PeerId> {
719        self.reserved.as_ref().map(|r| r.event.peer)
720    }
721
722    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
723    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
724    /// if already first-audited; the window screen is bypassed for the currently
725    /// reserved peer (so a successor is retained across the reservation, never
726    /// window-dropped); otherwise window-screened. Coalescing is
727    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
728    /// displaces a higher-count pending pin. An incumbent that has aged past
729    /// the answerability horizon is dropped (and accounted as an expiry) before
730    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
731    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
732    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
733    /// displacement is accounted as `capacity_evicted` and stamps no
734    /// suppression, so a displaced peer's next nomination is judged like any
735    /// newcomer. The drainer additionally offers a reservation opportunity
736    /// via [`Self::would_displace`] before calling this on an overflowing
737    /// arrival.
738    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
739        if event.peer == self.self_peer {
740            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
741            return;
742        }
743        if self.first_audited.contains(&event.pin) {
744            obs.duplicates.fetch_add(1, Ordering::Relaxed);
745            return;
746        }
747        let reserved_peer = self.reserved_peer();
748        let is_reserved_peer = reserved_peer == Some(event.peer);
749        if !is_reserved_peer
750            && !self
751                .limiter
752                .window_allows(&event.peer, event.key_count, Instant::now())
753        {
754            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
755            return;
756        }
757        // A pending incumbent past the answerability horizon can never launch,
758        // yet its (possibly higher) key count would still win the coalesce
759        // against a live incoming — e.g. a fresh post-prune lower-count pin —
760        // and under token starvation no reserve scan runs to collect it. Drop
761        // it first so the incoming is judged on its own merits.
762        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
763            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
764        });
765        if stale_incumbent {
766            self.pending.pop(&event.peer);
767            obs.outside_answerability_window
768                .fetch_add(1, Ordering::Relaxed);
769        }
770        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
771        // tie.
772        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
773            FirstAuditQueueOutcome::Queued => {
774                obs.queued.fetch_add(1, Ordering::Relaxed);
775            }
776            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
777                obs.coalesced.fetch_add(1, Ordering::Relaxed);
778            }
779            FirstAuditQueueOutcome::SuppressedLower => {
780                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
781            }
782            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
783                obs.queued.fetch_add(1, Ordering::Relaxed);
784                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
785            }
786        }
787    }
788
789    /// Attempt to create the single reservation from `pending` (E′ reserve).
790    /// Scans in the current lane order and reserves the FIRST eligible pin:
791    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
792    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
793    /// flip the lane — those happen only at promotion. Returns whether a
794    /// reservation was made. `cooldown` is a read-only snapshot (the
795    /// authoritative check-and-stamp is at promotion).
796    fn try_reserve(
797        &mut self,
798        mono_now: Instant,
799        inflight: u64,
800        jitter: Duration,
801        cooldown: &HashMap<PeerId, Instant>,
802        obs: &Arc<FirstAuditObservability>,
803    ) -> bool {
804        if self.reserved.is_some() || self.pending.is_empty() {
805            return false;
806        }
807        self.limiter.refill(mono_now);
808        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
809            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
810            return false;
811        }
812        // MRU->LRU order; reverse for the oldest-first lane so the preferred
813        // end is at the front.
814        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
815            .pending
816            .iter()
817            .enumerate()
818            .map(|(i, (p, e))| (i, *p, *e))
819            .collect();
820        self.pending.clear();
821        if self.oldest_first_lane {
822            ordered.reverse();
823        }
824        let mut chosen: Option<MonetizedPinEvent> = None;
825        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
826        for (idx, peer, event) in ordered {
827            if chosen.is_some() {
828                kept.push((idx, peer, event));
829                continue;
830            }
831            if self.first_audited.contains(&event.pin) {
832                obs.duplicates.fetch_add(1, Ordering::Relaxed);
833                continue; // drop: already audited
834            }
835            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
836                obs.outside_answerability_window
837                    .fetch_add(1, Ordering::Relaxed);
838                continue; // drop: cannot stay answerable through the jitter
839            }
840            // Window + budget + inflight. Tokens do not decrease during the
841            // scan (reserve happens after the loop) and `inflight` is fixed, so
842            // after the upfront budget gate `assess` never returns RateDeferred
843            // here; a defensive RateDeferred keeps the pin.
844            match self
845                .limiter
846                .assess(&peer, event.key_count, mono_now, inflight)
847            {
848                LimiterVerdict::WindowDeduped => {
849                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
850                    continue; // drop: recently first-audited, no count jump
851                }
852                LimiterVerdict::RateDeferred => {
853                    kept.push((idx, peer, event));
854                    continue; // keep (defensive; unreachable after upfront gate)
855                }
856                LimiterVerdict::Admit => {}
857            }
858            if !cooldown_would_allow(cooldown, &peer, mono_now) {
859                obs.cooldown_deferred_attempts
860                    .fetch_add(1, Ordering::Relaxed);
861                kept.push((idx, peer, event));
862                continue; // keep: on shared cooldown, retry later
863            }
864            chosen = Some(event);
865        }
866        // Restore relative recency (oldest re-put first -> newest stays MRU).
867        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
868        for (_, peer, event) in kept {
869            self.pending.put(peer, event);
870        }
871        let Some(event) = chosen else {
872            return false;
873        };
874        self.limiter.reserve_token();
875        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
876        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
877        self.reserved = Some(FirstAuditReservation {
878            event,
879            ready_at,
880            inflight: inflight_slot,
881        });
882        true
883    }
884
885    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
886    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
887        if self
888            .reserved
889            .as_ref()
890            .is_some_and(|r| mono_now >= r.ready_at)
891        {
892            self.reserved.take()
893        } else {
894            None
895        }
896    }
897
898    /// Authoritative promotion of a due reservation (E′). The caller holds the
899    /// shared cooldown write lock and passes the real send-time `wall_now` and
900    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
901    /// launch, or `None` when the launch was cancelled (answerability lapsed
902    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
903    /// On both `None` paths the token is refunded, the in-flight slot released,
904    /// and NO suppression is recorded.
905    ///
906    /// Known operational residual: suppression is stamped here, at promotion,
907    /// while the wire challenge is sent by the detached task the caller spawns
908    /// with the returned event. A task-start or encoding failure between the
909    /// two therefore leaves a stamped-but-unsent window. No remote input can
910    /// force that failure (it requires local task-spawn/alloc failure), so it
911    /// is accepted rather than closed; closing it would require stamping from
912    /// inside the spawned task and re-introduce the cancel-leaves-suppression
913    /// race this design exists to prevent.
914    fn resolve(
915        &mut self,
916        reservation: FirstAuditReservation,
917        wall_now: SystemTime,
918        mono_now: Instant,
919        cooldown: &mut HashMap<PeerId, Instant>,
920        obs: &Arc<FirstAuditObservability>,
921    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
922        let FirstAuditReservation {
923            event, inflight, ..
924        } = reservation;
925        // Authoritative answerability at the REAL send time.
926        if !quote_within_audit_window(event.quote_ts, wall_now) {
927            self.limiter.refund_token();
928            obs.outside_answerability_window
929                .fetch_add(1, Ordering::Relaxed);
930            drop(inflight);
931            return None; // cancelled; nothing stamped, nothing to roll back
932        }
933        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
934        // concurrent gossip audit requeues the reserved event through the SAME
935        // security-aware coalescing: the reserved event is OLDER than any
936        // same-peer successor (`incoming_is_newer = false`), so a higher-count
937        // reserved event still wins over a lower-count successor (the inflated
938        // pin must be audited), while an equal/higher successor is preserved.
939        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
940            self.limiter.refund_token();
941            obs.cooldown_deferred_attempts
942                .fetch_add(1, Ordering::Relaxed);
943            drop(inflight);
944            // Account for the requeue outcome (the nomination itself was already
945            // counted at ingress, so `queued` is not re-incremented): a capacity
946            // eviction of a DIFFERENT peer and a suppressed reserved event are
947            // both observable per the ADR funnel.
948            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
949                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
950                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
951                }
952                FirstAuditQueueOutcome::SuppressedLower => {
953                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
954                }
955                FirstAuditQueueOutcome::Queued
956                | FirstAuditQueueOutcome::Coalesced
957                | FirstAuditQueueOutcome::RetainedOnTie => {}
958            }
959            return None;
960        }
961        // Promote: stamp durable suppression, flip the lane, count the launch.
962        self.limiter.promote(event.peer, event.key_count, mono_now);
963        self.first_audited.put(event.pin, ());
964        self.oldest_first_lane = !self.oldest_first_lane;
965        obs.launched.fetch_add(1, Ordering::Relaxed);
966        Some((event, inflight))
967    }
968}
969
970// ---------------------------------------------------------------------------
971// Constants
972// ---------------------------------------------------------------------------
973
974/// Prefix used by saorsa-core's request-response mechanism.
975const RR_PREFIX: &str = "/rr/";
976
977/// Bounded handoff from the P2P broadcast receiver to serial non-audit
978/// replication processing.
979///
980/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
981/// bulk/non-audit messages here. If this fills, the message is **dropped** —
982/// `start_message_handler` must never block on a full queue, because a stalled
983/// receiver laps the P2P broadcast ring and silently loses messages it never
984/// observed. Every serial-lane class has protocol recovery, so a drop costs a
985/// retry rather than the message.
986///
987/// This bounds a message COUNT, but a queued item is an owned decoded message
988/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
989/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
990/// for: the lane carries small requests and challenges alongside
991/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
992/// right for both. Responses never reach here — `replication_payload_from_event`
993/// filters them out and their requesters correlate them. ADR-0005 decision 12
994/// records the trade and why byte accounting is the correct eventual fix.
995const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
996
997/// Maximum fresh-replication offers processed concurrently, away from the
998/// serial non-audit loop.
999///
1000/// Fresh offers can perform an on-chain payment verification and a 4 MiB
1001/// write. Four workers keep that latency off the responder dispatch path while
1002/// keeping concurrent EVM/storage pressure small and predictable.
1003const FRESH_OFFER_WORKER_LIMIT: usize = 4;
1004
1005/// Maximum fresh offers admitted at once, counting both those running on a
1006/// worker and those queued for one.
1007///
1008/// An admitted offer holds its payload until it completes, so this bounds
1009/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1010/// Offers past the bound are refused rather than queued or handled inline —
1011/// handling one on the message loop stalls every other non-audit message behind
1012/// a payment verification and a multi-MiB write. A refusal is not free: the
1013/// sender does not read it, so it resurfaces as a missing key at the delayed
1014/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1015/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1016/// bound is sized to make refusal rare rather than cheap.
1017const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1018
1019/// Distinct payment proofs queued for one fresh-offer key.
1020///
1021/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1022/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1023/// chunk out to the close group, so a receiver sees the same key from about that
1024/// many senders. They differ only in their proof — the bytes are provably
1025/// identical, since `fresh_offer_structural_rejection` has confirmed
1026/// `key == BLAKE3(data)` before any of them is queued.
1027///
1028/// Sizing the queue to the number of legitimate senders is what lets a failing
1029/// proof fall through to the next one instead of costing the node the record.
1030///
1031/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1032/// admitted, and a proof the handler has popped has spent its slot rather than
1033/// returned it. That distinction is what bounds the work an attacker can buy —
1034/// at most this many on-chain verifications per key, after which the entry
1035/// refuses everyone until it closes. Gating on the queue's instantaneous length
1036/// instead would let a stream of distinct sources refill each popped slot and
1037/// run unbounded sequential verifications while holding one of the four worker
1038/// slots. One attempt per source additionally means a single peer can only ever
1039/// consume one of these.
1040const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1041
1042/// Fresh-offer slots kept reachable by sources that hold none.
1043///
1044/// The property worth guaranteeing is that one peer cannot *starve* others, not
1045/// that any peer is held to a small quota. Expressing the bound as a reserve
1046/// rather than a quota is what keeps those two apart.
1047const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1048
1049/// Maximum fresh offers admitted from one source peer.
1050///
1051/// Without a per-source bound, one peer can hold every slot in the global pool
1052/// and every honest offer arriving in that window is refused — and because a
1053/// refusal is later read as absence by the sender's delayed possession check,
1054/// those refusals land as audit-severity trust penalties on the *refuser*.
1055/// That makes an unbounded global pool a targeted eviction primitive.
1056///
1057/// The bound is deliberately far looser than the other responder classes'
1058/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1059/// the opposite shape. Those are request/response: a requester needs only a
1060/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1061/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1062/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1063/// for request/response traffic therefore binds on completely legitimate
1064/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1065/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1066/// ceiling and none to the global pool.
1067///
1068/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1069/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1070/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1071// The cast is from a compile-time constant difference of two small literals
1072// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1073// relationship visible in the code rather than only in a test.
1074#[allow(clippy::cast_possible_truncation)]
1075const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1076    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1077
1078/// Maximum paid-list notifications served concurrently.
1079///
1080/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1081/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1082/// Two workers keep cross-peer progress without multiplying concurrent EVM
1083/// and DHT lookup pressure.
1084const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1085
1086/// Maximum paid-list notifications admitted across workers and their waiters.
1087///
1088/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1089/// is one-way: the protocol defines no response and the sender never retries,
1090/// so a refused notify is information permanently lost to this node until a
1091/// later verification cycle happens to re-derive the key's paid status from a
1092/// paid-list quorum. A tight admission bound therefore does not shed load, it
1093/// discards durable state — which is why the class's real protection is
1094/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1095/// is actually expensive, rather than this queue depth.
1096///
1097/// A client PUT fans one notify per key out to the whole paid close group, so
1098/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1099/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1100/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1101/// carry no chunk payload.
1102const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1103
1104/// Maximum admitted paid-list notifications from one source peer.
1105///
1106/// A quarter of the pool. One peer legitimately supplies a whole upload's
1107/// worth of notifies, so this must comfortably exceed a typical file's chunk
1108/// count in flight; it exists to stop a single source evicting every other
1109/// peer's durable paid-list evidence, not to ration ordinary traffic.
1110const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1111
1112/// Maximum fetch responses served concurrently.
1113///
1114/// Each successful response can upload a 4 MiB chunk. Matching
1115/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1116/// simultaneous chunk data, which avoids saturating typical home upload links.
1117const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1118
1119/// Maximum fetch requests admitted across workers and their bounded waiters.
1120///
1121/// Four worker waves absorb short bursts without retaining chunk bytes—the
1122/// request contains only a key—while the dequeue deadline sheds work before a
1123/// sustained flood can keep the node serving requests whose callers timed out.
1124const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1125
1126/// Maximum admitted fetch requests from one source peer.
1127///
1128/// Two requests let one peer pipeline useful reads while leaving at least one
1129/// of the three workers available to other peers under a single-source flood.
1130const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1131
1132/// Maximum verification batches served concurrently.
1133///
1134/// Point lookups are fast, but a batch can contain 8,192 of them. Two
1135/// workers isolate that synchronous work from message dispatch without turning
1136/// large batches into an I/O fan-out throughput contest.
1137const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1138
1139/// Maximum verification batches admitted across workers and bounded waiters.
1140///
1141/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1142/// deadline prevents queued batches from consuming lookup capacity after their
1143/// requesters have stopped waiting.
1144const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1145
1146/// Maximum admitted verification batches from one source peer.
1147///
1148/// Senders already aggregate a peer's keys into one batch. One outstanding
1149/// batch therefore preserves useful work while reserving the other worker and
1150/// the bounded queue for different peers.
1151const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1152
1153/// Maximum neighbor-sync requests served concurrently across source peers.
1154///
1155/// Building a response scans local keys and performs DHT lookups, so two
1156/// workers allow cross-peer progress without multiplying that expensive scan
1157/// into broad network and storage contention.
1158const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1159
1160/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1161///
1162/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1163/// payloads bounded; expired waiters are shed before any key scan begins.
1164const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1165
1166/// Maximum admitted neighbor-sync requests from one source peer.
1167///
1168/// Sync history must be updated before repair proofs for the same peer. A
1169/// single slot preserves that ordering while independent peers remain parallel.
1170const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1171
1172/// Match an inbound topic against the replication protocol ids, in both the bare
1173/// gossip form and the `/rr/<id>` request-response form.
1174///
1175/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1176/// was the RR form. The matched id is carried into the handler so it can enforce
1177/// that subtree messages only arrive on the subtree id.
1178fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1179    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1180        if topic == id {
1181            return Some((id, false));
1182        }
1183        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1184            if rest == id {
1185                return Some((id, true));
1186            }
1187        }
1188    }
1189    None
1190}
1191
1192/// Whether a decoded body belongs on the protocol id it arrived on:
1193/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1194/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1195///
1196/// The receive guard drops any mismatch (a cross-version or misrouted message);
1197/// sharing this one predicate between the guard and its regression test means a
1198/// change to the rule cannot pass the test unnoticed.
1199fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1200    protocol == response_protocol_for(body)
1201}
1202
1203/// The protocol id a body belongs on — the single source of truth for BOTH
1204/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1205/// response selector in `send_replication_response_checked`.
1206///
1207/// Sharing one function makes the subtree/core isolation symmetric.
1208fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1209    if body.is_subtree_audit() {
1210        SUBTREE_AUDIT_PROTOCOL_ID
1211    } else {
1212        REPLICATION_PROTOCOL_ID
1213    }
1214}
1215
1216fn fresh_offer_payment_context() -> VerificationContext {
1217    VerificationContext::FreshReplication
1218}
1219
1220fn paid_notify_payment_context() -> VerificationContext {
1221    VerificationContext::PaidListAdmission
1222}
1223
1224/// Boxed future type for in-flight fetch tasks.
1225type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1226
1227/// Fresh-offer keys currently being handled, each with the proofs still to try.
1228///
1229/// Concurrent duplicates are routine: a client PUT is confirmed by
1230/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1231/// commonly arrives from several senders at once. Collapsing them onto one
1232/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1233/// and an on-chain verification per copy.
1234///
1235/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1236/// refusing every later offer outright made the first arrival the only arrival:
1237/// if its proof failed, the record was lost even though a valid proof for the
1238/// same bytes was queued behind it, and the resulting absence was charged to
1239/// this node by the delayed possession check. So the entry holds the bytes once
1240/// and queues each sender's proof, and the handler works down that queue. A
1241/// later offer therefore costs a proof, not a payload — sound only because
1242/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1243/// every one of them before it is queued, which is what makes their bytes
1244/// provably identical.
1245///
1246/// Entries are exact keys rather than hash shards. A node only receives offers
1247/// for keys it is close to, so the accepted key set clusters tightly around its
1248/// own ID — any index derived from the key would land nearly every offer on one
1249/// shard and serialize unrelated keys behind each other. Exact keys keep them
1250/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1251/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1252///
1253/// The critical section is a map insert, pop, or remove and is never held across
1254/// an await, so this is a blocking mutex rather than an async one.
1255type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1256
1257/// One sender's unverified claim to have paid for a key already in flight.
1258///
1259/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1260/// content-address check ran before this attempt was queued.
1261struct FreshOfferAttempt {
1262    source: PeerId,
1263    proof_of_payment: Vec<u8>,
1264    request_id: u64,
1265    rr_message_id: Option<String>,
1266}
1267
1268/// Proofs still to try for one in-flight key, and who supplied them.
1269///
1270/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1271/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1272struct FreshOfferEntry {
1273    /// Untried proofs in arrival order. The handler holds the current one.
1274    pending: VecDeque<FreshOfferAttempt>,
1275    /// Sources already represented, so one peer cannot fill the queue alone.
1276    sources: HashSet<PeerId>,
1277    /// Proofs admitted over this entry's whole life, **never decremented**.
1278    ///
1279    /// The budget has to be spent by admissions rather than held by the queue.
1280    /// The handler pops a proof before verifying it, so gating on
1281    /// `pending.len()` would let a fresh source refill the slot that pop just
1282    /// freed, and a stream of distinct sources could then run unbounded
1283    /// sequential payment verifications while holding one of only four worker
1284    /// slots. Counting admissions makes the cap a lifetime budget instead.
1285    admitted: usize,
1286}
1287
1288/// How an arriving fresh offer joined the work already in flight for its key.
1289enum FreshOfferAdmission {
1290    /// Opened the entry. This offer's handler owns the key and drives every
1291    /// queued proof, including proofs that arrive later.
1292    Opened(Box<FreshOfferEntryGuard>),
1293    /// Merged into an entry another offer opened; its handler reaches this proof
1294    /// if the ones ahead of it fail.
1295    Joined,
1296    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1297    Full,
1298    /// This source already has a proof queued for this key.
1299    DuplicateSource,
1300}
1301
1302// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1303// `debug!`, which compiles to nothing without the feature.
1304#[cfg(feature = "logging")]
1305impl FreshOfferAdmission {
1306    /// Why the offer added nothing to the work already queued for its key.
1307    ///
1308    /// Local logging only — the wire reason stays uniform so a probing peer
1309    /// cannot tell a full queue from a repeat of its own proof.
1310    const fn surplus_reason(&self) -> &'static str {
1311        match self {
1312            Self::DuplicateSource => "this source already has a proof queued",
1313            Self::Full => "the key already holds its full complement of proofs",
1314            Self::Opened(_) | Self::Joined => "not surplus",
1315        }
1316    }
1317}
1318
1319/// RAII ownership of one in-flight fresh-offer key.
1320///
1321/// Clears the entry on drop, so an early return, an error, or a panic cannot
1322/// strand a key as permanently in flight. Also owns the single copy of the
1323/// offered bytes that every queued proof is tried against.
1324struct FreshOfferEntryGuard {
1325    in_flight: FreshOfferInFlight,
1326    key: XorName,
1327    /// The bytes every attempt for this key shares, held exactly once.
1328    data: Vec<u8>,
1329    /// Arrival of the offer that opened the entry.
1330    received_at: Instant,
1331    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1332    /// a *later* offer has since opened for the same key.
1333    holds_entry: bool,
1334}
1335
1336impl FreshOfferEntryGuard {
1337    /// Open an entry for this offer's key, or queue its proof behind the entry
1338    /// already open.
1339    ///
1340    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1341    /// on every other outcome they are dropped here rather than held for the
1342    /// lifetime of the entry.
1343    fn admit(
1344        in_flight: &FreshOfferInFlight,
1345        offer: protocol::FreshReplicationOffer,
1346        source: PeerId,
1347        request_id: u64,
1348        rr_message_id: Option<String>,
1349        received_at: Instant,
1350    ) -> FreshOfferAdmission {
1351        let key = offer.key;
1352        let attempt = FreshOfferAttempt {
1353            source,
1354            proof_of_payment: offer.proof_of_payment,
1355            request_id,
1356            rr_message_id,
1357        };
1358
1359        let mut in_flight_map = in_flight.lock();
1360        if let Some(entry) = in_flight_map.get_mut(&key) {
1361            if entry.sources.contains(&source) {
1362                return FreshOfferAdmission::DuplicateSource;
1363            }
1364            // Lifetime budget, not queue depth: a proof the handler has already
1365            // popped has spent its slot, not returned it.
1366            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1367                return FreshOfferAdmission::Full;
1368            }
1369            entry.admitted = entry.admitted.saturating_add(1);
1370            entry.sources.insert(source);
1371            entry.pending.push_back(attempt);
1372            return FreshOfferAdmission::Joined;
1373        }
1374
1375        let mut sources = HashSet::new();
1376        sources.insert(source);
1377        let mut pending = VecDeque::new();
1378        pending.push_back(attempt);
1379        in_flight_map.insert(
1380            key,
1381            FreshOfferEntry {
1382                pending,
1383                sources,
1384                admitted: 1,
1385            },
1386        );
1387        drop(in_flight_map);
1388        FreshOfferAdmission::Opened(Box::new(Self {
1389            in_flight: Arc::clone(in_flight),
1390            key,
1391            data: offer.data,
1392            received_at,
1393            holds_entry: true,
1394        }))
1395    }
1396
1397    /// The bytes every proof for this key is tried against.
1398    fn data(&self) -> &[u8] {
1399        &self.data
1400    }
1401
1402    /// When the first offer for this key arrived.
1403    fn received_at(&self) -> Instant {
1404        self.received_at
1405    }
1406
1407    /// Take the next untried proof, releasing the key when none remain.
1408    ///
1409    /// Popping and releasing happen under one lock so a proof arriving exactly
1410    /// as the queue empties is never silently discarded: it either lands in this
1411    /// entry and is returned here, or finds no entry and opens its own.
1412    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1413        let mut in_flight = self.in_flight.lock();
1414        let Some(entry) = in_flight.get_mut(&self.key) else {
1415            self.holds_entry = false;
1416            return None;
1417        };
1418        if let Some(attempt) = entry.pending.pop_front() {
1419            return Some(attempt);
1420        }
1421        in_flight.remove(&self.key);
1422        self.holds_entry = false;
1423        None
1424    }
1425
1426    /// Release the key and return the proofs that were never tried, so their
1427    /// senders can be told the outcome the key reached without them.
1428    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1429        let mut in_flight = self.in_flight.lock();
1430        self.holds_entry = false;
1431        in_flight
1432            .remove(&self.key)
1433            .map(|entry| entry.pending.into_iter().collect())
1434            .unwrap_or_default()
1435    }
1436}
1437
1438impl Drop for FreshOfferEntryGuard {
1439    fn drop(&mut self) {
1440        if self.holds_entry {
1441            self.in_flight.lock().remove(&self.key);
1442        }
1443    }
1444}
1445
1446/// Shared dependencies for one verification worker cycle.
1447struct VerificationCycleContext<'a> {
1448    p2p_node: &'a Arc<P2PNode>,
1449    paid_list: &'a Arc<PaidList>,
1450    storage: &'a Arc<ChunkStore>,
1451    queues: &'a Arc<RwLock<ReplicationQueues>>,
1452    config: &'a ReplicationConfig,
1453    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1454    is_bootstrapping: &'a Arc<RwLock<bool>>,
1455    bootstrap_complete_notify: &'a Arc<Notify>,
1456    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1457    /// peer's Present claim to Unresolved unless they're a credited
1458    /// holder of the key (i.e. they recently passed a commitment-bound
1459    /// audit on it under their currently-credited commitment hash).
1460    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1461    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1462    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1463}
1464
1465/// Fetch worker polling interval in milliseconds.
1466const FETCH_WORKER_POLL_MS: u64 = 100;
1467
1468/// Verification worker polling interval in milliseconds.
1469const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1470
1471/// Verification cycle duration that is worth surfacing at info level.
1472const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1473
1474/// Standard trust event weight for per-operation success/failure signals.
1475///
1476/// Used for individual replication fetch outcomes, integrity check failures,
1477/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1478/// is reserved for confirmed audit failures.
1479const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1480/// Bound trust updates from one verification cycle. A malicious peer can
1481/// advertise thousands of bad singleton keys at once; a few independent
1482/// contradictions are enough for the trust engine without flooding it.
1483const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1484
1485/// Bootstrap drain check interval in seconds.
1486const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1487
1488/// Grace period `shutdown()` waits for each long-lived background task to
1489/// observe the cancellation token and terminate before aborting it.
1490///
1491/// Detached tasks are drained without a timeout because storage-capable work
1492/// may be awaiting a `spawn_blocking` storage operation, which continues running
1493/// if its async waiter is dropped.
1494const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1495
1496/// How often the responder rebuilds + rotates its storage commitment.
1497///
1498/// Each rebuild scans the store to compute leaf hashes; for ~10k keys this is
1499/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1500/// rotation-anchored: the responder stays answerable for the current
1501/// commitment plus every root it recently gossiped that is still in-window
1502/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1503/// its last emission (see `commitment_state`). So the rotation cadence does
1504/// not by itself bound answerability — a gossiped commitment stays
1505/// answerable across rotations until its gossip TTL lapses.
1506///
1507/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1508/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1509/// comfortably exceeds the gap between our rotation and the next gossip
1510/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1511/// Idle audit-skip pattern from being the common case.
1512///
1513/// Why not faster: the v12 pin is bound to a specific point-in-time
1514/// commitment, so rotation isn't security-critical for pin freshness —
1515/// only for keeping the committed key set current as the responder
1516/// writes new keys. 1 hour is plenty for that, and slow enough that
1517/// honest auditors mostly hit `current` or `previous` rather than the
1518/// "rotated past" case.
1519const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1520
1521/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1522/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1523/// durable well before it could matter to a restart, while the write-on-change
1524/// guard keeps idle nodes from needless disk writes.
1525const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1526
1527/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1528/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1529/// default that keeps log volume negligible.
1530const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1531
1532/// Cadence of the read-only bootstrap state snapshot used to separate drain
1533/// debt from cache and broader connectivity failures in fleet logs.
1534#[cfg(feature = "logging")]
1535const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1536
1537/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1538/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1539/// for first audit only if its SIGNED `quote_ts` lands in
1540/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1541/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1542/// badly-skewed or replayed quote) and one too old (the responder may have aged
1543/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1544/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1545/// within this margin); a legit first audit fires moments after payment
1546/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1547/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1548/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1549const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_mins(30);
1550
1551/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1552/// inside the answerability window relative to `now`, so first-auditing it cannot
1553/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1554/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1555/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1556/// All comparisons use `duration_since` (no `Duration` overflow).
1557fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1558    let too_future = quote_ts
1559        .duration_since(now)
1560        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1561    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1562    let too_old = now
1563        .duration_since(quote_ts)
1564        .is_ok_and(|age| age >= audit_cutoff);
1565    !(too_future || too_old)
1566}
1567
1568/// Minimum interval between commitment signature verifications for a
1569/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1570///
1571/// A sybil that bypasses the routing-table gate (e.g. by transient
1572/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1573/// per gossip message. This rate limit caps the verify-per-peer rate
1574/// at 1/min, which is comfortably above the legitimate gossip cadence
1575/// (the 10-20 min neighbor-sync round on each peer).
1576const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_mins(1);
1577
1578/// Hard cap on the size of `last_commitment_by_peer`.
1579///
1580/// Bounds the per-process memory cost of the auditor's per-peer
1581/// commitment cache. Each entry holds a `StorageCommitment`
1582/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1583/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1584/// realistic close-group neighborhood. When the cap is hit, one
1585/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1586/// order is unspecified; we do not track insertion order). The
1587/// `PeerRemoved` handler proactively drops entries as the DHT
1588/// detects departures, and `ingest_peer_commitment` only admits
1589/// commitments from peers currently in the routing table — together
1590/// the cap is the third line of defence against sybil/churn flooding.
1591const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1592
1593/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1594/// sized to the launch budget instead of the commitment cache.
1595///
1596/// The token bucket can launch at most one audit per
1597/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1598/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1599/// launchable for at most the effective answerability window
1600/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1601/// occupancy beyond `window / interval + burst` is work that cannot launch
1602/// before it expires, so admitting it only builds an aging backlog whose
1603/// telemetry measures the backlog instead of schedulable work.
1604///
1605/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1606/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1607/// rolling sample in which no arrival order lets an attacker deterministically
1608/// flush a chosen target; a fresh pin always enters the sample with an
1609/// unpredictable chance of near-immediate audit, whereas refusing at the door
1610/// would let a sustained payment flood guarantee that every later pin is never
1611/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1612/// ADR-0004 Amendment 4 for the eviction-cost math.
1613///
1614/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1615/// is usable only if the quote stays answerable through `a` plus the maximum
1616/// launch jitter and send slack, so the last usable refill is the largest
1617/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1618/// simulates the shipped predicate instant-by-instant and must agree.
1619#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1620const FIRST_AUDIT_PENDING_CAP: usize = {
1621    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1622        .as_secs()
1623        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1624        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1625        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1626    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1627    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1628    // if the launch interval is ever zeroed: a zero interval makes the budget
1629    // (and this cap) meaningless.
1630    let refills =
1631        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1632    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1633};
1634
1635// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1636// strictly tighter than the commitment-cache bound it replaced.
1637const _: () = {
1638    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1639    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1640};
1641
1642/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1643/// long-running bootstrap node cannot have the set grow without limit
1644/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1645/// the set comfortably outlives normal LRU churn but still caps the
1646/// blast radius of identity-rotation attacks. Once full we refuse new
1647/// inserts (no eviction) — keeps the historic set stable; new v12
1648/// peers above the cap are treated as legacy on rejoin, which matches
1649/// the behaviour before this set existed, not a security regression.
1650const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1651
1652// ---------------------------------------------------------------------------
1653// ReplicationEngine
1654// ---------------------------------------------------------------------------
1655
1656/// The replication engine manages all replication background tasks and state.
1657pub struct ReplicationEngine {
1658    /// Replication configuration (shared across spawned tasks).
1659    config: Arc<ReplicationConfig>,
1660    /// P2P networking node.
1661    p2p_node: Arc<P2PNode>,
1662    /// Local chunk storage.
1663    storage: Arc<ChunkStore>,
1664    /// Persistent paid-for-list.
1665    paid_list: Arc<PaidList>,
1666    /// Payment verifier for `PoP` validation.
1667    payment_verifier: Arc<PaymentVerifier>,
1668    /// Replication pipeline queues.
1669    queues: Arc<RwLock<ReplicationQueues>>,
1670    /// Neighbor sync cycle state.
1671    sync_state: Arc<RwLock<NeighborSyncState>>,
1672    /// Per-peer sync history (for `RepairOpportunity`).
1673    ///
1674    /// This map grows with peer churn and is intentionally unbounded: entries
1675    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1676    /// naturally bounded by the routing table's k-bucket capacity.
1677    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1678    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1679    ///
1680    /// Records when each peer was last audited so a burst of gossiped
1681    /// commitment changes cannot spawn back-to-back audits of the same peer.
1682    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1683    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1684    /// Gossip-private lottery attempt window (one roll per peer per window,
1685    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1686    /// ticket never stamps the shared map and thus never defers a monetized
1687    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1688    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1689    /// Completed local neighbor-sync cycle epoch for proof maturity.
1690    sync_cycle_epoch: Arc<RwLock<u64>>,
1691    /// Per-key repair proof tracking for audit eligibility.
1692    repair_proofs: Arc<RwLock<RepairProofs>>,
1693    /// Bootstrap state tracking.
1694    bootstrap_state: Arc<RwLock<BootstrapState>>,
1695    /// Whether this node is currently bootstrapping.
1696    is_bootstrapping: Arc<RwLock<bool>>,
1697    /// Trigger for early neighbor sync (signalled on topology changes).
1698    sync_trigger: Arc<Notify>,
1699    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1700    bootstrap_complete_notify: Arc<Notify>,
1701    /// Node identity (for signing storage commitments).
1702    ///
1703    /// Phase 3 of the v12 storage-bound audit design. The responder
1704    /// uses this to sign its periodically-built `StorageCommitment`.
1705    identity: Arc<NodeIdentity>,
1706    /// Responder-side commitment state (two-slot atomic rotation).
1707    ///
1708    /// Periodically rebuilt from the live key set; gossiped on
1709    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1710    /// commitment-bound audit handler.
1711    commitment_state: Arc<ResponderCommitmentState>,
1712    /// Path to the persisted responder retention snapshot
1713    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1714    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1715    /// removing audit grace safe (an unanswerable in-window pin is then provable
1716    /// misbehaviour, not an honest crash-restart).
1717    retention_path: PathBuf,
1718    /// Auditor-side per-peer commitment record (last known commitment +
1719    /// sticky `commitment_capable` flag).
1720    ///
1721    /// Populated whenever an inbound gossip carries a verified
1722    /// commitment from the sender. Used by `audit_tick` to snapshot
1723    /// `expected_commitment_hash` into outbound challenges, and by
1724    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1725    /// proof should be honoured. The sticky `commitment_capable` flag
1726    /// flips true on first successful ingest and never reverts (§2
1727    /// step 5).
1728    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1729    /// Sticky set of peer IDs we have EVER seen carrying a v12
1730    /// commitment, independent of whether their commitment bytes are
1731    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1732    /// closure consults this set to keep treating churned-out
1733    /// previously-v12 peers as v12-capable (rather than degrading them
1734    /// to "legacy" credit-unconditionally) when they re-appear on the
1735    /// network before their next gossip arrives. Bounded growth: even
1736    /// at one million peers seen over the node's lifetime, the set is
1737    /// 32 MB.
1738    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1739    /// Auditor-side holder-eligibility cache (v12 §6).
1740    ///
1741    /// Recorded on successful commitment-bound audit; read by future
1742    /// quorum / paid-list eligibility checks (phase-3 stretch).
1743    recent_provers: Arc<RwLock<RecentProvers>>,
1744    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1745    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1746    /// failure) so a peer we've never successfully verified can't burn
1747    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1748    /// Lives separately from `last_commitment_by_peer` because that
1749    /// map's records only exist after a successful verify.
1750    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1751    /// Limits concurrent outbound replication sends to prevent bandwidth
1752    /// saturation on home broadband connections.
1753    send_semaphore: Arc<Semaphore>,
1754    /// Bounds how many encoded fresh offers can wait behind `send_semaphore`;
1755    /// see [`MAX_PENDING_FRESH_OFFERS`].
1756    pending_offer_semaphore: Arc<Semaphore>,
1757    /// Fresh offers encoded and handed to their per-peer sends.
1758    fresh_offers_dispatched: Arc<AtomicU64>,
1759    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1760    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1761    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1762    /// message loop so disk
1763    /// reads don't block replication; the semaphore restores a global
1764    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1765    /// / multi-MiB byte serves.
1766    audit_responder_semaphore: Arc<Semaphore>,
1767    /// Per-source in-flight audit-responder counts, capped at
1768    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1769    /// flood-fair: one peer spamming challenges could occupy every slot and
1770    /// starve honest auditors, whose dropped challenges then convert to
1771    /// audit timeouts against HONEST peers (codex-r2 A). This
1772    /// per-peer cap guarantees no single source can hold more than its share,
1773    /// so a flood self-throttles without denying service to everyone else.
1774    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1775    /// Windowed per-origin capacity and processing-time telemetry for every
1776    /// request sharing the audit responder pool.
1777    audit_responder_metrics: Arc<AuditResponderMetrics>,
1778    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1779    ///
1780    /// Responsible-chunk audits, prune confirmations, and possession checks
1781    /// all use this before sending so local bursts wait instead of breaching
1782    /// the responder's deployed per-source admission cap.
1783    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1784    /// Worker permits for bandwidth-bound fetch responses.
1785    fetch_responder_worker_semaphore: Arc<Semaphore>,
1786    /// Admission permits bounding fetch workers and queued waiters together.
1787    fetch_responder_admission_semaphore: Arc<Semaphore>,
1788    /// Per-source fetch responder counts for flood-fair admission.
1789    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1790    /// Worker permits for lookup-heavy verification batches.
1791    verification_responder_worker_semaphore: Arc<Semaphore>,
1792    /// Admission permits bounding verification workers and queued waiters.
1793    verification_responder_admission_semaphore: Arc<Semaphore>,
1794    /// Per-source verification responder counts for flood-fair admission.
1795    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1796    /// Worker permits for expensive inbound neighbor-sync requests.
1797    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1798    /// Admission permits bounding sync workers and queued waiters together.
1799    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1800    /// Per-source sync responder counts; capped at one to preserve ordering.
1801    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1802    /// Bounded worker permits for expensive fresh-offer handling.
1803    fresh_offer_worker_semaphore: Arc<Semaphore>,
1804    /// Admission permits bounding offers running on a worker or queued for one.
1805    fresh_offer_admission_semaphore: Arc<Semaphore>,
1806    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1807    /// and turn honest senders' refusals into trust penalties on this node.
1808    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1809    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1810    /// duplicates collapse onto one verification and one write.
1811    fresh_offer_in_flight: FreshOfferInFlight,
1812    /// Bounded worker permits for paid-list notification proof verification.
1813    paid_notify_worker_semaphore: Arc<Semaphore>,
1814    /// Admission permits bounding notifies on a worker or queued for one.
1815    paid_notify_admission_semaphore: Arc<Semaphore>,
1816    /// Per-source paid-notify counts for flood-fair admission.
1817    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1818    /// Resource controls for the HEAVY subtree-audit round 1: its own
1819    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1820    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1821    /// sessions binding a slice challenge to a matching round 1.
1822    subtree_round1: SubtreeRound1Limiter,
1823    /// Receiver for fresh-write events from the chunk PUT handler.
1824    ///
1825    /// When present, `start()` spawns the fresh-write drainer, which records
1826    /// paid-list evidence for each event immediately and forwards it to the
1827    /// offer dispatcher.
1828    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1829    /// Pointer replication (ADR-0016), when this node stores pointers.
1830    pointers: Option<Arc<pointer::PointerReplication>>,
1831    /// Receiver for fresh pointer writes, taken by `start()`.
1832    pointer_fresh_rx: Option<mpsc::UnboundedReceiver<pointer::PointerFreshWrite>>,
1833    /// Sender for delayed possession-check events (ADR-0003). Sending a write's
1834    /// fresh offers (`fresh::send_fresh_offers`) pushes its responsible
1835    /// close-group peers here; the possession-check scheduler drains the paired
1836    /// receiver.
1837    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1838    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1839    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1840    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1841    /// for a deterministic first audit. The matching receiver is drained by
1842    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1843    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1844    /// like launches; a dropped nomination is penalty-free — the peer's
1845    /// gossiped commitments stay lottery-covered and its next settled payment
1846    /// re-nominates the paid pin.
1847    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1848    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1849    /// `start_first_audit_drainer`.
1850    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1851    /// Counters shared with the first-audit drainer task, so the scheduler's
1852    /// decisions (queued / launched / self-target skipped / outcome) stay
1853    /// observable from the engine after the drainer takes the receiver.
1854    first_audit_observability: Arc<FirstAuditObservability>,
1855    /// Shutdown token.
1856    shutdown: CancellationToken,
1857    /// Background task handles.
1858    task_handles: Vec<JoinHandle<()>>,
1859    /// Tracks detached, short-lived work spawned by background producers.
1860    ///
1861    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1862    /// tasks, and delayed possession checks may retain storage or P2P state
1863    /// after their producer exits, so shutdown drains them before those
1864    /// resources may be reopened.
1865    detached_task_tracker: TaskTracker,
1866}
1867
1868impl ReplicationEngine {
1869    /// Create a new replication engine.
1870    ///
1871    /// # Errors
1872    ///
1873    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1874    /// or if the configuration fails validation.
1875    #[allow(clippy::too_many_arguments)]
1876    pub async fn new(
1877        config: ReplicationConfig,
1878        p2p_node: Arc<P2PNode>,
1879        storage: Arc<ChunkStore>,
1880        payment_verifier: Arc<PaymentVerifier>,
1881        identity: Arc<NodeIdentity>,
1882        root_dir: &Path,
1883        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1884        shutdown: CancellationToken,
1885    ) -> Result<Self> {
1886        config.validate().map_err(Error::Config)?;
1887
1888        let paid_list = Arc::new(
1889            PaidList::new(root_dir)
1890                .await
1891                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1892        );
1893
1894        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1895        let config = Arc::new(config);
1896        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1897
1898        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1899        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1900        // now capacity-limited — ingress queue here, pending set (LRU), and
1901        // launch rate (token bucket).
1902        let (monetized_pin_tx, monetized_pin_rx) =
1903            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1904
1905        let engine = Self {
1906            config: Arc::clone(&config),
1907            p2p_node,
1908            storage,
1909            paid_list,
1910            payment_verifier,
1911            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1912            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1913            sync_history: Arc::new(RwLock::new(HashMap::new())),
1914            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1915            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1916            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1917            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1918            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1919            is_bootstrapping: Arc::new(RwLock::new(true)),
1920            sync_trigger: Arc::new(Notify::new()),
1921            bootstrap_complete_notify: Arc::new(Notify::new()),
1922            identity,
1923            commitment_state: Arc::new(ResponderCommitmentState::new()),
1924            retention_path: root_dir.join("commitment_retention.bin"),
1925            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1926            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1927            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1928            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1929            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1930            pending_offer_semaphore: Arc::new(Semaphore::new(MAX_PENDING_FRESH_OFFERS)),
1931            fresh_offers_dispatched: Arc::new(AtomicU64::new(0)),
1932            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1933            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1934            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1935            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1936            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1937                FETCH_RESPONDER_WORKER_LIMIT,
1938            )),
1939            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1940                FETCH_RESPONDER_MAX_OUTSTANDING,
1941            )),
1942            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1943            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1944                VERIFICATION_RESPONDER_WORKER_LIMIT,
1945            )),
1946            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1947                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1948            )),
1949            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1950            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1951                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1952            )),
1953            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1954                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1955            )),
1956            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1957            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1958            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1959            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1960            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1961            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1962            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1963            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1964            subtree_round1: SubtreeRound1Limiter::new(
1965                config.subtree_round1_responder_cooldown,
1966                config.subtree_round1_max_concurrent,
1967            ),
1968            fresh_write_rx: Some(fresh_write_rx),
1969            pointers: None,
1970            pointer_fresh_rx: None,
1971            possession_check_tx,
1972            possession_check_rx: Some(possession_check_rx),
1973            monetized_pin_tx,
1974            monetized_pin_rx: Some(monetized_pin_rx),
1975            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1976            shutdown,
1977            task_handles: Vec::new(),
1978            detached_task_tracker: TaskTracker::new(),
1979        };
1980        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1981        // spawns, so an honest restarted node is answerable for its pre-restart
1982        // pins from the first audit it serves, and the persist loop never races
1983        // an empty snapshot over the good on-disk file.
1984        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1985        Ok(engine)
1986    }
1987
1988    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1989    /// (commitments that backed a payment) for a first audit. Cloneable; the
1990    /// engine drains the matching receiver. Bounded: senders must `try_send`
1991    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1992    #[must_use]
1993    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1994        self.monetized_pin_tx.clone()
1995    }
1996
1997    /// Get a reference to the `PaidList`.
1998    #[must_use]
1999    pub fn paid_list(&self) -> &Arc<PaidList> {
2000        &self.paid_list
2001    }
2002
2003    /// Get a reference to the responder's commitment state. Used by audit
2004    /// handlers to look up commitments by hash; used by the rotation tick
2005    /// to install fresh ones.
2006    #[must_use]
2007    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
2008        &self.commitment_state
2009    }
2010
2011    /// Get a reference to the auditor's last-commitment-by-peer table.
2012    #[must_use]
2013    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2014        &self.last_commitment_by_peer
2015    }
2016
2017    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2018    /// will be read by quorum / paid-list eligibility checks.
2019    #[must_use]
2020    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2021        &self.recent_provers
2022    }
2023
2024    /// Test-only: rebuild + rotate this node's storage commitment now over its
2025    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2026    /// just stored without waiting for the rotation cadence.
2027    ///
2028    /// # Errors
2029    ///
2030    /// Propagates any error from reading the local key set or building/signing
2031    /// the commitment.
2032    #[cfg(any(test, feature = "test-utils"))]
2033    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2034        rebuild_and_rotate_commitment(
2035            &self.storage,
2036            self.pointers.as_ref().map(|p| p.store()),
2037            &self.identity,
2038            &self.commitment_state,
2039            &self.p2p_node,
2040            &self.config,
2041        )
2042        .await
2043    }
2044
2045    /// Test-only: directly seed this node's cached commitment for `peer`,
2046    /// simulating "we received `peer`'s gossiped commitment" without depending
2047    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2048    /// peer's commitment deterministically.
2049    #[cfg(any(feature = "test-utils", test))]
2050    pub async fn inject_peer_commitment_for_test(
2051        &self,
2052        peer: &PeerId,
2053        commitment: StorageCommitment,
2054    ) {
2055        let now = Instant::now();
2056        self.last_commitment_by_peer
2057            .write()
2058            .await
2059            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2060        self.ever_capable_peers.write().await.insert(*peer);
2061    }
2062
2063    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2064    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2065    /// window and clears any shared cooldown stamped by an earlier gossip
2066    /// launch. The locks follow the production gossip-audit lock order.
2067    #[cfg(any(test, feature = "test-utils"))]
2068    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2069        let now = Instant::now();
2070        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2071        let mut launched = self.audit_on_gossip_cooldown.write().await;
2072        lottery_attempts.insert(*peer, now);
2073        launched.remove(peer);
2074    }
2075
2076    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2077    /// commitment this node has cached for it (from gossip), over the live wire.
2078    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2079    /// in a real two-node setting without waiting for the gossip cadence.
2080    ///
2081    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2082    /// peer yet (gossip hasn't reached us). Gated to test builds.
2083    #[cfg(any(test, feature = "test-utils"))]
2084    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2085        let target = {
2086            let map = self.last_commitment_by_peer.read().await;
2087            map.get(peer)
2088                .and_then(PeerCommitmentRecord::last_commitment)
2089                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2090        };
2091        let Some((pin, key_count)) = target else {
2092            return audit::AuditTickResult::Idle;
2093        };
2094        let credit = storage_commitment_audit::AuditCredit {
2095            recent_provers: &self.recent_provers,
2096        };
2097        storage_commitment_audit::run_subtree_audit(
2098            &self.p2p_node,
2099            &self.config,
2100            peer,
2101            pin,
2102            key_count,
2103            Some(&credit),
2104        )
2105        .await
2106    }
2107
2108    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2109    /// tests assert what the live drainer decided for an injected
2110    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2111    #[cfg(any(test, feature = "test-utils"))]
2112    #[must_use]
2113    pub fn first_audit_stats(&self) -> FirstAuditStats {
2114        let o = &self.first_audit_observability;
2115        FirstAuditStats {
2116            received: o.received.load(Ordering::Relaxed),
2117            queued: o.queued.load(Ordering::Relaxed),
2118            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2119            launched: o.launched.load(Ordering::Relaxed),
2120            passed: o.passed.load(Ordering::Relaxed),
2121            timed_out: o.timed_out.load(Ordering::Relaxed),
2122            failed: o.failed.load(Ordering::Relaxed),
2123        }
2124    }
2125
2126    /// Test-only: run the possession check immediately for `key` against
2127    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2128    ///
2129    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2130    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2131    /// deterministically without waiting for the scheduled check.
2132    #[cfg(any(test, feature = "test-utils"))]
2133    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2134        possession::run_possession_check(
2135            key,
2136            peers,
2137            &self.p2p_node,
2138            &self.storage,
2139            &self.config,
2140            &self.sync_state,
2141            &self.audit_challenge_coordinator,
2142            &self.shutdown,
2143        )
2144        .await;
2145    }
2146
2147    /// Test-only: place `key` directly into the fetch queue as though a
2148    /// verification cycle had just promoted it, with `sources` as its
2149    /// verified holders. Returns whether the key was enqueued.
2150    ///
2151    /// Bypasses admission, verification, and the promotion-time
2152    /// responsibility pre-filter, modelling a promotion decision that has
2153    /// since gone stale (topology churn between promotion and download).
2154    /// The only guard left standing is the per-attempt recheck inside
2155    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2156    /// exercise.
2157    ///
2158    /// A replica hint for `key` that reached pending verification first is
2159    /// dropped, so the key enters the fetch queue as it would have without
2160    /// it. Callers host the chunk on a holder before calling this, which makes
2161    /// it advertisable, and a change to the holder's closest peers starts a
2162    /// neighbour-sync round at once. Left in place, the hint's entry made
2163    /// `enqueue_fetch` refuse the key, and with one holder and no paid-list
2164    /// entry it does not reach a quorum, so the key was not fetched that way
2165    /// either. A key already in the fetch queue or in flight, or a full fetch
2166    /// queue, still returns `false`.
2167    #[cfg(any(test, feature = "test-utils"))]
2168    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2169        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2170        let mut queues = self.queues.write().await;
2171        queues.remove_pending(&key);
2172        queues.enqueue_fetch(key, distance, sources)
2173    }
2174
2175    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2176    /// (pending verification, fetch queue, or in-flight fetch).
2177    #[cfg(any(test, feature = "test-utils"))]
2178    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2179        self.queues.read().await.contains_key(key)
2180    }
2181
2182    /// Test-only: whether `key` is in the fetch queue or in flight, which is
2183    /// where a candidate placed by [`Self::enqueue_fetch_for_test`] stays
2184    /// until it resolves.
2185    ///
2186    /// Such a candidate carries no verification retry metadata, so it is never
2187    /// requeued for verification: once it leaves these two stages it is done.
2188    /// Pending verification is left out on purpose. The chunk the test hosted
2189    /// stays advertisable, so a replica hint can put the key there after the
2190    /// candidate resolved, and counting that entry would hold a test's wait
2191    /// loop until its deadline.
2192    #[cfg(any(test, feature = "test-utils"))]
2193    pub async fn fetch_queued_or_in_flight_for_test(&self, key: &XorName) -> bool {
2194        self.queues.read().await.fetch_queued_or_in_flight(key)
2195    }
2196
2197    /// Test-only: place `key` into pending verification as though `hinter` had
2198    /// just advertised it with a replica hint. Returns whether it was admitted.
2199    ///
2200    /// Enters the pipeline one stage earlier than
2201    /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2202    /// decides about the key is observable.
2203    #[cfg(any(test, feature = "test-utils"))]
2204    pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2205        let now = Instant::now();
2206        let entry = VerificationEntry {
2207            state: VerificationState::PendingVerify,
2208            verified_sources: Vec::new(),
2209            tried_sources: HashSet::new(),
2210            created_at: now,
2211            next_verify_at: now,
2212            hint_sources: HashSet::from([hinter]),
2213            replica_hint_sources: HashSet::from([hinter]),
2214            unresolved_retries: 0,
2215            no_holder_reported: false,
2216        };
2217        self.queues
2218            .write()
2219            .await
2220            .add_pending_verify(key, entry)
2221            .admitted()
2222    }
2223
2224    /// Test-only: how far ahead `key`'s next verification round is scheduled,
2225    /// or `None` when the key is not pending verification.
2226    #[cfg(any(test, feature = "test-utils"))]
2227    pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2228        self.queues.read().await.get_pending(key).map(|entry| {
2229            entry
2230                .next_verify_at
2231                .saturating_duration_since(Instant::now())
2232        })
2233    }
2234
2235    /// Replicate pointers too (ADR-0016): the records in `store`, and the
2236    /// fresh writes the pointer PUT handler sends on `fresh_writes`.
2237    ///
2238    /// The PUT handler is not wired to ask this engine anything before it
2239    /// takes a final state (ADR-0018); [`Self::with_pointer_service`] wires
2240    /// both.
2241    ///
2242    /// Call before [`Self::start`].
2243    pub fn with_pointers(
2244        &mut self,
2245        store: PointerStore,
2246        fresh_writes: mpsc::UnboundedReceiver<pointer::PointerFreshWrite>,
2247    ) {
2248        self.pointers = Some(Arc::new(pointer::PointerReplication::new(
2249            store,
2250            Arc::clone(&self.storage),
2251            Arc::clone(&self.p2p_node),
2252            Arc::clone(&self.payment_verifier),
2253            Arc::clone(&self.config),
2254            Arc::clone(&self.is_bootstrapping),
2255            Arc::clone(&self.send_semaphore),
2256            self.shutdown.clone(),
2257            self.detached_task_tracker.clone(),
2258        )));
2259        self.pointer_fresh_rx = Some(fresh_writes);
2260    }
2261
2262    /// Replicate the pointers `service` stores (ADR-0016), and wire the
2263    /// service to this engine both ways: it hands each newly stored paid
2264    /// state here to be offered on, and asks here before it takes a final
2265    /// state (ADR-0018).
2266    ///
2267    /// Call before [`Self::start`].
2268    pub fn with_pointer_service(&mut self, service: &PointerService) {
2269        let (writes, fresh_writes) = mpsc::unbounded_channel();
2270        service.attach_fresh_writes(writes);
2271        self.with_pointers(service.store().clone(), fresh_writes);
2272        if let Some(replication) = &self.pointers {
2273            let witness: Arc<dyn FinalStateWitness> = replication.clone();
2274            service.attach_final_state_witness(witness);
2275        }
2276    }
2277
2278    /// The pointer replication, when enabled. Tests use it to drive rounds.
2279    #[cfg(any(test, feature = "test-utils"))]
2280    #[must_use]
2281    pub fn pointer_replication(&self) -> Option<&Arc<pointer::PointerReplication>> {
2282        self.pointers.as_ref()
2283    }
2284
2285    /// Test-only: pending-offer permits not currently held by an encoded
2286    /// fresh offer. Equals [`MAX_PENDING_FRESH_OFFERS`] when no fresh
2287    /// replication is in flight, which is how tests prove a burst of writes
2288    /// drained without leaking a permit.
2289    #[cfg(any(test, feature = "test-utils"))]
2290    #[must_use]
2291    pub fn pending_offer_permits_available(&self) -> usize {
2292        self.pending_offer_semaphore.available_permits()
2293    }
2294
2295    /// Test-only: fresh offers encoded and handed to their per-peer sends
2296    /// since the engine was created. A write skipped because its chunk is gone
2297    /// is not counted.
2298    #[cfg(any(test, feature = "test-utils"))]
2299    #[must_use]
2300    pub fn fresh_offers_dispatched(&self) -> u64 {
2301        self.fresh_offers_dispatched.load(Ordering::Relaxed)
2302    }
2303
2304    /// Test-only: take every outbound replication send permit. Until the
2305    /// returned permit is dropped, encoded fresh offers wait behind the send
2306    /// stage, so a test can fill the pending-offer budget deterministically.
2307    /// The send semaphore is never closed, so this returns `Some`.
2308    #[cfg(any(test, feature = "test-utils"))]
2309    pub async fn hold_replication_sends(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
2310        let all = u32::try_from(MAX_CONCURRENT_REPLICATION_SENDS).ok()?;
2311        Arc::clone(&self.send_semaphore)
2312            .acquire_many_owned(all)
2313            .await
2314            .ok()
2315    }
2316
2317    /// Start all background tasks.
2318    ///
2319    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2320    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2321    /// missed by the bootstrap-sync gate.
2322    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2323        if !self.task_handles.is_empty() {
2324            error!("ReplicationEngine::start() called while already running — ignoring");
2325            return;
2326        }
2327        info!("Starting replication engine");
2328
2329        self.start_message_handler();
2330        // Takes out of service the rotted chunks that round-1 proofs report.
2331        self.start_corrupt_recheck_worker();
2332        self.start_neighbor_sync_loop();
2333        self.start_self_lookup_loop();
2334        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2335        // chunks they SHOULD store (responsibility + prior hint).
2336        self.start_audit_loop();
2337        // Audit #1 (storage-commitment) is gossip-triggered in the message
2338        // handler when a peer's commitment is ingested, not on a periodic tick.
2339        self.start_commitment_rotation_loop();
2340        self.start_retention_persist_loop();
2341        self.start_fetch_worker();
2342        self.start_verification_worker();
2343        self.start_bootstrap_sync(dht_events);
2344        self.start_fresh_replication();
2345        self.start_possession_check_scheduler();
2346        if let Some(pointers) = &self.pointers {
2347            self.task_handles.push(pointers.start_verification_loop());
2348            if let Some(writes) = self.pointer_fresh_rx.take() {
2349                self.task_handles.push(pointers.start_fresh_drainer(writes));
2350            }
2351        }
2352        // ADR-0004: deterministic first audit of commitments that backed a
2353        // payment (surfaced by the verifier cross-check).
2354        self.start_first_audit_drainer();
2355        // V2-623: periodic cumulative per-variant traffic accounting.
2356        self.start_traffic_summary_loop();
2357        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2358        #[cfg(feature = "logging")]
2359        self.start_bootstrap_state_snapshot_loop();
2360        #[cfg(feature = "logging")]
2361        self.start_audit_responder_summary_loop();
2362
2363        info!(
2364            "Replication engine started with {} background tasks",
2365            self.task_handles.len()
2366        );
2367    }
2368
2369    /// Returns `true` if the node is still in the replication bootstrap phase.
2370    ///
2371    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2372    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2373    pub async fn is_bootstrapping(&self) -> bool {
2374        *self.is_bootstrapping.read().await
2375    }
2376
2377    /// Wait until the replication bootstrap phase completes.
2378    ///
2379    /// Returns immediately if bootstrap has already completed. Useful for
2380    /// readiness probes, health checks, and test harnesses that need the
2381    /// node to be fully operational before proceeding.
2382    ///
2383    /// Returns `true` if bootstrap completed within the timeout, `false`
2384    /// if the timeout elapsed first.
2385    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2386        // Register the notification future *before* checking the flag so that
2387        // a transition between the read and the await is not missed.
2388        let notified = self.bootstrap_complete_notify.notified();
2389        tokio::pin!(notified);
2390        notified.as_mut().enable();
2391
2392        if !*self.is_bootstrapping.read().await {
2393            return true;
2394        }
2395
2396        tokio::time::timeout(timeout, notified).await.is_ok()
2397    }
2398
2399    /// Cancel all background tasks and wait for them to terminate.
2400    ///
2401    /// This must be awaited before dropping the engine when the caller needs
2402    /// the `Arc<ChunkStore>` references held by background tasks to be
2403    /// released (e.g. before reopening the same store).
2404    ///
2405    /// When this returns, no engine-spawned task still holds
2406    /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no blocking storage operation
2407    /// (read or write, against either the chunk store or the paid-list LMDB
2408    /// environment) is still running.  Engine tasks race their work against
2409    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2410    /// operation running detached, so this method additionally waits
2411    /// for both storage layers to go quiescent before returning.
2412    pub async fn shutdown(&mut self) {
2413        self.shutdown.cancel();
2414        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2415            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2416                Ok(Ok(())) => {}
2417                Ok(Err(e)) if e.is_cancelled() => {}
2418                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2419                Err(_) => {
2420                    warn!(
2421                        "Replication task {i} did not stop within {}s, aborting",
2422                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2423                    );
2424                    handle.abort();
2425                    // `abort` only requests cancellation. Await the handle so
2426                    // synchronous sections finish and the task drops every
2427                    // storage/P2P clone before we claim producer quiescence.
2428                    match handle.await {
2429                        Ok(()) => {}
2430                        Err(e) if e.is_cancelled() => {}
2431                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2432                    }
2433                }
2434            }
2435        }
2436
2437        // Close the responder worker pools. Detached tasks still queued for a
2438        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2439        // rather than waiting for a slot that will never free up — without
2440        // this, work admitted just before shutdown would queue behind the last
2441        // in-flight batch and hold the drain below open for its full duration.
2442        self.fresh_offer_worker_semaphore.close();
2443        self.paid_notify_worker_semaphore.close();
2444        self.fetch_responder_worker_semaphore.close();
2445        self.verification_responder_worker_semaphore.close();
2446        self.neighbor_sync_responder_worker_semaphore.close();
2447
2448        // All producers have stopped, so close and drain their detached work.
2449        // A started storage operation must run to completion: dropping an async
2450        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2451        // while a blocking storage operation is still running.
2452        //
2453        // Deliberately unbounded: every worker has to release its
2454        // `Arc<ChunkStore>` before the caller may reopen the store, whose lock
2455        // admits one process at a time, and a timeout here could return with one
2456        // still held.
2457        // What makes that safe is that every detached task is now guaranteed to
2458        // finish — the pools above are closed, stale work is shed at dequeue,
2459        // and the one genuinely unbounded await (payment verification) races
2460        // `self.shutdown` via `verify_payment_until_shutdown`.
2461        self.detached_task_tracker.close();
2462        self.detached_task_tracker.wait().await;
2463
2464        // Every producer is gone, but a select! racing the shutdown token may
2465        // have dropped a future while it awaited a storage `spawn_blocking` op
2466        // (fetch `storage.put`, prune `storage.delete` /
2467        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2468        // detached blocking closure owns a cloned `Env`; wait for both
2469        // environments to go quiescent — bounded by one in-flight transaction
2470        // per op — so the caller may reopen them.
2471        self.storage.wait_idle().await;
2472        self.paid_list.wait_idle().await;
2473    }
2474
2475    /// Trigger an early neighbor sync round.
2476    ///
2477    /// Useful after topology changes (new nodes joining, network heal after
2478    /// partition) when the caller wants replication to converge faster than
2479    /// the regular 10-20 minute cadence.
2480    pub fn trigger_neighbor_sync(&self) {
2481        self.sync_trigger.notify_one();
2482    }
2483
2484    /// Execute fresh replication for a newly stored record: announce it, then
2485    /// send its offers and schedule the delayed possession check for the
2486    /// responsible close-group peers (ADR-0003), as the PUT path does.
2487    ///
2488    /// Unlike the PUT path, this waits for a pending-offer permit before
2489    /// returning, and it offers the caller's bytes rather than reading them
2490    /// back from storage.
2491    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2492        fresh::announce_paid_write(
2493            key,
2494            proof_of_payment,
2495            &self.paid_list,
2496            &self.p2p_node,
2497            &self.config,
2498        )
2499        .await;
2500        // Never closed, so this cannot fail; the arm keeps the call panic-free.
2501        let Ok(pending_offer) = Arc::clone(&self.pending_offer_semaphore)
2502            .acquire_owned()
2503            .await
2504        else {
2505            return;
2506        };
2507        fresh::send_fresh_offers(
2508            &self.fresh_offer_context(),
2509            key,
2510            data.to_vec(),
2511            proof_of_payment.to_vec(),
2512            pending_offer,
2513        )
2514        .await;
2515    }
2516
2517    /// Handles the offer dispatcher and the direct entry point share.
2518    fn fresh_offer_context(&self) -> fresh::FreshOfferContext {
2519        fresh::FreshOfferContext {
2520            p2p_node: Arc::clone(&self.p2p_node),
2521            config: Arc::clone(&self.config),
2522            send_semaphore: Arc::clone(&self.send_semaphore),
2523            possession_check_tx: self.possession_check_tx.clone(),
2524            dispatched: Arc::clone(&self.fresh_offers_dispatched),
2525        }
2526    }
2527
2528    // =======================================================================
2529    // Background task launchers
2530    // =======================================================================
2531
2532    /// Spawn fresh replication's two stages, joined by an unbounded FIFO of
2533    /// key + proof events: the drainer, which announces every write at arrival
2534    /// rate, and the offer dispatcher, the only permit-gated stage.
2535    fn start_fresh_replication(&mut self) {
2536        let Some(writes) = self.fresh_write_rx.take() else {
2537            return;
2538        };
2539        let (offer_tx, offer_rx) = mpsc::unbounded_channel();
2540        self.start_fresh_write_drainer(writes, offer_tx.clone());
2541        self.start_fresh_offer_dispatcher(offer_rx, offer_tx);
2542    }
2543
2544    /// Spawn a task that drains the fresh-write channel: it announces each
2545    /// newly-stored chunk and hands it to the offer dispatcher.
2546    fn start_fresh_write_drainer(
2547        &mut self,
2548        mut rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
2549        offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2550    ) {
2551        let p2p = Arc::clone(&self.p2p_node);
2552        let paid_list = Arc::clone(&self.paid_list);
2553        let config = Arc::clone(&self.config);
2554        let shutdown = self.shutdown.clone();
2555
2556        let handle = tokio::spawn(async move {
2557            loop {
2558                let event = tokio::select! {
2559                    () = shutdown.cancelled() => break,
2560                    event = rx.recv() => {
2561                        let Some(event) = event else { break };
2562                        event
2563                    }
2564                };
2565                // Stage one never waits for chunk back-pressure: the paid-list
2566                // entry and PaidNotify are what let peers repair the key later,
2567                // so every queued write gets them at arrival rate.
2568                fresh::announce_paid_write(
2569                    &event.key,
2570                    &event.payment_proof,
2571                    &paid_list,
2572                    &p2p,
2573                    &config,
2574                )
2575                .await;
2576                if offer_tx
2577                    .send(fresh::FreshOfferEvent {
2578                        key: event.key,
2579                        payment_proof: event.payment_proof,
2580                        read_attempts: 0,
2581                    })
2582                    .is_err()
2583                {
2584                    break;
2585                }
2586            }
2587            debug!("Fresh-write drainer shut down");
2588        });
2589        self.task_handles.push(handle);
2590    }
2591
2592    /// Spawn the fresh-offer dispatcher: the only stage of fresh replication
2593    /// that waits for a pending-offer permit.
2594    ///
2595    /// For each forwarded write it acquires a permit, reads the chunk back
2596    /// from storage and dispatches the offers. A missing chunk is skipped; a
2597    /// failed read is retried up to `MAX_FRESH_READ_ATTEMPTS` times, backing
2598    /// off over about a minute with the permit released in between, so a
2599    /// transient I/O fault does not lose the write's replication. The retry
2600    /// waits on its own task, never on the dispatcher.
2601    fn start_fresh_offer_dispatcher(
2602        &mut self,
2603        mut rx: mpsc::UnboundedReceiver<fresh::FreshOfferEvent>,
2604        offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2605    ) {
2606        let storage = Arc::clone(&self.storage);
2607        let pending_offer_semaphore = Arc::clone(&self.pending_offer_semaphore);
2608        let ctx = self.fresh_offer_context();
2609        let shutdown = self.shutdown.clone();
2610        let retries = self.detached_task_tracker.clone();
2611
2612        let handle = tokio::spawn(async move {
2613            loop {
2614                let event = tokio::select! {
2615                    () = shutdown.cancelled() => break,
2616                    event = rx.recv() => {
2617                        let Some(event) = event else { break };
2618                        event
2619                    }
2620                };
2621                // Wait for a pending-offer permit before touching the chunk so a
2622                // send backlog holds queued events, not encoded chunk buffers.
2623                let pending_offer = tokio::select! {
2624                    () = shutdown.cancelled() => break,
2625                    permit = Arc::clone(&pending_offer_semaphore).acquire_owned() => {
2626                        let Ok(permit) = permit else { break };
2627                        permit
2628                    }
2629                };
2630                let key_hex = hex::encode(event.key);
2631                // The same verified read the fetch path serves from. The bytes
2632                // were content-checked when they were stored, but they come
2633                // off disk now, possibly long after, and every receiver
2634                // charges the sender for an offer that does not hash to its
2635                // key. A chunk that fails verification is quarantined by this
2636                // read, so its retry finds it gone and skips it.
2637                let data = match storage.get(&event.key).await {
2638                    Ok(Some(data)) => data,
2639                    Ok(None) => {
2640                        debug!("Chunk {key_hex} no longer stored, skipping fresh replication");
2641                        continue;
2642                    }
2643                    Err(e) => {
2644                        // The permit is released as this iteration ends, well
2645                        // before any retry is due.
2646                        let attempts = event.read_attempts + 1;
2647                        if attempts >= MAX_FRESH_READ_ATTEMPTS {
2648                            warn!(
2649                                "Giving up fresh replication of {key_hex} after {attempts} failed reads: {e}"
2650                            );
2651                            continue;
2652                        }
2653                        // One warning per write: a store-wide fault fails the
2654                        // whole backlog, once per retry.
2655                        if attempts == 1 {
2656                            warn!(
2657                                "Failed to read chunk {key_hex} for fresh replication; will retry: {e}"
2658                            );
2659                        } else {
2660                            debug!(
2661                                "Failed to read chunk {key_hex} for fresh replication (attempt {attempts}): {e}"
2662                            );
2663                        }
2664                        // Wait on a task of its own: a read fault is often
2665                        // shared (exhausted descriptors), and sleeping here
2666                        // would hold every healthy write queued behind this
2667                        // one for the whole delay, once per failed read. The
2668                        // delay grows, so a store-wide fault spends a write's
2669                        // attempts over about a minute rather than seconds.
2670                        let retry_tx = offer_tx.clone();
2671                        let retry_shutdown = shutdown.clone();
2672                        let delay = fresh_read_retry_delay(attempts);
2673                        retries.spawn(async move {
2674                            tokio::select! {
2675                                () = retry_shutdown.cancelled() => {}
2676                                () = tokio::time::sleep(delay) => {
2677                                    let _ = retry_tx.send(fresh::FreshOfferEvent {
2678                                        read_attempts: attempts,
2679                                        ..event
2680                                    });
2681                                }
2682                            }
2683                        });
2684                        continue;
2685                    }
2686                };
2687                fresh::send_fresh_offers(
2688                    &ctx,
2689                    &event.key,
2690                    data,
2691                    event.payment_proof,
2692                    pending_offer,
2693                )
2694                .await;
2695            }
2696            debug!("Fresh-offer dispatcher shut down");
2697        });
2698        self.task_handles.push(handle);
2699    }
2700
2701    /// Spawn the possession-check scheduler (ADR-0003).
2702    ///
2703    /// Drains scheduled possession-check events and, for each, waits a
2704    /// randomised 5-15 minute settle delay before probing every responsible
2705    /// peer for actual possession. A peer that fails to prove possession or does
2706    /// not answer is penalised at `AuditChallenge` severity.
2707    fn start_possession_check_scheduler(&mut self) {
2708        let Some(mut rx) = self.possession_check_rx.take() else {
2709            return;
2710        };
2711        let p2p = Arc::clone(&self.p2p_node);
2712        let storage = Arc::clone(&self.storage);
2713        let config = Arc::clone(&self.config);
2714        let sync_state = Arc::clone(&self.sync_state);
2715        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2716        let shutdown = self.shutdown.clone();
2717        let detached_task_tracker = self.detached_task_tracker.clone();
2718
2719        let handle = tokio::spawn(async move {
2720            loop {
2721                tokio::select! {
2722                    () = shutdown.cancelled() => break,
2723                    event = rx.recv() => {
2724                        let Some(event) = event else { break };
2725                        // Spawn a per-chunk delayed check so the drain loop
2726                        // keeps pace with the write rate. Each check sleeps the
2727                        // randomised settle delay, then probes every peer.
2728                        let p2p = Arc::clone(&p2p);
2729                        let storage = Arc::clone(&storage);
2730                        let config = Arc::clone(&config);
2731                        let sync_state = Arc::clone(&sync_state);
2732                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2733                        let shutdown = shutdown.clone();
2734                        let delay_min = config.possession_check_delay_min;
2735                        let delay_max = config.possession_check_delay_max;
2736                        detached_task_tracker.spawn(async move {
2737                            let delay = possession::random_delay(delay_min, delay_max);
2738                            // Race shutdown against the whole settle-then-probe
2739                            // sequence, not just the sleep. Once a check starts it
2740                            // may park on the per-target audit coordinator, which
2741                            // has no deadline of its own: with the settle delay
2742                            // inside the branch BODY the select is already resolved,
2743                            // so those waiters would drain only at the probe timeout
2744                            // (roughly `queued / per-target-limit` probes deep) while
2745                            // `detached_task_tracker.wait()` — deliberately unbounded
2746                            // for the storage contract — held shutdown open.
2747                            //
2748                            // Dropping this future mid-probe is safe and is the same
2749                            // shape the neighbor-sync round uses: a parked coordinator
2750                            // acquire releases its counted reference via
2751                            // `ReferenceGuard`, and a dropped storage `spawn_blocking` is
2752                            // covered by the storage-quiescence wait in `shutdown`.
2753                            tokio::select! {
2754                                () = shutdown.cancelled() => {}
2755                                () = async {
2756                                    tokio::time::sleep(delay).await;
2757                                    possession::run_possession_check(
2758                                        event.key,
2759                                        event.peers,
2760                                        &p2p,
2761                                        &storage,
2762                                        &config,
2763                                        &sync_state,
2764                                        &audit_challenge_coordinator,
2765                                        &shutdown,
2766                                    )
2767                                    .await;
2768                                } => {}
2769                            }
2770                        });
2771                    }
2772                }
2773            }
2774            debug!("Possession-check scheduler shut down");
2775        });
2776        self.task_handles.push(handle);
2777    }
2778
2779    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2780    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2781    /// as the gossip path, under the same per-peer cooldown and concurrency
2782    /// caps, but with the probability lottery BYPASSED (the lottery governs
2783    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2784    /// deterministic first audit; a peer minting fresh pins faster than the
2785    /// cooldown forfeits the older ones' coverage, never the newest's (the
2786    /// channel surfaces newest pins as they are monetized).
2787    #[allow(clippy::too_many_lines)]
2788    fn start_first_audit_drainer(&mut self) {
2789        let Some(mut rx) = self.monetized_pin_rx.take() else {
2790            return;
2791        };
2792        let gossip_audit = GossipAuditTrigger {
2793            p2p_node: Arc::clone(&self.p2p_node),
2794            config: Arc::clone(&self.config),
2795            recent_provers: Arc::clone(&self.recent_provers),
2796            sync_state: Arc::clone(&self.sync_state),
2797            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2798            detached_task_tracker: self.detached_task_tracker.clone(),
2799            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2800        };
2801        let shutdown = self.shutdown.clone();
2802        let observability = Arc::clone(&self.first_audit_observability);
2803        let self_peer = *self.p2p_node.peer_id();
2804
2805        let handle = tokio::spawn(async move {
2806            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2807            // scheduler. Payments only NOMINATE pins; the token bucket launches
2808            // them at a fixed per-node rate, and durable suppression is stamped
2809            // only at PROMOTION (after an authoritative post-jitter answerability
2810            // + cooldown check), so a cancelled reservation leaves nothing behind.
2811            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2812            // Periodic retry tick so budget/cooldown-deferred pins get retried
2813            // even when no new nomination arrives. `Skip` collapses a backlog.
2814            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2815            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2816            let mut last_summary = Instant::now();
2817            loop {
2818                // The reservation's jitter deadline is a wake source: if a
2819                // reservation is outstanding, sleep until it is due; otherwise
2820                // a far-future deadline effectively disables that arm and only
2821                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2822                // newly reserved (earlier) deadline is honoured next turn.
2823                let promotion_due = scheduler
2824                    .reserved_ready_at()
2825                    .unwrap_or_else(first_audit_far_future);
2826                tokio::select! {
2827                    () = shutdown.cancelled() => break,
2828                    event = rx.recv() => match event {
2829                        Some(e) => {
2830                            observability.received.fetch_add(1, Ordering::Relaxed);
2831                            // Pre-overflow reservation opportunity: before an
2832                            // arrival may displace a DIFFERENT peer, let the
2833                            // queue launch — a successful reservation frees the
2834                            // slot without eviction. One reservation can be
2835                            // outstanding at a time, so this consumes at most
2836                            // one slot per jitter window; arrivals beyond it
2837                            // fall through to random displacement (ADR-0004
2838                            // Amendment 4).
2839                            if scheduler.would_displace(&e) {
2840                                open_first_audit_reservation(
2841                                    &mut scheduler,
2842                                    &gossip_audit.cooldown,
2843                                    &observability,
2844                                )
2845                                .await;
2846                            }
2847                            scheduler.enqueue(e, &observability);
2848                            // Drain a bounded burst so a flood cannot starve the
2849                            // launch phase.
2850                            let mut drained = 1usize;
2851                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2852                                match rx.try_recv() {
2853                                    Ok(e) => {
2854                                        observability.received.fetch_add(1, Ordering::Relaxed);
2855                                        if scheduler.would_displace(&e) {
2856                                            open_first_audit_reservation(
2857                                                &mut scheduler,
2858                                                &gossip_audit.cooldown,
2859                                                &observability,
2860                                            )
2861                                            .await;
2862                                        }
2863                                        scheduler.enqueue(e, &observability);
2864                                        drained += 1;
2865                                    }
2866                                    Err(_) => break,
2867                                }
2868                            }
2869                        }
2870                        None => break,
2871                    },
2872                    _ = tick.tick() => {}
2873                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2874                }
2875
2876                // 1) Promote a due reservation. Resolved after EVERY wake (not
2877                //    only when the timer arm wins) so a continuously-ready `rx`
2878                //    cannot indefinitely delay a due promotion. The authoritative
2879                //    answerability + cooldown check-and-stamp happens here under
2880                //    the shared cooldown write lock, immediately before the send.
2881                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2882                    let promoted = {
2883                        let mut cooldown = gossip_audit.cooldown.write().await;
2884                        scheduler.resolve(
2885                            reservation,
2886                            SystemTime::now(),
2887                            Instant::now(),
2888                            &mut cooldown,
2889                            &observability,
2890                        )
2891                    };
2892                    if let Some((event, inflight_slot)) = promoted {
2893                        debug!(
2894                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2895                            event.peer, hex::encode(event.pin), event.key_count,
2896                            observability.inflight.load(Ordering::Relaxed)
2897                        );
2898                        let trigger = gossip_audit.clone();
2899                        let audit_observability = Arc::clone(&observability);
2900                        // Track the launch so `shutdown()`'s detached drain
2901                        // covers it. This task outlives the drainer loop that
2902                        // spawned it — the loop breaks on the shutdown token
2903                        // while the audit is still awaiting its response — so a
2904                        // bare spawn would let an in-flight subtree audit keep
2905                        // running, and keep its `Arc<P2PNode>`, past the point
2906                        // `shutdown()` claims every engine task has stopped.
2907                        let tracker = trigger.detached_task_tracker.clone();
2908                        tracker.spawn(async move {
2909                            // The jitter already elapsed as the reservation's
2910                            // timer; the slot is held for the audit's duration
2911                            // and released on drop (panic-safe).
2912                            let inflight_slot = inflight_slot;
2913                            let started = Instant::now();
2914                            let credit = storage_commitment_audit::AuditCredit {
2915                                recent_provers: &trigger.recent_provers,
2916                            };
2917                            let result = storage_commitment_audit::run_subtree_audit(
2918                                &trigger.p2p_node,
2919                                &trigger.config,
2920                                &event.peer,
2921                                event.pin,
2922                                event.key_count,
2923                                Some(&credit),
2924                            )
2925                            .await;
2926                            let outcome = first_audit_terminal_outcome(&result);
2927                            match outcome {
2928                                FirstAuditTerminalOutcome::Passed => {
2929                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2930                                }
2931                                FirstAuditTerminalOutcome::Timeout => {
2932                                    audit_observability
2933                                        .timed_out
2934                                        .fetch_add(1, Ordering::Relaxed);
2935                                }
2936                                FirstAuditTerminalOutcome::Failed => {
2937                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2938                                }
2939                                FirstAuditTerminalOutcome::BootstrapClaim => {
2940                                    audit_observability
2941                                        .bootstrap_claims
2942                                        .fetch_add(1, Ordering::Relaxed);
2943                                }
2944                                FirstAuditTerminalOutcome::Idle => {
2945                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2946                                }
2947                                FirstAuditTerminalOutcome::InsufficientKeys => {
2948                                    audit_observability
2949                                        .insufficient_keys
2950                                        .fetch_add(1, Ordering::Relaxed);
2951                                }
2952                            }
2953                            drop(inflight_slot);
2954                            debug!(
2955                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2956                                outcome.as_str(),
2957                                event.peer, hex::encode(event.pin), event.key_count,
2958                                started.elapsed().as_millis(),
2959                                audit_observability.inflight.load(Ordering::Relaxed)
2960                            );
2961                            handle_subtree_audit_result(
2962                                &result,
2963                                &trigger.p2p_node,
2964                                &trigger.sync_state,
2965                                &trigger.recent_provers,
2966                                &trigger.config,
2967                            )
2968                            .await;
2969                        });
2970                    }
2971                }
2972
2973                // 2) Open the single reservation from the pending queue if none
2974                //    is outstanding (read-only cooldown snapshot; the
2975                //    authoritative stamp is at promotion). Serializing
2976                //    reservations preserves per-launch lane alternation and keeps
2977                //    at most one jitter timer live.
2978                open_first_audit_reservation(
2979                    &mut scheduler,
2980                    &gossip_audit.cooldown,
2981                    &observability,
2982                )
2983                .await;
2984
2985                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2986                    // Token-independent hygiene: collect entries that aged past
2987                    // the answerability horizon while the budget gate kept the
2988                    // reserve scan from running, so the summary below reports
2989                    // only live work.
2990                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2991                    if swept > 0 {
2992                        debug!(
2993                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2994                            scheduler.pending_len()
2995                        );
2996                    }
2997                    info!(
2998                        "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={}",
2999                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
3000                        observability.received.load(Ordering::Relaxed),
3001                        observability.queued.load(Ordering::Relaxed),
3002                        observability.coalesced.load(Ordering::Relaxed),
3003                        observability.suppressed_lower.load(Ordering::Relaxed),
3004                        observability.duplicates.load(Ordering::Relaxed),
3005                        observability.capacity_evicted.load(Ordering::Relaxed),
3006                        observability.self_target_skipped.load(Ordering::Relaxed),
3007                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
3008                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
3009                        observability.window_deduped.load(Ordering::Relaxed),
3010                        observability.launched.load(Ordering::Relaxed),
3011                        observability.passed.load(Ordering::Relaxed),
3012                        observability.timed_out.load(Ordering::Relaxed),
3013                        observability.failed.load(Ordering::Relaxed),
3014                        observability.bootstrap_claims.load(Ordering::Relaxed),
3015                        observability.idle.load(Ordering::Relaxed),
3016                        observability.insufficient_keys.load(Ordering::Relaxed),
3017                        observability.outside_answerability_window.load(Ordering::Relaxed),
3018                        scheduler.pending_len(),
3019                        FIRST_AUDIT_PENDING_CAP,
3020                        u8::from(scheduler.has_reservation()),
3021                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
3022                        observability.inflight.load(Ordering::Relaxed),
3023                        scheduler.tokens(),
3024                    );
3025                    last_summary = Instant::now();
3026                }
3027            }
3028            debug!("First-audit drainer shut down");
3029        });
3030        self.task_handles.push(handle);
3031    }
3032
3033    #[allow(clippy::too_many_lines)]
3034    fn start_message_handler(&mut self) {
3035        let mut p2p_events = self.p2p_node.subscribe_events();
3036        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
3037        let p2p = Arc::clone(&self.p2p_node);
3038        let storage = Arc::clone(&self.storage);
3039        let paid_list = Arc::clone(&self.paid_list);
3040        let payment_verifier = Arc::clone(&self.payment_verifier);
3041        let queues = Arc::clone(&self.queues);
3042        let config = Arc::clone(&self.config);
3043        let shutdown = self.shutdown.clone();
3044        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3045        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3046        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3047        let sync_history = Arc::clone(&self.sync_history);
3048        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3049        let repair_proofs = Arc::clone(&self.repair_proofs);
3050        let sync_trigger = Arc::clone(&self.sync_trigger);
3051        let my_commitment_state = Arc::clone(&self.commitment_state);
3052        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3053        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3054        let recent_provers = Arc::clone(&self.recent_provers);
3055        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3056        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
3057        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
3058        let sync_state = Arc::clone(&self.sync_state);
3059        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
3060        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
3061        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
3062        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
3063        let fetch_responder_admission_semaphore =
3064            Arc::clone(&self.fetch_responder_admission_semaphore);
3065        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
3066        let verification_responder_worker_semaphore =
3067            Arc::clone(&self.verification_responder_worker_semaphore);
3068        let verification_responder_admission_semaphore =
3069            Arc::clone(&self.verification_responder_admission_semaphore);
3070        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
3071        let neighbor_sync_responder_worker_semaphore =
3072            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
3073        let neighbor_sync_responder_admission_semaphore =
3074            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
3075        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
3076        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
3077        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
3078        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
3079        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
3080        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
3081        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
3082        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
3083        let detached_task_tracker = self.detached_task_tracker.clone();
3084        let subtree_round1 = self.subtree_round1.clone();
3085
3086        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
3087        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
3088        let gossip_audit = GossipAuditTrigger {
3089            p2p_node: Arc::clone(&p2p),
3090            config: Arc::clone(&config),
3091            recent_provers: Arc::clone(&recent_provers),
3092            sync_state: Arc::clone(&sync_state),
3093            cooldown: Arc::clone(&audit_on_gossip_cooldown),
3094            detached_task_tracker: detached_task_tracker.clone(),
3095            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
3096        };
3097
3098        let handler_context = ReplicationMessageHandlerContext {
3099            p2p_node: Arc::clone(&p2p),
3100            storage,
3101            paid_list,
3102            payment_verifier,
3103            queues,
3104            config: Arc::clone(&config),
3105            is_bootstrapping,
3106            bootstrap_state,
3107            sync_history,
3108            sync_cycle_epoch,
3109            repair_proofs: Arc::clone(&repair_proofs),
3110            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
3111            ever_capable_peers,
3112            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
3113            my_commitment_state,
3114            gossip_audit,
3115            audit_responder_semaphore,
3116            audit_responder_inflight,
3117            audit_responder_metrics,
3118            subtree_round1,
3119            fetch_responder_worker_semaphore,
3120            fetch_responder_admission_semaphore,
3121            fetch_responder_inflight,
3122            verification_responder_worker_semaphore,
3123            verification_responder_admission_semaphore,
3124            verification_responder_inflight,
3125            neighbor_sync_responder_worker_semaphore,
3126            neighbor_sync_responder_admission_semaphore,
3127            neighbor_sync_responder_inflight,
3128            fresh_offer_worker_semaphore,
3129            fresh_offer_admission_semaphore,
3130            fresh_offer_responder_inflight,
3131            fresh_offer_in_flight,
3132            paid_notify_worker_semaphore,
3133            paid_notify_admission_semaphore,
3134            paid_notify_responder_inflight,
3135            pointers: self.pointers.clone(),
3136            shutdown: shutdown.clone(),
3137            detached_task_tracker,
3138        };
3139
3140        let (replication_tx, mut replication_rx) =
3141            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
3142        let serial_context = handler_context.clone();
3143        let serial_shutdown = shutdown.clone();
3144        let serial_handle = tokio::spawn(async move {
3145            loop {
3146                tokio::select! {
3147                    () = serial_shutdown.cancelled() => break,
3148                    inbound = replication_rx.recv() => {
3149                        let Some(inbound) = inbound else { break };
3150                        let source = inbound.source;
3151                        match handle_replication_message(
3152                            &source,
3153                            inbound.msg,
3154                            &serial_context,
3155                            inbound.received_at,
3156                            inbound.rr_message_id.as_deref(),
3157                        )
3158                        .await
3159                        {
3160                            Ok(()) => {}
3161                            Err(e) => {
3162                                debug!("Replication message from {source} error: {e}");
3163                            }
3164                        }
3165                    }
3166                }
3167            }
3168            debug!("Replication non-audit serial handler shut down");
3169        });
3170        self.task_handles.push(serial_handle);
3171
3172        let handle = tokio::spawn(async move {
3173            loop {
3174                tokio::select! {
3175                    () = shutdown.cancelled() => break,
3176                    event = p2p_events.recv() => {
3177                        let event = match event {
3178                            Ok(event) => event,
3179                            Err(error) => match handle_replication_event_recv_error(&error) {
3180                                ControlFlow::Continue(()) => continue,
3181                                ControlFlow::Break(()) => break,
3182                            },
3183                        };
3184                        let Some((source, payload, inbound_protocol, rr_message_id)) =
3185                            replication_payload_from_event(event)
3186                        else {
3187                            continue;
3188                        };
3189                        let received_at = Instant::now();
3190                        let msg = match ReplicationMessage::decode(&payload) {
3191                            Ok(msg) => msg,
3192                            Err(e) => {
3193                                debug!("Replication message from {source} decode error: {e}");
3194                                continue;
3195                            }
3196                        };
3197                        if !body_matches_protocol(&msg.body, inbound_protocol) {
3198                            debug!(
3199                                "Dropping replication body (variant {}) on protocol \
3200                                 {inbound_protocol}: wrong id for its family \
3201                                 (cross-version or misrouted)",
3202                                msg.body.variant_index()
3203                            );
3204                            continue;
3205                        }
3206                        if let Some(class) = audit_responder_class(&msg.body) {
3207                            handler_context
3208                                .audit_responder_metrics
3209                                .record_received(source, class);
3210                        }
3211                        let inbound = InboundReplicationMessage {
3212                            source,
3213                            msg,
3214                            rr_message_id,
3215                            received_at,
3216                        };
3217                        if matches!(
3218                            inbound.msg.body,
3219                            ReplicationMessageBody::AuditChallenge(_)
3220                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
3221                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
3222                        ) {
3223                            let source = inbound.source;
3224                            match handle_replication_message(
3225                                &source,
3226                                inbound.msg,
3227                                &handler_context,
3228                                inbound.received_at,
3229                                inbound.rr_message_id.as_deref(),
3230                            )
3231                            .await
3232                            {
3233                                Ok(()) => {}
3234                                Err(e) => {
3235                                    debug!("Replication message from {source} error: {e}");
3236                                }
3237                            }
3238                            continue;
3239                        }
3240                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
3241                            if dropped.audit_responder_class.is_some() {
3242                                handler_context
3243                                    .audit_responder_metrics
3244                                    .record_serial_queue_drop(dropped.source);
3245                            }
3246                            // Every serial-lane class has protocol recovery: syncs rerun,
3247                            // fetches retry, verification re-asks, and a dropped fresh
3248                            // offer is refilled by neighbor sync (the possession check
3249                            // penalises the absence but never re-offers). Responses are
3250                            // covered by their requester's deadline/retry path. Never run
3251                            // a bulk handler here: event receipt must remain non-blocking.
3252                            warn!(
3253                                message_class = dropped.message_class,
3254                                source = %dropped.source,
3255                                queue_depth = dropped.queue_depth,
3256                                reason = dropped.reason.as_str(),
3257                                "Replication serial-queue message dropped"
3258                            );
3259                        }
3260                    }
3261                    // Gap 4: Topology churn handling (Section 13).
3262                    //
3263                    // The DHT routing table emits KClosestPeersChanged when the
3264                    // K-closest peer set actually changes, which is the precise
3265                    // signal for triggering neighbor sync. This replaces the
3266                    // previous approach of checking every PeerConnected /
3267                    // PeerDisconnected event against the close group.
3268                    dht_event = dht_events.recv() => {
3269                        let dht_event = match dht_event {
3270                            Ok(event) => event,
3271                            Err(RecvError::Lagged(missed)) => {
3272                                // Under heavy churn the broadcast buffer can overflow
3273                                // and drop routing-table events — the moment
3274                                // convergence matters most. A dropped
3275                                // KClosestPeersChanged means its entrants were never
3276                                // queued and its departures were never pruned, so
3277                                // draining priority_order cannot recover either.
3278                                // Resync from ground truth instead: snapshot the
3279                                // current close-peer set, prune pending peers that
3280                                // left it during the lost window (retain_sync_peers,
3281                                // as the normal topology-change path does), and queue
3282                                // every member. Dedup (queue_priority_peers) and
3283                                // per-peer cooldown (select_next_sync_peer) drop peers
3284                                // already queued or recently synced, so only genuine
3285                                // entrants surface.
3286                                warn!(
3287                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3288                                );
3289                                let self_id = *p2p.peer_id();
3290                                let neighbors = neighbor_sync::snapshot_close_neighbors(
3291                                    &p2p,
3292                                    &self_id,
3293                                    config.neighbor_sync_scope,
3294                                )
3295                                .await;
3296                                let neighbor_set =
3297                                    neighbors.iter().copied().collect::<HashSet<_>>();
3298                                let (requeued, sync_removals) = {
3299                                    let mut state = sync_state.write().await;
3300                                    let sync_removals =
3301                                        state.retain_sync_peers(&neighbor_set);
3302                                    let requeued = state.queue_priority_peers(neighbors);
3303                                    (requeued, sync_removals)
3304                                };
3305                                if sync_removals > 0 {
3306                                    debug!(
3307                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3308                                    );
3309                                }
3310                                if requeued > 0 {
3311                                    debug!(
3312                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3313                                    );
3314                                    sync_trigger.notify_one();
3315                                }
3316                                continue;
3317                            }
3318                            Err(RecvError::Closed) => {
3319                                // A closed broadcast channel never yields again;
3320                                // continuing would spin the select! loop forever.
3321                                warn!(
3322                                    "DHT event stream closed on replication branch; stopping message handler"
3323                                );
3324                                break;
3325                            }
3326                        };
3327                        match dht_event {
3328                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3329                                let old_peers = old
3330                                    .iter()
3331                                    .take(config.neighbor_sync_scope)
3332                                    .copied()
3333                                    .collect::<HashSet<_>>();
3334                                let new_scoped = new
3335                                    .iter()
3336                                    .take(config.neighbor_sync_scope)
3337                                    .copied()
3338                                    .collect::<Vec<_>>();
3339                                let new_peers =
3340                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3341                                let entrants = new_scoped
3342                                    .iter()
3343                                    .copied()
3344                                    .filter(|peer| !old_peers.contains(peer))
3345                                    .collect::<Vec<_>>();
3346                                let entrant_count = entrants.len();
3347                                let (priority_insertions, sync_removals) = {
3348                                    let mut state = sync_state.write().await;
3349                                    let sync_removals = state.retain_sync_peers(&new_peers);
3350                                    let priority_insertions = state.queue_priority_peers(entrants);
3351                                    (priority_insertions, sync_removals)
3352                                };
3353                                if priority_insertions > 0 {
3354                                    debug!(
3355                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3356                                    );
3357                                } else {
3358                                    debug!(
3359                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3360                                    );
3361                                }
3362                                sync_trigger.notify_one();
3363                            }
3364                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3365                                sync_state.write().await.remove_peer(&peer_id);
3366                                repair_proofs.write().await.remove_peer(&peer_id);
3367                                if let Some(pointers) = &handler_context.pointers {
3368                                    pointers.forget_peer(&peer_id);
3369                                }
3370                                update_bootstrap_after_peer_removed(
3371                                    &peer_id,
3372                                    &handler_context.bootstrap_state,
3373                                    &handler_context.queues,
3374                                    &handler_context.is_bootstrapping,
3375                                    &bootstrap_complete_notify,
3376                                )
3377                                .await;
3378                                // v12: drop the commitment bytes and the
3379                                // recent-prover credit so a churn / sybil
3380                                // attacker cannot leave behind one
3381                                // StorageCommitment per identity in
3382                                // `last_commitment_by_peer`. Also drop the
3383                                // sig-verify rate-limit timestamp.
3384                                last_commitment_by_peer.write().await.remove(&peer_id);
3385                                recent_provers.write().await.forget_peer(&peer_id);
3386                                sig_verify_attempts.write().await.remove(&peer_id);
3387                                // Same for the gossip-audit cooldown (ADR-0002)
3388                                // and the lottery-attempt window.
3389                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3390                                gossip_lottery_attempts.write().await.remove(&peer_id);
3391                                // The sticky `commitment_capable` flag is
3392                                // preserved orthogonally via
3393                                // `ever_capable_peers` — even after this
3394                                // removal, a re-joining peer continues to
3395                                // be treated as v12-capable rather than
3396                                // legacy (§3 shield).
3397                            }
3398                            _ => {}
3399                        }
3400                    }
3401                }
3402            }
3403            debug!("Replication message handler shut down");
3404        });
3405        self.task_handles.push(handle);
3406    }
3407
3408    fn start_neighbor_sync_loop(&mut self) {
3409        let pointers = self.pointers.clone();
3410        let p2p = Arc::clone(&self.p2p_node);
3411        let storage = Arc::clone(&self.storage);
3412        let paid_list = Arc::clone(&self.paid_list);
3413        let queues = Arc::clone(&self.queues);
3414        let config = Arc::clone(&self.config);
3415        let shutdown = self.shutdown.clone();
3416        let sync_state = Arc::clone(&self.sync_state);
3417        let sync_history = Arc::clone(&self.sync_history);
3418        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3419        let repair_proofs = Arc::clone(&self.repair_proofs);
3420        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3421        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3422        let sync_trigger = Arc::clone(&self.sync_trigger);
3423        let commitment_state = Arc::clone(&self.commitment_state);
3424        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3425        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3426        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3427        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3428        let detached_task_tracker = self.detached_task_tracker.clone();
3429        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3430        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3431        // here too so a peer that only ever answers — never initiates sync —
3432        // is still audited; otherwise it could fully evade auditing.
3433        let gossip_audit = GossipAuditTrigger {
3434            p2p_node: Arc::clone(&p2p),
3435            config: Arc::clone(&config),
3436            recent_provers: Arc::clone(&self.recent_provers),
3437            sync_state: Arc::clone(&sync_state),
3438            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3439            detached_task_tracker,
3440            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3441        };
3442
3443        let handle = tokio::spawn(async move {
3444            loop {
3445                // Park for the periodic tick or an explicit trigger ONLY when no
3446                // priority (topology-change) peers are queued. `sync_trigger` is a
3447                // coalescing `Notify`, so a churn burst that queues many entrants
3448                // produces a single wakeup; parking after draining one batch would
3449                // leave the rest waiting up to a full periodic tick. `priority_order`
3450                // is the durable record of pending work, so drain it back-to-back —
3451                // each round removes the peers it selects (`select_next_sync_peer`),
3452                // so the drain terminates once the queue empties.
3453                if !sync_state.read().await.has_priority_peers() {
3454                    let interval = config.random_neighbor_sync_interval();
3455                    tokio::select! {
3456                        () = shutdown.cancelled() => break,
3457                        () = tokio::time::sleep(interval) => {}
3458                        () = sync_trigger.notified() => {
3459                            debug!("Neighbor sync triggered by topology change");
3460                        }
3461                    }
3462                }
3463                // Wrap the sync round in a select so shutdown cancels
3464                // in-progress network operations rather than waiting for
3465                // the full round to complete.
3466                tokio::select! {
3467                    () = shutdown.cancelled() => break,
3468                    () = run_neighbor_sync_round(
3469                        &p2p,
3470                        &storage,
3471                        &paid_list,
3472                        &queues,
3473                        &config,
3474                        &sync_state,
3475                        &sync_history,
3476                        &sync_cycle_epoch,
3477                        &repair_proofs,
3478                        &is_bootstrapping,
3479                        &bootstrap_state,
3480                        &commitment_state,
3481                        &last_commitment_by_peer,
3482                        &ever_capable_peers,
3483                        &sig_verify_attempts,
3484                        &audit_challenge_coordinator,
3485                        &gossip_audit,
3486                        pointers.as_ref(),
3487                    ) => {}
3488                }
3489            }
3490            debug!("Neighbor sync loop shut down");
3491        });
3492        self.task_handles.push(handle);
3493    }
3494
3495    fn start_self_lookup_loop(&mut self) {
3496        let p2p = Arc::clone(&self.p2p_node);
3497        let config = Arc::clone(&self.config);
3498        let shutdown = self.shutdown.clone();
3499
3500        let handle = tokio::spawn(async move {
3501            loop {
3502                let interval = config.random_self_lookup_interval();
3503                tokio::select! {
3504                    () = shutdown.cancelled() => break,
3505                    () = tokio::time::sleep(interval) => {
3506                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3507                            debug!("Self-lookup failed: {e}");
3508                        }
3509                    }
3510                }
3511            }
3512            debug!("Self-lookup loop shut down");
3513        });
3514        self.task_handles.push(handle);
3515    }
3516
3517    /// Spawn the one task that takes chunks audits found rotted out of service.
3518    ///
3519    /// One, so that the rechecks hold at most one blocking thread between them however
3520    /// many audits report rot; see [`ChunkStore::run_corrupt_rechecks`]. Tracked with
3521    /// the detached storage work rather than the engine's loops, because shutdown aborts
3522    /// a loop that outlasts its drain timeout and a recheck must not be dropped part-way.
3523    /// The worker itself stops at the shutdown token, between rechecks.
3524    fn start_corrupt_recheck_worker(&self) {
3525        let storage = Arc::clone(&self.storage);
3526        let shutdown = self.shutdown.clone();
3527        self.detached_task_tracker.spawn(async move {
3528            storage.run_corrupt_rechecks(&shutdown).await;
3529            debug!("Corrupt-chunk recheck worker shut down");
3530        });
3531    }
3532
3533    /// Periodic responsible-chunk audit loop (audit #2): every
3534    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3535    /// eligible close peer for the chunks it *should* be storing (by
3536    /// responsibility and prior repair hint), independent of the gossip-triggered
3537    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3538    /// immediately and periodically thereafter.
3539    fn start_audit_loop(&mut self) {
3540        let p2p = Arc::clone(&self.p2p_node);
3541        let storage = Arc::clone(&self.storage);
3542        let config = Arc::clone(&self.config);
3543        let shutdown = self.shutdown.clone();
3544        let sync_history = Arc::clone(&self.sync_history);
3545        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3546        let repair_proofs = Arc::clone(&self.repair_proofs);
3547        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3548        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3549        let sync_state = Arc::clone(&self.sync_state);
3550        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3551
3552        let handle = tokio::spawn(async move {
3553            // Invariant 19: wait for bootstrap to drain before starting audits.
3554            loop {
3555                tokio::select! {
3556                    () = shutdown.cancelled() => return,
3557                    () = tokio::time::sleep(
3558                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3559                    ) => {
3560                        if bootstrap_state.read().await.is_drained() {
3561                            break;
3562                        }
3563                    }
3564                }
3565            }
3566
3567            // Run one audit tick immediately after bootstrap drain.
3568            {
3569                let bootstrapping = *is_bootstrapping.read().await;
3570                let result = {
3571                    let history = sync_history.read().await;
3572                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3573                    audit::audit_tick_with_repair_proofs(
3574                        &p2p,
3575                        &storage,
3576                        &config,
3577                        &history,
3578                        &repair_proofs,
3579                        &audit_challenge_coordinator,
3580                        current_sync_epoch,
3581                        bootstrapping,
3582                    )
3583                    .await
3584                };
3585                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3586            }
3587
3588            // Then run periodically.
3589            loop {
3590                let interval = config.random_audit_tick_interval();
3591                tokio::select! {
3592                    () = shutdown.cancelled() => break,
3593                    () = tokio::time::sleep(interval) => {
3594                        let bootstrapping = *is_bootstrapping.read().await;
3595                        let result = {
3596                            let history = sync_history.read().await;
3597                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3598                            audit::audit_tick_with_repair_proofs(
3599                                &p2p,
3600                                &storage,
3601                                &config,
3602                                &history,
3603                                &repair_proofs,
3604                                &audit_challenge_coordinator,
3605                                current_sync_epoch,
3606                                bootstrapping,
3607                            )
3608                            .await
3609                        };
3610                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3611                    }
3612                }
3613            }
3614            debug!("Audit loop shut down");
3615        });
3616        self.task_handles.push(handle);
3617    }
3618
3619    /// Periodically rebuild + sign + rotate the responder's storage
3620    /// commitment.
3621    ///
3622    /// Phase 3 of the v12 storage-bound audit. Once per
3623    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3624    /// current key set, builds a Merkle tree (for content-addressed
3625    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3626    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3627    /// into `commitment_state`. Old `previous` slot is dropped by the
3628    /// rotate (per `ResponderCommitmentState::rotate`).
3629    ///
3630    /// Skips if the key set is empty (no commitment to make) — the
3631    /// auditor side falls back to the legacy plain-digest path for
3632    /// peers that have never gossiped a commitment.
3633    fn start_commitment_rotation_loop(&mut self) {
3634        let storage = Arc::clone(&self.storage);
3635        let identity = Arc::clone(&self.identity);
3636        let commitment_state = Arc::clone(&self.commitment_state);
3637        let shutdown = self.shutdown.clone();
3638        let p2p = Arc::clone(&self.p2p_node);
3639        let config = Arc::clone(&self.config);
3640        let sync_trigger = Arc::clone(&self.sync_trigger);
3641        let recent_provers = Arc::clone(&self.recent_provers);
3642        let pointer_store = self.pointers.as_ref().map(|p| p.store().clone());
3643
3644        let handle = tokio::spawn(async move {
3645            // Build the first commitment immediately on startup so a
3646            // restarted node can answer commitment-bound audits right
3647            // away — otherwise current() stays None for a full rotation
3648            // interval and audits silently fall back to legacy.
3649            //
3650            // After the first build, trigger an immediate neighbor-sync
3651            // round so the new commitment gossips out within seconds.
3652            // Without this, after a restart remote auditors keep pinning
3653            // the pre-restart (rotated-away) hash until their normal
3654            // sync cadence elapses — up to 1 h in the worst case,
3655            // during which time commitment-bound audits hit "unknown
3656            // commitment hash" -> Idle no-ops.
3657            // ML-DSA signatures are randomized so we cannot reproduce
3658            // the pre-restart hash; the only honest path to recovery
3659            // is fast re-gossip.
3660            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3661            // spawned), so this initial rebuild no-ops when the key set is
3662            // unchanged — preserving the reloaded current pin; otherwise the
3663            // reloaded roots stay answerable as retained slots until their gossip
3664            // TTL lapses. Persistence is handled by the retention-persist loop.
3665            if let Err(e) = rebuild_and_rotate_commitment(
3666                &storage,
3667                pointer_store.as_ref(),
3668                &identity,
3669                &commitment_state,
3670                &p2p,
3671                &config,
3672            )
3673            .await
3674            {
3675                warn!("Initial commitment build failed: {e}");
3676            } else {
3677                sync_trigger.notify_one();
3678            }
3679            loop {
3680                tokio::select! {
3681                    () = shutdown.cancelled() => break,
3682                    () = tokio::time::sleep(
3683                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3684                    ) => {
3685                        if let Err(e) = rebuild_and_rotate_commitment(
3686                            &storage,
3687                            pointer_store.as_ref(),
3688                            &identity,
3689                            &commitment_state,
3690                            &p2p,
3691                            &config,
3692                        ).await {
3693                            warn!("Commitment rotation failed: {e}");
3694                        }
3695                        // Piggyback a sweep of expired recent_provers
3696                        // entries on the rotation tick (same cadence,
3697                        // 1 h). is_credited_holder already honours the
3698                        // TTL on read, but the sweep reclaims memory
3699                        // for entries we'll never re-read.
3700                        let dropped = recent_provers.write().await.sweep_expired(
3701                            std::time::Instant::now()
3702                        );
3703                        if dropped > 0 {
3704                            debug!("recent_provers: swept {dropped} expired entries");
3705                        }
3706                    }
3707                }
3708            }
3709            debug!("Commitment rotation loop shut down");
3710        });
3711        self.task_handles.push(handle);
3712    }
3713
3714    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3715    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3716    /// rotations — survives a restart. Flushes once immediately, then every
3717    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3718    fn start_retention_persist_loop(&mut self) {
3719        let commitment_state = Arc::clone(&self.commitment_state);
3720        let retention_path = self.retention_path.clone();
3721        let shutdown = self.shutdown.clone();
3722        let handle = tokio::spawn(async move {
3723            let mut last: Option<Vec<u8>> = None;
3724            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3725            loop {
3726                tokio::select! {
3727                    () = shutdown.cancelled() => {
3728                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3729                            .await;
3730                        break;
3731                    }
3732                    () = tokio::time::sleep(std::time::Duration::from_secs(
3733                        RETENTION_PERSIST_INTERVAL_SECS,
3734                    )) => {
3735                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3736                            .await;
3737                    }
3738                }
3739            }
3740            debug!("Commitment retention persist loop shut down");
3741        });
3742        self.task_handles.push(handle);
3743    }
3744
3745    /// Periodically emit the cumulative replication traffic summaries: the
3746    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3747    /// (V2-684). Both read process-global counter tables maintained by the
3748    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3749    /// state.
3750    fn start_traffic_summary_loop(&mut self) {
3751        let shutdown = self.shutdown.clone();
3752        let handle = tokio::spawn(async move {
3753            loop {
3754                tokio::select! {
3755                    () = shutdown.cancelled() => break,
3756                    () = tokio::time::sleep(std::time::Duration::from_secs(
3757                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3758                    )) => {
3759                        protocol::log_traffic_summary();
3760                        protocol::log_served_peers_summary();
3761                        protocol::log_audit_outcome_summary();
3762                        audit_metrics::log_responder_admission_summary();
3763                        // V2-834 Part D: chunk RPC, upgrade and EVM RPC attribution
3764                        // ride the same cadence.
3765                        crate::storage::traffic::log_chunk_rpc_traffic_summary();
3766                        crate::upgrade::traffic::log_upgrade_traffic_summary();
3767                        crate::payment::traffic::log_evm_rpc_summary();
3768                    }
3769                }
3770            }
3771            debug!("Replication traffic summary loop shut down");
3772        });
3773        self.task_handles.push(handle);
3774    }
3775
3776    /// Periodically expose the state that gates bootstrap completion and prune
3777    /// admission. The state counts are copied before reading `is_bootstrapping`
3778    /// so this diagnostic path never nests async locks.
3779    #[cfg(feature = "logging")]
3780    fn start_bootstrap_state_snapshot_loop(&mut self) {
3781        let shutdown = self.shutdown.clone();
3782        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3783        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3784        let started_at = Instant::now();
3785        let handle = tokio::spawn(async move {
3786            loop {
3787                tokio::select! {
3788                    () = shutdown.cancelled() => break,
3789                    () = tokio::time::sleep(Duration::from_secs(
3790                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3791                    )) => {
3792                        let (
3793                            drained,
3794                            pending_peer_requests,
3795                            pending_keys,
3796                            capacity_rejected_sources,
3797                        ) = {
3798                            let state = bootstrap_state.read().await;
3799                            (
3800                                state.drained,
3801                                state.pending_peer_requests,
3802                                state.pending_keys.len(),
3803                                state.capacity_rejected_sources.len(),
3804                            )
3805                        };
3806                        let bootstrapping = *is_bootstrapping.read().await;
3807                        let snapshot_state = if drained && !bootstrapping {
3808                            "healthy"
3809                        } else if drained {
3810                            "drained_waiting_for_bootstrap_flag"
3811                        } else {
3812                            "pending"
3813                        };
3814                        info!(
3815                            drained,
3816                            pending_peer_requests,
3817                            pending_keys,
3818                            capacity_rejected_sources,
3819                            is_bootstrapping = bootstrapping,
3820                            snapshot_state,
3821                            uptime_secs = started_at.elapsed().as_secs(),
3822                            "Replication bootstrap state snapshot"
3823                        );
3824                        if drained && !bootstrapping {
3825                            info!(
3826                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3827                            );
3828                            break;
3829                        }
3830                    }
3831                }
3832            }
3833            debug!("Bootstrap state snapshot loop shut down");
3834        });
3835        self.task_handles.push(handle);
3836    }
3837
3838    /// Periodically rank remote peers using the shared audit responder pool and
3839    /// report handler-only versus end-to-end latency. Windowed values make a
3840    /// burst visible even after a long-running node has accumulated traffic.
3841    #[cfg(feature = "logging")]
3842    fn start_audit_responder_summary_loop(&mut self) {
3843        let shutdown = self.shutdown.clone();
3844        let metrics = Arc::clone(&self.audit_responder_metrics);
3845        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3846        let handle = tokio::spawn(async move {
3847            let mut window_started = Instant::now();
3848            loop {
3849                tokio::select! {
3850                    () = shutdown.cancelled() => {
3851                        log_audit_responder_summary(
3852                            &metrics,
3853                            &semaphore,
3854                            window_started.elapsed(),
3855                        );
3856                        break;
3857                    }
3858                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3859                        log_audit_responder_summary(
3860                            &metrics,
3861                            &semaphore,
3862                            window_started.elapsed(),
3863                        );
3864                        window_started = Instant::now();
3865                    }
3866                }
3867            }
3868            debug!("Audit responder summary loop shut down");
3869        });
3870        self.task_handles.push(handle);
3871    }
3872
3873    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3874    fn start_fetch_worker(&mut self) {
3875        let p2p = Arc::clone(&self.p2p_node);
3876        let storage = Arc::clone(&self.storage);
3877        let queues = Arc::clone(&self.queues);
3878        let config = Arc::clone(&self.config);
3879        let shutdown = self.shutdown.clone();
3880        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3881        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3882        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3883        let detached_task_tracker = self.detached_task_tracker.clone();
3884        let concurrency = max_parallel_fetch();
3885
3886        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3887
3888        let handle = tokio::spawn(async move {
3889            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3890            // always recover the key — even if the inner task panics.
3891            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3892
3893            loop {
3894                // Fill up to `concurrency` slots from the queue.
3895                {
3896                    let mut q = queues.write().await;
3897                    while in_flight.len() < concurrency {
3898                        let Some(candidate) = q.dequeue_fetch() else {
3899                            break;
3900                        };
3901                        let fetch_key = candidate.key;
3902                        let Some(&source) = candidate.sources.first() else {
3903                            warn!(
3904                                "Fetch candidate {} has no sources; requeueing for verification",
3905                                hex::encode(fetch_key)
3906                            );
3907                            let _ = q.requeue_candidate_for_verification(
3908                                candidate,
3909                                config.verification_request_timeout,
3910                            );
3911                            continue;
3912                        };
3913                        q.start_dequeued_fetch(candidate, source);
3914
3915                        let p2p = Arc::clone(&p2p);
3916                        let storage = Arc::clone(&storage);
3917                        let config = Arc::clone(&config);
3918                        let token = shutdown.clone();
3919                        let tracker = detached_task_tracker.clone();
3920                        in_flight.push(Box::pin(async move {
3921                            // Tracked so shutdown() still awaits the task if
3922                            // this awaiter is dropped (e.g. the worker is
3923                            // aborted): it holds Arc<ChunkStore> and must
3924                            // not outlive the engine.
3925                            let handle = tracker.spawn(async move {
3926                                // Cancel-aware: abort when the engine shuts down.
3927                                tokio::select! {
3928                                    () = token.cancelled() => FetchOutcome {
3929                                        key: fetch_key,
3930                                        result: FetchResult::SourceFailed,
3931                                    },
3932                                    outcome = execute_single_fetch(
3933                                        p2p, storage, config, fetch_key, source,
3934                                    ) => outcome,
3935                                }
3936                            });
3937                            match handle.await {
3938                                Ok(outcome) => (outcome.key, Some(outcome)),
3939                                Err(e) => {
3940                                    error!(
3941                                        "Fetch task for {} panicked: {e}",
3942                                        hex::encode(fetch_key)
3943                                    );
3944                                    (fetch_key, None)
3945                                }
3946                            }
3947                        }));
3948                    }
3949                } // release queues write lock
3950
3951                if in_flight.is_empty() {
3952                    // No work — wait for new items or shutdown.
3953                    tokio::select! {
3954                        () = shutdown.cancelled() => break,
3955                        () = tokio::time::sleep(
3956                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3957                        ) => continue,
3958                    }
3959                }
3960
3961                // Wait for the next fetch to complete and process the result.
3962                tokio::select! {
3963                    () = shutdown.cancelled() => break,
3964                    Some((key, maybe_outcome)) = in_flight.next() => {
3965                        let mut q = queues.write().await;
3966                        let terminal = if let Some(outcome) = maybe_outcome {
3967                            match apply_fetch_result(
3968                                &mut q,
3969                                &key,
3970                                &outcome.result,
3971                                config.verification_request_timeout,
3972                            ) {
3973                                FetchFollowUp::Terminal => true,
3974                                FetchFollowUp::RequeuedForVerification => false,
3975                                FetchFollowUp::RetryFrom(next_peer) => {
3976                                    // Spawn a new fetch task for the next source.
3977                                    let p2p = Arc::clone(&p2p);
3978                                    let storage = Arc::clone(&storage);
3979                                    let config = Arc::clone(&config);
3980                                    let token = shutdown.clone();
3981                                    let tracker = detached_task_tracker.clone();
3982                                    let fetch_key = key;
3983                                    in_flight.push(Box::pin(async move {
3984                                        // Tracked for the same reason as the
3985                                        // initial fetch spawn above.
3986                                        let handle = tracker.spawn(async move {
3987                                            tokio::select! {
3988                                                () = token.cancelled() => FetchOutcome {
3989                                                    key: fetch_key,
3990                                                    result: FetchResult::SourceFailed,
3991                                                },
3992                                                outcome = execute_single_fetch(
3993                                                    p2p, storage, config, fetch_key, next_peer,
3994                                                ) => outcome,
3995                                            }
3996                                        });
3997                                        match handle.await {
3998                                            Ok(outcome) => (outcome.key, Some(outcome)),
3999                                            Err(e) => {
4000                                                error!(
4001                                                    "Fetch task for {} panicked: {e}",
4002                                                    hex::encode(fetch_key)
4003                                                );
4004                                                (fetch_key, None)
4005                                            }
4006                                        }
4007                                    }));
4008                                    false
4009                                }
4010                            }
4011                        } else {
4012                            // Task panicked — retry verification when this was
4013                            // a verified repair, otherwise reclaim the slot.
4014                            !q.requeue_fetch_for_verification(
4015                                &key,
4016                                config.verification_request_timeout,
4017                            )
4018                        };
4019
4020                        // Shrink bootstrap pending set on terminal exit.
4021                        if terminal {
4022                            drop(q); // release queues lock before acquiring bootstrap_state
4023                            if !bootstrap_state.read().await.is_drained() {
4024                                bootstrap_state.write().await.remove_key(&key);
4025                                let q = queues.read().await;
4026                                if bootstrap::check_bootstrap_drained(
4027                                    &bootstrap_state,
4028                                    &q,
4029                                )
4030                                .await
4031                                {
4032                                    complete_bootstrap(
4033                                        &is_bootstrapping,
4034                                        &bootstrap_complete_notify,
4035                                    ).await;
4036                                }
4037                            }
4038                        }
4039                    }
4040                }
4041            }
4042
4043            // Cancel and drain remaining in-flight fetches on shutdown.
4044            // The CancellationToken is already cancelled by this point, so
4045            // spawned tasks will see cancellation via their select! branches.
4046            while in_flight.next().await.is_some() {}
4047            debug!("Fetch worker shut down");
4048        });
4049        self.task_handles.push(handle);
4050    }
4051
4052    fn start_verification_worker(&mut self) {
4053        let p2p = Arc::clone(&self.p2p_node);
4054        let storage = Arc::clone(&self.storage);
4055        let queues = Arc::clone(&self.queues);
4056        let paid_list = Arc::clone(&self.paid_list);
4057        let config = Arc::clone(&self.config);
4058        let shutdown = self.shutdown.clone();
4059        let bootstrap_state = Arc::clone(&self.bootstrap_state);
4060        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4061        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4062        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4063        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4064        let recent_provers = Arc::clone(&self.recent_provers);
4065
4066        let handle = tokio::spawn(async move {
4067            loop {
4068                tokio::select! {
4069                    () = shutdown.cancelled() => break,
4070                    () = tokio::time::sleep(
4071                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
4072                    ) => {
4073                        let ctx = VerificationCycleContext {
4074                            p2p_node: &p2p,
4075                            paid_list: &paid_list,
4076                            storage: &storage,
4077                            queues: &queues,
4078                            config: &config,
4079                            bootstrap_state: &bootstrap_state,
4080                            is_bootstrapping: &is_bootstrapping,
4081                            bootstrap_complete_notify: &bootstrap_complete_notify,
4082                            last_commitment_by_peer: &last_commitment_by_peer,
4083                            ever_capable_peers: &ever_capable_peers,
4084                            recent_provers: &recent_provers,
4085                        };
4086                        run_verification_cycle(ctx).await;
4087                    }
4088                }
4089            }
4090            debug!("Verification worker shut down");
4091        });
4092        self.task_handles.push(handle);
4093    }
4094
4095    /// Gap 3: Run a one-shot bootstrap sync on startup.
4096    ///
4097    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
4098    /// (indicating the routing table is populated) before snapshotting
4099    /// close neighbors. Falls back after a timeout so bootstrap nodes
4100    /// (which have no peers and therefore never receive the event) still
4101    /// proceed.
4102    ///
4103    /// After the gate, finds close neighbors, syncs with each in
4104    /// round-robin batches, admits returned hints into the verification
4105    /// pipeline, and tracks discovered keys for bootstrap drain detection.
4106    #[allow(clippy::too_many_lines)]
4107    fn start_bootstrap_sync(
4108        &mut self,
4109        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
4110    ) {
4111        let p2p = Arc::clone(&self.p2p_node);
4112        let storage = Arc::clone(&self.storage);
4113        let paid_list = Arc::clone(&self.paid_list);
4114        let queues = Arc::clone(&self.queues);
4115        let config = Arc::clone(&self.config);
4116        let shutdown = self.shutdown.clone();
4117        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4118        let bootstrap_state = Arc::clone(&self.bootstrap_state);
4119        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4120        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
4121        let repair_proofs = Arc::clone(&self.repair_proofs);
4122        let my_commitment_state = Arc::clone(&self.commitment_state);
4123        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4124        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4125        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
4126
4127        let handle = tokio::spawn(async move {
4128            // Wait for DHT bootstrap to complete before snapshotting
4129            // neighbors. The routing table is empty until saorsa-core
4130            // finishes its FIND_NODE rounds and bucket refreshes.
4131            let gate = bootstrap::wait_for_bootstrap_complete(
4132                dht_events,
4133                config.bootstrap_complete_timeout_secs,
4134                &shutdown,
4135            )
4136            .await;
4137
4138            if gate == bootstrap::BootstrapGateResult::Shutdown {
4139                return;
4140            }
4141
4142            let self_id = *p2p.peer_id();
4143            let neighbors =
4144                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
4145                    .await;
4146
4147            if neighbors.is_empty() {
4148                info!("Bootstrap sync: no close neighbors found, marking drained");
4149                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
4150                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4151                return;
4152            }
4153
4154            let neighbor_count = neighbors.len();
4155            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
4156
4157            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
4158            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
4159                if shutdown.is_cancelled() {
4160                    break;
4161                }
4162
4163                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
4164                    batch,
4165                    &storage,
4166                    &paid_list,
4167                    &p2p,
4168                    config.close_group_size,
4169                    config.paid_list_close_group_size,
4170                )
4171                .await;
4172
4173                // Keep the batch outstanding until every response has been
4174                // admitted and bootstrap accounting is updated. The verification
4175                // worker uses this counter as a batch barrier, so it cannot race
4176                // the source aggregation below.
4177                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
4178                let bootstrapping = *is_bootstrapping.read().await;
4179
4180                let sync_futures = batch.iter().map(|peer| {
4181                    let peer = *peer;
4182                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
4183                    // Atomically snapshot + mark-gossiped for each emitted
4184                    // bootstrap request so we remain answerable for it.
4185                    let commitment = my_commitment_state
4186                        .current_for_gossip()
4187                        .map(|binding| binding.commitment().clone());
4188                    let p2p = &p2p;
4189                    let config = &config;
4190                    async move {
4191                        let outcome = neighbor_sync::sync_with_peer_with_hints(
4192                            &peer,
4193                            p2p,
4194                            config,
4195                            bootstrapping,
4196                            hints,
4197                            commitment,
4198                        )
4199                        .await;
4200                        (peer, outcome)
4201                    }
4202                });
4203                let completed = join_all(sync_futures).await;
4204
4205                // Process response metadata before exposing any of this batch's
4206                // hints to verification.
4207                for (peer, outcome) in &completed {
4208                    if let Some(outcome) = outcome {
4209                        // Ingest the peer's piggybacked commitment from the
4210                        // response (same verification as the request path).
4211                        // Bootstrap is the FIRST gossip we receive from most
4212                        // peers, so this populates last_commitment_by_peer.
4213                        //
4214                        // We intentionally do NOT trigger a gossip-audit here:
4215                        // during bootstrap this node may itself still be
4216                        // bootstrapping (audits are gated on that), and the
4217                        // close-group/RT view is not yet stable. The peer is
4218                        // audited on the first STEADY-STATE neighbor-sync round
4219                        // after bootstrap drains (request + response paths both
4220                        // trigger), which is within one sync cycle — so caching
4221                        // the commitment here is sufficient and there is no
4222                        // coverage gap (ADR-0002).
4223                        ingest_peer_commitment(
4224                            peer,
4225                            outcome.response.commitment.as_ref(),
4226                            &p2p,
4227                            &last_commitment_by_peer,
4228                            &ever_capable_peers,
4229                            &sig_verify_attempts,
4230                        )
4231                        .await; // sig_verify_attempts in scope from line ~1080
4232
4233                        if !outcome.response.bootstrapping {
4234                            record_sent_replica_hints(
4235                                peer,
4236                                &outcome.sent_replica_hints,
4237                                &repair_proofs,
4238                                &sync_cycle_epoch,
4239                            )
4240                            .await;
4241                        }
4242                    }
4243                }
4244
4245                let pending_keys: HashSet<XorName> = {
4246                    let q = queues.read().await;
4247                    q.pending_keys().into_iter().collect()
4248                };
4249                let admission_futures = completed.iter().map(async |(_, outcome)| match outcome {
4250                    Some(outcome) if !outcome.response.bootstrapping => Some(
4251                        admission::admit_hints(
4252                            &self_id,
4253                            &outcome.response.replica_hints,
4254                            &outcome.response.paid_hints,
4255                            &p2p,
4256                            &config,
4257                            &storage,
4258                            &paid_list,
4259                            &pending_keys,
4260                        )
4261                        .await,
4262                    ),
4263                    _ => None,
4264                });
4265                let admitted = join_all(admission_futures).await;
4266
4267                // Queue every peer's admitted hints under one write lock. Once
4268                // released, source-count ordering sees the complete batch.
4269                let (batch_outcomes, batch_discovered) = {
4270                    let mut q = queues.write().await;
4271                    let outcomes = completed
4272                        .iter()
4273                        .zip(admitted)
4274                        .filter_map(|((peer, _), admitted)| {
4275                            admitted.map(|admitted| {
4276                                (
4277                                    *peer,
4278                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
4279                                )
4280                            })
4281                        })
4282                        .collect::<Vec<_>>();
4283                    let live_discovered = outcomes
4284                        .iter()
4285                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
4286                        .filter(|key| q.contains_key(key))
4287                        .collect::<HashSet<_>>();
4288                    (outcomes, live_discovered)
4289                };
4290
4291                publish_bootstrap_admission_outcomes(
4292                    &bootstrap_state,
4293                    &batch_outcomes,
4294                    &batch_discovered,
4295                )
4296                .await;
4297
4298                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4299            }
4300
4301            // Check drain condition.
4302            {
4303                let q = queues.read().await;
4304                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4305                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4306                }
4307            }
4308
4309            info!("Bootstrap sync completed");
4310        });
4311        self.task_handles.push(handle);
4312    }
4313}
4314
4315// ===========================================================================
4316// Free functions for background tasks
4317// ===========================================================================
4318
4319#[cfg(feature = "logging")]
4320fn log_audit_responder_summary(
4321    metrics: &AuditResponderMetrics,
4322    semaphore: &Semaphore,
4323    window: Duration,
4324) {
4325    let snapshot = metrics.take_snapshot();
4326    if snapshot.origins.is_empty() {
4327        return;
4328    }
4329
4330    let total = snapshot.total;
4331    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4332        total.received_by_class;
4333    let global_inflight =
4334        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4335    info!(
4336        target: "ant_node::replication::audit_responder",
4337        window_ms = window.as_millis(),
4338        source_count = snapshot.origins.len(),
4339        received = total.received(),
4340        digest_received,
4341        subtree_received,
4342        byte_received,
4343        commitment_pin_received,
4344        admitted = total.admitted,
4345        global_pool_drops = total.global_pool_drops,
4346        per_peer_cap_drops = total.per_peer_cap_drops,
4347        serial_queue_drops = total.serial_queue_drops,
4348        completed = total.completed,
4349        send_failures = total.send_failures,
4350        processing_avg_ms = total.processing_avg_ms(),
4351        processing_max_ms = total.processing_max_ms,
4352        total_avg_ms = total.total_avg_ms(),
4353        total_max_ms = total.total_max_ms,
4354        global_inflight,
4355        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4356        peak_global_inflight = total.peak_global_inflight,
4357        "Audit responder summary"
4358    );
4359
4360    for (index, origin) in snapshot
4361        .origins
4362        .iter()
4363        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4364        .enumerate()
4365    {
4366        let Some(source) = origin.source else {
4367            continue;
4368        };
4369        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4370            origin.received_by_class;
4371        info!(
4372            target: "ant_node::replication::audit_responder",
4373            rank = index + 1,
4374            source = %source,
4375            received = origin.received(),
4376            digest_received,
4377            subtree_received,
4378            byte_received,
4379            commitment_pin_received,
4380            admitted = origin.admitted,
4381            global_pool_drops = origin.global_pool_drops,
4382            per_peer_cap_drops = origin.per_peer_cap_drops,
4383            serial_queue_drops = origin.serial_queue_drops,
4384            completed = origin.completed,
4385            send_failures = origin.send_failures,
4386            processing_avg_ms = origin.processing_avg_ms(),
4387            processing_max_ms = origin.processing_max_ms,
4388            total_avg_ms = origin.total_avg_ms(),
4389            total_max_ms = origin.total_max_ms,
4390            peak_global_inflight = origin.peak_global_inflight,
4391            peak_peer_inflight = origin.peak_peer_inflight,
4392            "Audit responder top origin"
4393        );
4394    }
4395}
4396
4397/// Which ceiling rejected an audit-responder admission attempt.
4398///
4399/// Stable, machine-readable so a production log-scrape can bucket drops by
4400/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4401/// single opaque "capacity reached" line; this splits the two distinct causes
4402/// so the next such investigation can tell a global-pool exhaustion (the whole
4403/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4404/// without re-instrumenting.
4405///
4406/// This branch runs a SINGLE shared audit-responder pool for all challenge
4407/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4408/// pool to distinguish here — the `kind=` log field already separates the
4409/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4410/// dedicated slow pool is later split out, add its variants here.
4411#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4412enum ResponderRejectReason {
4413    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4414    /// free; the per-peer cap was not the binding constraint.
4415    GlobalPoolFull,
4416    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4417    /// share, so the global permit was never attempted.
4418    PerPeerCapFull,
4419}
4420
4421impl ResponderRejectReason {
4422    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4423    /// frozen — production log tooling greps for them.
4424    fn as_str(self) -> &'static str {
4425        match self {
4426            Self::GlobalPoolFull => "global_pool_full",
4427            Self::PerPeerCapFull => "per_peer_cap_full",
4428        }
4429    }
4430}
4431
4432impl From<ResponderRejectReason> for AuditResponderDropReason {
4433    fn from(reason: ResponderRejectReason) -> Self {
4434        match reason {
4435            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4436            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4437        }
4438    }
4439}
4440
4441impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4442    fn from(reason: ResponderRejectReason) -> Self {
4443        match reason {
4444            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4445            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4446        }
4447    }
4448}
4449
4450/// Cumulative fresh-offer admission refusals in this process.
4451///
4452/// **Expected value in healthy operation is zero.** A node that refuses a
4453/// legitimate fresh offer does not merely shed load: the sender transmits
4454/// offers one-way and never reads the refusal, so the chunk's absence
4455/// resurfaces at the sender's delayed possession check and is charged to the
4456/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4457/// means the node is either under-provisioned for its offered load or its
4458/// admission share is mis-sized — and is accruing unearned trust damage either
4459/// way. Operators should alarm on any sustained non-zero rate.
4460///
4461/// Process-global rather than per-engine, which is exactly right in production
4462/// (one node per process) and adequate in multi-node test harnesses, where the
4463/// useful assertion is that *no* node in the fleet refused.
4464#[must_use]
4465pub fn fresh_offer_admission_refusals() -> u64 {
4466    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4467}
4468
4469/// Cumulative paid-list notification admission refusals in this process.
4470///
4471/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4472/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4473/// paid-list evidence outright rather than pushing work back onto a requester.
4474#[must_use]
4475pub fn paid_notify_admission_refusals() -> u64 {
4476    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4477}
4478
4479/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4480///
4481/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4482/// different things: this one says the node was saturated across all sources
4483/// and is genuinely under-provisioned for its offered load.
4484#[must_use]
4485pub fn fresh_offer_refusals_global_pool() -> u64 {
4486    audit_metrics::responder_admission_drops_by_ceiling(
4487        ReplicationResponderClass::FreshOffer,
4488        ResponderAdmissionCeiling::GlobalPool,
4489    )
4490}
4491
4492/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4493///
4494/// For fresh offers this usually indicts the *share's size* rather than the
4495/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4496/// node handling a client's PUT and fanning it out — so a share sized for
4497/// request/response traffic will refuse ordinary uploads.
4498#[must_use]
4499pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4500    audit_metrics::responder_admission_drops_by_ceiling(
4501        ReplicationResponderClass::FreshOffer,
4502        ResponderAdmissionCeiling::PerPeerShare,
4503    )
4504}
4505
4506/// Why an audit-responder admission attempt failed, with the decision-time
4507/// capacity counters that let a drop be logged with full context.
4508///
4509/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4510/// decision was made (the two ceilings are read under different locks, so they
4511/// are not a single atomic view), but they are exact enough to tell a saturated
4512/// node from a single self-throttling flooder.
4513#[derive(Debug, Clone, Copy)]
4514struct ResponderAdmissionFailure {
4515    reason: ResponderRejectReason,
4516    /// Global permits in use across the whole engine at decision time.
4517    global_inflight: usize,
4518    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4519    global_limit: usize,
4520    /// In-flight audit responders already held for `source` at decision time.
4521    peer_inflight: u32,
4522    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4523    peer_limit: u32,
4524}
4525
4526impl fmt::Display for ResponderAdmissionFailure {
4527    /// Renders the stable `reason=... global_inflight=... global_limit=...
4528    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4530        write!(
4531            f,
4532            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4533            self.reason.as_str(),
4534            self.global_inflight,
4535            self.global_limit,
4536            self.peer_inflight,
4537            self.peer_limit,
4538        )
4539    }
4540}
4541
4542/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4543/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4544/// spawned task ties both bounds to the task's exact lifetime — no manual
4545/// decrement to forget on an early return or panic.
4546struct ResponderGuard {
4547    _permit: tokio::sync::OwnedSemaphorePermit,
4548    _peer_slot: PeerResponderSlot,
4549    global_inflight: usize,
4550    peer_inflight: u32,
4551}
4552
4553type AuditResponderGuard = ResponderGuard;
4554type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4555
4556/// Provisional or admitted per-peer responder slot.
4557///
4558/// The slot is claimed before the global permit is attempted. Keeping that
4559/// claim under RAII means cancellation while rolling a failed admission back
4560/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4561/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4562struct PeerResponderSlot {
4563    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4564    peer: PeerId,
4565}
4566
4567#[derive(Clone)]
4568struct ReplicationMessageHandlerContext {
4569    p2p_node: Arc<P2PNode>,
4570    storage: Arc<ChunkStore>,
4571    paid_list: Arc<PaidList>,
4572    payment_verifier: Arc<PaymentVerifier>,
4573    queues: Arc<RwLock<ReplicationQueues>>,
4574    config: Arc<ReplicationConfig>,
4575    is_bootstrapping: Arc<RwLock<bool>>,
4576    bootstrap_state: Arc<RwLock<BootstrapState>>,
4577    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4578    sync_cycle_epoch: Arc<RwLock<u64>>,
4579    repair_proofs: Arc<RwLock<RepairProofs>>,
4580    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4581    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4582    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4583    my_commitment_state: Arc<ResponderCommitmentState>,
4584    gossip_audit: GossipAuditTrigger,
4585    audit_responder_semaphore: Arc<Semaphore>,
4586    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4587    audit_responder_metrics: Arc<AuditResponderMetrics>,
4588    subtree_round1: SubtreeRound1Limiter,
4589    fetch_responder_worker_semaphore: Arc<Semaphore>,
4590    fetch_responder_admission_semaphore: Arc<Semaphore>,
4591    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4592    verification_responder_worker_semaphore: Arc<Semaphore>,
4593    verification_responder_admission_semaphore: Arc<Semaphore>,
4594    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4595    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4596    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4597    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4598    fresh_offer_worker_semaphore: Arc<Semaphore>,
4599    fresh_offer_admission_semaphore: Arc<Semaphore>,
4600    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4601    fresh_offer_in_flight: FreshOfferInFlight,
4602    paid_notify_worker_semaphore: Arc<Semaphore>,
4603    paid_notify_admission_semaphore: Arc<Semaphore>,
4604    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4605    /// Pointer replication, when this node stores pointers.
4606    pointers: Option<Arc<pointer::PointerReplication>>,
4607    /// The engine's shutdown token, for detached responder work.
4608    ///
4609    /// Workers on [`Self::detached_task_tracker`] race this around their
4610    /// *network* phase only — never around a storage `spawn_blocking` await,
4611    /// where dropping the awaiter would detach a live transaction. This is
4612    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4613    /// terminate: the wait stays safe because it is now guaranteed finite.
4614    shutdown: CancellationToken,
4615    /// Shared tracker for detached work so `shutdown()` can await release of
4616    /// storage and P2P resources after all producer tasks have stopped.
4617    detached_task_tracker: TaskTracker,
4618}
4619
4620struct InboundReplicationMessage {
4621    source: PeerId,
4622    msg: ReplicationMessage,
4623    rr_message_id: Option<String>,
4624    received_at: Instant,
4625}
4626
4627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4628enum SerialQueueDropReason {
4629    Full,
4630    Closed,
4631}
4632
4633#[cfg(feature = "logging")]
4634impl SerialQueueDropReason {
4635    const fn as_str(self) -> &'static str {
4636        match self {
4637            Self::Full => "full",
4638            Self::Closed => "closed",
4639        }
4640    }
4641}
4642
4643#[derive(Debug, Clone, Copy)]
4644#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4645struct SerialQueueDrop {
4646    source: PeerId,
4647    message_class: &'static str,
4648    audit_responder_class: Option<AuditResponderClass>,
4649    queue_depth: usize,
4650    reason: SerialQueueDropReason,
4651}
4652
4653fn try_enqueue_serial_message(
4654    sender: &mpsc::Sender<InboundReplicationMessage>,
4655    inbound: InboundReplicationMessage,
4656) -> std::result::Result<(), SerialQueueDrop> {
4657    let source = inbound.source;
4658    let message_class = replication_message_class(&inbound.msg.body);
4659    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4660    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4661    sender.try_send(inbound).map_err(|error| {
4662        let (reason, dropped) = match error {
4663            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4664            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4665        };
4666        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4667        SerialQueueDrop {
4668            source,
4669            message_class,
4670            audit_responder_class,
4671            queue_depth,
4672            reason,
4673        }
4674    })
4675}
4676
4677const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4678    match body {
4679        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4680        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4681        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4682        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4683        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4684        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4685        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4686        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4687        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4688        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4689        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4690        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4691        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4692        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4693        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4694        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4695        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4696        ReplicationMessageBody::PointerFreshOffer(_) => "pointer_fresh_offer",
4697        ReplicationMessageBody::PointerHints(_) => "pointer_hints",
4698        ReplicationMessageBody::PointerFetchRequest(_) => "pointer_fetch_request",
4699        ReplicationMessageBody::PointerFetchResponse(_) => "pointer_fetch_response",
4700        ReplicationMessageBody::PointerStateRequest(_) => "pointer_state_request",
4701        ReplicationMessageBody::PointerStateResponse(_) => "pointer_state_response",
4702    }
4703}
4704
4705const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4706    match body {
4707        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4708        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4709        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4710        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4711        _ => None,
4712    }
4713}
4714
4715impl AuditResponderClass {
4716    const fn per_peer_limit(self) -> u32 {
4717        match self {
4718            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4719            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4720        }
4721    }
4722}
4723
4724fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4725    match error {
4726        RecvError::Lagged(missed) => {
4727            audit_metrics::record_replication_event_lagged(*missed);
4728            warn!(
4729                "Missed {missed} P2P events on replication branch (broadcast lag); \
4730                 replication messages may have been dropped before dispatch"
4731            );
4732            ControlFlow::Continue(())
4733        }
4734        RecvError::Closed => {
4735            // A closed broadcast channel never yields again, so the branch
4736            // would otherwise be immediately ready on every select! iteration.
4737            warn!("P2P event stream closed on replication branch; stopping message handler");
4738            ControlFlow::Break(())
4739        }
4740    }
4741}
4742
4743fn replication_payload_from_event(
4744    event: P2PEvent,
4745) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4746    let P2PEvent::Message {
4747        topic,
4748        source: Some(source),
4749        data,
4750        ..
4751    } = event
4752    else {
4753        return None;
4754    };
4755
4756    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4757    if !is_rr {
4758        return Some((source, data, matched_id, None));
4759    }
4760    if is_rr {
4761        return P2PNode::parse_request_envelope(&data)
4762            .filter(|(_, is_resp, _)| !is_resp)
4763            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4764    }
4765    None
4766}
4767
4768impl Drop for PeerResponderSlot {
4769    fn drop(&mut self) {
4770        // Decrement (and prune to keep the map bounded) without blocking the
4771        // async runtime: a short lock on a tiny map.
4772        //
4773        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4774        // with no spawn. Otherwise defer to a task — but only if a runtime is
4775        // actually current, so `Drop` during shutdown (no runtime) can never
4776        // panic. A missed decrement at shutdown is harmless: the whole map is
4777        // being dropped with the engine.
4778        let peer = self.peer;
4779        if let Ok(mut map) = self.inflight.try_write() {
4780            if let Some(n) = map.get_mut(&peer) {
4781                *n = n.saturating_sub(1);
4782                if *n == 0 {
4783                    map.remove(&peer);
4784                }
4785            }
4786            return;
4787        }
4788        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4789            let inflight = Arc::clone(&self.inflight);
4790            handle.spawn(async move {
4791                let mut map = inflight.write().await;
4792                if let Some(n) = map.get_mut(&peer) {
4793                    *n = n.saturating_sub(1);
4794                    if *n == 0 {
4795                        map.remove(&peer);
4796                    }
4797                }
4798            });
4799        }
4800    }
4801}
4802
4803/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4804/// and then a global permit. The limits are parameters so independent responder
4805/// classes can reuse the same flood-fair admission and cancellation semantics.
4806async fn admit_bounded_responder(
4807    semaphore: &Arc<Semaphore>,
4808    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4809    source: &PeerId,
4810    global_limit: usize,
4811    peer_limit: u32,
4812) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4813    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4814
4815    let admitted_peer_inflight = {
4816        let mut map = inflight.write().await;
4817        let entry = map.entry(*source).or_insert(0);
4818        if *entry >= peer_limit {
4819            let peer_inflight = *entry;
4820            drop(map);
4821            return Err(ResponderAdmissionFailure {
4822                reason: ResponderRejectReason::PerPeerCapFull,
4823                global_inflight: global_inflight(semaphore),
4824                global_limit,
4825                peer_inflight,
4826                peer_limit,
4827            });
4828        }
4829        *entry += 1;
4830        *entry
4831    };
4832
4833    let peer_slot = PeerResponderSlot {
4834        inflight: Arc::clone(inflight),
4835        peer: *source,
4836    };
4837    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4838        return Err(ResponderAdmissionFailure {
4839            reason: ResponderRejectReason::GlobalPoolFull,
4840            global_inflight: global_inflight(semaphore),
4841            global_limit,
4842            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4843            peer_limit,
4844        });
4845    };
4846
4847    Ok(ResponderGuard {
4848        _permit: permit,
4849        _peer_slot: peer_slot,
4850        global_inflight: global_inflight(semaphore),
4851        peer_inflight: admitted_peer_inflight,
4852    })
4853}
4854
4855/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4856struct SubtreeSession {
4857    commitment_hash: [u8; 32],
4858    nonce: [u8; 32],
4859    inserted: Instant,
4860    /// What round 1 bound for each pointer it proved, so round 2 serves that
4861    /// record however many updates land in between (ADR-0019).
4862    pointer_bindings: PointerBindings,
4863}
4864
4865/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4866/// read and hash, refilled continuously at
4867/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4868/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4869///
4870/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4871/// identity may ask, so it is refilled by acquiring more identities; this is
4872/// charged for work done regardless of who asked, so it is not.
4873///
4874/// Charged after the fact, with the bytes the proof actually covered: the cost
4875/// of a request is not known until the pinned commitment has been resolved and
4876/// its subtree selected, both of which happen inside the handler. Admission
4877/// therefore asks only whether the balance is positive, and a proof that costs
4878/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4879/// Carrying the debt is what makes the bound real: without it a maximal proof
4880/// would cost the same as a trivial one, since either way the next request only
4881/// has to wait for the balance to climb back above zero. With it, sustained
4882/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4883/// admitted proportionally less often.
4884struct Round1WorkBudget {
4885    /// Signed, so an over-large proof leaves debt to work off.
4886    balance: i64,
4887    last_refill: Instant,
4888}
4889
4890impl Round1WorkBudget {
4891    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4892    /// for longer than the burst takes to refill.
4893    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4894    /// Nanoseconds per second, for the sub-second part of a refill.
4895    const NANOS_PER_SEC: i64 = 1_000_000_000;
4896
4897    fn new() -> Self {
4898        Self {
4899            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4900            last_refill: Instant::now(),
4901        }
4902    }
4903
4904    /// Add the tokens accrued since the last touch, capped at the burst size.
4905    fn refill(&mut self, now: Instant) {
4906        let elapsed = now.saturating_duration_since(self.last_refill);
4907        self.last_refill = now;
4908        let whole_secs = i64::try_from(elapsed.as_secs())
4909            .unwrap_or(i64::MAX)
4910            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4911        let sub_sec = i64::from(elapsed.subsec_nanos())
4912            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4913            / Self::NANOS_PER_SEC;
4914        self.balance = self
4915            .balance
4916            .saturating_add(whole_secs.saturating_add(sub_sec))
4917            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4918    }
4919
4920    /// Whether budget remains for a new round-1 proof.
4921    fn has_budget(&mut self, now: Instant) -> bool {
4922        self.refill(now);
4923        self.balance > 0
4924    }
4925
4926    /// Charge `bytes` of completed proof work, carrying debt down to
4927    /// [`Self::MAX_DEBT`].
4928    fn charge(&mut self, bytes: i64, now: Instant) {
4929        self.refill(now);
4930        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4931    }
4932}
4933
4934/// Resource controls for the HEAVY subtree-audit round 1: a tight
4935/// admission pool separate from the light responsible/slice audits, a per-peer
4936/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4937/// challenge is only served after a matching round 1.
4938///
4939/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4940/// bounds not keyed by peer identity, and so the only one that bounds sustained
4941/// work rather than concurrency or per-identity frequency.
4942#[derive(Clone)]
4943struct SubtreeRound1Limiter {
4944    semaphore: Arc<Semaphore>,
4945    /// Global ceiling on concurrent round-1 proofs (config-driven;
4946    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4947    /// semaphore because the per-peer admission helper needs the same number.
4948    max_concurrent: usize,
4949    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4950    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4951    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4952    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4953    cooldown_interval: Duration,
4954    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4955    /// Identity-independent ceiling on sustained round-1 work.
4956    work: Arc<RwLock<Round1WorkBudget>>,
4957}
4958
4959impl SubtreeRound1Limiter {
4960    /// `max_concurrent` of 0 would wedge the responder into refusing every
4961    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4962    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4963    /// rather than to off.
4964    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4965        let max_concurrent = max_concurrent.max(1);
4966        Self {
4967            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4968            max_concurrent,
4969            inflight: Arc::new(RwLock::new(HashMap::new())),
4970            cooldown: Arc::new(RwLock::new(HashMap::new())),
4971            cooldown_interval,
4972            sessions: Arc::new(RwLock::new(HashMap::new())),
4973            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4974        }
4975    }
4976
4977    /// Charge completed round-1 proof work against the responder-wide budget.
4978    async fn charge_work(&self, content_bytes: i64) {
4979        self.work
4980            .write()
4981            .await
4982            .charge(content_bytes, Instant::now());
4983    }
4984
4985    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4986    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4987    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4988    /// drops the challenge (the remote auditor applies its own graced-timeout
4989    /// policy).
4990    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4991        let guard = admit_bounded_responder(
4992            &self.semaphore,
4993            &self.inflight,
4994            source,
4995            self.max_concurrent,
4996            MAX_SUBTREE_ROUND1_PER_PEER,
4997        )
4998        .await
4999        .ok()?;
5000        // Checked before the per-peer cooldown is stamped, so a peer refused for
5001        // want of budget is not also charged its next allowance.
5002        if !self.work.write().await.has_budget(Instant::now()) {
5003            return None; // guard drops here, releasing the permit + slot
5004        }
5005        let now = Instant::now();
5006        let mut cooldown = self.cooldown.write().await;
5007        if let Some(&last) = cooldown.get(source) {
5008            if now.duration_since(last) < self.cooldown_interval {
5009                return None; // guard drops here, releasing the permit + slot
5010            }
5011        }
5012        // Evict lapsed entries (their cooldown has expired, so they no longer
5013        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
5014        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
5015        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
5016            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
5017                cooldown.remove(&oldest);
5018            }
5019        }
5020        cooldown.insert(*source, now);
5021        Some(guard)
5022    }
5023
5024    /// Record a single-use session once a round-1 proof is built and about to be
5025    /// sent, so the matching round 2 is admitted exactly once.
5026    ///
5027    /// The session keeps what round 1 bound for each pointer it proved, while
5028    /// every live session together holds no more than
5029    /// [`MAX_SESSION_POINTER_BINDINGS`] of them. A session whose bindings do
5030    /// not fit is not opened and `false` is returned, so its proof is not
5031    /// sent and round 1 is answered `Transient` instead: the bindings of
5032    /// sessions already answered are never given up, because their round 2 is
5033    /// owed them (ADR-0019).
5034    async fn open_session(
5035        &self,
5036        source: PeerId,
5037        challenge_id: u64,
5038        commitment_hash: [u8; 32],
5039        nonce: [u8; 32],
5040        pointer_bindings: PointerBindings,
5041    ) -> bool {
5042        let now = Instant::now();
5043        let mut sessions = self.sessions.write().await;
5044        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
5045        // Checked before anything is evicted, so a session refused here costs
5046        // no other session its place.
5047        let held: usize = sessions.values().map(|e| e.pointer_bindings.len()).sum();
5048        if held.saturating_add(pointer_bindings.len()) > MAX_SESSION_POINTER_BINDINGS {
5049            return false;
5050        }
5051        if sessions.len() >= MAX_SUBTREE_SESSIONS {
5052            if let Some(oldest) = sessions
5053                .iter()
5054                .min_by_key(|(_, e)| e.inserted)
5055                .map(|(k, _)| *k)
5056            {
5057                sessions.remove(&oldest);
5058            }
5059        }
5060        sessions.insert(
5061            (source, challenge_id),
5062            SubtreeSession {
5063                commitment_hash,
5064                nonce,
5065                inserted: now,
5066                pointer_bindings,
5067            },
5068        );
5069        true
5070    }
5071
5072    /// Atomically consume the round-2 session for this exchange. `Some` iff a
5073    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
5074    /// existed (and is now removed), carrying what its round 1 bound for each
5075    /// pointer; a miss silently drops round 2 to the graced timeout lane
5076    /// (sessions are ephemeral and can be lost across a restart).
5077    async fn consume_session(
5078        &self,
5079        source: &PeerId,
5080        challenge_id: u64,
5081        commitment_hash: &[u8; 32],
5082        nonce: &[u8; 32],
5083    ) -> Option<PointerBindings> {
5084        let mut sessions = self.sessions.write().await;
5085        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
5086            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
5087                && &e.commitment_hash == commitment_hash
5088                && &e.nonce == nonce
5089        });
5090        if matches {
5091            sessions
5092                .remove(&(*source, challenge_id))
5093                .map(|e| e.pointer_bindings)
5094        } else {
5095            None
5096        }
5097    }
5098}
5099
5100/// Outcome of admitting a round-2 slice challenge.
5101enum SliceAdmission {
5102    /// Admitted: the guard holds the global permit and the per-peer slot, and
5103    /// the single-use round-1 session has been consumed, yielding what its
5104    /// round 1 bound for each pointer.
5105    Admitted(AuditResponderGuard, PointerBindings),
5106    /// Refused at a responder ceiling. The round-1 session is left INTACT.
5107    Capacity(AuditResponderAdmissionFailure),
5108    /// No live round-1 session matched this challenge.
5109    NoSession,
5110}
5111
5112/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
5113/// the single-use round-1 session.
5114///
5115/// The order is the point: a single-use token must not be spent on work that is
5116/// then refused. Consuming first and testing admission second leaves the session
5117/// destroyed by a purely local capacity drop, so the refusal is not recoverable
5118/// even in principle.
5119///
5120/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
5121/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
5122/// auditor does not currently re-send round 2 within an audit. The preserved
5123/// session is therefore not yet *recovering* an audit — it keeps a refusal
5124/// truthful (temporary means temporary) and keeps the invariant available for a
5125/// retry, rather than baking "capacity drop is permanent" into the state
5126/// machine. If an application-level retry is ruled out for good, this ordering
5127/// still costs nothing over the alternative.
5128///
5129/// Cost of the ordering: the permit and per-peer slot are held across the
5130/// session probe, which is one in-memory map lookup and no chunk work. The
5131/// per-peer cap still bounds a peer sending unsessioned challenges to the same
5132/// share it could already occupy with well-formed ones, so the admission
5133/// surface is unchanged.
5134async fn admit_slice_challenge(
5135    semaphore: &Arc<Semaphore>,
5136    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5137    round1: &SubtreeRound1Limiter,
5138    source: &PeerId,
5139    challenge: &protocol::SubtreeSliceChallenge,
5140) -> SliceAdmission {
5141    let guard =
5142        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
5143            Ok(guard) => guard,
5144            Err(failure) => return SliceAdmission::Capacity(failure),
5145        };
5146    let Some(pointer_bindings) = round1
5147        .consume_session(
5148            source,
5149            challenge.challenge_id,
5150            &challenge.expected_commitment_hash,
5151            &challenge.nonce,
5152        )
5153        .await
5154    else {
5155        // Release the permit and per-peer slot before the caller replies: no
5156        // chunk work follows, so holding them would shrink the pool for nothing.
5157        drop(guard);
5158        return SliceAdmission::NoSession;
5159    };
5160    SliceAdmission::Admitted(guard, pointer_bindings)
5161}
5162
5163/// Try to admit one audit-responder task for `source`: take a global permit AND
5164/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
5165/// its decision-time counters (caller drops the challenge, leaving the remote
5166/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
5167/// so one flooder can neither exhaust the global pool's effect on others nor
5168/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
5169/// log exactly WHY the drop happened rather than a single opaque "capacity
5170/// reached".
5171async fn admit_audit_responder(
5172    semaphore: &Arc<Semaphore>,
5173    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5174    source: &PeerId,
5175    class: AuditResponderClass,
5176) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
5177    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
5178    let peer_limit = class.per_peer_limit();
5179    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
5180}
5181
5182/// Handle an incoming replication protocol message.
5183///
5184/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
5185/// request-response path and the response must be sent via `send_response`
5186/// so saorsa-core can route it back to the waiting `send_request` caller.
5187#[allow(clippy::too_many_lines)]
5188async fn handle_replication_message(
5189    source: &PeerId,
5190    msg: ReplicationMessage,
5191    ctx: &ReplicationMessageHandlerContext,
5192    received_at: Instant,
5193    rr_message_id: Option<&str>,
5194) -> Result<()> {
5195    match msg.body {
5196        ReplicationMessageBody::FreshReplicationOffer(offer) => {
5197            dispatch_fresh_offer(
5198                *source,
5199                offer,
5200                ctx,
5201                msg.request_id,
5202                received_at,
5203                rr_message_id,
5204            )
5205            .await
5206        }
5207        ReplicationMessageBody::PaidNotify(notify) => {
5208            dispatch_paid_notify(*source, notify, ctx, received_at).await
5209        }
5210        ReplicationMessageBody::NeighborSyncRequest(request) => {
5211            let bootstrapping = *ctx.is_bootstrapping.read().await;
5212            // Phase-3 storage-bound audit: store the sender's
5213            // commitment for use as `expected_commitment_hash` in
5214            // future audits. Verify signature before storing so a peer
5215            // cannot inject a forged commitment for someone else.
5216            if let Some(target) = ingest_peer_commitment(
5217                source,
5218                request.commitment.as_ref(),
5219                &ctx.p2p_node,
5220                &ctx.last_commitment_by_peer,
5221                &ctx.ever_capable_peers,
5222                &ctx.sig_verify_attempts,
5223            )
5224            .await
5225            {
5226                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
5227            }
5228            dispatch_neighbor_sync_request(
5229                *source,
5230                request,
5231                ctx,
5232                bootstrapping,
5233                // Atomically snapshot + mark-gossiped: emitted in the sync
5234                // response, so we must stay answerable for it (ADR-0002).
5235                ctx.my_commitment_state
5236                    .current_for_gossip()
5237                    .map(|b| b.commitment().clone()),
5238                msg.request_id,
5239                received_at,
5240                rr_message_id,
5241            )
5242            .await
5243        }
5244        ReplicationMessageBody::VerificationRequest(request) => {
5245            dispatch_verification_request(
5246                *source,
5247                request,
5248                ctx,
5249                msg.request_id,
5250                received_at,
5251                rr_message_id,
5252            )
5253            .await
5254        }
5255        ReplicationMessageBody::FetchRequest(request) => {
5256            dispatch_fetch_request(
5257                *source,
5258                request,
5259                ctx,
5260                msg.request_id,
5261                received_at,
5262                rr_message_id,
5263            )
5264            .await
5265        }
5266        ReplicationMessageBody::AuditChallenge(challenge) => {
5267            // Responsible-chunk audit (audit #2) responder: answer with per-key
5268            // possession digests. This same handler also answers the
5269            // prune-confirmation audit, which sends the same `AuditChallenge`
5270            // wire message.
5271            //
5272            // Answering digests the stored bytes of every challenged key, so —
5273            // like the subtree/byte audits below — run it on a detached task off
5274            // this serial message loop. Handling it inline lets one challenge
5275            // block all other replication traffic until its digests complete
5276            // (head-of-line blocking). The same flood-fair admission applies: a
5277            // global ceiling AND a per-peer cap, dropping the challenge if either
5278            // is hit. A dropped challenge reads as a penalised timeout to the
5279            // auditor, so the caps must remain high enough for honest audit load;
5280            // the per-peer share still prevents one flooder from starving others.
5281            let class = AuditResponderClass::Digest;
5282            let guard = match admit_audit_responder(
5283                &ctx.audit_responder_semaphore,
5284                &ctx.audit_responder_inflight,
5285                source,
5286                class,
5287            )
5288            .await
5289            {
5290                Ok(guard) => guard,
5291                Err(failure) => {
5292                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
5293                    audit_metrics::record_admission_drop(class);
5294                    ctx.audit_responder_metrics
5295                        .record_drop(*source, failure.reason.into());
5296                    warn!(
5297                        target: "ant_node::replication::audit_responder",
5298                        event = "admission_dropped",
5299                        kind = "responsible",
5300                        responder_class = class.as_str(),
5301                        source = %source,
5302                        challenge_id = challenge.challenge_id,
5303                        key_count = challenge.keys.len(),
5304                        request_response = rr_message_id.is_some(),
5305                        dispatch_ms = received_at.elapsed().as_millis(),
5306                        reason = failure.reason.as_str(),
5307                        global_inflight = failure.global_inflight,
5308                        global_limit = failure.global_limit,
5309                        peer_inflight = failure.peer_inflight,
5310                        peer_limit = failure.peer_limit,
5311                        "Audit responder admission dropped"
5312                    );
5313                    return Ok(());
5314                }
5315            };
5316            let admission_global_inflight = guard.global_inflight;
5317            let admission_peer_inflight = guard.peer_inflight;
5318            ctx.audit_responder_metrics.record_admitted(
5319                *source,
5320                admission_global_inflight,
5321                admission_peer_inflight,
5322            );
5323            info!(
5324                target: "ant_node::replication::audit_responder",
5325                event = "admitted",
5326                kind = "responsible",
5327                responder_class = class.as_str(),
5328                source = %source,
5329                challenge_id = challenge.challenge_id,
5330                key_count = challenge.keys.len(),
5331                request_response = rr_message_id.is_some(),
5332                dispatch_ms = received_at.elapsed().as_millis(),
5333                global_inflight = admission_global_inflight,
5334                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5335                peer_inflight = admission_peer_inflight,
5336                peer_limit = class.per_peer_limit(),
5337                "Audit responder request admitted"
5338            );
5339            let bootstrapping = *ctx.is_bootstrapping.read().await;
5340            let dispatch_latency = received_at.elapsed();
5341            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5342            debug!(
5343                audit_type = "digest_responder",
5344                dispatch_latency_ms = dispatch_latency.as_millis(),
5345                source = %source,
5346                "Audit challenge dispatch latency measured"
5347            );
5348            let storage = Arc::clone(&ctx.storage);
5349            let p2p_node = Arc::clone(&ctx.p2p_node);
5350            let source = *source;
5351            let request_id = msg.request_id;
5352            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5353            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5354            ctx.detached_task_tracker.spawn(async move {
5355                let _guard = guard; // global permit + per-peer slot, held until done
5356                let worker_started = Instant::now();
5357                match handle_audit_challenge_msg(
5358                    &source,
5359                    &challenge,
5360                    &storage,
5361                    &p2p_node,
5362                    bootstrapping,
5363                    ReplyRoute {
5364                        request_id,
5365                        rr_message_id: rr_message_id.as_deref(),
5366                        protocol: REPLICATION_PROTOCOL_ID,
5367                    },
5368                )
5369                .await
5370                {
5371                    Ok(completion) => log_audit_responder_completion(
5372                        &responder_metrics,
5373                        source,
5374                        class,
5375                        "responsible",
5376                        challenge.challenge_id,
5377                        challenge.keys.len(),
5378                        completion.response_kind,
5379                        completion.sent,
5380                        received_at,
5381                        worker_started,
5382                        completion.processing,
5383                        completion.response_send,
5384                    ),
5385                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5386                }
5387            });
5388            Ok(())
5389        }
5390        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5391            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5392            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5393            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5394            // detached task so this serial message loop is never blocked on disk
5395            // I/O — otherwise one audit stalls all replication traffic (§5).
5396            //
5397            // A bounded, flood-fair admission restores backpressure (codex#1 +
5398            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5399            // we drop this challenge. Subtree auditors grace timeout
5400            // non-responses, so capacity drops throttle flooders without turning
5401            // into trust penalties (and one source cannot starve other peers,
5402            // since its share is capped per-peer).
5403            let class = AuditResponderClass::Subtree;
5404            info!(
5405                "Audit challenge received: kind=subtree source={source} request_response={}",
5406                rr_message_id.is_some(),
5407            );
5408            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5409            // so it uses its own tight admission pool + per-peer rate cooldown,
5410            // separate from the light responsible/slice audits, and a miss silently
5411            // drops (subtree auditors grace timeouts).
5412            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5413                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5414                warn!(
5415                    target: "ant_node::replication::audit_responder",
5416                    event = "admission_dropped",
5417                    kind = "subtree",
5418                    responder_class = class.as_str(),
5419                    source = %source,
5420                    challenge_id = challenge.challenge_id,
5421                    request_response = rr_message_id.is_some(),
5422                    dispatch_ms = received_at.elapsed().as_millis(),
5423                    reason = "heavy_pool_cooldown_or_work_budget",
5424                    "Audit responder admission dropped"
5425                );
5426                return Ok(());
5427            };
5428            let admission_global_inflight = guard.global_inflight;
5429            let admission_peer_inflight = guard.peer_inflight;
5430            ctx.audit_responder_metrics.record_admitted(
5431                *source,
5432                admission_global_inflight,
5433                admission_peer_inflight,
5434            );
5435            info!(
5436                target: "ant_node::replication::audit_responder",
5437                event = "admitted",
5438                kind = "subtree",
5439                responder_class = class.as_str(),
5440                source = %source,
5441                challenge_id = challenge.challenge_id,
5442                request_response = rr_message_id.is_some(),
5443                dispatch_ms = received_at.elapsed().as_millis(),
5444                global_inflight = admission_global_inflight,
5445                global_limit = ctx.subtree_round1.max_concurrent,
5446                peer_inflight = admission_peer_inflight,
5447                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5448                "Audit responder request admitted"
5449            );
5450            let bootstrapping = *ctx.is_bootstrapping.read().await;
5451            let storage = Arc::clone(&ctx.storage);
5452            let p2p_node = Arc::clone(&ctx.p2p_node);
5453            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5454            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5455            let source = *source;
5456            let request_id = msg.request_id;
5457            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5458            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5459            let subtree_round1 = ctx.subtree_round1.clone();
5460            ctx.detached_task_tracker.spawn(async move {
5461                let _guard = guard; // global permit + per-peer slot, held until done
5462                let worker_started = Instant::now();
5463                let processing_started = Instant::now();
5464                let storage_commitment_audit::Round1Work {
5465                    response,
5466                    content_bytes,
5467                    corrupt_keys,
5468                } = storage_commitment_audit::handle_subtree_challenge_measured_with_pointers(
5469                    &challenge,
5470                    &storage,
5471                    pointer_store.as_ref(),
5472                    p2p_node.peer_id(),
5473                    bootstrapping,
5474                    Some(&my_commitment_state),
5475                )
5476                .await;
5477                let processing = processing_started.elapsed();
5478                // Committed chunks this proof found rotted go to the chunk store's
5479                // single recheck worker. Queueing never waits, so no number of
5480                // audits over a rotted chunk can pile up cleanup work outside this
5481                // task's admission.
5482                storage.report_corrupt(&corrupt_keys);
5483                // Charge the work actually done, on EVERY outcome.
5484                //
5485                // This used to charge only the `Proof` arm, reasoning that the
5486                // rejecting paths either read nothing or reflected this node's
5487                // own broken storage. The second half of that was wrong: a
5488                // retained commitment containing one unreadable key still costs
5489                // a full run of reads and keyed-BLAKE3 passes over every leaf
5490                // before it, and then rejects. An attacker who finds such a
5491                // commitment could replay subtrees over it indefinitely for
5492                // free. The per-peer cooldown does not catch that either, since
5493                // it is escapable by rotating identity — the responder-wide
5494                // budget is the only bound that applies, so it has to see the
5495                // work. A zero charge is a no-op, so the untouched paths are
5496                // unaffected.
5497                subtree_round1.charge_work(content_bytes).await;
5498                // A round-1 proof authorizes exactly one matching round 2: open a
5499                // single-use session so a slice challenge cannot be served without
5500                // a live round-1 exchange.
5501                let mut response = response;
5502                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5503                {
5504                    let opened = subtree_round1
5505                        .open_session(
5506                            source,
5507                            challenge.challenge_id,
5508                            challenge.expected_commitment_hash,
5509                            challenge.nonce,
5510                            storage_commitment_audit::pointer_bindings(&response),
5511                        )
5512                        .await;
5513                    // A proof round 2 could not be answered for is not sent.
5514                    // The node says so instead, as for a local read error: the
5515                    // auditor's timeout lane, with no trust penalty, where
5516                    // silence would read as a peer that did not answer
5517                    // (ADR-0019).
5518                    if !opened {
5519                        protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5520                        warn!(
5521                            target: "ant_node::replication::audit_responder",
5522                            event = "admission_dropped",
5523                            kind = "subtree",
5524                            responder_class = class.as_str(),
5525                            source = %source,
5526                            challenge_id = challenge.challenge_id,
5527                            request_response = rr_message_id.is_some(),
5528                            reason = "pointer_binding_budget",
5529                            "Audit responder admission dropped"
5530                        );
5531                        response = crate::replication::protocol::SubtreeAuditResponse::Rejected {
5532                            challenge_id: challenge.challenge_id,
5533                            kind: protocol::RejectKind::Transient,
5534                            reason: "pointer binding budget full".to_string(),
5535                        };
5536                    }
5537                }
5538                let response_kind = subtree_audit_response_kind(&response);
5539                let work_items = subtree_audit_response_work_items(&response);
5540                let response_send_started = Instant::now();
5541                let sent = send_replication_response_checked(
5542                    &source,
5543                    &p2p_node,
5544                    request_id,
5545                    ReplicationMessageBody::SubtreeAuditResponse(response),
5546                    rr_message_id.as_deref(),
5547                    None,
5548                )
5549                .await;
5550                let response_send = response_send_started.elapsed();
5551                log_audit_responder_completion(
5552                    &responder_metrics,
5553                    source,
5554                    class,
5555                    "subtree",
5556                    challenge.challenge_id,
5557                    work_items,
5558                    response_kind,
5559                    sent,
5560                    received_at,
5561                    worker_started,
5562                    processing,
5563                    response_send,
5564                );
5565            });
5566            Ok(())
5567        }
5568        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5569            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5570            // block of each auditor-selected spot-check key with a Bao verified
5571            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5572            // build the proofs, so it runs off the serial loop under the light
5573            // audit pool's global and per-peer ceilings.
5574            let class = AuditResponderClass::Byte;
5575            info!(
5576                "Audit challenge received: kind=slice source={source} request_response={}",
5577                rr_message_id.is_some(),
5578            );
5579            let (guard, pointer_bindings) = match admit_slice_challenge(
5580                &ctx.audit_responder_semaphore,
5581                &ctx.audit_responder_inflight,
5582                &ctx.subtree_round1,
5583                source,
5584                &challenge,
5585            )
5586            .await
5587            {
5588                SliceAdmission::Admitted(guard, pointer_bindings) => (guard, pointer_bindings),
5589                SliceAdmission::Capacity(failure) => {
5590                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5591                    audit_metrics::record_admission_drop(class);
5592                    ctx.audit_responder_metrics
5593                        .record_drop(*source, failure.reason.into());
5594                    warn!(
5595                        target: "ant_node::replication::audit_responder",
5596                        event = "admission_dropped",
5597                        kind = "byte",
5598                        responder_class = class.as_str(),
5599                        source = %source,
5600                        challenge_id = challenge.challenge_id,
5601                        key_count = challenge.openings.len(),
5602                        request_response = rr_message_id.is_some(),
5603                        dispatch_ms = received_at.elapsed().as_millis(),
5604                        reason = failure.reason.as_str(),
5605                        global_inflight = failure.global_inflight,
5606                        global_limit = failure.global_limit,
5607                        peer_inflight = failure.peer_inflight,
5608                        peer_limit = failure.peer_limit,
5609                        "Audit responder admission dropped"
5610                    );
5611                    return Ok(());
5612                }
5613                // No live round-1 session: reply with a cheap `Transient` rejection
5614                // rather than dropping silently. Sessions are ephemeral (an honest
5615                // responder that restarts between rounds loses its session), and an
5616                // unanswered `send_request` would make saorsa-core record a
5617                // transport trust failure against that honest responder — an
5618                // ongoing effect, not just a rollout-window one. A `Transient`
5619                // reply routes the auditor to the graced timeout lane (no trust
5620                // penalty; the responder re-earns pinned credit on the next audit)
5621                // and does no chunk work, so it is not a DoS lever.
5622                SliceAdmission::NoSession => {
5623                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5624                    debug!(
5625                        "Slice challenge without a live round-1 session source={source} \
5626                         challenge_id={} → Transient reject",
5627                        challenge.challenge_id
5628                    );
5629                    send_replication_response_checked(
5630                        source,
5631                        &ctx.p2p_node,
5632                        msg.request_id,
5633                        ReplicationMessageBody::SubtreeSliceResponse(
5634                            protocol::SubtreeSliceResponse::Rejected {
5635                                challenge_id: challenge.challenge_id,
5636                                kind: protocol::RejectKind::Transient,
5637                                reason: "no live round-1 session".to_string(),
5638                            },
5639                        ),
5640                        rr_message_id,
5641                        None,
5642                    )
5643                    .await;
5644                    return Ok(());
5645                }
5646            };
5647            let admission_global_inflight = guard.global_inflight;
5648            let admission_peer_inflight = guard.peer_inflight;
5649            ctx.audit_responder_metrics.record_admitted(
5650                *source,
5651                admission_global_inflight,
5652                admission_peer_inflight,
5653            );
5654            info!(
5655                target: "ant_node::replication::audit_responder",
5656                event = "admitted",
5657                kind = "byte",
5658                responder_class = class.as_str(),
5659                source = %source,
5660                challenge_id = challenge.challenge_id,
5661                key_count = challenge.openings.len(),
5662                request_response = rr_message_id.is_some(),
5663                dispatch_ms = received_at.elapsed().as_millis(),
5664                global_inflight = admission_global_inflight,
5665                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5666                peer_inflight = admission_peer_inflight,
5667                peer_limit = class.per_peer_limit(),
5668                "Audit responder request admitted"
5669            );
5670            let bootstrapping = *ctx.is_bootstrapping.read().await;
5671            let storage = Arc::clone(&ctx.storage);
5672            let p2p_node = Arc::clone(&ctx.p2p_node);
5673            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5674            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5675            let source = *source;
5676            let request_id = msg.request_id;
5677            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5678            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5679            ctx.detached_task_tracker.spawn(async move {
5680                let _guard = guard; // global permit + per-peer slot, held until done
5681                let worker_started = Instant::now();
5682                let processing_started = Instant::now();
5683                let response =
5684                    storage_commitment_audit::handle_subtree_slice_challenge_with_pointer_bindings(
5685                        &challenge,
5686                        &storage,
5687                        pointer_store.as_ref(),
5688                        &pointer_bindings,
5689                        p2p_node.peer_id(),
5690                        bootstrapping,
5691                        Some(&my_commitment_state),
5692                    )
5693                    .await;
5694                let processing = processing_started.elapsed();
5695                let response_kind = subtree_slice_response_kind(&response);
5696                let response_send_started = Instant::now();
5697                let sent = send_replication_response_checked(
5698                    &source,
5699                    &p2p_node,
5700                    request_id,
5701                    ReplicationMessageBody::SubtreeSliceResponse(response),
5702                    rr_message_id.as_deref(),
5703                    None,
5704                )
5705                .await;
5706                let response_send = response_send_started.elapsed();
5707                log_audit_responder_completion(
5708                    &responder_metrics,
5709                    source,
5710                    class,
5711                    "byte",
5712                    challenge.challenge_id,
5713                    challenge.openings.len(),
5714                    response_kind,
5715                    sent,
5716                    received_at,
5717                    worker_started,
5718                    processing,
5719                    response_send,
5720                );
5721            });
5722            Ok(())
5723        }
5724        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5725            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5726            // only. `lookup_by_hash` is an allocation-light read over the
5727            // bounded slot set; it returns the live current commitment or any
5728            // still-answerable recently-gossiped/quoted one. A miss is reported
5729            // as `NotRetained` (graced, never confirmed) rather than an error,
5730            // so an aged-out pin can never brand an honest node.
5731            //
5732            // Reuse the audit-responder admission guard (global ceiling + per-peer
5733            // cap) so a flood of fetches cannot drive unbounded commitment
5734            // clone/encode/send work; over-limit is dropped, which the fetching
5735            // peer graces exactly like a missed audit response.
5736            let class = AuditResponderClass::CommitmentPin;
5737            let guard = match admit_audit_responder(
5738                &ctx.audit_responder_semaphore,
5739                &ctx.audit_responder_inflight,
5740                source,
5741                class,
5742            )
5743            .await
5744            {
5745                Ok(guard) => guard,
5746                Err(failure) => {
5747                    audit_metrics::record_admission_drop(class);
5748                    ctx.audit_responder_metrics
5749                        .record_drop(*source, failure.reason.into());
5750                    warn!(
5751                        target: "ant_node::replication::audit_responder",
5752                        event = "admission_dropped",
5753                        kind = "commitment_pin",
5754                        responder_class = class.as_str(),
5755                        source = %source,
5756                        challenge_id = msg.request_id,
5757                        request_response = rr_message_id.is_some(),
5758                        dispatch_ms = received_at.elapsed().as_millis(),
5759                        reason = failure.reason.as_str(),
5760                        global_inflight = failure.global_inflight,
5761                        global_limit = failure.global_limit,
5762                        peer_inflight = failure.peer_inflight,
5763                        peer_limit = failure.peer_limit,
5764                        "Audit responder admission dropped"
5765                    );
5766                    return Ok(());
5767                }
5768            };
5769            ctx.audit_responder_metrics.record_admitted(
5770                *source,
5771                guard.global_inflight,
5772                guard.peer_inflight,
5773            );
5774            info!(
5775                target: "ant_node::replication::audit_responder",
5776                event = "admitted",
5777                kind = "commitment_pin",
5778                responder_class = class.as_str(),
5779                source = %source,
5780                challenge_id = msg.request_id,
5781                request_response = rr_message_id.is_some(),
5782                dispatch_ms = received_at.elapsed().as_millis(),
5783                global_inflight = guard.global_inflight,
5784                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5785                peer_inflight = guard.peer_inflight,
5786                peer_limit = class.per_peer_limit(),
5787                "Audit responder request admitted"
5788            );
5789            let worker_started = Instant::now();
5790            let processing_started = Instant::now();
5791            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5792                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5793                |built| protocol::GetCommitmentByPinResponse::Found {
5794                    commitment: built.commitment().clone(),
5795                },
5796            );
5797            let processing = processing_started.elapsed();
5798            let response_kind = commitment_pin_response_kind(&response);
5799            let response_send_started = Instant::now();
5800            let sent = send_replication_response_checked(
5801                source,
5802                &ctx.p2p_node,
5803                msg.request_id,
5804                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5805                rr_message_id,
5806                None,
5807            )
5808            .await;
5809            let response_send = response_send_started.elapsed();
5810            log_audit_responder_completion(
5811                &ctx.audit_responder_metrics,
5812                *source,
5813                class,
5814                "commitment_pin",
5815                msg.request_id,
5816                1,
5817                response_kind,
5818                sent,
5819                received_at,
5820                worker_started,
5821                processing,
5822                response_send,
5823            );
5824            drop(guard);
5825            Ok(())
5826        }
5827        // Pointers (ADR-0016). A node that does not store pointers ignores
5828        // them, and so is never marked capable and never asked anything.
5829        ReplicationMessageBody::PointerFreshOffer(offer) => {
5830            if let Some(pointers) = &ctx.pointers {
5831                pointers.accept_offer_detached(*source, offer);
5832            }
5833            Ok(())
5834        }
5835        ReplicationMessageBody::PointerHints(hints) => {
5836            if let Some(pointers) = &ctx.pointers {
5837                pointers.handle_hints(*source, hints.hints).await;
5838            }
5839            Ok(())
5840        }
5841        ReplicationMessageBody::PointerFetchRequest(request) => {
5842            if let Some(pointers) = &ctx.pointers {
5843                pointers
5844                    .serve_fetch_detached(
5845                        *source,
5846                        request,
5847                        msg.request_id,
5848                        rr_message_id.map(ToOwned::to_owned),
5849                    )
5850                    .await;
5851            }
5852            Ok(())
5853        }
5854        ReplicationMessageBody::PointerStateRequest(request) => {
5855            if let Some(pointers) = &ctx.pointers {
5856                pointers
5857                    .serve_state_detached(
5858                        *source,
5859                        request,
5860                        msg.request_id,
5861                        rr_message_id.map(ToOwned::to_owned),
5862                    )
5863                    .await;
5864            }
5865            Ok(())
5866        }
5867        // Response messages are handled by their respective request initiators.
5868        ReplicationMessageBody::FreshReplicationResponse(_)
5869        | ReplicationMessageBody::NeighborSyncResponse(_)
5870        | ReplicationMessageBody::VerificationResponse(_)
5871        | ReplicationMessageBody::FetchResponse(_)
5872        | ReplicationMessageBody::AuditResponse(_)
5873        | ReplicationMessageBody::SubtreeAuditResponse(_)
5874        | ReplicationMessageBody::SubtreeSliceResponse(_)
5875        | ReplicationMessageBody::GetCommitmentByPinResponse(_)
5876        | ReplicationMessageBody::PointerFetchResponse(_)
5877        | ReplicationMessageBody::PointerStateResponse(_) => Ok(()),
5878    }
5879}
5880
5881// ---------------------------------------------------------------------------
5882// Per-message-type handlers
5883// ---------------------------------------------------------------------------
5884
5885/// Verify a payment proof, yielding early if the engine is shutting down.
5886///
5887/// Returns `None` when shutdown won the race, meaning no verdict was reached
5888/// and the caller must abandon the message without storing or penalising.
5889///
5890/// Payment verification is pure network I/O — an EVM round trip and, on the
5891/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5892/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5893/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5894/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5895/// is guaranteed to end.
5896///
5897/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5898/// dropping its awaiter would detach a live storage operation and break the
5899/// very contract the unbounded wait exists to uphold.
5900async fn verify_payment_until_shutdown(
5901    payment_verifier: &Arc<PaymentVerifier>,
5902    key: &XorName,
5903    proof_of_payment: &[u8],
5904    context: VerificationContext,
5905    shutdown: &CancellationToken,
5906) -> Option<Result<crate::payment::PaymentStatus>> {
5907    tokio::select! {
5908        () = shutdown.cancelled() => None,
5909        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5910            Some(result)
5911        }
5912    }
5913}
5914
5915/// A fresh offer rejected on payload shape alone.
5916struct FreshOfferRejection {
5917    /// Wire-visible reason returned to the sender.
5918    reason: String,
5919    /// Whether the sender is charged for it. Reserved for offers no honest
5920    /// node would construct, so an ordinary capacity refusal stays free.
5921    penalise: bool,
5922}
5923
5924/// Reject a fresh offer on payload shape, or return `None` to admit it.
5925///
5926/// Pure and non-blocking by construction: these are the checks answerable from
5927/// the payload alone, run on the serial message loop *before* the in-flight
5928/// claim and the admission permit, so a malformed offer can neither lock an
5929/// honest offer out of its key nor occupy one of the scarce
5930/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5931/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5932/// verification — stays on the worker.
5933///
5934/// The content-address hash is deliberately included despite costing real CPU
5935/// on the loop: it is what makes the entry below *earned* rather than merely
5936/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5937/// arrive at link speed, so a flooder can never make this loop hash faster than
5938/// it can deliver the bytes, and delivering them already cost it more than the
5939/// hash costs us. The receive path has in any case already deserialised the
5940/// same buffer.
5941///
5942/// Every rejection here is penalised. These are the conditions no honest sender
5943/// can produce — an absent, undersized, oversized, or non-matching payload — as
5944/// distinct from a capacity refusal, which is this node's own state and stays
5945/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5946/// proof that fails to verify may simply have been read against a lagging chain
5947/// view, and penalising that would charge honest senders in correlated bursts.
5948fn fresh_offer_structural_rejection(
5949    key: &XorName,
5950    data: &[u8],
5951    proof_of_payment: &[u8],
5952) -> Option<FreshOfferRejection> {
5953    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5954    // and an absent proof is the cheapest possible slot-filler, so this is the
5955    // first thing checked.
5956    if proof_of_payment.is_empty() {
5957        return Some(FreshOfferRejection {
5958            reason: "Missing proof of payment".to_string(),
5959            penalise: true,
5960        });
5961    }
5962
5963    // Bound the proof before it can be queued. The verifier applies the same
5964    // limits, but only once the offer reaches a worker — too late here, because
5965    // an entry retains a proof per queued sender, and a proof is capped on the
5966    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5967    // a byte of data and a 10 MiB "proof" would be admitted, and
5968    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5969    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5970    // admission bound exists to enforce.
5971    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5972        return Some(FreshOfferRejection {
5973            reason: format!(
5974                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5975                proof_of_payment.len(),
5976            ),
5977            penalise: true,
5978        });
5979    }
5980    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5981        return Some(FreshOfferRejection {
5982            reason: format!(
5983                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5984                proof_of_payment.len(),
5985            ),
5986            penalise: true,
5987        });
5988    }
5989
5990    // Enforce chunk size invariant: the normal PUT path rejects data larger
5991    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5992    // prevent peers from pushing oversized records through replication.
5993    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5994        return Some(FreshOfferRejection {
5995            reason: format!(
5996                "Data size {} exceeds maximum chunk size {}",
5997                data.len(),
5998                crate::ant_protocol::MAX_CHUNK_SIZE,
5999            ),
6000            penalise: true,
6001        });
6002    }
6003
6004    // Mirror the normal PUT path: the advertised key must be the content
6005    // address of the supplied bytes. Ordered last so an oversized payload is
6006    // refused without being hashed.
6007    //
6008    // This is the check that makes the entry safe to open, and safe for later
6009    // offers to be folded into. Until it passes, the sender has only *asserted*
6010    // an association between the key and the bytes. Opening an entry on an
6011    // assertion would let any peer that knows a key — every recipient of its
6012    // `PaidNotify`, not just the close group — seize it with junk; folding a
6013    // later offer into an entry on an assertion would be worse still, since the
6014    // handler tries each queued proof against the *opener's* bytes and would be
6015    // storing bytes nobody offered for that proof.
6016    let computed_key = crate::client::compute_address(data);
6017    if computed_key != *key {
6018        return Some(FreshOfferRejection {
6019            reason: format!(
6020                "Content address mismatch: expected {}, computed {}",
6021                hex::encode(key),
6022                hex::encode(computed_key),
6023            ),
6024            penalise: true,
6025        });
6026    }
6027
6028    None
6029}
6030
6031/// Tell `source` its offer for `key` was not taken.
6032///
6033/// Note the sender does not currently read this: `fresh::send_fresh_offers` uses
6034/// one-way `send_message`, so the refusal is observed only as a later absence by
6035/// the delayed possession check. Recorded in ADR-0005 as a known gap.
6036async fn refuse_fresh_offer(
6037    source: &PeerId,
6038    key: XorName,
6039    reason: String,
6040    ctx: &ReplicationMessageHandlerContext,
6041    request_id: u64,
6042    rr_message_id: Option<&str>,
6043) {
6044    send_replication_response(
6045        source,
6046        &ctx.p2p_node,
6047        request_id,
6048        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6049            key,
6050            reason,
6051        }),
6052        rr_message_id,
6053    )
6054    .await;
6055}
6056
6057/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
6058/// the sender when the defect is one no honest node could produce.
6059///
6060/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
6061/// two say opposite things: this is the sender's fault, that one is ours.
6062async fn refuse_malformed_fresh_offer(
6063    source: &PeerId,
6064    key: XorName,
6065    rejection: FreshOfferRejection,
6066    ctx: &ReplicationMessageHandlerContext,
6067    request_id: u64,
6068    rr_message_id: Option<&str>,
6069) {
6070    if rejection.penalise {
6071        warn!(
6072            "Rejecting fresh offer for key {} from {source}: {}",
6073            hex::encode(key),
6074            rejection.reason
6075        );
6076        ctx.p2p_node
6077            .report_trust_event(
6078                source,
6079                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6080            )
6081            .await;
6082    } else {
6083        debug!(
6084            "Fresh offer for {} from {source} refused before admission: {}",
6085            hex::encode(key),
6086            rejection.reason
6087        );
6088    }
6089    refuse_fresh_offer(
6090        source,
6091        key,
6092        rejection.reason,
6093        ctx,
6094        request_id,
6095        rr_message_id,
6096    )
6097    .await;
6098}
6099
6100/// Tell senders whose proofs joined an entry that was torn down before a handler
6101/// ever ran for it.
6102///
6103/// Only reachable in the window between opening an entry and failing to take an
6104/// admission permit. Their proofs are answered rather than dropped with the
6105/// entry, so the refusal count reflects what actually happened.
6106async fn refuse_stranded_fresh_offers(
6107    key: XorName,
6108    stranded: Vec<FreshOfferAttempt>,
6109    ctx: &ReplicationMessageHandlerContext,
6110) {
6111    for attempt in stranded {
6112        refuse_fresh_offer(
6113            &attempt.source,
6114            key,
6115            "Receiver at fresh-offer capacity".to_string(),
6116            ctx,
6117            attempt.request_id,
6118            attempt.rr_message_id.as_deref(),
6119        )
6120        .await;
6121    }
6122}
6123
6124/// Admit a fresh offer for handling on a worker, or refuse it.
6125///
6126/// This runs on the serial non-audit message loop, so it must stay cheap: every
6127/// path here is a set insert, a permit try, or a small response send. The offer
6128/// itself — an on-chain payment verification and a multi-MiB write — always
6129/// runs on a tracked worker task, never inline, because stalling this loop backs
6130/// up the inbound queue and ultimately drops replication messages wholesale.
6131///
6132/// Admission is bounded **per source** as well as globally
6133/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
6134/// hold every slot, and since a refusal is later read as absence by the
6135/// sender's delayed possession check, the resulting refusals land as
6136/// audit-severity penalties on this node rather than on the flooder.
6137///
6138/// The structurally-invalid checks run **before** the entry is opened and before
6139/// the permit is taken, so junk can neither seize a key nor occupy a slot for
6140/// the duration of a payment verification.
6141///
6142/// Only the offer that *opens* an entry costs a permit and a worker. Later
6143/// offers for the same key contribute their proof and are answered by whatever
6144/// the opener's handler concludes, which is what keeps the routine
6145/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
6146/// one verification per key.
6147async fn dispatch_fresh_offer(
6148    source: PeerId,
6149    offer: protocol::FreshReplicationOffer,
6150    ctx: &ReplicationMessageHandlerContext,
6151    request_id: u64,
6152    received_at: Instant,
6153    rr_message_id: Option<&str>,
6154) -> Result<()> {
6155    if let Some(rejection) =
6156        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
6157    {
6158        refuse_malformed_fresh_offer(
6159            &source,
6160            offer.key,
6161            rejection,
6162            ctx,
6163            request_id,
6164            rr_message_id,
6165        )
6166        .await;
6167        return Ok(());
6168    }
6169
6170    // Join the work already in flight for this key before taking an admission
6171    // permit, so the duplicates a single client PUT produces cost one permit
6172    // between them rather than one each.
6173    //
6174    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
6175    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
6176    // already held for the key. That is what lets its payload be dropped here
6177    // and only its proof retained: the handler will try that proof against the
6178    // bytes it already has.
6179    let key = offer.key;
6180    let admission_outcome = FreshOfferEntryGuard::admit(
6181        &ctx.fresh_offer_in_flight,
6182        offer,
6183        source,
6184        request_id,
6185        rr_message_id.map(ToOwned::to_owned),
6186        received_at,
6187    );
6188    let mut entry = match admission_outcome {
6189        FreshOfferAdmission::Opened(entry) => entry,
6190        FreshOfferAdmission::Joined => {
6191            // No response yet: this proof has not been judged. The handler that
6192            // owns the key answers every queued sender once it settles.
6193            debug!(
6194                "Fresh offer for {} from {source} queued behind the handler already \
6195                 holding the key",
6196                hex::encode(key)
6197            );
6198            return Ok(());
6199        }
6200        // Surplus, not suspect: the proofs already queued are enough to place
6201        // the record, so neither case is charged as misbehaviour.
6202        surplus => {
6203            debug!(
6204                "Fresh offer for {} from {source} refused: {}",
6205                hex::encode(key),
6206                surplus.surplus_reason()
6207            );
6208            refuse_fresh_offer(
6209                &source,
6210                key,
6211                "Duplicate offer already in flight".to_string(),
6212                ctx,
6213                request_id,
6214                rr_message_id,
6215            )
6216            .await;
6217            return Ok(());
6218        }
6219    };
6220
6221    let admission = match admit_bounded_responder(
6222        &ctx.fresh_offer_admission_semaphore,
6223        &ctx.fresh_offer_responder_inflight,
6224        &source,
6225        FRESH_OFFER_MAX_OUTSTANDING,
6226        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
6227    )
6228    .await
6229    {
6230        Ok(guard) => guard,
6231        Err(failure) => {
6232            audit_metrics::record_responder_admission_drop(
6233                ReplicationResponderClass::FreshOffer,
6234                failure.reason.into(),
6235            );
6236            // WARN, not DEBUG: a healthy node should never refuse a legitimate
6237            // fresh offer. The sender does not read this refusal, so it
6238            // resurfaces as a missing key at the delayed possession check and
6239            // is charged to US at audit severity. Log the binding ceiling
6240            // locally; the wire reason stays generic so a probing peer cannot
6241            // map out this node's live occupancy.
6242            warn!(
6243                responder_class = "fresh_offer",
6244                source = %source,
6245                key = %hex::encode(key),
6246                "Fresh offer refused at admission; this node will be penalised for the \
6247                 resulting absence: {failure}"
6248            );
6249            // Release the key explicitly rather than on drop, so the next offer
6250            // opens a fresh entry rather than queueing behind a handler that was
6251            // never spawned — and so any proof that joined in the window between
6252            // opening the entry and failing here is answered rather than
6253            // discarded with it.
6254            let stranded = entry.release();
6255            refuse_fresh_offer(
6256                &source,
6257                key,
6258                "Receiver at fresh-offer capacity".to_string(),
6259                ctx,
6260                request_id,
6261                rr_message_id,
6262            )
6263            .await;
6264            refuse_stranded_fresh_offers(key, stranded, ctx).await;
6265            return Ok(());
6266        }
6267    };
6268
6269    let ctx = ctx.clone();
6270    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
6271    // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
6272    // those references be released before the caller reopens the environment.
6273    ctx.detached_task_tracker
6274        .clone()
6275        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
6276    Ok(())
6277}
6278
6279/// Body of one tracked fresh-offer worker: drive one key to a verdict.
6280///
6281/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
6282/// A started handler is never cancelled: `storage.put()` awaits
6283/// `spawn_blocking`, and dropping that awaiter would detach the live storage
6284/// transaction. Shutdown responsiveness comes from the closed worker semaphore
6285/// and from `handle_fresh_offer` racing the token around payment verification.
6286///
6287/// Works down the key's queued proofs rather than judging the key on the first
6288/// one. A proof that fails to establish payment disqualifies its *sender*, not
6289/// the record: the bytes are content-addressed and identical across every offer,
6290/// so the next sender's proof is tried against the copy already in hand — no
6291/// second payload, no second permit, no refetch. Only when a failure is about
6292/// the key itself (not responsible, no capacity, shutting down) does rotating
6293/// become pointless, because every remaining proof would meet the same wall.
6294async fn run_fresh_offer_worker(
6295    key: XorName,
6296    mut entry: Box<FreshOfferEntryGuard>,
6297    ctx: ReplicationMessageHandlerContext,
6298    admission: ResponderGuard,
6299) {
6300    // The admission permit is released on completion, freeing the payload's
6301    // memory budget and the opening source's per-peer share. The entry releases
6302    // the key itself, either as the queue empties or on drop.
6303    let _admission = admission;
6304    let received_at = entry.received_at();
6305    // Wait for a worker slot here rather than in the caller. The worker bound
6306    // caps concurrent EVM and storage pressure; making the message loop wait on
6307    // it is what put that pressure back on the loop.
6308    //
6309    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
6310    // path for offers still queued behind a worker when the engine stops — not
6311    // dead code.
6312    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
6313        .acquire_owned()
6314        .await
6315    else {
6316        debug!(
6317            "Fresh offer for {} dropped: worker pool shut down",
6318            hex::encode(key)
6319        );
6320        return;
6321    };
6322    // Fresh offers are fire-and-forget (`send_message`), so there is no
6323    // requester deadline to honour and a late store is still genuinely useful.
6324    // The threshold is the point past which the offer has already cost us what
6325    // it was going to cost: the possession check (ADR-0003) has run by then and
6326    // charged the absence to this node, and it does not re-offer the key —
6327    // repair comes later from neighbor sync. Shedding here trades a copy that
6328    // would have arrived after the penalty for the multi-MiB payload it is
6329    // holding, and keeps a backlog from outliving its own admission bound.
6330    //
6331    // Note this is a memory-pressure decision, not a redundancy one: the copy
6332    // is late, not useless, so on a node with headroom finishing it would still
6333    // beat waiting for neighbor sync.
6334    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
6335        debug!(
6336            responder_class = "fresh_offer",
6337            key = %hex::encode(key),
6338            request_age_ms = received_at.elapsed().as_millis(),
6339            "Superseded fresh offer shed at dequeue"
6340        );
6341        return;
6342    }
6343
6344    let mut verdict = FreshOfferOutcome::Abandoned;
6345    while let Some(attempt) = entry.next_attempt() {
6346        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
6347            Ok(outcome) => {
6348                verdict = outcome;
6349                match outcome {
6350                    // Settled: the record is down and every remaining sender
6351                    // wanted exactly that. Abandoned: the key cannot be placed
6352                    // by anyone right now, so the proofs behind this one would
6353                    // fail identically. Either way there is nothing left to try.
6354                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
6355                    // This sender's claim to have paid did not hold up. Say so
6356                    // to that sender alone and try the next proof.
6357                    FreshOfferOutcome::ProofRejected => {}
6358                }
6359            }
6360            Err(e) => {
6361                debug!(
6362                    "Fresh replication offer for {} from {} error: {e}",
6363                    hex::encode(key),
6364                    attempt.source
6365                );
6366                verdict = FreshOfferOutcome::Abandoned;
6367                break;
6368            }
6369        }
6370    }
6371
6372    // Answer the senders whose proofs were never reached. A stored record is
6373    // what they were asking for, so it is an acceptance even though their own
6374    // proof went untested.
6375    let unreached = entry.release();
6376    if unreached.is_empty() {
6377        return;
6378    }
6379    let response = match verdict {
6380        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
6381        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
6382            FreshReplicationResponse::Rejected {
6383                key,
6384                reason: "Record could not be stored from any offered proof".to_string(),
6385            }
6386        }
6387    };
6388    for attempt in unreached {
6389        send_replication_response(
6390            &attempt.source,
6391            &ctx.p2p_node,
6392            attempt.request_id,
6393            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
6394            attempt.rr_message_id.as_deref(),
6395        )
6396        .await;
6397    }
6398}
6399
6400/// What one proof concluded, and whether another proof for the same key is worth
6401/// trying.
6402///
6403/// The distinction the worker acts on is *what the failure was about*. A
6404/// rejected proof is a statement about its sender; anything else is a statement
6405/// about the key or this node, which no other sender's proof can change.
6406#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6407enum FreshOfferOutcome {
6408    /// The record is stored. The key is done.
6409    Settled,
6410    /// This proof did not establish payment. A different sender's proof for the
6411    /// same bytes may still succeed.
6412    ProofRejected,
6413    /// Nothing about this key can succeed right now — not responsible, no disk,
6414    /// shutting down, or a write that failed. Rotating repeats the failure.
6415    Abandoned,
6416}
6417
6418// A linear sequence of protocol steps — structural recheck, responsibility,
6419// capacity, payment, write — each with its own refusal response. Splitting it
6420// would scatter one decision across several functions.
6421#[allow(clippy::too_many_lines)]
6422async fn handle_fresh_offer(
6423    key: &XorName,
6424    data: &[u8],
6425    attempt: &FreshOfferAttempt,
6426    ctx: &ReplicationMessageHandlerContext,
6427) -> Result<FreshOfferOutcome> {
6428    let source = &attempt.source;
6429    let request_id = attempt.request_id;
6430    let rr_message_id = attempt.rr_message_id.as_deref();
6431    let p2p_node = &ctx.p2p_node;
6432    let config = &ctx.config;
6433    let self_id = *p2p_node.peer_id();
6434
6435    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6436    // proof, bad proof size, oversized payload, content-address mismatch —
6437    // before opening the entry or taking an admission permit, so nothing
6438    // reaching a worker should trip them. Kept so the handler is correct in
6439    // isolation. Note this re-checks the *pairing* actually being used: these
6440    // bytes against this attempt's proof.
6441    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6442    {
6443        if rejection.penalise {
6444            warn!(
6445                "Rejecting fresh offer for key {}: {}",
6446                hex::encode(key),
6447                rejection.reason
6448            );
6449            p2p_node
6450                .report_trust_event(
6451                    source,
6452                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6453                )
6454                .await;
6455        }
6456        send_replication_response(
6457            source,
6458            p2p_node,
6459            request_id,
6460            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6461                key: *key,
6462                reason: rejection.reason,
6463            }),
6464            rr_message_id,
6465        )
6466        .await;
6467        // Structurally invalid is a fact about this attempt, not the key.
6468        return Ok(FreshOfferOutcome::ProofRejected);
6469    }
6470
6471    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6472    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6473    // the same width client PUTs use), not just the close group plus a small
6474    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6475    // table may still list closer full nodes it hasn't evicted yet, ranking it
6476    // outside the narrow window in its own view; the wider accept window absorbs
6477    // that transient skew so the chunk still lands. Retention (pruning) stays at
6478    // `storage_admission_width`, so steady-state replication is unchanged.
6479    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6480    {
6481        send_replication_response(
6482            source,
6483            p2p_node,
6484            request_id,
6485            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6486                key: *key,
6487                reason: "Not in storage-admission range for this key".to_string(),
6488            }),
6489            rr_message_id,
6490        )
6491        .await;
6492        // About the key and this node's place in the routing table, not about
6493        // the sender: every queued proof would be refused identically.
6494        return Ok(FreshOfferOutcome::Abandoned);
6495    }
6496
6497    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6498    // never store this record, so reject it before the expensive payment
6499    // verification (EVM on-chain query / merkle pool work) rather than verifying
6500    // and only then failing at `storage.put` below. Reuses the cached capacity
6501    // check (passing results only, so freed space is detected promptly), and the
6502    // store path keeps its own check as defence-in-depth.
6503    if let Err(e) = ctx.storage.check_capacity() {
6504        info!(
6505            target: "ant_node::storage::disk_precheck",
6506            key = %hex::encode(key),
6507            "Rejecting fresh replication offer before payment verification: {e}"
6508        );
6509        send_replication_response(
6510            source,
6511            p2p_node,
6512            request_id,
6513            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6514                key: *key,
6515                reason: e.to_string(),
6516            }),
6517            rr_message_id,
6518        )
6519        .await;
6520        // A full disk is this node's condition, not the sender's.
6521        return Ok(FreshOfferOutcome::Abandoned);
6522    }
6523
6524    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6525    // part of the immediate write fan-out: this receiver is about to store the
6526    // record as if the client had PUT it here directly. Storage admission
6527    // was checked above before proof work. FreshReplication verification is
6528    // identical to ClientPut — store-strength cache semantics, paid-quote
6529    // issuer K-closeness checks for single-node proofs, merkle candidate
6530    // closeness for merkle proofs, and the same price-floor policy — the
6531    // distinct context only labels price-floor telemetry.
6532    let Some(verification) = verify_payment_until_shutdown(
6533        &ctx.payment_verifier,
6534        key,
6535        &attempt.proof_of_payment,
6536        fresh_offer_payment_context(),
6537        &ctx.shutdown,
6538    )
6539    .await
6540    else {
6541        debug!(
6542            "Fresh offer for {} from {source} abandoned: engine shutting down \
6543             during payment verification",
6544            hex::encode(key)
6545        );
6546        return Ok(FreshOfferOutcome::Abandoned);
6547    };
6548    match verification {
6549        Ok(status) if status.can_store() => {
6550            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6551        }
6552        // The chain has no record of this payment. That is a statement about
6553        // *this sender's* proof, so the key rotates to the next one rather than
6554        // being written off — the whole point of queueing them.
6555        //
6556        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6557        // not "definitively unpaid", so a lagging or reorganising chain view
6558        // renders honest senders indistinguishable from forgers, and penalising
6559        // would land on the entire close group at once. The structural checks in
6560        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6561        // because those cannot be produced by an honest sender at all.
6562        Ok(_) => {
6563            debug!(
6564                "Fresh offer for {} from {source}: no payment found for this proof",
6565                hex::encode(key)
6566            );
6567            send_replication_response(
6568                source,
6569                p2p_node,
6570                request_id,
6571                ReplicationMessageBody::FreshReplicationResponse(
6572                    FreshReplicationResponse::Rejected {
6573                        key: *key,
6574                        reason: "Payment verification failed: payment required".to_string(),
6575                    },
6576                ),
6577                rr_message_id,
6578            )
6579            .await;
6580            return Ok(FreshOfferOutcome::ProofRejected);
6581        }
6582        // A verification *error* is usually ours — an unreachable or failing EVM
6583        // endpoint — so it is neither penalised nor treated as this sender's
6584        // fault. Another proof still gets its turn, since the next call may well
6585        // succeed against a recovered endpoint.
6586        Err(e) => {
6587            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6588            send_replication_response(
6589                source,
6590                p2p_node,
6591                request_id,
6592                ReplicationMessageBody::FreshReplicationResponse(
6593                    FreshReplicationResponse::Rejected {
6594                        key: *key,
6595                        reason: format!("Payment verification error: {e}"),
6596                    },
6597                ),
6598                rr_message_id,
6599            )
6600            .await;
6601            return Ok(FreshOfferOutcome::ProofRejected);
6602        }
6603    }
6604
6605    // Rule 6: add to PaidForList.
6606    if let Err(e) = ctx.paid_list.insert(key).await {
6607        warn!("Failed to add key to PaidForList: {e}");
6608    }
6609
6610    // Store the record.
6611    match ctx.storage.put(key, data).await {
6612        Ok(_) => {
6613            send_replication_response(
6614                source,
6615                p2p_node,
6616                request_id,
6617                ReplicationMessageBody::FreshReplicationResponse(
6618                    FreshReplicationResponse::Accepted { key: *key },
6619                ),
6620                rr_message_id,
6621            )
6622            .await;
6623            Ok(FreshOfferOutcome::Settled)
6624        }
6625        Err(e) => {
6626            send_replication_response(
6627                source,
6628                p2p_node,
6629                request_id,
6630                ReplicationMessageBody::FreshReplicationResponse(
6631                    FreshReplicationResponse::Rejected {
6632                        key: *key,
6633                        reason: e.to_string(),
6634                    },
6635                ),
6636                rr_message_id,
6637            )
6638            .await;
6639            // The payment was good and the write still failed, so this is local
6640            // storage trouble that another proof cannot get around.
6641            Ok(FreshOfferOutcome::Abandoned)
6642        }
6643    }
6644}
6645
6646/// Admit a paid-list notification for handling on a worker, or drop it.
6647///
6648/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6649/// meant one message could park every other non-audit message behind a full
6650/// payment verification. That verification is not a bounded local computation:
6651/// on the merkle path it performs an iterative Kademlia lookup capped only by
6652/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6653/// the loop for minutes while the bounded inbound queue behind it overflowed
6654/// and dropped unrelated replication traffic wholesale.
6655///
6656/// It now follows the same detached-responder pattern as neighbor sync and
6657/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6658/// when stale, and run on a tracked worker.
6659///
6660/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6661/// refused notify is simply dropped. The sender's own paid-list convergence
6662/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6663/// the recovery path, exactly as for a notify lost in transit.
6664async fn dispatch_paid_notify(
6665    source: PeerId,
6666    notify: protocol::PaidNotify,
6667    ctx: &ReplicationMessageHandlerContext,
6668    received_at: Instant,
6669) -> Result<()> {
6670    let admission = match admit_bounded_responder(
6671        &ctx.paid_notify_admission_semaphore,
6672        &ctx.paid_notify_responder_inflight,
6673        &source,
6674        PAID_NOTIFY_MAX_OUTSTANDING,
6675        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6676    )
6677    .await
6678    {
6679        Ok(guard) => guard,
6680        Err(failure) => {
6681            audit_metrics::record_responder_admission_drop(
6682                ReplicationResponderClass::PaidNotify,
6683                failure.reason.into(),
6684            );
6685            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6686            // so a refusal discards durable paid-list evidence outright rather
6687            // than pushing work back onto a requester.
6688            warn!(
6689                responder_class = "paid_notify",
6690                source = %source,
6691                key = %hex::encode(notify.key),
6692                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6693            );
6694            return Ok(());
6695        }
6696    };
6697
6698    let ctx = ctx.clone();
6699    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6700    // Deliberately NOT the verification request deadline used by the
6701    // request/response responders. Nobody is waiting on a notify, and shedding
6702    // one discards durable paid-list evidence rather than a reply a requester
6703    // has already given up on. The threshold is instead the point at which the
6704    // pull path would have learned the same fact anyway: one slow-cadence
6705    // neighbor-sync interval, after which the verification cycle's paid-list
6706    // quorum makes this notify genuinely redundant.
6707    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6708    ctx.detached_task_tracker.clone().spawn(async move {
6709        let _admission = admission;
6710        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6711        // still queued behind a worker when the engine stops.
6712        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6713            debug!("Paid notify from {source} dropped: worker pool shut down");
6714            return;
6715        };
6716        if request_is_stale(received_at, queue_max_age) {
6717            debug!(
6718                responder_class = "paid_notify",
6719                source = %source,
6720                request_age_ms = received_at.elapsed().as_millis(),
6721                "Redundant paid notify shed at dequeue"
6722            );
6723            return;
6724        }
6725        if let Err(e) = handle_paid_notify(
6726            &source,
6727            &notify,
6728            &ctx.paid_list,
6729            &ctx.payment_verifier,
6730            &ctx.p2p_node,
6731            &ctx.config,
6732            &ctx.shutdown,
6733        )
6734        .await
6735        {
6736            debug!("Paid notify from {source} error: {e}");
6737        }
6738    });
6739
6740    Ok(())
6741}
6742
6743async fn handle_paid_notify(
6744    _source: &PeerId,
6745    notify: &protocol::PaidNotify,
6746    paid_list: &Arc<PaidList>,
6747    payment_verifier: &Arc<PaymentVerifier>,
6748    p2p_node: &Arc<P2PNode>,
6749    config: &ReplicationConfig,
6750    shutdown: &CancellationToken,
6751) -> Result<()> {
6752    let self_id = *p2p_node.peer_id();
6753
6754    // Rule 3: validate PoP presence before adding.
6755    if notify.proof_of_payment.is_empty() {
6756        return Ok(());
6757    }
6758
6759    // Check if we're in PaidCloseGroup for this key.
6760    if !admission::is_in_paid_close_group(
6761        &self_id,
6762        &notify.key,
6763        p2p_node,
6764        config.paid_list_close_group_size,
6765    )
6766    .await
6767    {
6768        return Ok(());
6769    }
6770
6771    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6772    // paid-list metadata, so local paid-list close-group membership was checked
6773    // above before proof work. The verifier then runs the same payment proof
6774    // checks as ClientPut while writing a paid-list-strength cache entry.
6775    let Some(verification) = verify_payment_until_shutdown(
6776        payment_verifier,
6777        &notify.key,
6778        &notify.proof_of_payment,
6779        paid_notify_payment_context(),
6780        shutdown,
6781    )
6782    .await
6783    else {
6784        debug!(
6785            "Paid notify for {} abandoned: engine shutting down during payment \
6786             verification",
6787            hex::encode(notify.key)
6788        );
6789        return Ok(());
6790    };
6791    match verification {
6792        Ok(status) if status.can_store() => {
6793            debug!(
6794                "PoP validated for paid notify key {}",
6795                hex::encode(notify.key)
6796            );
6797        }
6798        Ok(_) => {
6799            warn!(
6800                "Paid notify rejected: payment required for key {}",
6801                hex::encode(notify.key)
6802            );
6803            return Ok(());
6804        }
6805        Err(e) => {
6806            warn!(
6807                "PoP verification error for paid notify key {}: {e}",
6808                hex::encode(notify.key)
6809            );
6810            return Ok(());
6811        }
6812    }
6813
6814    if let Err(e) = paid_list.insert(&notify.key).await {
6815        warn!("Failed to add paid notify key to PaidForList: {e}");
6816    }
6817
6818    Ok(())
6819}
6820
6821#[allow(clippy::too_many_arguments)]
6822async fn dispatch_neighbor_sync_request(
6823    source: PeerId,
6824    request: protocol::NeighborSyncRequest,
6825    ctx: &ReplicationMessageHandlerContext,
6826    is_bootstrapping: bool,
6827    my_commitment: Option<StorageCommitment>,
6828    request_id: u64,
6829    received_at: Instant,
6830    rr_message_id: Option<&str>,
6831) -> Result<()> {
6832    let guard = match admit_bounded_responder(
6833        &ctx.neighbor_sync_responder_admission_semaphore,
6834        &ctx.neighbor_sync_responder_inflight,
6835        &source,
6836        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6837        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6838    )
6839    .await
6840    {
6841        Ok(guard) => guard,
6842        Err(failure) => {
6843            audit_metrics::record_responder_admission_drop(
6844                ReplicationResponderClass::NeighborSync,
6845                failure.reason.into(),
6846            );
6847            warn!(
6848                responder_class = "neighbor_sync",
6849                source = %source,
6850                "Neighbor-sync response dropped at admission: {failure}"
6851            );
6852            return Ok(());
6853        }
6854    };
6855    let pointers = ctx.pointers.clone();
6856    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6857    let p2p_node = Arc::clone(&ctx.p2p_node);
6858    let storage = Arc::clone(&ctx.storage);
6859    let paid_list = Arc::clone(&ctx.paid_list);
6860    let queues = Arc::clone(&ctx.queues);
6861    let config = Arc::clone(&ctx.config);
6862    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6863    let sync_history = Arc::clone(&ctx.sync_history);
6864    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6865    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6866    let request_timeout = ctx.config.verification_request_timeout;
6867    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6868    ctx.detached_task_tracker.spawn(async move {
6869        let _guard = guard;
6870        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6871            debug!(
6872                responder_class = "neighbor_sync",
6873                source = %source,
6874                "Neighbor-sync responder worker pool closed before dequeue"
6875            );
6876            return;
6877        };
6878        if request_is_stale(received_at, request_timeout) {
6879            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6880            debug!(
6881                responder_class = "neighbor_sync",
6882                source = %source,
6883                request_age_ms = received_at.elapsed().as_millis(),
6884                "Stale neighbor-sync request shed at dequeue"
6885            );
6886            return;
6887        }
6888        // A peer whose sync request is admitted and fresh gets our pointer
6889        // hints as well, including a node that is bootstrapping, which is how
6890        // it learns the pointers it should hold. Only such a request: each
6891        // answer scans every pointer held, and a refused or stale one must
6892        // cost nothing.
6893        if let Some(pointers) = &pointers {
6894            pointers.answer_sync_with_hints(source);
6895        }
6896        if let Err(e) = handle_neighbor_sync_request(
6897            &source,
6898            &request,
6899            &p2p_node,
6900            &storage,
6901            &paid_list,
6902            &queues,
6903            &config,
6904            is_bootstrapping,
6905            &bootstrap_state,
6906            &sync_history,
6907            &sync_cycle_epoch,
6908            &repair_proofs,
6909            my_commitment,
6910            request_id,
6911            rr_message_id.as_deref(),
6912        )
6913        .await
6914        {
6915            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6916        }
6917    });
6918
6919    Ok(())
6920}
6921
6922#[allow(clippy::too_many_arguments)]
6923async fn handle_neighbor_sync_request(
6924    source: &PeerId,
6925    request: &protocol::NeighborSyncRequest,
6926    p2p_node: &Arc<P2PNode>,
6927    storage: &Arc<ChunkStore>,
6928    paid_list: &Arc<PaidList>,
6929    queues: &Arc<RwLock<ReplicationQueues>>,
6930    config: &ReplicationConfig,
6931    is_bootstrapping: bool,
6932    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6933    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6934    sync_cycle_epoch: &Arc<RwLock<u64>>,
6935    repair_proofs: &Arc<RwLock<RepairProofs>>,
6936    my_commitment: Option<StorageCommitment>,
6937    request_id: u64,
6938    rr_message_id: Option<&str>,
6939) -> Result<()> {
6940    let self_id = *p2p_node.peer_id();
6941
6942    // No per-request hint count limit: the wire message size limit
6943    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6944    // challenges, sync hints don't drive expensive computation — they just
6945    // enter the verification queue. A per-request limit here would break
6946    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6947
6948    // Build response (outbound hints).
6949    let (response, sent_replica_hints, sender_in_rt) =
6950        neighbor_sync::handle_sync_request_with_proofs(
6951            source,
6952            request,
6953            p2p_node,
6954            storage,
6955            paid_list,
6956            config,
6957            is_bootstrapping,
6958            my_commitment.clone(),
6959        )
6960        .await;
6961
6962    // Send response.
6963    let response_sent = send_replication_response_checked(
6964        source,
6965        p2p_node,
6966        request_id,
6967        ReplicationMessageBody::NeighborSyncResponse(response),
6968        rr_message_id,
6969        None,
6970    )
6971    .await;
6972
6973    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6974    if !sender_in_rt {
6975        return Ok(());
6976    }
6977
6978    // Update sync history for this peer before recording repair proofs so a
6979    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6980    {
6981        let mut history = sync_history.write().await;
6982        let record = history.entry(*source).or_insert(PeerSyncRecord {
6983            last_sync: None,
6984            cycles_since_sync: 0,
6985        });
6986        record.last_sync = Some(Instant::now());
6987        record.cycles_since_sync = 0;
6988    }
6989
6990    if response_sent && !request.bootstrapping {
6991        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6992            .await;
6993    }
6994
6995    // Admit inbound hints and queue for verification.
6996    let outcome = admit_and_queue_hints(
6997        &self_id,
6998        source,
6999        &request.replica_hints,
7000        &request.paid_hints,
7001        p2p_node,
7002        config,
7003        storage,
7004        paid_list,
7005        queues,
7006    )
7007    .await;
7008
7009    // Track discovered keys for bootstrap drain detection so that hints
7010    // admitted via inbound sync requests are not missed. Capacity-rejected
7011    // hints keep this source on the "not yet drained" list until its next
7012    // sync re-admits them; a clean cycle clears the source.
7013    if is_bootstrapping {
7014        let live_discovered = outcome.discovered.clone();
7015        let outcomes = [(*source, outcome)];
7016        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
7017    }
7018
7019    Ok(())
7020}
7021
7022/// Test-only record of who *sent* a verification request covering a watched key.
7023///
7024/// The capacity gate's entire effect is a request that is never sent, and a
7025/// request that was not sent leaves no production counter anywhere — not on the
7026/// sender, whose traffic counters are process-global and so cannot separate one
7027/// node of a single-process testnet from another, and not on the responder,
7028/// which simply never hears from it. Recording who asked is what lets a test
7029/// tell "held the key back" apart from "probed the close group, was refused at
7030/// the dial, and then held the key back", which are otherwise identical from the
7031/// queue's point of view.
7032///
7033/// Arming replaces the previous watch, so the outer map holds exactly the keys
7034/// the current test named, and each inner map holds at most one entry per node
7035/// in the process. Nothing is recorded until a test arms it, and the armed path
7036/// costs one read lock on the sending side.
7037///
7038/// Counting is per key because a node that cannot write legitimately keeps
7039/// sending verification requests for keys it has not yet authorized — that is
7040/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
7041/// would assert something untrue.
7042///
7043/// It counts *send attempts*, deliberately, recorded immediately before the wire
7044/// call. A responder sheds requests at admission and as stale, so a
7045/// receiver-side count would report zero for probes that were really sent, and
7046/// an assertion that this node asked nobody would pass on the strength of the
7047/// receiver dropping the question. It is not proof of delivery: a send that
7048/// fails immediately, with no route or during shutdown, is still counted.
7049///
7050/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
7051/// MSRV.
7052#[cfg(any(test, feature = "test-utils"))]
7053type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
7054
7055#[cfg(any(test, feature = "test-utils"))]
7056static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
7057    std::sync::OnceLock::new();
7058
7059#[cfg(any(test, feature = "test-utils"))]
7060fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
7061    VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
7062}
7063
7064/// Test-only: start counting verification requests for `keys`, from zero.
7065///
7066/// Replaces any previous watch rather than adding to it, so the map is bounded
7067/// by the keys of the test that armed it last and nothing accumulates across a
7068/// process running many tests.
7069#[cfg(any(test, feature = "test-utils"))]
7070pub fn watch_verification_requests_for_test(keys: &[XorName]) {
7071    if let Ok(mut watch) = verification_watch().write() {
7072        watch.clear();
7073        for key in keys {
7074            watch.insert(*key, HashMap::new());
7075        }
7076    }
7077}
7078
7079/// Record that `requester` sent a verification request covering `keys`, for
7080/// whichever of them are watched. A poisoned lock is ignored rather than
7081/// propagated: this is observation for tests and must never change behaviour.
7082#[cfg(any(test, feature = "test-utils"))]
7083pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
7084    // Fast path under a read lock: with nothing watched — every production
7085    // build, and every test that did not ask — this is all the sender pays.
7086    match verification_watch().read() {
7087        Ok(watch) if watch.is_empty() => return,
7088        Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
7089        Ok(_) => {}
7090        Err(_) => return,
7091    }
7092    if let Ok(mut watch) = verification_watch().write() {
7093        for key in keys {
7094            if let Some(by_peer) = watch.get_mut(key) {
7095                *by_peer.entry(*requester).or_insert(0) += 1;
7096            }
7097        }
7098    }
7099}
7100
7101/// Test-only: how many times `requester` has asked this process about `key`.
7102/// Zero unless the key was registered with `watch_verification_requests_for_test`.
7103#[cfg(any(test, feature = "test-utils"))]
7104#[must_use]
7105pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
7106    verification_watch().read().map_or(0, |watch| {
7107        watch
7108            .get(key)
7109            .and_then(|by_peer| by_peer.get(requester))
7110            .copied()
7111            .unwrap_or(0)
7112    })
7113}
7114
7115async fn handle_verification_request(
7116    source: &PeerId,
7117    request: &protocol::VerificationRequest,
7118    storage: &Arc<ChunkStore>,
7119    paid_list: &Arc<PaidList>,
7120    p2p_node: &Arc<P2PNode>,
7121    request_id: u64,
7122    rr_message_id: Option<&str>,
7123) -> Result<()> {
7124    #[derive(Clone, Copy)]
7125    enum CachedPaidLookup {
7126        NotChecked,
7127        Checked(Option<bool>),
7128    }
7129
7130    #[derive(Clone, Copy)]
7131    struct CachedVerificationLookup {
7132        present: Option<bool>,
7133        paid: CachedPaidLookup,
7134    }
7135
7136    if verification_request_exceeds_limit(request.keys.len()) {
7137        warn!(
7138            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
7139            request.keys.len(),
7140        );
7141        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7142        return Ok(());
7143    }
7144
7145    let requested_keys = request.keys.as_slice();
7146
7147    if request.paid_list_check_indices.len() > request.keys.len() {
7148        warn!(
7149            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
7150            request.paid_list_check_indices.len(),
7151            request.keys.len(),
7152        );
7153        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7154        return Ok(());
7155    }
7156
7157    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
7158    let paid_check_set: HashSet<u32> = request
7159        .paid_list_check_indices
7160        .iter()
7161        .copied()
7162        .filter(|&idx| {
7163            if idx >= keys_len {
7164                warn!(
7165                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
7166                    requested_keys.len(),
7167                );
7168                false
7169            } else {
7170                true
7171            }
7172        })
7173        .collect();
7174
7175    let mut results = Vec::with_capacity(requested_keys.len());
7176    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
7177    for (i, key) in requested_keys.iter().enumerate() {
7178        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
7179        let cached = lookup_cache.entry(*key).or_insert_with(|| {
7180            let present = match storage.exists(key) {
7181                Ok(present) => Some(present),
7182                Err(e) => {
7183                    warn!(
7184                        "Verification request from {source}: failed to check storage for {}: {e}",
7185                        hex::encode(key)
7186                    );
7187                    None
7188                }
7189            };
7190            CachedVerificationLookup {
7191                present,
7192                paid: CachedPaidLookup::NotChecked,
7193            }
7194        });
7195
7196        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
7197            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
7198                Ok(paid) => Some(paid),
7199                Err(e) => {
7200                    warn!(
7201                        "Verification request from {source}: failed to check paid-list for {}: {e}",
7202                        hex::encode(key)
7203                    );
7204                    None
7205                }
7206            });
7207        }
7208
7209        let paid = if needs_paid {
7210            match cached.paid {
7211                CachedPaidLookup::Checked(paid) => paid,
7212                CachedPaidLookup::NotChecked => None,
7213            }
7214        } else {
7215            None
7216        };
7217
7218        if cached.present.is_none() && paid.is_none() {
7219            continue;
7220        }
7221
7222        results.push(protocol::KeyVerificationResult {
7223            key: *key,
7224            present: cached.present.unwrap_or(false),
7225            paid,
7226        });
7227    }
7228
7229    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
7230
7231    Ok(())
7232}
7233
7234async fn dispatch_verification_request(
7235    source: PeerId,
7236    request: protocol::VerificationRequest,
7237    ctx: &ReplicationMessageHandlerContext,
7238    request_id: u64,
7239    received_at: Instant,
7240    rr_message_id: Option<&str>,
7241) -> Result<()> {
7242    let guard = match admit_bounded_responder(
7243        &ctx.verification_responder_admission_semaphore,
7244        &ctx.verification_responder_inflight,
7245        &source,
7246        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
7247        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7248    )
7249    .await
7250    {
7251        Ok(guard) => guard,
7252        Err(failure) => {
7253            audit_metrics::record_responder_admission_drop(
7254                ReplicationResponderClass::Verification,
7255                failure.reason.into(),
7256            );
7257            warn!(
7258                responder_class = "verification",
7259                source = %source,
7260                "Verification response dropped at admission: {failure}"
7261            );
7262            return Ok(());
7263        }
7264    };
7265
7266    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
7267    let storage = Arc::clone(&ctx.storage);
7268    let paid_list = Arc::clone(&ctx.paid_list);
7269    let p2p_node = Arc::clone(&ctx.p2p_node);
7270    let request_timeout = ctx.config.verification_request_timeout;
7271    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7272    ctx.detached_task_tracker.spawn(async move {
7273        let _guard = guard;
7274        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7275            debug!(
7276                responder_class = "verification",
7277                source = %source,
7278                "Verification responder worker pool closed before dequeue"
7279            );
7280            return;
7281        };
7282        if request_is_stale(received_at, request_timeout) {
7283            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
7284            debug!(
7285                responder_class = "verification",
7286                source = %source,
7287                request_age_ms = received_at.elapsed().as_millis(),
7288                "Stale verification request shed at dequeue"
7289            );
7290            return;
7291        }
7292        if let Err(e) = handle_verification_request(
7293            &source,
7294            &request,
7295            &storage,
7296            &paid_list,
7297            &p2p_node,
7298            request_id,
7299            rr_message_id.as_deref(),
7300        )
7301        .await
7302        {
7303            debug!(source = %source, "Verification request handling failed: {e}");
7304        }
7305    });
7306
7307    Ok(())
7308}
7309
7310const fn verification_request_exceeds_limit(key_count: usize) -> bool {
7311    key_count > MAX_INCOMING_VERIFICATION_KEYS
7312}
7313
7314async fn send_verification_results(
7315    source: &PeerId,
7316    p2p_node: &Arc<P2PNode>,
7317    request_id: u64,
7318    results: Vec<protocol::KeyVerificationResult>,
7319    rr_message_id: Option<&str>,
7320) {
7321    send_replication_response(
7322        source,
7323        p2p_node,
7324        request_id,
7325        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
7326        rr_message_id,
7327    )
7328    .await;
7329}
7330
7331async fn dispatch_fetch_request(
7332    source: PeerId,
7333    request: protocol::FetchRequest,
7334    ctx: &ReplicationMessageHandlerContext,
7335    request_id: u64,
7336    received_at: Instant,
7337    rr_message_id: Option<&str>,
7338) -> Result<()> {
7339    let guard = match admit_bounded_responder(
7340        &ctx.fetch_responder_admission_semaphore,
7341        &ctx.fetch_responder_inflight,
7342        &source,
7343        FETCH_RESPONDER_MAX_OUTSTANDING,
7344        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7345    )
7346    .await
7347    {
7348        Ok(guard) => guard,
7349        Err(failure) => {
7350            audit_metrics::record_responder_admission_drop(
7351                ReplicationResponderClass::Fetch,
7352                failure.reason.into(),
7353            );
7354            warn!(
7355                responder_class = "fetch",
7356                source = %source,
7357                "Fetch response dropped at admission: {failure}"
7358            );
7359            return Ok(());
7360        }
7361    };
7362
7363    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
7364    let storage = Arc::clone(&ctx.storage);
7365    let p2p_node = Arc::clone(&ctx.p2p_node);
7366    let request_timeout = ctx.config.fetch_request_timeout;
7367    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7368    ctx.detached_task_tracker.spawn(async move {
7369        let _guard = guard;
7370        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7371            debug!(
7372                responder_class = "fetch",
7373                source = %source,
7374                "Fetch responder worker pool closed before dequeue"
7375            );
7376            return;
7377        };
7378        if request_is_stale(received_at, request_timeout) {
7379            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
7380            debug!(
7381                responder_class = "fetch",
7382                source = %source,
7383                request_age_ms = received_at.elapsed().as_millis(),
7384                "Stale fetch request shed at dequeue"
7385            );
7386            return;
7387        }
7388        if let Err(e) = handle_fetch_request(
7389            &source,
7390            &request,
7391            &storage,
7392            &p2p_node,
7393            request_id,
7394            rr_message_id.as_deref(),
7395        )
7396        .await
7397        {
7398            debug!(source = %source, "Fetch request handling failed: {e}");
7399        }
7400    });
7401
7402    Ok(())
7403}
7404
7405fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
7406    received_at.elapsed() >= timeout
7407}
7408
7409/// Turn the responder's storage read into the answer it sends back.
7410///
7411/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7412/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7413/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7414/// Nothing about a node giving chunks up produces the second.
7415fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7416    match read {
7417        Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7418        Ok(None) => protocol::FetchResponse::NotFound { key },
7419        Err(e) => protocol::FetchResponse::Error {
7420            key,
7421            reason: format!("{e}"),
7422        },
7423    }
7424}
7425
7426async fn handle_fetch_request(
7427    source: &PeerId,
7428    request: &protocol::FetchRequest,
7429    storage: &Arc<ChunkStore>,
7430    p2p_node: &Arc<P2PNode>,
7431    request_id: u64,
7432    rr_message_id: Option<&str>,
7433) -> Result<()> {
7434    let response = fetch_response_for(request.key, storage.get(&request.key).await);
7435
7436    send_replication_response(
7437        source,
7438        p2p_node,
7439        request_id,
7440        ReplicationMessageBody::FetchResponse(response),
7441        rr_message_id,
7442    )
7443    .await;
7444
7445    Ok(())
7446}
7447
7448/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7449/// the prune-confirmation audit, which reuses the same wire message): reply with
7450/// per-key possession digests.
7451struct AuditResponderCompletion {
7452    response_kind: &'static str,
7453    sent: bool,
7454    processing: Duration,
7455    response_send: Duration,
7456}
7457
7458async fn handle_audit_challenge_msg(
7459    source: &PeerId,
7460    challenge: &protocol::AuditChallenge,
7461    storage: &Arc<ChunkStore>,
7462    p2p_node: &Arc<P2PNode>,
7463    is_bootstrapping: bool,
7464    reply: ReplyRoute<'_>,
7465) -> Result<AuditResponderCompletion> {
7466    #[allow(clippy::cast_possible_truncation)]
7467    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7468    info!(
7469        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7470        challenge.keys.len(),
7471        is_bootstrapping,
7472        reply.rr_message_id.is_some(),
7473    );
7474
7475    let processing_started = Instant::now();
7476    let response = audit::handle_audit_challenge(
7477        challenge,
7478        storage,
7479        p2p_node.peer_id(),
7480        is_bootstrapping,
7481        stored_chunks,
7482    )
7483    .await;
7484    let processing = processing_started.elapsed();
7485    let response_kind = audit_response_kind(&response);
7486
7487    let response_send_started = Instant::now();
7488    let sent = send_replication_response_checked(
7489        source,
7490        p2p_node,
7491        reply.request_id,
7492        ReplicationMessageBody::AuditResponse(response),
7493        reply.rr_message_id,
7494        Some(reply.protocol),
7495    )
7496    .await;
7497    let response_send = response_send_started.elapsed();
7498
7499    Ok(AuditResponderCompletion {
7500        response_kind,
7501        sent,
7502        processing,
7503        response_send,
7504    })
7505}
7506
7507#[allow(clippy::too_many_arguments)]
7508fn log_audit_responder_completion(
7509    metrics: &AuditResponderMetrics,
7510    source: PeerId,
7511    class: AuditResponderClass,
7512    kind: &'static str,
7513    challenge_id: u64,
7514    work_items: usize,
7515    response_kind: &'static str,
7516    sent: bool,
7517    received_at: Instant,
7518    worker_started: Instant,
7519    processing: Duration,
7520    response_send: Duration,
7521) {
7522    let dispatch = worker_started.saturating_duration_since(received_at);
7523    let total = received_at.elapsed();
7524    metrics.record_completed(source, processing, total, sent);
7525    if sent {
7526        info!(
7527            target: "ant_node::replication::audit_responder",
7528            event = "completed",
7529            kind,
7530            responder_class = class.as_str(),
7531            source = %source,
7532            challenge_id,
7533            work_items,
7534            response = response_kind,
7535            sent,
7536            dispatch_ms = dispatch.as_millis(),
7537            processing_ms = processing.as_millis(),
7538            response_send_ms = response_send.as_millis(),
7539            total_ms = total.as_millis(),
7540            "Audit responder request completed"
7541        );
7542    } else {
7543        warn!(
7544            target: "ant_node::replication::audit_responder",
7545            event = "completed",
7546            kind,
7547            responder_class = class.as_str(),
7548            source = %source,
7549            challenge_id,
7550            work_items,
7551            response = response_kind,
7552            sent,
7553            dispatch_ms = dispatch.as_millis(),
7554            processing_ms = processing.as_millis(),
7555            response_send_ms = response_send.as_millis(),
7556            total_ms = total.as_millis(),
7557            "Audit responder request completed without sending a reply"
7558        );
7559    }
7560}
7561
7562/// Where a reply goes and how it is addressed.
7563///
7564/// Grouped because the audit responder needs all three together and one of them
7565/// is not derivable from the body: during the rollout window a possession reply
7566/// may have to go out on the core id rather than its family's own (see
7567/// [`is_legacy_possession_challenge`]).
7568struct ReplyRoute<'a> {
7569    /// Correlates the reply with the challenge, at the replication layer.
7570    request_id: u64,
7571    /// Present when the challenge arrived over request-response, in which case
7572    /// the reply rides the same exchange back.
7573    rr_message_id: Option<&'a str>,
7574    /// The protocol id to answer on.
7575    protocol: &'static str,
7576}
7577
7578fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7579    match response {
7580        protocol::AuditResponse::Digests { .. } => "digests",
7581        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7582        protocol::AuditResponse::Rejected { .. } => "rejected",
7583    }
7584}
7585
7586fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7587    match response {
7588        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7589        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7590        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7591    }
7592}
7593
7594fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7595    match response {
7596        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7597        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7598        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7599    }
7600}
7601
7602fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7603    match response {
7604        protocol::SubtreeSliceResponse::Items { .. } => "items",
7605        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7606        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7607    }
7608}
7609
7610fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7611    match response {
7612        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7613        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7614    }
7615}
7616
7617// ---------------------------------------------------------------------------
7618// Message sending helper
7619// ---------------------------------------------------------------------------
7620
7621/// Send a replication response message as a best-effort reply.
7622///
7623/// Encode and send failures are logged by the checked helper. Most response
7624/// paths do not need to branch on send success, so this wrapper keeps those
7625/// call sites explicit about their best-effort behavior.
7626async fn send_replication_response(
7627    peer: &PeerId,
7628    p2p_node: &Arc<P2PNode>,
7629    request_id: u64,
7630    body: ReplicationMessageBody,
7631    rr_message_id: Option<&str>,
7632) {
7633    let _ =
7634        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7635            .await;
7636}
7637
7638/// Send a replication response message and report whether it was accepted.
7639///
7640/// Returns `true` after the message is encoded and accepted by the P2P send
7641/// path. Returns `false` after logging an encode or send failure. Repair-proof
7642/// recording uses this to avoid trusting hints that were not actually sent.
7643///
7644/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7645/// request-response path so saorsa-core can route it back to the caller's
7646/// `send_request` future. Otherwise it is sent as a plain message.
7647///
7648/// `protocol` overrides the id the body would route on by family. Exactly one
7649/// caller needs it: a possession challenge from a peer that predates the family
7650/// split has to be answered where it was asked (see
7651/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7652/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7653async fn send_replication_response_checked(
7654    peer: &PeerId,
7655    p2p_node: &Arc<P2PNode>,
7656    request_id: u64,
7657    body: ReplicationMessageBody,
7658    rr_message_id: Option<&str>,
7659    protocol: Option<&'static str>,
7660) -> bool {
7661    let msg = ReplicationMessage { request_id, body };
7662    let encoded = match msg.encode() {
7663        Ok(data) => data,
7664        Err(e) => {
7665            warn!("Failed to encode replication response: {e}");
7666            return false;
7667        }
7668    };
7669    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7670    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7671    // included for completeness. Other response variants (verification/audit/
7672    // commitment) are intentionally excluded — the round-2 audit reply is now a
7673    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7674    if matches!(
7675        msg.body,
7676        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7677    ) {
7678        protocol::record_served(peer, encoded.len());
7679    }
7680    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7681    let result = if let Some(msg_id) = rr_message_id {
7682        p2p_node
7683            .send_response(peer, protocol, msg_id, encoded)
7684            .await
7685    } else {
7686        p2p_node.send_message(peer, protocol, encoded, &[]).await
7687    };
7688    if let Err(e) = result {
7689        debug!("Failed to send replication response to {peer}: {e}");
7690        return false;
7691    }
7692    true
7693}
7694
7695async fn record_sent_replica_hints(
7696    peer: &PeerId,
7697    hints: &[neighbor_sync::SentReplicaHint],
7698    repair_proofs: &Arc<RwLock<RepairProofs>>,
7699    sync_cycle_epoch: &Arc<RwLock<u64>>,
7700) {
7701    if hints.is_empty() {
7702        return;
7703    }
7704
7705    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7706    let mut proofs = repair_proofs.write().await;
7707    for hint in hints {
7708        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7709            debug!(
7710                "Recorded repair hint proof for peer {peer} and key {}",
7711                hex::encode(hint.key)
7712            );
7713        }
7714    }
7715}
7716
7717// ---------------------------------------------------------------------------
7718// Neighbor sync round
7719// ---------------------------------------------------------------------------
7720
7721/// Run one neighbor sync round.
7722#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7723async fn run_neighbor_sync_round(
7724    p2p_node: &Arc<P2PNode>,
7725    storage: &Arc<ChunkStore>,
7726    paid_list: &Arc<PaidList>,
7727    queues: &Arc<RwLock<ReplicationQueues>>,
7728    config: &ReplicationConfig,
7729    sync_state: &Arc<RwLock<NeighborSyncState>>,
7730    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7731    sync_cycle_epoch: &Arc<RwLock<u64>>,
7732    repair_proofs: &Arc<RwLock<RepairProofs>>,
7733    is_bootstrapping: &Arc<RwLock<bool>>,
7734    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7735    commitment_state: &Arc<ResponderCommitmentState>,
7736    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7737    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7738    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7739    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7740    gossip_audit: &GossipAuditTrigger,
7741    pointers: Option<&Arc<pointer::PointerReplication>>,
7742) {
7743    let self_id = *p2p_node.peer_id();
7744    let bootstrapping = *is_bootstrapping.read().await;
7745
7746    // Check if cycle is complete; start new one if needed.
7747    // We check under a read lock, then release it before the expensive
7748    // prune pass and DHT snapshot so other tasks are not starved.
7749    let cycle_complete = sync_state.read().await.is_cycle_complete();
7750    if cycle_complete {
7751        // A completed local neighbor-sync cycle advances the epoch component
7752        // of repair-proof maturity. The per-key wall-clock minimum age is
7753        // checked when audits are selected.
7754        {
7755            let mut history = sync_history.write().await;
7756            for record in history.values_mut() {
7757                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7758            }
7759        }
7760        {
7761            let mut epoch = sync_cycle_epoch.write().await;
7762            *epoch = epoch.saturating_add(1);
7763        }
7764
7765        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7766        // Prune candidacy is unconditional once the hysteresis elapses;
7767        // bootstrap state only defers the remote prune-confirmation audits
7768        // until bootstrap has drained.
7769        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7770        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7771            self_id: &self_id,
7772            storage,
7773            paid_list,
7774            p2p_node,
7775            config,
7776            sync_state,
7777            repair_proofs,
7778            allow_remote_prune_audits,
7779            commitment_state: Some(commitment_state),
7780            audit_challenge_coordinator,
7781        })
7782        .await;
7783        if let Some(pointers) = pointers {
7784            pointers
7785                .prune_pass(allow_remote_prune_audits, Some(commitment_state))
7786                .await;
7787        }
7788
7789        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7790        let neighbors =
7791            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7792                .await;
7793
7794        // Now re-acquire write lock and re-check before swapping cycle.
7795        let mut state = sync_state.write().await;
7796        if state.is_cycle_complete() {
7797            // Preserve cooldown and bootstrap-claim tracking across cycles.
7798            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7799            // would reset the abuse detection timer every cycle.
7800            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7801            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7802            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7803            let old_prune_cursor = state.prune_cursor;
7804            *state = NeighborSyncState::new_cycle(neighbors);
7805            state.last_sync_times = old_sync_times;
7806            state.bootstrap_claims = old_bootstrap_claims;
7807            state.bootstrap_claim_history = old_bootstrap_claim_history;
7808            state.prune_cursor = old_prune_cursor;
7809        }
7810    }
7811
7812    // Select batch of peers.
7813    let batch = {
7814        let mut state = sync_state.write().await;
7815        neighbor_sync::select_sync_batch(
7816            &mut state,
7817            config.neighbor_sync_peer_count,
7818            config.neighbor_sync_cooldown,
7819        )
7820    };
7821
7822    if batch.is_empty() {
7823        return;
7824    }
7825
7826    debug!("Neighbor sync: syncing with {} peers", batch.len());
7827    if let Some(pointers) = pointers {
7828        pointers.push_hints_detached(batch.clone());
7829    }
7830
7831    // Snapshot our current commitment once per round so all peers in
7832    // this batch see the same thing (gossip is the responder's attestation;
7833    // same value across the batch is fine and reduces RwLock churn). Atomically
7834    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7835    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7836    let my_commitment = commitment_state
7837        .current_for_gossip()
7838        .map(|b| b.commitment().clone());
7839
7840    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7841        &batch,
7842        storage,
7843        paid_list,
7844        p2p_node,
7845        config.close_group_size,
7846        config.paid_list_close_group_size,
7847    )
7848    .await;
7849
7850    // Sync with each peer in the batch.
7851    for peer in &batch {
7852        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7853        let outcome = neighbor_sync::sync_with_peer_with_hints(
7854            peer,
7855            p2p_node,
7856            config,
7857            bootstrapping,
7858            hints,
7859            my_commitment.clone(),
7860        )
7861        .await;
7862
7863        if let Some(outcome) = outcome {
7864            handle_sync_response(
7865                &self_id,
7866                peer,
7867                &outcome.response,
7868                &outcome.sent_replica_hints,
7869                p2p_node,
7870                config,
7871                bootstrapping,
7872                bootstrap_state,
7873                storage,
7874                paid_list,
7875                queues,
7876                sync_state,
7877                sync_history,
7878                sync_cycle_epoch,
7879                repair_proofs,
7880                last_commitment_by_peer,
7881                ever_capable_peers,
7882                sig_verify_attempts,
7883                gossip_audit,
7884            )
7885            .await;
7886        } else {
7887            // Sync failed -- remove peer and try to fill slot.
7888            let replacement = {
7889                let mut state = sync_state.write().await;
7890                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7891            };
7892
7893            // Attempt sync with the replacement peer (if one was found).
7894            if let Some(replacement_peer) = replacement {
7895                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7896                    std::slice::from_ref(&replacement_peer),
7897                    storage,
7898                    paid_list,
7899                    p2p_node,
7900                    config.close_group_size,
7901                    config.paid_list_close_group_size,
7902                )
7903                .await;
7904                let hints = replacement_hints
7905                    .remove(&replacement_peer)
7906                    .unwrap_or_default();
7907                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7908                    &replacement_peer,
7909                    p2p_node,
7910                    config,
7911                    bootstrapping,
7912                    hints,
7913                    my_commitment.clone(),
7914                )
7915                .await;
7916
7917                if let Some(outcome) = replacement_outcome {
7918                    handle_sync_response(
7919                        &self_id,
7920                        &replacement_peer,
7921                        &outcome.response,
7922                        &outcome.sent_replica_hints,
7923                        p2p_node,
7924                        config,
7925                        bootstrapping,
7926                        bootstrap_state,
7927                        storage,
7928                        paid_list,
7929                        queues,
7930                        sync_state,
7931                        sync_history,
7932                        sync_cycle_epoch,
7933                        repair_proofs,
7934                        last_commitment_by_peer,
7935                        ever_capable_peers,
7936                        sig_verify_attempts,
7937                        gossip_audit,
7938                    )
7939                    .await;
7940                }
7941            }
7942        }
7943    }
7944}
7945
7946/// Process a successful neighbor sync response: record the sync, check for
7947/// bootstrap claim abuse, and admit inbound hints.
7948#[allow(clippy::too_many_arguments)]
7949async fn handle_sync_response(
7950    self_id: &PeerId,
7951    peer: &PeerId,
7952    resp: &NeighborSyncResponse,
7953    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
7954    p2p_node: &Arc<P2PNode>,
7955    config: &ReplicationConfig,
7956    bootstrapping: bool,
7957    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7958    storage: &Arc<ChunkStore>,
7959    paid_list: &Arc<PaidList>,
7960    queues: &Arc<RwLock<ReplicationQueues>>,
7961    sync_state: &Arc<RwLock<NeighborSyncState>>,
7962    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7963    sync_cycle_epoch: &Arc<RwLock<u64>>,
7964    repair_proofs: &Arc<RwLock<RepairProofs>>,
7965    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7966    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7967    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7968    gossip_audit: &GossipAuditTrigger,
7969) {
7970    // Ingest the peer's commitment if they piggybacked one on the response.
7971    // Same verification as the request path (peer-id binding + signature);
7972    // forged commitments are dropped at the edge. A *changed* commitment here
7973    // is a gossip-audit trigger just like on the request path — so a peer that
7974    // only ever answers sync (never initiates) is still audited (ADR-0002).
7975    if let Some(target) = ingest_peer_commitment(
7976        peer,
7977        resp.commitment.as_ref(),
7978        p2p_node,
7979        last_commitment_by_peer,
7980        ever_capable_peers,
7981        sig_verify_attempts,
7982    )
7983    .await
7984    {
7985        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
7986    }
7987
7988    // Record successful sync.
7989    {
7990        let mut state = sync_state.write().await;
7991        neighbor_sync::record_successful_sync(&mut state, peer);
7992    }
7993    {
7994        let mut history = sync_history.write().await;
7995        let record = history.entry(*peer).or_insert(PeerSyncRecord {
7996            last_sync: None,
7997            cycles_since_sync: 0,
7998        });
7999        record.last_sync = Some(Instant::now());
8000        record.cycles_since_sync = 0;
8001    }
8002
8003    // Process inbound hints from response (skip if peer is bootstrapping).
8004    if resp.bootstrapping {
8005        // Gap 6: BootstrapClaimAbuse grace period enforcement.
8006        // Separate state mutation from network I/O to avoid holding the
8007        // write lock across report_trust_event.
8008        let should_report = {
8009            let now = Instant::now();
8010            let mut state = sync_state.write().await;
8011            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
8012                BootstrapClaimObservation::WithinGrace { .. } => false,
8013                BootstrapClaimObservation::PastGrace { first_seen } => {
8014                    warn!(
8015                        "Peer {peer} has been claiming bootstrap for {:?}, \
8016                         exceeding grace period of {:?} — reporting abuse",
8017                        now.duration_since(first_seen),
8018                        config.bootstrap_claim_grace_period,
8019                    );
8020                    true
8021                }
8022                BootstrapClaimObservation::Repeated { first_seen } => {
8023                    warn!(
8024                        "Peer {peer} repeated bootstrap claim after previously stopping; \
8025                         first claim was {:?} ago — reporting abuse",
8026                        now.duration_since(first_seen),
8027                    );
8028                    true
8029                }
8030            }
8031        };
8032        if should_report {
8033            p2p_node
8034                .report_trust_event(
8035                    peer,
8036                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8037                )
8038                .await;
8039        }
8040    } else {
8041        // Peer is not claiming bootstrap; clear active claim while retaining
8042        // history so the peer cannot start a second grace window later.
8043        {
8044            let mut state = sync_state.write().await;
8045            state.clear_active_bootstrap_claim(peer);
8046        }
8047        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
8048        let outcome = admit_and_queue_hints(
8049            self_id,
8050            peer,
8051            &resp.replica_hints,
8052            &resp.paid_hints,
8053            p2p_node,
8054            config,
8055            storage,
8056            paid_list,
8057            queues,
8058        )
8059        .await;
8060
8061        // Track discovered keys for bootstrap drain detection so that hints
8062        // admitted via regular neighbor sync are not missed. Capacity-
8063        // rejected hints keep this source on the "not yet drained" list
8064        // until its next sync replays them; a clean cycle clears it.
8065        if bootstrapping {
8066            let live_discovered = outcome.discovered.clone();
8067            let outcomes = [(*peer, outcome)];
8068            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
8069                .await;
8070        }
8071    }
8072}
8073
8074/// Admit hints and queue them for verification, returning newly-discovered keys.
8075///
8076/// Shared by neighbor-sync request handling, response handling, and bootstrap
8077/// sync so that admission + queueing logic lives in one place.
8078#[allow(clippy::too_many_arguments)]
8079/// Outcome of [`admit_and_queue_hints`].
8080///
8081/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
8082/// available; that source is kept outstanding until it re-hints. `displaced`
8083/// tracks older borrowed hints reclaimed for another sender; only the key is
8084/// dropped from bootstrap tracking — the former owner's standing is untouched
8085/// (see [`publish_bootstrap_admission_outcomes`]).
8086struct AdmissionOutcome {
8087    discovered: HashSet<XorName>,
8088    capacity_rejected_count: usize,
8089    displaced: Vec<CapacityDisplacement>,
8090}
8091
8092/// Publish one atomic admission unit into bootstrap drain accounting.
8093///
8094/// Only sources that were themselves capacity-rejected are kept outstanding.
8095/// A fairness displacement forfeits the displaced *key* but never stamps its
8096/// former owner: reclaiming a borrowed slot is this node's own fairness
8097/// decision, so charging it to the victim would let a sustained flooder wedge
8098/// our bootstrap drain open through an unrelated honest peer. Clean sources
8099/// are cleared only after every outcome in the unit is known, so peer
8100/// iteration order cannot falsely clear a rejection recorded later in the same
8101/// bootstrap batch.
8102async fn publish_bootstrap_admission_outcomes(
8103    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8104    outcomes: &[(PeerId, AdmissionOutcome)],
8105    live_discovered: &HashSet<XorName>,
8106) {
8107    let mut rejected_sources = HashSet::new();
8108    let mut clean_sources = HashSet::new();
8109    let mut displaced_keys = HashSet::new();
8110
8111    for (source, outcome) in outcomes {
8112        if outcome.capacity_rejected_count > 0 {
8113            rejected_sources.insert(*source);
8114        } else {
8115            clean_sources.insert(*source);
8116        }
8117        // Only the *key* of a fairness displacement is forfeited here, never
8118        // its owner's standing. Reclaiming a borrowed slot is our own fairness
8119        // decision, not a failure by the peer that held it: stamping the victim
8120        // would let a sustained flooder block our bootstrap drain through an
8121        // unrelated honest peer that never overflowed us. The displaced key
8122        // falls to the same post-bootstrap neighbor-sync and audit/repair
8123        // recovery path that TTL expiry already relies on.
8124        for displacement in &outcome.displaced {
8125            displaced_keys.insert(displacement.key);
8126        }
8127    }
8128    clean_sources.retain(|source| !rejected_sources.contains(source));
8129
8130    let now = Instant::now();
8131    let mut state = bootstrap_state.write().await;
8132    for key in displaced_keys {
8133        state.remove_key(&key);
8134    }
8135    state.pending_keys.extend(live_discovered);
8136    for source in clean_sources {
8137        state.capacity_rejected_sources.remove(&source);
8138    }
8139    for source in rejected_sources {
8140        // First-seen: a source that keeps overflowing us must not keep its own
8141        // record fresh, or bootstrap never drains and auditing stays off.
8142        state.note_capacity_rejected(source, now);
8143    }
8144}
8145
8146#[allow(clippy::too_many_arguments)]
8147async fn admit_and_queue_hints(
8148    self_id: &PeerId,
8149    source_peer: &PeerId,
8150    replica_hints: &[XorName],
8151    paid_hints: &[XorName],
8152    p2p_node: &Arc<P2PNode>,
8153    config: &ReplicationConfig,
8154    storage: &Arc<ChunkStore>,
8155    paid_list: &Arc<PaidList>,
8156    queues: &Arc<RwLock<ReplicationQueues>>,
8157) -> AdmissionOutcome {
8158    let pending_keys: HashSet<XorName> = {
8159        let q = queues.read().await;
8160        q.pending_keys().into_iter().collect()
8161    };
8162
8163    let admitted = admission::admit_hints(
8164        self_id,
8165        replica_hints,
8166        paid_hints,
8167        p2p_node,
8168        config,
8169        storage,
8170        paid_list,
8171        &pending_keys,
8172    )
8173    .await;
8174
8175    let mut q = queues.write().await;
8176    queue_admitted_hints(source_peer, admitted, storage, &mut q)
8177}
8178
8179fn queue_admitted_hints(
8180    source_peer: &PeerId,
8181    admitted: admission::AdmissionResult,
8182    storage: &ChunkStore,
8183    q: &mut ReplicationQueues,
8184) -> AdmissionOutcome {
8185    let mut discovered = HashSet::new();
8186    let mut capacity_rejected_count: usize = 0;
8187    let mut displaced = Vec::new();
8188    let now = Instant::now();
8189
8190    for key in admitted.replica_keys {
8191        if !storage.exists(&key).unwrap_or(false) {
8192            let result = q.add_pending_verify(
8193                key,
8194                VerificationEntry {
8195                    state: VerificationState::PendingVerify,
8196                    verified_sources: Vec::new(),
8197                    tried_sources: HashSet::new(),
8198                    created_at: now,
8199                    next_verify_at: now,
8200                    hint_sources: HashSet::from([*source_peer]),
8201                    // Non-empty: this peer claimed possession, so it is a
8202                    // fetch-source candidate. Derives HintPipeline::Replica.
8203                    replica_hint_sources: HashSet::from([*source_peer]),
8204                    unresolved_retries: 0,
8205                    no_holder_reported: false,
8206                },
8207            );
8208            match result {
8209                crate::replication::scheduling::AdmissionResult::Admitted => {
8210                    discovered.insert(key);
8211                }
8212                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8213                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8214                    capacity_rejected_count += 1;
8215                }
8216            }
8217        }
8218    }
8219
8220    for key in admitted.paid_only_keys {
8221        let result = q.add_pending_verify(
8222            key,
8223            VerificationEntry {
8224                state: VerificationState::PendingVerify,
8225                verified_sources: Vec::new(),
8226                tried_sources: HashSet::new(),
8227                created_at: now,
8228                next_verify_at: now,
8229                hint_sources: HashSet::from([*source_peer]),
8230                // Empty: a paid hint makes no possession claim, so this peer is
8231                // not a fetch source. Derives HintPipeline::PaidOnly.
8232                replica_hint_sources: HashSet::new(),
8233                unresolved_retries: 0,
8234                no_holder_reported: false,
8235            },
8236        );
8237        match result {
8238            crate::replication::scheduling::AdmissionResult::Admitted => {
8239                discovered.insert(key);
8240            }
8241            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8242            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8243                capacity_rejected_count += 1;
8244            }
8245        }
8246    }
8247
8248    if capacity_rejected_count > 0 {
8249        debug!(
8250            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
8251             rejected at queue capacity; source will need to re-hint after pending_verify drains"
8252        );
8253    }
8254
8255    displaced.extend(q.take_capacity_displacements());
8256
8257    AdmissionOutcome {
8258        discovered,
8259        capacity_rejected_count,
8260        displaced,
8261    }
8262}
8263
8264// ---------------------------------------------------------------------------
8265// Verification cycle
8266// ---------------------------------------------------------------------------
8267
8268/// Run one verification cycle: process pending keys through quorum checks.
8269#[allow(clippy::too_many_lines)]
8270async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
8271    let cycle_started = Instant::now();
8272    let VerificationCycleContext {
8273        p2p_node,
8274        paid_list,
8275        storage,
8276        queues,
8277        config,
8278        bootstrap_state,
8279        is_bootstrapping,
8280        bootstrap_complete_notify,
8281        last_commitment_by_peer,
8282        ever_capable_peers,
8283        recent_provers,
8284    } = ctx;
8285
8286    // Self-heal the bootstrap drain before any early-return below: abandoned
8287    // capacity-rejection records must expire, and a drain condition that
8288    // became true without a triggering event must still be observed. Pending
8289    // peer requests legitimately block the drain check itself, but not this.
8290    expire_and_recheck_bootstrap_drain(
8291        bootstrap_state,
8292        queues,
8293        is_bootstrapping,
8294        bootstrap_complete_notify,
8295        config.capacity_rejected_max_age(),
8296    )
8297    .await;
8298
8299    // Bootstrap admits one concurrent neighbor batch as an atomic source
8300    // aggregation unit. Do not select newly queued keys until that batch's
8301    // hints and drain accounting have both been published.
8302    if bootstrap_state.read().await.pending_peer_requests > 0 {
8303        return;
8304    }
8305
8306    // Evict stale entries that have been pending too long (e.g. unreachable
8307    // verification targets during a network partition).
8308    let stale_pending_keys = {
8309        let mut q = queues.write().await;
8310        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
8311    };
8312    if !stale_pending_keys.is_empty() {
8313        update_bootstrap_after_verification(
8314            &stale_pending_keys,
8315            bootstrap_state,
8316            queues,
8317            is_bootstrapping,
8318            bootstrap_complete_notify,
8319        )
8320        .await;
8321    }
8322
8323    let pending_keys = {
8324        let mut q = queues.write().await;
8325        // Re-check while holding the queue write lock used by fair selection.
8326        // This closes the race
8327        // where a bootstrap batch starts after the early check: the batch
8328        // cannot publish its hints under the queue write lock until this
8329        // selection either returns or declines to run.
8330        if bootstrap_state.read().await.pending_peer_requests > 0 {
8331            return;
8332        }
8333        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
8334    };
8335
8336    if pending_keys.is_empty() {
8337        return;
8338    }
8339    let initial_pending_count = pending_keys.len();
8340
8341    // Capacity verdict for this cycle — the same pre-check the PUT handler and
8342    // the fresh-offer path already run (V2-411), read once and reused below.
8343    //
8344    // It gates only the two steps that exist to enable a fetch: the presence
8345    // probe that discovers holders, and the promotion that queues the download.
8346    // Everything a cycle does that does not need a local write still runs on a
8347    // full node — the local paid-list fast path, `PaidForList` convergence
8348    // through the quorum round, and the terminal checks that retire a key this
8349    // node already holds or is no longer admitted for. Gating earlier than this
8350    // would stop a full node learning which of its keys were paid for, and
8351    // would strand keys that should have retired, which keeps bootstrap drain
8352    // pending and audits disabled until stale eviction.
8353    // Only a *full* disk is a standing condition worth minutes of backoff. A
8354    // failed `statvfs` says nothing about available space and may have cleared
8355    // by the next cycle, so it is treated as writable here and left to the
8356    // pre-check at the dial, which queries again and may well permit the write.
8357    let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8358    // Counted per gate rather than combined. `local_paid_probe` below counts
8359    // probes actually sent, so it reads zero once the first gate fires; keeping
8360    // the two deferral counts apart is what lets an operator see which branch a
8361    // full node's keys are taking without adding a code path to find out.
8362    let mut capacity_deferred_probe = 0usize;
8363    let mut capacity_deferred_promote = 0usize;
8364
8365    let self_id = *p2p_node.peer_id();
8366
8367    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8368    // step 4). Paid-list membership settles *validity* — the key is known-paid,
8369    // so no quorum round is needed. It says nothing about whether we must hold
8370    // the bytes; that is decided below.
8371    let mut local_paid_keys = Vec::new();
8372    let mut keys_needing_network = Vec::new();
8373    let mut terminal_keys: Vec<XorName> = Vec::new();
8374    {
8375        let mut q = queues.write().await;
8376        for key in &pending_keys {
8377            if paid_list.contains(key).unwrap_or(false) {
8378                if q.set_pending_state(key, VerificationState::PaidListVerified) {
8379                    local_paid_keys.push(*key);
8380                }
8381            } else {
8382                keys_needing_network.push(*key);
8383            }
8384        }
8385    }
8386
8387    // Storage responsibility is a live routing question, decided identically
8388    // for every known-paid key regardless of how the advertising peer labelled
8389    // its hint — a replica hint is a possession *claim* by the sender, never
8390    // permission for us to store. Held outside the queue lock: `is_responsible`
8391    // awaits into the DHT manager.
8392    let mut local_paid_presence_probe_keys = Vec::new();
8393    if !local_paid_keys.is_empty() {
8394        let mut terminal_paid = Vec::new();
8395        for key in local_paid_keys {
8396            if storage.exists(&key).unwrap_or(false) {
8397                terminal_paid.push(key);
8398            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8399                // We carry storage responsibility and lack the bytes. The
8400                // presence probe below discovers holders to fetch from; it is
8401                // source discovery, not re-verification.
8402                local_paid_presence_probe_keys.push(key);
8403            } else {
8404                terminal_paid.push(key);
8405            }
8406        }
8407
8408        if !terminal_paid.is_empty() {
8409            let mut q = queues.write().await;
8410            for key in terminal_paid {
8411                q.remove_pending(&key);
8412                terminal_keys.push(key);
8413            }
8414        }
8415
8416        // Capacity gate, first of two. Everything above this point has already
8417        // run: authorization succeeded via the local `PaidForList` hit, and the
8418        // keys that should retire (already held, or no longer storage-admitted)
8419        // have retired. What is left is a probe whose only purpose is finding a
8420        // holder to download from, and this node cannot write what it would
8421        // download.
8422        if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8423            let mut q = queues.write().await;
8424            for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8425                if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8426                    capacity_deferred_probe += 1;
8427                }
8428            }
8429        }
8430    }
8431
8432    let local_paid_probe_count = local_paid_presence_probe_keys.len();
8433    let keys_needing_network_count = keys_needing_network.len();
8434    // Keys this cycle put back because no peer claimed possession. Reported in
8435    // aggregate below; the per-key line is warned once per entry, not per retry.
8436    let mut no_holder_deferrals = 0usize;
8437
8438    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8439    // step 4, authorization succeeds immediately; run a presence-only probe
8440    // to find any holder we can fetch from.
8441    if !local_paid_presence_probe_keys.is_empty() {
8442        let targets = quorum::compute_presence_targets(
8443            &local_paid_presence_probe_keys,
8444            p2p_node,
8445            config,
8446            &self_id,
8447        )
8448        .await;
8449        let evidence = quorum::run_verification_round(
8450            &local_paid_presence_probe_keys,
8451            &targets,
8452            p2p_node,
8453            config,
8454        )
8455        .await;
8456
8457        let mut q = queues.write().await;
8458        for key in local_paid_presence_probe_keys {
8459            if storage.exists(&key).unwrap_or(false) {
8460                q.remove_pending(&key);
8461                terminal_keys.push(key);
8462                continue;
8463            }
8464            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8465                quorum::present_sources_for_key(&key, ev, &targets)
8466            });
8467            if let Some(entry) = q.get_pending(&key) {
8468                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8469            }
8470            if sources.is_empty() {
8471                no_holder_deferrals += 1;
8472                let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8473                let first_report = q.claim_no_holder_report(&key);
8474                report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8475            } else {
8476                // A holder answered, so whatever came before is not a run of
8477                // consecutive failures any more. Clear before promoting: if the
8478                // fetch queue is full the entry stays pending, and it must not
8479                // carry the old backoff.
8480                q.clear_unresolved(&key);
8481                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8482                // Atomic remove+enqueue: if fetch_queue is at capacity, the
8483                // pending entry is preserved and retried next cycle (no
8484                // silent drop of verified replica-repair work).
8485                let _ = q.promote_pending_to_fetch(key, distance, sources);
8486            }
8487        }
8488    }
8489
8490    // Steps 2-5: Network verification (skipped if all keys resolved locally).
8491    if !keys_needing_network.is_empty() {
8492        // Step 2: Compute targets and run network verification round.
8493        let targets =
8494            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8495                .await;
8496
8497        let evidence =
8498            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8499
8500        // Step 3: Evaluate results — collect outcomes without holding the write
8501        // lock across paid-list I/O.
8502        //
8503        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8504        // table and recent_provers cache up front so the synchronous
8505        // evaluate_key_evidence_with_holder_check predicate can consult
8506        // them without awaiting. The predicate downgrades a Present
8507        // claim to Unresolved unless the peer is credited for that key.
8508        // Snapshot per-peer commitment data. We need two views:
8509        //   - `commitment_by_peer_snapshot`: peers that currently have
8510        //     a verified commitment record on file (used to look up
8511        //     their current hash).
8512        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
8513        //     set. Sourced from a separate set rather than the
8514        //     commitment map so eviction (PeerRemoved cleanup, sybil
8515        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8516        //     a previously-v12 peer to "legacy" credit-unconditionally.
8517        //     Legacy / pre-v12 peers that have never sent a commitment
8518        //     remain absent from the set and are credited via the
8519        //     legacy path so mixed-version networks stay live.
8520        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8521            let map = last_commitment_by_peer.read().await;
8522            map.iter()
8523                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8524                // of every peer's ~5 KiB commitment.
8525                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8526                .collect()
8527        };
8528        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8529        // Take a full snapshot of recent_provers under the read lock,
8530        // then release. The cache is bounded (16/key × keys), so the
8531        // clone is cheap.
8532        let provers_snapshot = recent_provers.read().await.clone();
8533        // For the replica-fetch path, we need to know whether THIS
8534        // node already holds the key being verified. The v12 §6
8535        // holder-credit gate is meant to prevent uncredited Present
8536        // claims from contributing to paid-list / reward quorum for
8537        // keys we DO hold (and could audit ourselves). For keys we
8538        // are trying to FETCH (i.e. not in local storage), there is
8539        // no possible local audit credit, and gating the presence
8540        // quorum on credit would deadlock replica-repair in a
8541        // fully v12-capable close group.
8542        let mut locally_held: HashSet<XorName> = HashSet::new();
8543        for key in &keys_needing_network {
8544            if storage.exists(key).unwrap_or(false) {
8545                locally_held.insert(*key);
8546            }
8547        }
8548        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8549            if !locally_held.contains(key) {
8550                // Replica-fetch path: we don't hold this key, so we
8551                // cannot have collected audit credit for it. Trust
8552                // Present claims to drive fetch-source promotion;
8553                // chunk-PUT payment_verifier is the security backstop
8554                // when the bytes actually arrive.
8555                return true;
8556            }
8557            if !capable_peer_snapshot.contains(peer) {
8558                // Pre-v12 / legacy peer that has never gossiped a
8559                // commitment. The v12 §6 holder-eligibility check
8560                // doesn't apply: their Present evidence comes through
8561                // the legacy path and we credit it unconditionally
8562                // so a mixed-version network stays live during
8563                // transition.
8564                return true;
8565            }
8566            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8567                // Peer is commitment_capable (sticky) but currently
8568                // has no live commitment record on file (e.g. their
8569                // last gossip was evicted from the LRU cache, or it
8570                // failed verification). Withhold credit until they
8571                // re-prove storage under a fresh commitment.
8572                return false;
8573            };
8574            provers_snapshot.is_credited_holder(key, peer, hash)
8575        };
8576
8577        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8578        {
8579            let q = queues.read().await;
8580            for key in &keys_needing_network {
8581                let Some(ev) = evidence.get(key) else {
8582                    continue;
8583                };
8584                if q.get_pending(key).is_none() {
8585                    continue;
8586                }
8587                let outcome = quorum::evaluate_key_evidence_with_holder_check(
8588                    key,
8589                    ev,
8590                    &targets,
8591                    config,
8592                    holder_credit,
8593                );
8594                evaluated.push((*key, outcome));
8595            }
8596        } // read lock released
8597
8598        // Step 4: Insert verified keys into PaidForList (no lock held).
8599        let mut paid_insert_keys: Vec<XorName> = Vec::new();
8600        for (key, outcome) in &evaluated {
8601            if matches!(
8602                outcome,
8603                KeyVerificationOutcome::QuorumVerified { .. }
8604                    | KeyVerificationOutcome::PaidListVerified { .. }
8605            ) {
8606                paid_insert_keys.push(*key);
8607            }
8608        }
8609        for key in &paid_insert_keys {
8610            if let Err(e) = paid_list.insert(key).await {
8611                warn!("Failed to add verified key to PaidForList: {e}");
8612            }
8613        }
8614
8615        // Verification established validity; the paid-list insert above records
8616        // it. Downloading the bytes is a separate duty, owed only by the
8617        // storage-admission group, asked on the same terms for every verified
8618        // key — the advertising peer's replica/paid labelling is a claim about
8619        // itself and carries no authority over what we store. This check is a
8620        // cheap pre-filter that keeps never-responsible keys out of the fetch
8621        // queue entirely; the authoritative gate is the per-attempt recheck in
8622        // `execute_single_fetch`, because a key can wait in the nearest-first
8623        // fetch queue long enough for this promotion-time answer to go stale.
8624        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8625        for (key, outcome) in &evaluated {
8626            if matches!(
8627                outcome,
8628                KeyVerificationOutcome::QuorumVerified { .. }
8629                    | KeyVerificationOutcome::PaidListVerified { .. }
8630            ) && !storage.exists(key).unwrap_or(false)
8631                && is_storage_admitted(&self_id, key, p2p_node, config).await
8632            {
8633                fetch_allowed_keys.insert(*key);
8634            }
8635        }
8636
8637        // Step 5: Update queues with the evaluated outcomes.
8638        let mut bad_singleton_hints: HashMap<PeerId, usize> = HashMap::new();
8639        let mut q = queues.write().await;
8640        for (key, outcome) in evaluated {
8641            let replica_hint_sources = q
8642                .get_pending(&key)
8643                .map(|entry| entry.replica_hint_sources.clone())
8644                .unwrap_or_default();
8645            if let Some(ev) = evidence.get(&key) {
8646                if let Some(source) =
8647                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8648                {
8649                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8650                }
8651            }
8652            match outcome {
8653                KeyVerificationOutcome::QuorumVerified { sources }
8654                | KeyVerificationOutcome::PaidListVerified { sources } => {
8655                    let mut fetch_sources = sources;
8656                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8657                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8658                    if fetch_eligible && write_blocked {
8659                        // Capacity gate, second of two, and deliberately after
8660                        // Step 4: the key is now recorded in `PaidForList` and
8661                        // its verification stands. Only the download is held,
8662                        // because `execute_single_fetch` would refuse it and
8663                        // hand the key straight back here.
8664                        if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8665                            capacity_deferred_promote += 1;
8666                        }
8667                    } else if fetch_eligible && !fetch_sources.is_empty() {
8668                        // A holder answered; see the matching clear on the
8669                        // local-paid path.
8670                        q.clear_unresolved(&key);
8671                        let distance =
8672                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8673                        // Atomic remove+enqueue: on fetch_queue capacity miss
8674                        // the pending entry is preserved so this verified key
8675                        // is retried on the next cycle (no silent drop).
8676                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8677                        // Not terminal — either moved to fetch queue, or
8678                        // retained as pending until queue drains.
8679                    } else if fetch_eligible && fetch_sources.is_empty() {
8680                        no_holder_deferrals += 1;
8681                        let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8682                        let first_report = q.claim_no_holder_report(&key);
8683                        report_unresolved_deferral(
8684                            "Verified storage-admitted key",
8685                            &key,
8686                            outcome,
8687                            first_report,
8688                        );
8689                    } else {
8690                        q.remove_pending(&key);
8691                        terminal_keys.push(key);
8692                    }
8693                }
8694                KeyVerificationOutcome::QuorumFailed => {
8695                    q.remove_pending(&key);
8696                    terminal_keys.push(key);
8697                }
8698                KeyVerificationOutcome::QuorumInconclusive => {
8699                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8700                    // Backed off like any other unresolved round, but it does
8701                    // NOT claim the no-holder report: nothing yet says this key
8702                    // has no holder, so the first round that does say so must
8703                    // still be the one that warns.
8704                    let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8705                }
8706            }
8707        }
8708        drop(q);
8709
8710        for (peer, bad_hint_count) in bad_singleton_hints {
8711            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8712            warn!(
8713                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8714                 sole-source replica hints; \
8715                 reporting {reports} bounded trust failure(s)"
8716            );
8717            for _ in 0..reports {
8718                p2p_node
8719                    .report_trust_event(
8720                        &peer,
8721                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8722                    )
8723                    .await;
8724            }
8725        }
8726    }
8727
8728    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8729    // the drain condition.
8730    update_bootstrap_after_verification(
8731        &terminal_keys,
8732        bootstrap_state,
8733        queues,
8734        is_bootstrapping,
8735        bootstrap_complete_notify,
8736    )
8737    .await;
8738
8739    let (pending_after, fetch_after, in_flight_after) = {
8740        let q = queues.read().await;
8741        (
8742            q.pending_count(),
8743            q.fetch_queue_count(),
8744            q.in_flight_count(),
8745        )
8746    };
8747    let terminal_key_count = terminal_keys.len();
8748    let elapsed_ms = cycle_started.elapsed().as_millis();
8749
8750    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8751        info!(
8752            target: "ant_node::replication::verification",
8753            "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}",
8754        );
8755    } else {
8756        debug!(
8757            target: "ant_node::replication::verification",
8758            "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}",
8759        );
8760    }
8761}
8762
8763/// Report a verification round that left a key without a usable holder.
8764///
8765/// Warns once per entry — the first failure is news, and by the hundredth the
8766/// node is re-asking peers it has already exhausted. Later failures stay at
8767/// `debug`, and the per-cycle count is carried in the cycle summary so the
8768/// scale of a backlog is still visible without a line per key per retry.
8769///
8770/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8771/// number: a round may advance the count without producing a no-holder result,
8772/// and such a round must not consume the warning.
8773///
8774/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8775/// a holder clears it, so a later relapse warns again: "once per episode", not
8776/// "once ever".
8777fn report_unresolved_deferral(
8778    what: &str,
8779    key: &XorName,
8780    outcome: Option<DeferralOutcome>,
8781    first_report: bool,
8782) {
8783    let Some(outcome) = outcome else {
8784        // The entry left `pending_verify` under the same lock; nothing deferred.
8785        return;
8786    };
8787    if first_report {
8788        warn!(
8789            "{what} {} has no responding holders yet; deferring retry",
8790            hex::encode(key)
8791        );
8792    } else {
8793        debug!(
8794            "{what} {} still has no responding holders after {} attempts; \
8795             retrying in {}s",
8796            hex::encode(key),
8797            outcome.attempt,
8798            outcome.retry_after.as_secs()
8799        );
8800    }
8801}
8802
8803/// Add peers that claimed possession as fallback fetch sources.
8804///
8805/// Paid-only advertisers make no possession claim and are absent from
8806/// `replica_hint_sources` by construction, so they are never added.
8807fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8808    for source in replica_hint_sources {
8809        if !sources.contains(source) {
8810            sources.push(*source);
8811        }
8812    }
8813}
8814
8815/// Return the sole replica advertiser when either the close group definitively
8816/// rejects the key or the advertiser explicitly denies possessing it.
8817/// Paid-only advertisements, corroborated replica hints, and inconclusive
8818/// rounds without that direct contradiction are deliberately non-penalizing.
8819fn punishable_singleton_replica_hint_source(
8820    replica_hint_sources: &HashSet<PeerId>,
8821    outcome: &KeyVerificationOutcome,
8822    evidence: &crate::replication::types::KeyVerificationEvidence,
8823) -> Option<PeerId> {
8824    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8825    // reserved for peers that actually claimed possession.
8826    if replica_hint_sources.len() != 1 {
8827        return None;
8828    }
8829    let source = *replica_hint_sources.iter().next()?;
8830    let rejected_by_close_group = matches!(outcome, KeyVerificationOutcome::QuorumFailed);
8831    let denied_possession = evidence.presence.get(&source) == Some(&PresenceEvidence::Absent);
8832
8833    (rejected_by_close_group || denied_possession).then_some(source)
8834}
8835
8836/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8837/// bootstrap pending set and transition out of bootstrapping when drained.
8838async fn update_bootstrap_after_verification(
8839    terminal_keys: &[XorName],
8840    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8841    queues: &Arc<RwLock<ReplicationQueues>>,
8842    is_bootstrapping: &Arc<RwLock<bool>>,
8843    bootstrap_complete_notify: &Arc<Notify>,
8844) {
8845    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8846        return;
8847    }
8848    {
8849        let mut bs = bootstrap_state.write().await;
8850        for key in terminal_keys {
8851            bs.remove_key(key);
8852        }
8853    }
8854    let q = queues.read().await;
8855    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8856        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8857    }
8858}
8859
8860/// Retire bootstrap work owed by a peer that permanently left the routing
8861/// table, then immediately re-check drain so this removal can complete
8862/// bootstrap without waiting for an unrelated pipeline event.
8863async fn update_bootstrap_after_peer_removed(
8864    peer: &PeerId,
8865    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8866    queues: &Arc<RwLock<ReplicationQueues>>,
8867    is_bootstrapping: &Arc<RwLock<bool>>,
8868    bootstrap_complete_notify: &Arc<Notify>,
8869) {
8870    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8871    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8872
8873    if !orphaned_keys.is_empty() {
8874        let mut state = bootstrap_state.write().await;
8875        for key in &orphaned_keys {
8876            state.remove_key(key);
8877        }
8878    }
8879
8880    if orphaned_keys.is_empty() && !cleared_rejection {
8881        return;
8882    }
8883    let q = queues.read().await;
8884    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8885        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8886    }
8887}
8888
8889/// Periodic bootstrap-drain self-healing, run on every verification worker
8890/// tick until bootstrap drains.
8891///
8892/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8893/// recording of a capacity rejection leaves an entry no future event can
8894/// clear — `max_age` expiry is its only exit. And a clean-cycle
8895/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8896/// quiet node the drain condition can become true with nothing left to
8897/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8898/// drain itself, so this is invoked before `run_verification_cycle`'s
8899/// early-returns.
8900async fn expire_and_recheck_bootstrap_drain(
8901    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8902    queues: &Arc<RwLock<ReplicationQueues>>,
8903    is_bootstrapping: &Arc<RwLock<bool>>,
8904    bootstrap_complete_notify: &Arc<Notify>,
8905    max_age: Duration,
8906) {
8907    if bootstrap_state.read().await.is_drained() {
8908        return;
8909    }
8910    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
8911    let q = queues.read().await;
8912    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8913        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8914    }
8915}
8916
8917/// Set `is_bootstrapping` to `false` and wake all waiters.
8918async fn complete_bootstrap(
8919    is_bootstrapping: &Arc<RwLock<bool>>,
8920    bootstrap_complete_notify: &Arc<Notify>,
8921) {
8922    *is_bootstrapping.write().await = false;
8923    bootstrap_complete_notify.notify_waiters();
8924    info!("Replication bootstrap complete");
8925}
8926
8927// ---------------------------------------------------------------------------
8928// Fetch types and single-fetch executor
8929// ---------------------------------------------------------------------------
8930
8931/// Result classification for a single fetch attempt.
8932enum FetchResult {
8933    /// Data fetched, integrity-checked, and stored successfully.
8934    Stored,
8935    /// Content-address integrity check failed — do not retry.
8936    IntegrityFailed,
8937    /// Source failed (network error or non-success response) — retryable.
8938    SourceFailed,
8939    /// This node could not write the chunk locally: the capacity pre-check
8940    /// refused before the dial, or `put` failed after the bytes arrived.
8941    ///
8942    /// Distinct from [`Self::SourceFailed`] because nothing about the source
8943    /// is implicated, and because the remedy is the opposite one. A source
8944    /// failure should move on to the next holder; a local write failure must
8945    /// not — every remaining source would send the same chunk into the same
8946    /// full disk. The key returns to verification instead, so a later cycle
8947    /// retries it once local capacity allows. That is a retry path, not a
8948    /// liveness guarantee: `evict_stale` still expires the entry at
8949    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
8950    /// which re-acquisition depends on a fresh hint.
8951    LocalWriteFailed,
8952    /// This node already holds the key, so there is nothing to fetch —
8953    /// terminal, exactly like [`Self::Stored`], because the duty is already
8954    /// discharged.
8955    ///
8956    /// Responsibility is rechecked at download time; possession has to be too.
8957    /// The earlier gates already drop held keys out of the fetch pipeline —
8958    /// `queue_admitted_hints` skips them, and the promotion-time
8959    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
8960    /// them. (`is_relevant` is not one of them: possession there makes a key
8961    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
8962    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
8963    /// client PUT, or another source landing first. The nearest-first fetch
8964    /// queue is deep enough for that window to be real.
8965    ///
8966    /// This check must also precede the capacity pre-check below, because
8967    /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
8968    /// it, a full node would decline a key it already holds, which `put` would
8969    /// have accepted as a duplicate.
8970    AlreadyHeld,
8971    /// Live routing state no longer places this node in the storage-admission
8972    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
8973    /// the fetch was serving has lapsed, so no alternate source is tried and
8974    /// no trust event is reported: the source did nothing wrong.
8975    NoLongerResponsible,
8976}
8977
8978/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
8979/// worker loop to update queue state.
8980struct FetchOutcome {
8981    key: XorName,
8982    result: FetchResult,
8983}
8984
8985/// What the fetch worker must do next for a key whose fetch attempt resolved.
8986#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8987enum FetchFollowUp {
8988    /// The key terminally left the fetch pipeline (its in-flight entry is
8989    /// removed and any verification retry-slot reservation released); the
8990    /// caller must run bootstrap accounting for it.
8991    Terminal,
8992    /// The key returned to `pending_verify` for a later verification round.
8993    RequeuedForVerification,
8994    /// Retry immediately from this next untried verified source.
8995    RetryFrom(PeerId),
8996}
8997
8998/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
8999///
9000/// Split out of the fetch-worker loop so the per-variant queue transitions
9001/// are unit-testable without a live network. The caller holds the queues
9002/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
9003/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
9004/// retry-slot reservation, and the caller's terminal handling shrinks the
9005/// bootstrap pending set — dropping the key without that accounting would
9006/// stall bootstrap drain forever.
9007///
9008/// The nursery `option_if_let_else` rewrite is impossible here: both
9009/// `map_or_else` closures would need `&mut *q` simultaneously.
9010#[allow(clippy::option_if_let_else)]
9011fn apply_fetch_result(
9012    q: &mut ReplicationQueues,
9013    key: &XorName,
9014    result: &FetchResult,
9015    verification_retry_after: Duration,
9016) -> FetchFollowUp {
9017    match result {
9018        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
9019            q.complete_fetch(key);
9020            FetchFollowUp::Terminal
9021        }
9022        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
9023            if let Some(next_peer) = q.retry_fetch(key) {
9024                FetchFollowUp::RetryFrom(next_peer)
9025            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
9026                FetchFollowUp::RequeuedForVerification
9027            } else {
9028                FetchFollowUp::Terminal
9029            }
9030        }
9031        // No `retry_fetch`: the local write is what failed, so every other
9032        // source would be asked to send the same chunk into the same full
9033        // disk. Requeueing for verification is what keeps the key from being
9034        // stranded — it comes back once capacity allows — and the fallthrough
9035        // to `Terminal` when there is no retry metadata is what keeps
9036        // bootstrap drain accounting correct, exactly as for a source failure.
9037        //
9038        // The ordinary requeue delay, deliberately. A standing capacity block
9039        // does not need a longer one here: the key returns to pending, and the
9040        // gate at the head of the next cycle defers it for minutes. A separate
9041        // backoff on this path would duplicate that to save one 15 s round, on
9042        // a race the gate already makes rare.
9043        FetchResult::LocalWriteFailed => {
9044            if q.requeue_fetch_for_verification(key, verification_retry_after) {
9045                FetchFollowUp::RequeuedForVerification
9046            } else {
9047                FetchFollowUp::Terminal
9048            }
9049        }
9050    }
9051}
9052
9053/// Whether this node currently sits inside the storage-admission group for
9054/// `key`, per live local routing state.
9055///
9056/// This is the one question every storage decision in this module asks; see
9057/// [`admission::is_responsible`]. A purely local routing-table lookup — no
9058/// network I/O — but it awaits into the DHT manager, so callers must not
9059/// hold the queues lock across it.
9060async fn is_storage_admitted(
9061    self_id: &PeerId,
9062    key: &XorName,
9063    p2p_node: &Arc<P2PNode>,
9064    config: &ReplicationConfig,
9065) -> bool {
9066    admission::is_responsible(
9067        self_id,
9068        key,
9069        p2p_node,
9070        storage_admission_width(config.close_group_size),
9071    )
9072    .await
9073}
9074
9075#[allow(clippy::too_many_lines)]
9076/// Execute a single fetch request against `source` for `key`.
9077///
9078/// Handles encoding, network I/O, integrity checking, storage, and trust
9079/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
9080/// queue state without holding any locks during the network round-trip.
9081///
9082/// This is the authoritative storage-responsibility gate: each attempt —
9083/// including every per-source retry, which re-enters here — rechecks live
9084/// routing state before spending bandwidth, and once more before writing
9085/// bytes that arrived after a round-trip. The verification-time check that
9086/// promoted the key into the fetch queue is only a pre-filter; the queue is
9087/// nearest-first and deep, so a promotion decision can go stale under
9088/// topology churn before the key is ever dequeued.
9089async fn execute_single_fetch(
9090    p2p_node: Arc<P2PNode>,
9091    storage: Arc<ChunkStore>,
9092    config: Arc<ReplicationConfig>,
9093    key: XorName,
9094    source: PeerId,
9095) -> FetchOutcome {
9096    let self_id = *p2p_node.peer_id();
9097    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9098        debug!(
9099            "Skipping fetch for {}: no longer in the storage-admission group",
9100            hex::encode(key)
9101        );
9102        return FetchOutcome {
9103            key,
9104            result: FetchResult::NoLongerResponsible,
9105        };
9106    }
9107
9108    // Possession, then capacity — both before the dial, and in that order.
9109    //
9110    // `ChunkStore::put` tests `exists` before it tests disk space, so a full
9111    // node still accepts a key it already holds. Checking possession first is
9112    // what keeps this pair of gates from declining work `put` would have
9113    // taken.
9114    if storage.exists(&key).unwrap_or(false) {
9115        debug!(
9116            "Skipping fetch for {}: already held locally",
9117            hex::encode(key)
9118        );
9119        return FetchOutcome {
9120            key,
9121            result: FetchResult::AlreadyHeld,
9122        };
9123    }
9124
9125    // Capacity is checked before the dial rather than after the bytes arrive.
9126    // `put` runs this same check on every write of a key it does not already
9127    // hold, so this reaches the same verdict `put` would reach *at this
9128    // instant*. It is not a guarantee about the later write: both answers can
9129    // change across the round trip. Space freed in between would have let a
9130    // post-download `put` succeed, so a refusal here can cost a fleeting
9131    // acquisition and one retry cycle of delay; space lost in between is why
9132    // the check inside `put` still has to stay.
9133    //
9134    // What it buys is that the refusal costs no bandwidth. Without it a
9135    // disk-full node pulls the whole chunk over the network first, and the
9136    // failure is then classified as the source's — no trust event, but the
9137    // worker walks to every remaining holder, and each re-uploads the same
9138    // chunk into the same full disk.
9139    if let Err(e) = storage.check_capacity() {
9140        debug!(
9141            "Skipping fetch for {}: local storage cannot accept a write: {e}",
9142            hex::encode(key)
9143        );
9144        return FetchOutcome {
9145            key,
9146            result: FetchResult::LocalWriteFailed,
9147        };
9148    }
9149
9150    let request = protocol::FetchRequest { key };
9151    let msg = ReplicationMessage {
9152        request_id: rand::thread_rng().gen::<u64>(),
9153        body: ReplicationMessageBody::FetchRequest(request),
9154    };
9155
9156    let encoded = match msg.encode() {
9157        Ok(data) => data,
9158        Err(e) => {
9159            warn!("Failed to encode fetch request: {e}");
9160            return FetchOutcome {
9161                key,
9162                result: FetchResult::SourceFailed,
9163            };
9164        }
9165    };
9166
9167    let result = p2p_node
9168        .send_request(
9169            &source,
9170            REPLICATION_PROTOCOL_ID,
9171            encoded,
9172            config.fetch_request_timeout,
9173        )
9174        .await;
9175
9176    match result {
9177        Ok(response) => {
9178            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
9179                p2p_node
9180                    .report_trust_event(
9181                        &source,
9182                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9183                    )
9184                    .await;
9185                return FetchOutcome {
9186                    key,
9187                    result: FetchResult::SourceFailed,
9188                };
9189            };
9190
9191            match resp_msg.body {
9192                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
9193                    key: resp_key,
9194                    data,
9195                }) => {
9196                    // Validate the response key matches the requested key.
9197                    // A malicious peer could serve valid data for a different
9198                    // key, passing integrity checks while the requested key
9199                    // is falsely marked as fetched.
9200                    if resp_key != key {
9201                        warn!(
9202                            "Fetch response key mismatch: requested {}, got {}",
9203                            hex::encode(key),
9204                            hex::encode(resp_key)
9205                        );
9206                        p2p_node
9207                            .report_trust_event(
9208                                &source,
9209                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9210                            )
9211                            .await;
9212                        return FetchOutcome {
9213                            key,
9214                            result: FetchResult::IntegrityFailed,
9215                        };
9216                    }
9217
9218                    // Enforce chunk size invariant on fetched data.
9219                    // Checked before the content-address hash to avoid
9220                    // hashing up to 10 MiB of oversized junk data.
9221                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
9222                        warn!(
9223                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
9224                            hex::encode(resp_key),
9225                            data.len(),
9226                            crate::ant_protocol::MAX_CHUNK_SIZE,
9227                        );
9228                        p2p_node
9229                            .report_trust_event(
9230                                &source,
9231                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9232                            )
9233                            .await;
9234                        return FetchOutcome {
9235                            key,
9236                            result: FetchResult::IntegrityFailed,
9237                        };
9238                    }
9239
9240                    // Content-address integrity check.
9241                    let computed = crate::client::compute_address(&data);
9242                    if computed != resp_key {
9243                        warn!(
9244                            "Fetched record integrity check failed: expected {}, got {}",
9245                            hex::encode(resp_key),
9246                            hex::encode(computed)
9247                        );
9248                        p2p_node
9249                            .report_trust_event(
9250                                &source,
9251                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9252                            )
9253                            .await;
9254                        return FetchOutcome {
9255                            key,
9256                            result: FetchResult::IntegrityFailed,
9257                        };
9258                    }
9259
9260                    // Responsibility can lapse during the network round-trip.
9261                    // The bandwidth is already spent; declining the write is
9262                    // what still avoids the disk write and the later
9263                    // fetch→store→prune churn. Edge flapping is dampened by
9264                    // the margin `storage_admission_width` adds over
9265                    // `close_group_size`.
9266                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9267                        debug!(
9268                            "Fetched {} but responsibility lapsed in transit; not storing",
9269                            hex::encode(key)
9270                        );
9271                        return FetchOutcome {
9272                            key,
9273                            result: FetchResult::NoLongerResponsible,
9274                        };
9275                    }
9276
9277                    if let Err(e) = storage.put(&resp_key, &data).await {
9278                        // The bytes arrived and passed the content-address
9279                        // check, so the source did its job; the failure is
9280                        // entirely local (disk-full, or a storage error). Any
9281                        // valid source must serve identical content, so trying
9282                        // the next one cannot cure a local error — it only
9283                        // re-downloads the same chunk into the same store.
9284                        warn!(
9285                            "Failed to store fetched record {}: {e}",
9286                            hex::encode(resp_key)
9287                        );
9288                        return FetchOutcome {
9289                            key,
9290                            result: FetchResult::LocalWriteFailed,
9291                        };
9292                    }
9293
9294                    FetchOutcome {
9295                        key,
9296                        result: FetchResult::Stored,
9297                    }
9298                }
9299                ReplicationMessageBody::FetchResponse(
9300                    ref response @ (protocol::FetchResponse::NotFound { .. }
9301                    | protocol::FetchResponse::Error { .. }),
9302                ) => {
9303                    // This peer was selected as a fetch source because it recently
9304                    // answered `Present` during verification, so either answer means it
9305                    // could not serve a chunk it had just claimed.
9306                    if let protocol::FetchResponse::Error { reason, .. } = response {
9307                        warn!(
9308                            "Fetch: peer {source} returned error for {}: {reason}",
9309                            hex::encode(key)
9310                        );
9311                    } else {
9312                        warn!(
9313                            "Fetch: verified source {source} returned NotFound for {}",
9314                            hex::encode(key)
9315                        );
9316                    }
9317                    p2p_node
9318                        .report_trust_event(
9319                            &source,
9320                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9321                        )
9322                        .await;
9323                    FetchOutcome {
9324                        key,
9325                        result: FetchResult::SourceFailed,
9326                    }
9327                }
9328                _ => {
9329                    // Unexpected message type — treat as malformed.
9330                    p2p_node
9331                        .report_trust_event(
9332                            &source,
9333                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9334                        )
9335                        .await;
9336                    FetchOutcome {
9337                        key,
9338                        result: FetchResult::SourceFailed,
9339                    }
9340                }
9341            }
9342        }
9343        Err(e) => {
9344            debug!("Fetch request to {source} failed: {e}");
9345            // No ApplicationFailure here — P2PNode::send_request() already
9346            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9347            FetchOutcome {
9348                key,
9349                result: FetchResult::SourceFailed,
9350            }
9351        }
9352    }
9353}
9354
9355// ---------------------------------------------------------------------------
9356// Audit result handler
9357// ---------------------------------------------------------------------------
9358
9359/// Format the first confirmed-failed key as a 16-hex-char label.
9360///
9361/// Pairs with `challenged_peer` to form a stable cross-host correlation
9362/// handle in the audit-failure log line, e.g.
9363///
9364/// ```text
9365/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9366/// ```
9367///
9368/// Falls back to `"0x"` when the list is empty so the log line never
9369/// contains a misleading default.
9370fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9371    confirmed_failed_keys.first().map_or_else(
9372        || "0x".to_string(),
9373        |k| format!("0x{}", hex::encode(&k[..8])),
9374    )
9375}
9376
9377/// Execute the side effects for a subtree storage-commitment audit failure.
9378///
9379/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9380/// legitimately time out on slow or loaded honest peers, so it never touches the
9381/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9382/// failures still penalise immediately and revoke holder credit.
9383async fn handle_subtree_failed_audit(
9384    challenged_peer: &PeerId,
9385    confirmed_failed_key_count: usize,
9386    reason: &AuditFailureReason,
9387    p2p_node: &Arc<P2PNode>,
9388    sync_state: &Arc<RwLock<NeighborSyncState>>,
9389    recent_provers: &Arc<RwLock<RecentProvers>>,
9390) {
9391    if matches!(reason, AuditFailureReason::Timeout) {
9392        debug!(
9393            "Audit timeout for {challenged_peer} fully graced \
9394             (subtree audit does not evict on timeout)"
9395        );
9396        return;
9397    }
9398
9399    // The caller already logged the rich failure line with reason + per-category
9400    // summary; avoid a redundant second error log here.
9401    let _ = confirmed_failed_key_count;
9402    {
9403        let mut state = sync_state.write().await;
9404        state.clear_active_bootstrap_claim(challenged_peer);
9405    }
9406    {
9407        let mut provers_guard = recent_provers.write().await;
9408        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9409    }
9410    p2p_node
9411        .report_trust_event(
9412            challenged_peer,
9413            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9414        )
9415        .await;
9416}
9417
9418/// Handle audit result: log findings and emit trust events.
9419async fn handle_subtree_audit_result(
9420    result: &AuditTickResult,
9421    p2p_node: &Arc<P2PNode>,
9422    sync_state: &Arc<RwLock<NeighborSyncState>>,
9423    recent_provers: &Arc<RwLock<RecentProvers>>,
9424    config: &ReplicationConfig,
9425) {
9426    match result {
9427        AuditTickResult::Passed {
9428            challenged_peer,
9429            keys_checked,
9430        } => {
9431            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9432            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9433            // Peer responded normally — clear the active bootstrap claim while
9434            // retaining history so a later claim is treated as repeated abuse.
9435            {
9436                let mut state = sync_state.write().await;
9437                state.clear_active_bootstrap_claim(challenged_peer);
9438            }
9439            p2p_node
9440                .report_trust_event(
9441                    challenged_peer,
9442                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9443                )
9444                .await;
9445        }
9446        AuditTickResult::Failed {
9447            evidence,
9448            no_response_class,
9449        } => {
9450            if let FailureEvidence::AuditFailure {
9451                challenged_peer,
9452                confirmed_failed_keys,
9453                summary,
9454                reason,
9455                ..
9456            } = evidence
9457            {
9458                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9459                // Rich diagnostics (from main's audit-failure logging) + the
9460                // first-failed-key correlation handle.
9461                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9462                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9463                error!(
9464                    "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}",
9465                    audit_failure_class,
9466                    confirmed_failed_keys.len(),
9467                    summary.challenged_keys,
9468                    summary.absent_keys,
9469                    summary.digest_mismatch_keys,
9470                );
9471                // Route the side effects through the subtree-only failure path.
9472                // Responsible-chunk `AuditChallenge` handling intentionally uses
9473                // its own old immediate-penalty handler below.
9474                handle_subtree_failed_audit(
9475                    challenged_peer,
9476                    confirmed_failed_keys.len(),
9477                    reason,
9478                    p2p_node,
9479                    sync_state,
9480                    recent_provers,
9481                )
9482                .await;
9483            }
9484        }
9485        AuditTickResult::BootstrapClaim { peer } => {
9486            // Gap 6: BootstrapClaimAbuse grace period in audit path.
9487            // Separate state mutation from network I/O to avoid holding the
9488            // write lock across report_trust_event.
9489            let should_report = {
9490                let now = Instant::now();
9491                let mut state = sync_state.write().await;
9492                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9493                {
9494                    BootstrapClaimObservation::WithinGrace { .. } => {
9495                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9496                        false
9497                    }
9498                    BootstrapClaimObservation::PastGrace { first_seen } => {
9499                        warn!(
9500                            "Audit: peer {peer} claiming bootstrap past grace period \
9501                             ({:?} > {:?}), reporting abuse",
9502                            now.duration_since(first_seen),
9503                            config.bootstrap_claim_grace_period,
9504                        );
9505                        true
9506                    }
9507                    BootstrapClaimObservation::Repeated { first_seen } => {
9508                        warn!(
9509                            "Audit: peer {peer} repeated bootstrap claim after previously \
9510                             stopping; first claim was {:?} ago, reporting abuse",
9511                            now.duration_since(first_seen),
9512                        );
9513                        true
9514                    }
9515                }
9516            };
9517            if should_report {
9518                p2p_node
9519                    .report_trust_event(
9520                        peer,
9521                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9522                    )
9523                    .await;
9524            }
9525        }
9526        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9527    }
9528}
9529
9530/// Whether a confirmed audit failure with this reason clears the peer's active
9531/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9532/// bootstrapping); every confirmed storage-integrity reason does.
9533///
9534/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9535/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9536/// still reports the normal audit trust penalty.
9537fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9538    !matches!(reason, AuditFailureReason::Timeout)
9539}
9540
9541/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9542/// events and manage bootstrap-claim state.
9543///
9544/// This is intentionally separate from the subtree audit result handler. A
9545/// responsible-chunk `AuditChallenge` `Failed` result reports
9546/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9547/// restoring the pre-ADR-0002 behaviour.
9548#[allow(clippy::too_many_lines)]
9549async fn handle_audit_result(
9550    result: &AuditTickResult,
9551    p2p_node: &Arc<P2PNode>,
9552    sync_state: &Arc<RwLock<NeighborSyncState>>,
9553    config: &ReplicationConfig,
9554) {
9555    match result {
9556        AuditTickResult::Passed {
9557            challenged_peer,
9558            keys_checked,
9559        } => {
9560            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9561            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9562            {
9563                let mut state = sync_state.write().await;
9564                state.clear_active_bootstrap_claim(challenged_peer);
9565            }
9566            p2p_node
9567                .report_trust_event(
9568                    challenged_peer,
9569                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9570                )
9571                .await;
9572        }
9573        AuditTickResult::Failed {
9574            evidence,
9575            no_response_class,
9576        } => {
9577            if let FailureEvidence::AuditFailure {
9578                challenged_peer,
9579                confirmed_failed_keys,
9580                summary,
9581                reason,
9582                ..
9583            } = evidence
9584            {
9585                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9586                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9587                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9588                error!(
9589                    "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}",
9590                    audit_failure_class,
9591                    confirmed_failed_keys.len(),
9592                    summary.challenged_keys,
9593                    summary.absent_keys,
9594                    summary.digest_mismatch_keys,
9595                );
9596                if audit_failure_clears_bootstrap_claim(reason) {
9597                    let mut state = sync_state.write().await;
9598                    state.clear_active_bootstrap_claim(challenged_peer);
9599                } else {
9600                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9601                }
9602                p2p_node
9603                    .report_trust_event(
9604                        challenged_peer,
9605                        TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9606                    )
9607                    .await;
9608            }
9609        }
9610        AuditTickResult::BootstrapClaim { peer } => {
9611            let should_report = {
9612                let now = Instant::now();
9613                let mut state = sync_state.write().await;
9614                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9615                {
9616                    BootstrapClaimObservation::WithinGrace { .. } => {
9617                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9618                        false
9619                    }
9620                    BootstrapClaimObservation::PastGrace { first_seen } => {
9621                        warn!(
9622                            "Audit: peer {peer} claiming bootstrap past grace period \
9623                             ({:?} > {:?}), reporting abuse",
9624                            now.duration_since(first_seen),
9625                            config.bootstrap_claim_grace_period,
9626                        );
9627                        true
9628                    }
9629                    BootstrapClaimObservation::Repeated { first_seen } => {
9630                        warn!(
9631                            "Audit: peer {peer} repeated bootstrap claim after previously \
9632                             stopping; first claim was {:?} ago, reporting abuse",
9633                            now.duration_since(first_seen),
9634                        );
9635                        true
9636                    }
9637                }
9638            };
9639            if should_report {
9640                p2p_node
9641                    .report_trust_event(
9642                        peer,
9643                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9644                    )
9645                    .await;
9646            }
9647        }
9648        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9649    }
9650}
9651
9652/// Whether a confirmed audit failure with this reason should revoke the
9653/// peer's `recent_provers` holder credit immediately (v12 §6).
9654///
9655/// `true` for any reason where the peer actually answered (or admitted
9656/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9657/// bytes for committed key"), `MalformedResponse` — these prove the
9658/// peer no longer holds what it committed to, so it must not keep
9659/// holder credit for the proof TTL. `false` for `Timeout`: a single
9660/// dropped packet must not strip an honest peer; the 40-min TTL is the
9661/// deliberate liveness cushion there.
9662fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9663    !matches!(reason, AuditFailureReason::Timeout)
9664}
9665
9666/// Apply the holder-credit revocation decision for a confirmed audit
9667/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9668/// testable without a live `P2PNode`: the production `Failed` arm of
9669/// `handle_subtree_audit_result` calls exactly this.
9670fn apply_audit_failure_credit_revocation(
9671    provers: &mut RecentProvers,
9672    challenged_peer: &PeerId,
9673    reason: &AuditFailureReason,
9674) {
9675    if audit_failure_revokes_holder_credit(reason) {
9676        provers.forget_peer(challenged_peer);
9677    }
9678}
9679
9680// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9681
9682// ---------------------------------------------------------------------------
9683// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9684// ---------------------------------------------------------------------------
9685
9686/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9687/// message handler passes one value instead of a long argument list; all
9688/// fields are cheap `Arc` clones.
9689#[derive(Clone)]
9690struct GossipAuditTrigger {
9691    p2p_node: Arc<P2PNode>,
9692    config: Arc<ReplicationConfig>,
9693    recent_provers: Arc<RwLock<RecentProvers>>,
9694    sync_state: Arc<RwLock<NeighborSyncState>>,
9695    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9696    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9697    /// only when a real audit is about to be sent — never by a losing lottery
9698    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9699    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9700    detached_task_tracker: TaskTracker,
9701    /// Gossip-private lottery attempt window: stamped on every roll (win or
9702    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9703    /// The first-audit scheduler never reads this map.
9704    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9705}
9706
9707/// What a gossip ingest yields for the audit trigger: the commitment hash to
9708/// pin and the `key_count` needed to size the response deadline from the actual
9709/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9710/// or not) so a stable-keyset node stays auditable — not just on its first
9711/// commitment.
9712#[derive(Debug, Clone, Copy)]
9713struct AuditTarget {
9714    pin_hash: [u8; 32],
9715    key_count: u32,
9716}
9717
9718/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9719/// verifier's cross-check so it can receive a **deterministic first audit**.
9720///
9721/// Sent from the verifier to the replication engine's first-audit drainer. The
9722/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9723/// audits of the same peer revert to the gossip lottery), orders most-recently-
9724/// monetized first, and runs the same `run_subtree_audit` under the same
9725/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9726#[derive(Debug, Clone, Copy)]
9727pub struct MonetizedPinEvent {
9728    /// The peer whose commitment backed the payment.
9729    pub peer: PeerId,
9730    /// The pinned commitment hash.
9731    pub pin: [u8; 32],
9732    /// The committed key count (sizes the audit deadline).
9733    pub key_count: u32,
9734    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9735    /// pin whose quote is older than the answerability window (ADR-0004 A1
9736    /// guardrail A): with grace removed, challenging an aged-out pin would
9737    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9738    pub quote_ts: SystemTime,
9739}
9740
9741/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9742/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9743/// stamps `now`), `false` if it was audited within
9744/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9745/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9746/// without a live node: a burst of gossips from one peer yields at most one
9747/// `true` per cooldown window.
9748fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9749    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9750    let known = match map.get(peer) {
9751        Some(&last) => {
9752            if now.saturating_duration_since(last) < cooldown {
9753                return false;
9754            }
9755            true
9756        }
9757        None => false,
9758    };
9759    // Bound the map under churn like its siblings (drop the oldest stamp) before
9760    // admitting a brand-new peer.
9761    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9762        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9763            map.remove(&victim);
9764        }
9765    }
9766    map.insert(*peer, now);
9767    true
9768}
9769
9770/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9771/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9772/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9773/// already covered; the authoritative check-and-stamp still runs at promotion,
9774/// so this is only an optimization and never the security boundary.
9775fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9776    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9777    map.get(peer)
9778        .is_none_or(|&last| now.saturating_duration_since(last) >= cooldown)
9779}
9780
9781/// The gossip-audit launch decision in ONE place so the ordering is shared
9782/// between production and its test (ADR-0002 "occasional surprise exams").
9783///
9784/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9785/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9786/// sampled first, a gossip flood would re-roll it on every message until one
9787/// won, multiplying audits, so each peer gets at most one lottery roll per
9788/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9789/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9790/// also consults — only after a WIN, i.e. only when a real audit is about to be
9791/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9792/// wire, so it must not defer a paid first audit (repeatable losses could
9793/// otherwise hold a monetized pin past its answerability window). Production
9794/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9795/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9796/// here fails the test.
9797fn audit_launch_decision(
9798    attempts: &mut HashMap<PeerId, Instant>,
9799    launched: &mut HashMap<PeerId, Instant>,
9800    peer: &PeerId,
9801    now: Instant,
9802    lottery_wins: bool,
9803) -> bool {
9804    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9805    // window even on a loss; private to the gossip path).
9806    if !cooldown_allows_audit(attempts, peer, now) {
9807        return false;
9808    }
9809    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9810    // shared.
9811    if !lottery_wins {
9812        return false;
9813    }
9814    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9815    // either path still suppresses this launch), stamped only on launch.
9816    cooldown_allows_audit(launched, peer, now)
9817}
9818
9819/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9820/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9821/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9822/// handling is never blocked on a network round-trip.
9823async fn maybe_trigger_gossip_audit(
9824    trigger: &GossipAuditTrigger,
9825    peer: &PeerId,
9826    target: AuditTarget,
9827) {
9828    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9829    // lives in the pure `audit_launch_decision` so the ordering is shared with
9830    // its test. Sample the lottery here, then let the helper apply the gates.
9831    let now = Instant::now();
9832    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9833    {
9834        // Lock order: attempts before the shared cooldown; this is the only
9835        // place both are held together.
9836        let mut attempts = trigger.lottery_attempts.write().await;
9837        let mut launched = trigger.cooldown.write().await;
9838        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9839            return;
9840        }
9841    }
9842
9843    let detached_task_tracker = trigger.detached_task_tracker.clone();
9844    let trigger = trigger.clone();
9845    let peer = *peer;
9846    detached_task_tracker.spawn(async move {
9847        let credit = storage_commitment_audit::AuditCredit {
9848            recent_provers: &trigger.recent_provers,
9849        };
9850        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9851            &trigger.p2p_node,
9852            &trigger.config,
9853            &peer,
9854            target.pin_hash,
9855            target.key_count,
9856            Some(&credit),
9857            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9858        )
9859        .await;
9860        handle_subtree_audit_result(
9861            &result,
9862            &trigger.p2p_node,
9863            &trigger.sync_state,
9864            &trigger.recent_provers,
9865            &trigger.config,
9866        )
9867        .await;
9868    });
9869}
9870
9871/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9872///
9873/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9874/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9875/// of its last attempt. Holds one write lock across the decision so two
9876/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9877/// caller's expensive verify so a slow/failed verify still rate-limits the next
9878/// message. Bounds the map under a flood of distinct peer ids.
9879async fn sig_verify_rate_limit_ok(
9880    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9881    source: &PeerId,
9882    now: Instant,
9883) -> bool {
9884    let mut attempts = sig_verify_attempts.write().await;
9885    if let Some(&last) = attempts.get(source) {
9886        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9887            return false;
9888        }
9889    }
9890    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9891        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9892            attempts.remove(&victim);
9893        }
9894    }
9895    attempts.insert(*source, now);
9896    true
9897}
9898
9899/// Verify + store an inbound commitment from a gossip peer.
9900///
9901/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
9902/// the bootstrap-sync loop. Drops the commitment unless all five gates
9903/// pass:
9904///   1. `source` is in our DHT routing table (sybil/churn cap).
9905///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
9906///      binding to the authenticated transport peer).
9907///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
9908///      (the embedded pubkey actually belongs to the claimed identity —
9909///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
9910///   4. `verify_commitment_signature(commitment)` succeeds against the
9911///      embedded public key. The signed payload binds the pubkey, so an
9912///      adversary cannot swap the key while keeping the body.
9913///   5. The cache has room or this is an update for an existing entry
9914///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
9915///
9916/// On all-pass, the commitment is stored as the auditor's per-peer
9917/// "last known commitment" for use as `expected_commitment_hash` in
9918/// future audits.
9919///
9920/// Failures (no commitment / mismatched peer id / bad signature) are
9921/// silent drops — gossip is best-effort and a malformed commitment from
9922/// one peer should not affect anything else.
9923///
9924/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
9925/// or not its root changed), so the caller can run a probabilistic,
9926/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
9927/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
9928/// being auditable, so it cannot pass one audit and then delete data while
9929/// re-gossiping the same root forever. The cooldown + probability bound the
9930/// audit frequency. Returns `None` only if the commitment was dropped (failed a
9931/// gate) or there is nothing to pin.
9932///
9933/// Handle a capable peer gossiping `None` (a commitment downgrade).
9934///
9935/// A capable peer that previously gossiped a commitment but now gossips `None`
9936/// is trying to drop off the audit path. Within the answerability window we keep
9937/// the cached commitment pinned AND return it as an audit target so this gossip
9938/// still schedules a subtree audit against the peer's last known commitment — if
9939/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
9940/// the trigger MUST fire here or the downgrade is never re-challenged).
9941///
9942/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
9943/// honours for its own retired commitment: once that elapses since we last
9944/// received the peer's commitment, an honest peer has legitimately retired that
9945/// root (its responder side `retire_current`s and lets it age out) and can no
9946/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
9947/// failure, so we then forget the cached commitment (keeping the sticky
9948/// `commitment_capable` bit) and stop pinning it.
9949async fn handle_commitment_downgrade(
9950    source: &PeerId,
9951    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
9952) -> Option<AuditTarget> {
9953    let now = Instant::now();
9954    let cached = {
9955        let map = last_commitment_by_peer.read().await;
9956        map.get(source).and_then(|rec| {
9957            if !rec.commitment_capable {
9958                return None;
9959            }
9960            let last = rec.last_commitment()?;
9961            let pin = rec.commitment_hash()?;
9962            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
9963            Some((pin, last.key_count, fresh))
9964        })
9965    };
9966    match cached {
9967        Some((pin, key_count, true)) => {
9968            warn!(
9969                "ingest_peer_commitment: commitment-capable peer {source} sent None \
9970                 (downgrade attempt); auditing against its last cached commitment"
9971            );
9972            Some(AuditTarget {
9973                pin_hash: pin,
9974                key_count,
9975            })
9976        }
9977        Some((_, _, false)) => {
9978            // Cached commitment has aged past the answerability window — forget
9979            // it so we stop pinning a root the peer is no longer obliged to
9980            // answer. Keep `commitment_capable` (sticky). Re-check freshness
9981            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
9982            // from this peer may have refreshed `received_at` in the gap between
9983            // our read and write locks; if so, leave its fresh commitment intact.
9984            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
9985                let still_stale =
9986                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
9987                if still_stale {
9988                    rec.clear_commitment();
9989                    debug!(
9990                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
9991                         commitment aged past the answerability TTL; forgetting it"
9992                    );
9993                }
9994            }
9995            None
9996        }
9997        None => None,
9998    }
9999}
10000
10001async fn ingest_peer_commitment(
10002    source: &PeerId,
10003    commitment: Option<&StorageCommitment>,
10004    p2p_node: &Arc<P2PNode>,
10005    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
10006    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
10007    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
10008) -> Option<AuditTarget> {
10009    let Some(c) = commitment else {
10010        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
10011    };
10012    // RT-membership gate: only accept commitments from peers in our
10013    // routing table. Off-RT senders (sybils, drive-by relays) cannot
10014    // populate the cache, which closes the hole where a flood of
10015    // off-RT identities could fill the cap and evict honest
10016    // peers. The neighbor-sync request handler applies the same gate
10017    // before admitting inbound replication hints (see neighbor_sync.rs
10018    // `sender_in_rt`); we mirror that policy here for the commitment
10019    // piggyback.
10020    if !p2p_node.dht_manager().is_in_routing_table(source).await {
10021        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
10022        return None;
10023    }
10024    // Peer-id binding: the commitment's claimed sender must match the
10025    // authenticated transport peer (`source`). Defeats relay/replay
10026    // and also pins which embedded public key we are about to verify
10027    // against — the verify itself trusts the embedded key, so the
10028    // peer-id binding is the link to a real identity.
10029    if &c.sender_peer_id != source.as_bytes() {
10030        warn!(
10031            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
10032             (dropped, possible relay attempt)"
10033        );
10034        return None;
10035    }
10036    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
10037    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
10038    // with a throwaway key they own and lie about which identity it
10039    // belongs to (the embedded-key signature would verify trivially).
10040    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
10041    if derived_peer_id != c.sender_peer_id {
10042        warn!(
10043            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
10044             {source} (dropped, throwaway-key attack)"
10045        );
10046        return None;
10047    }
10048    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
10049    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
10050    // sybil/RT-membership-bypassing peer that flooded valid-looking
10051    // gossip would otherwise burn CPU on every message. The rate
10052    // limit is checked AFTER cheap structural gates (RT, peer-id
10053    // binding, pubkey-binding) and BEFORE the expensive sig verify.
10054    //
10055    // Tracked in `sig_verify_attempts` (separate from
10056    // last_commitment_by_peer) so EVERY attempt — successful or not —
10057    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
10058    // would skip the cap for peers we've never successfully verified,
10059    // letting a flood of invalid-but-structurally-plausible gossips
10060    // burn CPU.
10061    let now = Instant::now();
10062    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
10063        debug!(
10064            "ingest_peer_commitment: rate-limited sig verify from {source} \
10065             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
10066        );
10067        return None;
10068    }
10069    // Signature verify, using the public key embedded in the commitment
10070    // itself. The pubkey is bound by the signature payload (see
10071    // commitment_signed_payload) so an adversary cannot keep the body
10072    // and swap the key to one they hold the secret for.
10073    if !crate::replication::commitment::verify_commitment_signature(c) {
10074        warn!(
10075            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
10076             (dropped, forged commitment)"
10077        );
10078        return None;
10079    }
10080    // The new commitment's hash, used to store and to pin for the audit target.
10081    let new_hash = commitment_hash(c);
10082    let mut map = last_commitment_by_peer.write().await;
10083    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
10084    // evict an arbitrary existing entry to make room. Updates for peers
10085    // already in the map are always accepted (they replace, not grow).
10086    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
10087        // Drop one arbitrary entry. HashMap iter order is random which
10088        // is fine — over time PeerRemoved cleanup keeps the working set
10089        // anchored on the real RT membership; this cap only fires under
10090        // active flooding attempts.
10091        if let Some(victim) = map.keys().next().copied() {
10092            map.remove(&victim);
10093            warn!(
10094                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
10095                 evicted {victim} to admit {source}"
10096            );
10097        }
10098    }
10099    // Preserve sticky commitment_capable across updates — once true,
10100    // always true. New entries start with capable = true (we just
10101    // verified a valid commitment from this peer).
10102    map.entry(*source)
10103        .and_modify(|r| {
10104            // set_commitment refreshes the cached hash (§13) alongside the
10105            // commitment + received_at so they never drift.
10106            r.set_commitment(c.clone(), now);
10107            r.last_sig_verify_at = now;
10108            r.commitment_capable = true; // sticky-redundant but explicit
10109        })
10110        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
10111    drop(map);
10112    // Record the sticky "ever v12-capable" bit in a set independent of
10113    // `last_commitment_by_peer` (whose entries can be evicted by
10114    // `PeerRemoved` and the sybil cap). This is what the §3 audit
10115    // shield and the §6 holder-eligibility closure consult to decide
10116    // whether the peer is expected to speak v12.
10117    //
10118    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
10119    // identity-rotation attacks: once full, new entries are refused.
10120    // Refusal degrades over-cap peers to the behaviour before this set
10121    // existed (treated as legacy on rejoin), which is not a security
10122    // regression and preserves the historic set stable.
10123    {
10124        let mut set = ever_capable_peers.write().await;
10125        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
10126            set.insert(*source);
10127        } else {
10128            warn!(
10129                "ingest_peer_commitment: ever_capable_peers at cap \
10130                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
10131            );
10132        }
10133    }
10134    // Return an audit target for EVERY valid stored commitment (changed or
10135    // not), so the caller's cooldown+probability-gated trigger keeps a
10136    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
10137    // failure (new_hash == None, unreachable for a real commitment) yields None.
10138    new_hash.map(|pin_hash| AuditTarget {
10139        pin_hash,
10140        key_count: c.key_count,
10141    })
10142}
10143
10144// ---------------------------------------------------------------------------
10145// Storage-bound audit (v12) — responder commitment rotation
10146// ---------------------------------------------------------------------------
10147
10148/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
10149/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
10150/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
10151async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
10152    let bytes = match tokio::fs::read(path).await {
10153        Ok(b) => b,
10154        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
10155            debug!(
10156                "Commitment retention: no snapshot at {} (fresh start)",
10157                path.display()
10158            );
10159            return;
10160        }
10161        Err(e) => {
10162            warn!(
10163                "Commitment retention: failed to read {}: {e}",
10164                path.display()
10165            );
10166            return;
10167        }
10168    };
10169    if let Some(mut persisted) = PersistedRetention::from_bytes(&bytes) {
10170        let sidecar = pointer_leaves_path(path);
10171        match tokio::fs::read(&sidecar).await {
10172            Ok(leaves) => {
10173                if !persisted.attach_pointer_leaves(&leaves) {
10174                    warn!(
10175                        "Commitment retention: corrupt pointer leaves at {}; \
10176                         commitments holding pointers will not be restored",
10177                        sidecar.display()
10178                    );
10179                }
10180            }
10181            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
10182            Err(e) => warn!(
10183                "Commitment retention: failed to read {}: {e}",
10184                sidecar.display()
10185            ),
10186        }
10187        state.restore(&persisted);
10188        info!(
10189            "Commitment retention: reloaded {} slot(s) from {}",
10190            state.retained_slot_count(),
10191            path.display()
10192        );
10193    } else {
10194        warn!(
10195            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
10196            path.display()
10197        );
10198    }
10199}
10200
10201/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
10202/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
10203/// needless disk writes on idle nodes. On success updates `last` to the bytes
10204/// written; on a serialization/write error the existing on-disk snapshot is left
10205/// intact (never truncated).
10206///
10207/// The pointer leaves go to a sidecar written first (ADR-0016), so the
10208/// retention file never names a commitment whose pointer leaves are not yet
10209/// on disk. A crash between the two leaves a sidecar ahead of the file, which
10210/// is harmless: it is keyed by commitment hash.
10211async fn persist_retention_if_changed(
10212    state: &ResponderCommitmentState,
10213    path: &Path,
10214    last: &mut Option<Vec<u8>>,
10215) {
10216    let snapshot = state.snapshot();
10217    let (Some(bytes), Some(leaves)) = (snapshot.to_bytes(), snapshot.pointer_leaves_bytes()) else {
10218        warn!("Commitment retention: serialization failed; keeping previous snapshot");
10219        return;
10220    };
10221    let mut combined = leaves.clone();
10222    combined.extend_from_slice(&bytes);
10223    if last.as_deref() == Some(combined.as_slice()) {
10224        return;
10225    }
10226    if write_retention_atomic(&pointer_leaves_path(path), leaves).await
10227        && write_retention_atomic(path, bytes).await
10228    {
10229        *last = Some(combined);
10230    }
10231}
10232
10233/// Where the pointer leaves of the retention at `path` are kept.
10234fn pointer_leaves_path(path: &Path) -> PathBuf {
10235    path.with_file_name("commitment_retention_pointers.bin")
10236}
10237
10238/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
10239/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
10240/// success. Only the retention-persist loop writes this path, so a fixed temp
10241/// name is safe.
10242async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
10243    let path = path.to_path_buf();
10244    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
10245        let tmp = path.with_extension("tmp");
10246        std::fs::write(&tmp, &bytes)?;
10247        std::fs::File::open(&tmp)?.sync_all()?;
10248        std::fs::rename(&tmp, &path)?;
10249        // Fsync the directory so the rename (the durable-commit point) is not
10250        // lost on a crash right after it. An empty parent (relative filename)
10251        // means the current directory.
10252        let dir = path
10253            .parent()
10254            .filter(|p| !p.as_os_str().is_empty())
10255            .unwrap_or_else(|| Path::new("."));
10256        std::fs::File::open(dir)?.sync_all()?;
10257        Ok(())
10258    })
10259    .await;
10260    match res {
10261        Ok(Ok(())) => true,
10262        Ok(Err(e)) => {
10263            warn!("Commitment retention: persist failed: {e}");
10264            false
10265        }
10266        Err(e) => {
10267            warn!("Commitment retention: persist task join failed: {e}");
10268            false
10269        }
10270    }
10271}
10272
10273/// Read the current key set, build + sign a fresh
10274/// `StorageCommitment`, and rotate it into `state` as the new `current`.
10275/// The prior `current` is demoted to `previous`; the prior `previous` is
10276/// dropped (per `ResponderCommitmentState::rotate`).
10277///
10278/// For content-addressed chunks (Autonomi's chunk store), `address ==
10279/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
10280/// re-read each chunk's bytes to compute the leaf hash.
10281///
10282/// The pointers this node is responsible for are committed alongside, each as
10283/// `(address, pointer_leaf_hash(address))` (ADR-0016), so they are audited and
10284/// priced exactly as chunks are.
10285///
10286/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
10287/// rotate. The auditor side handles "no commitment for this peer" by
10288/// falling back to the legacy plain-digest audit path.
10289async fn rebuild_and_rotate_commitment(
10290    storage: &Arc<ChunkStore>,
10291    pointers: Option<&PointerStore>,
10292    identity: &Arc<NodeIdentity>,
10293    state: &Arc<ResponderCommitmentState>,
10294    p2p: &Arc<P2PNode>,
10295    config: &Arc<ReplicationConfig>,
10296) -> Result<()> {
10297    // `all_keys()` is what the store can answer for: it already drops a file marked suspect or
10298    // known-wrong, so a name that cannot be read is not offered here. It is NOT the commitment
10299    // set — that is narrowed to the keys this node is still responsible for, by the filter a
10300    // few lines below, and not by this call. The comment that used to be here said "not
10301    // `all_keys()`" immediately above the call to it, which is the sort of thing that sends
10302    // somebody to change the wrong layer.
10303    let stored_keys = storage
10304        .all_keys()
10305        .await
10306        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
10307
10308    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
10309    // everything currently on disk ("hold"). This is the half of the retention
10310    // contract that lets out-of-range chunks age out: a key that has left our
10311    // close group is excluded from the NEXT commitment, so once its last gossip
10312    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
10313    // set, `ResponderCommitmentState::is_held` goes false,
10314    // and the pruner (which until then vetoes its deletion) reclaims it. Without
10315    // this filter the pruner's reprieve would keep re-committing stale keys
10316    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
10317    // re-committed and re-gossiped every rotation — a permanent pin).
10318    let self_id = *p2p.peer_id();
10319    let mut keys = Vec::with_capacity(stored_keys.len());
10320    for k in stored_keys {
10321        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
10322            keys.push(k);
10323        }
10324    }
10325    // The same rule for pointers: an out-of-range pointer leaves the next
10326    // commitment, and the pruner reclaims it once no retained slot holds it.
10327    let mut pointer_keys = Vec::new();
10328    for state in pointers.map(PointerStore::held_states).unwrap_or_default() {
10329        if admission::is_responsible(&self_id, &state.address, p2p, config.close_group_size).await {
10330            pointer_keys.push(state.address);
10331        }
10332    }
10333
10334    if keys.is_empty() && pointer_keys.is_empty() {
10335        // There used to be a second branch here that dropped every retained root outright
10336        // when the node looked empty. It is gone, and the reason is worth keeping.
10337        //
10338        // "Empty" was decided from key counts, and every version of that test was wrong in
10339        // the same direction: a node can hold bytes the counts do not show, because a file is
10340        // published before it is indexed. Each fix closed one window and left another.
10341        //
10342        // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10343        // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10344        // lane, so a node that still holds the bytes is penalised for holding them. Retiring
10345        // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10346        // instead of vanishing now. Both set `has_current = false`; they differ only in
10347        // whether the node goes on being answerable in the meantime. A genuinely empty node
10348        // cannot answer either way, so retiring costs it nothing it had.
10349        //
10350        // So there is one branch, and no emptiness question to get wrong.
10351        //
10352        // A peer may still be pinning a root we gossiped
10353        // moments ago and could demand its bytes in a round-2 challenge, which
10354        // we can still answer (the bytes are present). But we must STOP
10355        // advertising the stale commitment: retire it so `current()` returns
10356        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10357        // The retired slot then ages out by its gossip-answerability TTL while
10358        // remaining answerable for in-flight pins until then. Once it ages out,
10359        // `is_held` flips false and the pruner reclaims the now-uncommitted,
10360        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10361        // pointing at the stale root, which the gossip loop would keep
10362        // re-stamping — pinning its keys forever.)
10363        debug!(
10364            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10365             (stays answerable until its gossip TTL lapses, bytes still on disk)"
10366        );
10367        state.retire_current();
10368        return Ok(());
10369    }
10370
10371    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10372    // to more than the protocol limit; auditor would reject the
10373    // commitment otherwise).
10374    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10375    let total = keys.len().saturating_add(pointer_keys.len());
10376    if total > cap {
10377        warn!(
10378            "Commitment rotation: key set ({total}) exceeds MAX_COMMITMENT_KEY_COUNT ({cap}); \
10379             truncating — investigate as this likely means a misconfiguration"
10380        );
10381    }
10382
10383    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10384    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10385    // full chunk re-read per rotation.
10386    //
10387    // Consequence to be precise about: because the leaf is `(key, key)`,
10388    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10389    // commitment therefore binds "which keys I claim to hold"; it does NOT
10390    // by itself prove byte possession. Byte possession is enforced by the
10391    // round-2 slice audit: a Bao verified slice decoded against the chunk
10392    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10393    // nonce, so a responder that holds the key list but dropped the bytes
10394    // cannot answer. This is sound ONLY while keys are content addresses;
10395    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10396    // (`evaluate_subtree_structure`), so a non-content-addressed
10397    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10398    // earn credit for `key`. If this module is ever reused for
10399    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10400    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10401    //
10402    // Pointers are that case, and are handled by being told apart rather than
10403    // hashed: a pointer leaf is `(address, pointer_leaf_hash(address))`, which
10404    // the verifier accepts only for a leaf of exactly a pointer's size, and
10405    // round 2 then demands the whole signed record in place of a Bao slice.
10406    // The root binds which pointers are held, never their current state, so an
10407    // update does not move it.
10408    //
10409    // A pointer address that is also a chunk key would need a BLAKE3 preimage;
10410    // the dedup only keeps such a collision from failing the whole build.
10411    let mut entries: Vec<_> = keys
10412        .into_iter()
10413        .map(|k| (k, k))
10414        .chain(
10415            pointer_keys
10416                .into_iter()
10417                .map(|address| (address, commitment::pointer_leaf_hash(&address))),
10418        )
10419        .collect();
10420    entries.sort_by_key(|(k, _)| *k);
10421    entries.dedup_by_key(|(k, _)| *k);
10422    entries.truncate(cap);
10423
10424    // No-op-rotation guard: compute just the Merkle root from `entries`
10425    // and compare against the currently-advertised commitment's root.
10426    // If they match, the key set is unchanged and a new rotation would
10427    // only swap a randomized ML-DSA signature for a fresh one — same
10428    // content, different commitment_hash. That invalidates every
10429    // outstanding `recent_provers` credit on this node across the
10430    // close group with no security benefit, breaking steady-state
10431    // quorum liveness on large nodes that can't re-audit every key
10432    // every rotation interval. Skip the rotation entirely when the
10433    // tree is unchanged.
10434    // Build the tree ONCE here (moving `entries`): it serves both the no-op
10435    // root check below and, if we proceed, the signed commitment via
10436    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10437    // inside `BuiltCommitment::build`).
10438    let candidate_tree = commitment::MerkleTree::build(entries)
10439        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10440    let candidate_root = candidate_tree.root();
10441    if let Some(current) = state.current() {
10442        if current.commitment().root == candidate_root {
10443            debug!(
10444                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10445                hex::encode(candidate_root)
10446            );
10447            // Even though we skip re-signing (to avoid invalidating holder
10448            // credit), retention must still advance on the wall clock: a
10449            // previously-gossiped commitment that holds a now-out-of-range key
10450            // must be able to age out of the answerability window even when the
10451            // committed key set is frozen here for many rotations. Without this,
10452            // the no-op guard would pin a stale slot — and its key — forever.
10453            state.age_out();
10454            return Ok(());
10455        }
10456    }
10457
10458    let sk_bytes = identity.secret_key_bytes().to_vec();
10459    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10460        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10461    let pk_bytes = identity.public_key().as_bytes().to_vec();
10462    let peer_id_bytes = *p2p.peer_id().as_bytes();
10463
10464    let built = commitment_state::BuiltCommitment::build_from_tree(
10465        candidate_tree,
10466        &peer_id_bytes,
10467        &sk,
10468        &pk_bytes,
10469    )
10470    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10471
10472    let hash = hex::encode(built.hash());
10473    let key_count = built.commitment().key_count;
10474    let pointer_count = built.tree().pointer_count();
10475    state.rotate(built);
10476    info!("Storage commitment rotated: hash={hash} key_count={key_count} pointers={pointer_count}");
10477    Ok(())
10478}
10479
10480#[cfg(test)]
10481#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10482mod tests {
10483
10484    /// The responder's answer says whether it lacks the chunk or failed to read it.
10485    ///
10486    /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10487    /// an I/O fault or a failed integrity check, reads as `Err`. Nothing turns the first
10488    /// into the second.
10489    #[tokio::test]
10490    async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10491        let dir = tempfile::tempdir().expect("temp dir");
10492        let storage = crate::storage::ChunkStore::new(crate::storage::ChunkStoreConfig {
10493            root_dir: dir.path().to_path_buf(),
10494            verify_on_read: true,
10495            disk_reserve: 0,
10496        })
10497        .await
10498        .expect("open store");
10499
10500        let absent = [9u8; 32];
10501        assert!(
10502            matches!(storage.get(&absent).await, Ok(None)),
10503            "a chunk this node does not hold must read as a plain miss, not a fault"
10504        );
10505
10506        // And the answer each read produces: a miss is `NotFound`, a failed read is `Error`.
10507        // Both are charged to a verified source that gives them, but they say different
10508        // things to whoever reads the logs.
10509        assert!(matches!(
10510            fetch_response_for(absent, Ok(None)),
10511            protocol::FetchResponse::NotFound { .. }
10512        ));
10513        assert!(matches!(
10514            fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10515            protocol::FetchResponse::Success { .. }
10516        ));
10517        assert!(matches!(
10518            fetch_response_for(
10519                absent,
10520                Err(crate::error::Error::Storage("read failed".into()))
10521            ),
10522            protocol::FetchResponse::Error { .. }
10523        ));
10524    }
10525    use super::*;
10526    use super::{
10527        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10528        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10529        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10530        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10531        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10532        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10533        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10534        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10535    };
10536    use crate::payment::VerificationContext;
10537    use crate::replication::audit::AuditTickResult;
10538    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10539    use crate::replication::recent_provers::RecentProvers;
10540    use crate::replication::types::{AuditFailureReason, FailureEvidence};
10541    use lru::LruCache;
10542    use saorsa_core::identity::PeerId;
10543    use std::collections::HashMap;
10544    use std::num::NonZeroUsize;
10545    use std::sync::atomic::Ordering;
10546    use std::sync::Arc;
10547    use std::time::Duration;
10548    use std::time::Instant;
10549    use std::time::SystemTime;
10550
10551    #[test]
10552    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10553        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10554            assert_eq!(match_replication_protocol(id), Some((id, false)));
10555            assert_eq!(
10556                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10557                Some((id, true))
10558            );
10559        }
10560        assert_eq!(
10561            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10562            None
10563        );
10564        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10565        assert_eq!(match_replication_protocol(RR_PREFIX), None);
10566    }
10567
10568    #[test]
10569    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10570        use crate::replication::protocol::{
10571            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10572            SubtreeSliceChallenge,
10573        };
10574
10575        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10576            challenge_id: 1,
10577            nonce: [0u8; 32],
10578            challenged_peer_id: [0u8; 32],
10579            expected_commitment_hash: [0u8; 32],
10580            openings: vec![],
10581        });
10582        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10583            challenge_id: 1,
10584            nonce: [0u8; 32],
10585            challenged_peer_id: [0u8; 32],
10586            keys: vec![[0u8; 32]],
10587        });
10588        let digest_response =
10589            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10590        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10591            key: [0u8; 32],
10592            data: vec![],
10593            proof_of_payment: vec![],
10594        });
10595
10596        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10597        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10598
10599        for body in [&digest_challenge, &digest_response, &core] {
10600            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10601            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10602        }
10603
10604        for body in [&subtree, &digest_challenge, &digest_response, &core] {
10605            assert!(body_matches_protocol(body, response_protocol_for(body)));
10606        }
10607    }
10608
10609    fn test_peer(b: u8) -> PeerId {
10610        let mut bytes = [0u8; 32];
10611        bytes[0] = b;
10612        PeerId::from_bytes(bytes)
10613    }
10614
10615    /// A structurally valid offer for `data`: real content address, a proof of
10616    /// the minimum accepted size, distinguished by `proof_marker` so a test can
10617    /// tell whose proof came back out of the queue.
10618    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10619        protocol::FreshReplicationOffer {
10620            key: crate::client::compute_address(&data),
10621            data,
10622            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10623        }
10624    }
10625
10626    fn admit_test_offer(
10627        in_flight: &FreshOfferInFlight,
10628        offer: protocol::FreshReplicationOffer,
10629        source: PeerId,
10630    ) -> FreshOfferAdmission {
10631        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10632    }
10633
10634    #[test]
10635    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10636        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10637        let data = vec![0x11u8; 64];
10638
10639        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10640        let FreshOfferAdmission::Opened(entry) = opened else {
10641            panic!("first offer for a key should open the entry")
10642        };
10643
10644        // A second sender contributes its proof instead of being turned away:
10645        // its bytes are provably the same, so only the proof is worth keeping.
10646        assert!(
10647            matches!(
10648                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10649                FreshOfferAdmission::Joined
10650            ),
10651            "a duplicate from a new source should queue its proof"
10652        );
10653        // The same peer twice is not extra evidence, just extra work.
10654        assert!(
10655            matches!(
10656                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10657                FreshOfferAdmission::DuplicateSource
10658            ),
10659            "one source should hold at most one queued proof per key"
10660        );
10661
10662        // An entry that outlived its handler would bar the key forever.
10663        drop(entry);
10664        assert!(
10665            matches!(
10666                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10667                FreshOfferAdmission::Opened(_)
10668            ),
10669            "a released key should be openable again"
10670        );
10671    }
10672
10673    #[test]
10674    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10675        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10676
10677        // A node only receives offers for keys close to its own ID, so accepted
10678        // keys share a long prefix. Any prefix-derived shard index would have
10679        // funnelled these two onto one lock and serialized them.
10680        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10681        assert!(
10682            matches!(
10683                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10684                FreshOfferAdmission::Opened(_)
10685            ),
10686            "distinct keys should never block each other"
10687        );
10688    }
10689
10690    /// The regression that motivated queueing proofs at all.
10691    ///
10692    /// A sender whose proof does not verify must cost the network its own
10693    /// attempt and nothing more. Refusing every later offer outright made the
10694    /// first arrival the only arrival, so one bad proof lost the record — and
10695    /// the delayed possession check then charged that absence to this node.
10696    #[test]
10697    fn a_failing_proof_hands_the_key_to_the_next_sender() {
10698        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10699        let data = vec![0x5Au8; 128];
10700        let forger = test_peer(0xF0);
10701        let genuine = test_peer(0x0F);
10702
10703        let FreshOfferAdmission::Opened(mut entry) =
10704            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10705        else {
10706            panic!("the first offer should open the entry");
10707        };
10708        assert!(
10709            matches!(
10710                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10711                FreshOfferAdmission::Joined
10712            ),
10713            "the genuine sender must not be turned away by the forger"
10714        );
10715
10716        let first = entry
10717            .next_attempt()
10718            .expect("the opener's proof comes first");
10719        assert_eq!(first.source, forger);
10720
10721        // Treat the forger's proof as failed: the next one is still reachable,
10722        // and it is tried against the bytes already held rather than a refetch.
10723        let second = entry
10724            .next_attempt()
10725            .expect("a failed proof must not consume the key");
10726        assert_eq!(second.source, genuine);
10727        assert_eq!(
10728            second.proof_of_payment,
10729            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10730        );
10731        assert_eq!(
10732            entry.data(),
10733            data.as_slice(),
10734            "every proof is tried against the one copy of the bytes"
10735        );
10736
10737        // Draining the queue releases the key rather than stranding it.
10738        assert!(entry.next_attempt().is_none());
10739        assert!(
10740            matches!(
10741                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10742                FreshOfferAdmission::Opened(_)
10743            ),
10744            "an exhausted entry should release its key"
10745        );
10746    }
10747
10748    /// The cap has to be a lifetime budget, not a queue depth.
10749    ///
10750    /// The handler pops a proof before verifying it, so gating admission on the
10751    /// *instantaneous* queue length lets a fresh source refill the slot that pop
10752    /// just freed. Each refill is another on-chain payment verification, run
10753    /// sequentially while the entry holds its admission permit and a worker
10754    /// slot, so a stream of distinct sources could keep one key's handler — and
10755    /// one of only four workers — busy indefinitely.
10756    #[test]
10757    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10758        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10759        let data = vec![0x3Du8; 32];
10760
10761        let FreshOfferAdmission::Opened(mut entry) =
10762            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10763        else {
10764            panic!("the first offer should open the entry")
10765        };
10766
10767        // Drive pop-then-admit with a fresh source every time, exactly as a
10768        // sybil stream would. The budget must be spent by admissions, not
10769        // returned by pops.
10770        let mut admitted = 1;
10771        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10772            let _ = entry.next_attempt();
10773            if matches!(
10774                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10775                FreshOfferAdmission::Joined
10776            ) {
10777                admitted += 1;
10778            }
10779        }
10780
10781        assert!(
10782            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10783            "a key accepted {admitted} proofs over its lifetime, but the budget is \
10784             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10785        );
10786    }
10787
10788    #[test]
10789    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10790        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10791        let data = vec![0x2Cu8; 32];
10792
10793        // The opener occupies the first slot, so the cap is reached after
10794        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10795        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10796        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10797            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10798            assert!(
10799                matches!(
10800                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10801                    FreshOfferAdmission::Joined
10802                ),
10803                "sender {i} is within the legitimate close-group fan-out"
10804            );
10805        }
10806
10807        let surplus = test_peer(0xEE);
10808        assert!(
10809            matches!(
10810                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10811                FreshOfferAdmission::Full
10812            ),
10813            "past the cap a proof is surplus: enough are already queued to place the record"
10814        );
10815    }
10816
10817    #[test]
10818    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10819        assert!(!verification_request_exceeds_limit(
10820            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10821        ));
10822        assert!(verification_request_exceeds_limit(
10823            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10824        ));
10825    }
10826
10827    // The heavy round-1 limiter enforces the per-peer rate cooldown
10828    // and single-use round-1 → round-2 sessions.
10829    #[tokio::test]
10830    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10831        let limiter = SubtreeRound1Limiter::new(
10832            Duration::from_hours(1),
10833            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10834        );
10835        let peer = test_peer(1);
10836
10837        // First round-1 is admitted; drop the guard so concurrency is free again.
10838        let guard = limiter.admit(&peer).await;
10839        assert!(guard.is_some(), "first round-1 admitted");
10840        drop(guard);
10841        // A second round-1 within the cooldown is dropped even though the heavy
10842        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10843        assert!(
10844            limiter.admit(&peer).await.is_none(),
10845            "second round-1 within cooldown is rate-dropped"
10846        );
10847        // A different peer has its own cooldown.
10848        assert!(limiter.admit(&test_peer(2)).await.is_some());
10849
10850        // Session: opened by round 1, consumed exactly once by the matching round 2.
10851        let hash = [7u8; 32];
10852        let nonce = [9u8; 32];
10853        assert!(
10854            limiter
10855                .open_session(peer, 42, hash, nonce, PointerBindings::new())
10856                .await
10857        );
10858        // Wrong nonce / commitment does not match.
10859        assert!(limiter
10860            .consume_session(&peer, 42, &hash, &[0u8; 32])
10861            .await
10862            .is_none());
10863        assert!(limiter
10864            .consume_session(&peer, 42, &[0u8; 32], &nonce)
10865            .await
10866            .is_none());
10867        // A round 2 with no prior round 1 (wrong challenge_id) misses.
10868        assert!(limiter
10869            .consume_session(&peer, 99, &hash, &nonce)
10870            .await
10871            .is_none());
10872        // The matching round 2 consumes it — and only once (single-use).
10873        assert!(limiter
10874            .consume_session(&peer, 42, &hash, &nonce)
10875            .await
10876            .is_some());
10877        assert!(limiter
10878            .consume_session(&peer, 42, &hash, &nonce)
10879            .await
10880            .is_none());
10881    }
10882
10883    // A session carries what its round 1 bound for each pointer to round 2,
10884    // and every live session together stays under the binding budget. A
10885    // session that does not fit is refused, and no session already opened
10886    // gives up its bindings or its place for it.
10887    #[tokio::test]
10888    async fn subtree_session_carries_pointer_bindings_within_the_budget() {
10889        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10890        let (hash, nonce) = ([1u8; 32], [2u8; 32]);
10891        let bindings = |from: u64, count: usize| -> PointerBindings {
10892            (from..)
10893                .take(count)
10894                .map(|i| {
10895                    let mut key = [0u8; 32];
10896                    key[..8].copy_from_slice(&i.to_le_bytes());
10897                    (key, [0xAB; 32])
10898                })
10899                .collect()
10900        };
10901
10902        let half = MAX_SESSION_POINTER_BINDINGS / 2;
10903        let first = bindings(0, half);
10904        assert!(
10905            limiter
10906                .open_session(test_peer(1), 1, hash, nonce, first.clone())
10907                .await
10908        );
10909        assert!(
10910            limiter
10911                .open_session(test_peer(2), 2, hash, nonce, bindings(1 << 40, half))
10912                .await
10913        );
10914        // The budget is full: one more binding is refused, but a round 1 with
10915        // no pointers in it still opens.
10916        assert!(
10917            !limiter
10918                .open_session(test_peer(3), 3, hash, nonce, bindings(1 << 41, 1))
10919                .await
10920        );
10921        assert!(
10922            limiter
10923                .open_session(test_peer(4), 4, hash, nonce, PointerBindings::new())
10924                .await
10925        );
10926
10927        assert_eq!(
10928            limiter
10929                .consume_session(&test_peer(1), 1, &hash, &nonce)
10930                .await,
10931            Some(first.clone()),
10932            "an opened session keeps every binding it was given"
10933        );
10934        assert!(
10935            limiter
10936                .consume_session(&test_peer(3), 3, &hash, &nonce)
10937                .await
10938                .is_none(),
10939            "a refused session was never opened"
10940        );
10941        assert_eq!(
10942            limiter
10943                .consume_session(&test_peer(2), 2, &hash, &nonce)
10944                .await
10945                .map(|b| b.len()),
10946            Some(half)
10947        );
10948
10949        // Consumed sessions free their room.
10950        assert!(
10951            limiter
10952                .open_session(test_peer(5), 5, hash, nonce, bindings(1 << 42, half))
10953                .await
10954        );
10955    }
10956
10957    // A session refused for the binding budget is refused before the session
10958    // cap evicts anything: with both full, the refusal costs no session its
10959    // place.
10960    #[tokio::test]
10961    async fn a_session_refused_for_bindings_evicts_no_other_session() {
10962        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
10963        let (hash, nonce) = ([1u8; 32], [2u8; 32]);
10964        let full: PointerBindings = (0u64..)
10965            .take(MAX_SESSION_POINTER_BINDINGS)
10966            .map(|i| {
10967                let mut key = [0u8; 32];
10968                key[..8].copy_from_slice(&i.to_le_bytes());
10969                (key, [0xCD; 32])
10970            })
10971            .collect();
10972        assert!(
10973            limiter
10974                .open_session(test_peer(0), 0, hash, nonce, full)
10975                .await
10976        );
10977        for id in 1..MAX_SUBTREE_SESSIONS as u64 {
10978            assert!(
10979                limiter
10980                    .open_session(test_peer(1), id, hash, nonce, PointerBindings::new())
10981                    .await
10982            );
10983        }
10984
10985        let one: PointerBindings = std::iter::once(([0xEE; 32], [0xEE; 32])).collect();
10986        assert!(
10987            !limiter
10988                .open_session(test_peer(2), u64::MAX, hash, nonce, one)
10989                .await
10990        );
10991        assert_eq!(
10992            limiter.sessions.read().await.len(),
10993            MAX_SUBTREE_SESSIONS,
10994            "every session is still there"
10995        );
10996        assert!(
10997            limiter
10998                .consume_session(&test_peer(0), 0, &hash, &nonce)
10999                .await
11000                .is_some(),
11001            "including the oldest"
11002        );
11003    }
11004
11005    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
11006    // so a party holding several identities refills its allowance by rotating
11007    // between them and can keep the heavy pool busy indefinitely. The work
11008    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
11009    // so a fresh identity is refused exactly like a repeat caller once it is
11010    // spent. That is the difference between bounding concurrency and bounding
11011    // sustained work.
11012    #[tokio::test]
11013    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
11014        // Cooldown disabled so only the work budget can refuse anything.
11015        let limiter =
11016            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11017        assert!(
11018            limiter.admit(&test_peer(1)).await.is_some(),
11019            "a node starts with budget in hand so it can serve audits at once"
11020        );
11021
11022        // Serve enough proof work to run the balance into debt. Charging exactly
11023        // the burst would leave it at zero, which the next nanosecond of refill
11024        // lifts back above the line — the debt is the point.
11025        limiter
11026            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
11027            .await;
11028
11029        for id in 2..8u8 {
11030            assert!(
11031                limiter.admit(&test_peer(id)).await.is_none(),
11032                "a never-seen peer must still be refused while the budget is spent"
11033            );
11034        }
11035    }
11036
11037    // The budget is a rate, not a quota: it comes back on its own, so an honest
11038    // auditor blocked by a flood is only delayed. Carrying the debt is what
11039    // prices an expensive proof above a cheap one — without it, a proof reading
11040    // a maximal subtree would cost no more of the next caller's wait than a
11041    // one-leaf proof.
11042    #[test]
11043    fn round1_work_budget_carries_debt_and_refills_over_time() {
11044        let now = Instant::now();
11045        let at = |secs: u64| {
11046            now.checked_add(Duration::from_secs(secs))
11047                .unwrap_or_else(Instant::now)
11048        };
11049        let mut budget = Round1WorkBudget {
11050            balance: 0,
11051            last_refill: now,
11052        };
11053        assert!(!budget.has_budget(now), "empty means empty");
11054
11055        // A proof costing four seconds' worth of refill leaves four seconds of
11056        // debt, so the wait scales with what was actually served.
11057        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
11058        assert!(
11059            !budget.has_budget(at(3)),
11060            "still in debt three seconds after an over-large proof"
11061        );
11062        assert!(
11063            budget.has_budget(at(5)),
11064            "the debt is worked off at the refill rate"
11065        );
11066
11067        // Idle time does not bank unbounded credit for a later flood.
11068        budget.refill(at(24 * 60 * 60));
11069        assert_eq!(
11070            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
11071            "refill is capped at the burst size"
11072        );
11073    }
11074
11075    // The heavy round-1 pool size is the tightest bound the responder applies and
11076    // the one least backed by fleet measurement, so it is read from config rather
11077    // than baked into the binary: a fleet that lands on the wrong number retunes
11078    // instead of waiting for a release. These pin that the configured value is
11079    // what actually gates admission, and that a 0 degrades to slow, not to off —
11080    // a wedged-shut responder would read on every auditor as a graced timeout,
11081    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
11082    #[tokio::test]
11083    async fn round1_pool_size_comes_from_config() {
11084        // Cooldown disabled so only concurrency can refuse anything.
11085        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
11086        let held = limiter.admit(&test_peer(1)).await;
11087        assert!(held.is_some(), "the single configured slot is admitted");
11088        assert!(
11089            limiter.admit(&test_peer(2)).await.is_none(),
11090            "a second concurrent round 1 is refused at a configured pool of 1, \
11091             proving admission follows config rather than the compiled-in default"
11092        );
11093        drop(held);
11094        assert!(
11095            limiter.admit(&test_peer(2)).await.is_some(),
11096            "the slot is reusable once the first proof completes"
11097        );
11098    }
11099
11100    #[tokio::test]
11101    async fn round1_pool_size_of_zero_is_clamped_to_one() {
11102        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
11103        assert!(
11104            limiter.admit(&test_peer(1)).await.is_some(),
11105            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
11106        );
11107    }
11108
11109    fn test_key(b: u8) -> crate::ant_protocol::XorName {
11110        let mut k = [0u8; 32];
11111        k[0] = b;
11112        k
11113    }
11114
11115    #[test]
11116    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
11117        let source = test_peer(0x91);
11118        let corroborator = test_peer(0x92);
11119        let mut evidence = types::KeyVerificationEvidence {
11120            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
11121            paid_list: HashMap::new(),
11122        };
11123        let failed = KeyVerificationOutcome::QuorumFailed;
11124
11125        assert_eq!(
11126            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11127            Some(source),
11128            "a close-group rejection of a sole-source hint is punishable"
11129        );
11130        assert_eq!(
11131            punishable_singleton_replica_hint_source(
11132                &HashSet::from([source, corroborator]),
11133                &failed,
11134                &evidence,
11135            ),
11136            None,
11137            "corroborated hints must not use the sole-source penalty lane"
11138        );
11139        assert_eq!(
11140            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
11141            None,
11142            "paid-list advertisements do not claim possession, so they leave the \
11143             replica-hint source set empty and cannot be penalized"
11144        );
11145
11146        evidence
11147            .presence
11148            .insert(source, PresenceEvidence::Unresolved);
11149        assert_eq!(
11150            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11151            Some(source),
11152            "definitive close-group rejection is punishable without direct contradiction"
11153        );
11154        assert_eq!(
11155            punishable_singleton_replica_hint_source(
11156                &HashSet::from([source]),
11157                &KeyVerificationOutcome::QuorumInconclusive,
11158                &evidence,
11159            ),
11160            None,
11161            "timeouts and inconclusive evidence are neutral"
11162        );
11163
11164        evidence.presence.insert(source, PresenceEvidence::Absent);
11165        assert_eq!(
11166            punishable_singleton_replica_hint_source(
11167                &HashSet::from([source]),
11168                &KeyVerificationOutcome::QuorumVerified {
11169                    sources: vec![corroborator],
11170                },
11171                &evidence,
11172            ),
11173            Some(source),
11174            "an explicit denial is punishable regardless of the overall outcome"
11175        );
11176    }
11177
11178    /// Build a round-2 slice challenge matching an open session. `openings` is
11179    /// empty: these tests exercise admission and session handling only, which
11180    /// run before any block is opened.
11181    fn slice_challenge(
11182        challenge_id: u64,
11183        commitment_hash: [u8; 32],
11184        nonce: [u8; 32],
11185    ) -> protocol::SubtreeSliceChallenge {
11186        protocol::SubtreeSliceChallenge {
11187            challenge_id,
11188            nonce,
11189            challenged_peer_id: [0u8; 32],
11190            expected_commitment_hash: commitment_hash,
11191            openings: Vec::new(),
11192        }
11193    }
11194
11195    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
11196    // responder caps MUST NOT burn the single-use round-1 session.
11197    //
11198    // The handler used to consume the session first and admit second, so a
11199    // transient local capacity drop permanently destroyed that audit exchange —
11200    // every retry hit the `no live round-1 session` path and got `Transient`,
11201    // even after load cleared. Turning momentary local load into a deterministic
11202    // round-2 miss costs the responder its whole-slice credit for that round.
11203    #[tokio::test]
11204    async fn capacity_refused_slice_challenge_preserves_round1_session() {
11205        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11206        let inflight = Arc::new(RwLock::new(HashMap::new()));
11207        let round1 =
11208            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11209        let peer = test_peer(0xB1);
11210        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
11211        let challenge = slice_challenge(id, hash, nonce);
11212
11213        assert!(
11214            round1
11215                .open_session(peer, id, hash, nonce, PointerBindings::new())
11216                .await
11217        );
11218
11219        // Saturate this peer's share so the next admission must be refused.
11220        let mut hold = Vec::new();
11221        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11222            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
11223                .await
11224            {
11225                Ok(guard) => hold.push(guard),
11226                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
11227            }
11228        }
11229
11230        let refused =
11231            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11232        assert!(
11233            matches!(refused, SliceAdmission::Capacity(_)),
11234            "a saturated peer share must refuse on capacity, not on session"
11235        );
11236
11237        // Load clears. The session must have survived the refusal.
11238        drop(hold);
11239        let retried =
11240            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11241        assert!(
11242            matches!(retried, SliceAdmission::Admitted(..)),
11243            "the round-1 session must survive a capacity refusal so the retry succeeds"
11244        );
11245
11246        // Still single-use: the successful admission consumed it exactly once.
11247        drop(retried);
11248        let replayed =
11249            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11250        assert!(
11251            matches!(replayed, SliceAdmission::NoSession),
11252            "a consumed session must not be replayable"
11253        );
11254    }
11255
11256    // The permit taken for the session probe is released when the probe misses,
11257    // so an unsessioned flood cannot pin the responder pool shut.
11258    #[tokio::test]
11259    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
11260        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11261        let inflight = Arc::new(RwLock::new(HashMap::new()));
11262        let round1 =
11263            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11264        let peer = test_peer(0xB2);
11265        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
11266
11267        // Far more unsessioned challenges than the per-peer cap would allow if
11268        // the slot leaked on the miss path.
11269        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
11270            let outcome =
11271                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11272            assert!(
11273                matches!(outcome, SliceAdmission::NoSession),
11274                "no session was ever opened, so every attempt must miss"
11275            );
11276        }
11277
11278        assert_eq!(
11279            semaphore.available_permits(),
11280            MAX_CONCURRENT_AUDIT_RESPONSES,
11281            "every global permit must be returned"
11282        );
11283        assert!(
11284            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
11285            "no per-peer slot may be left occupied"
11286        );
11287    }
11288
11289    #[test]
11290    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
11291        assert!(!audit_failure_revokes_holder_credit(
11292            &AuditFailureReason::Timeout
11293        ));
11294        assert!(audit_failure_revokes_holder_credit(
11295            &AuditFailureReason::DigestMismatch
11296        ));
11297    }
11298
11299    #[tokio::test]
11300    async fn audit_responder_admission_reports_per_peer_cap_full() {
11301        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11302        let inflight = Arc::new(RwLock::new(HashMap::new()));
11303        let peer = test_peer(0xA1);
11304
11305        let mut guards = Vec::new();
11306        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11307            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
11308                .await
11309            {
11310                Ok(guard) => guards.push(guard),
11311                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
11312            }
11313        }
11314
11315        let Err(err) =
11316            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11317        else {
11318            panic!("admission should fail once per-peer cap is full");
11319        };
11320        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
11321        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
11322        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11323        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11324
11325        drop(guards);
11326    }
11327
11328    #[tokio::test]
11329    async fn audit_responder_admission_reports_global_pool_full() {
11330        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11331        let inflight = Arc::new(RwLock::new(HashMap::new()));
11332        let peer = test_peer(0xA2);
11333
11334        let mut held_global_permits = Vec::new();
11335        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
11336            held_global_permits.push(
11337                Arc::clone(&semaphore)
11338                    .try_acquire_owned()
11339                    .expect("test should be able to exhaust the global pool"),
11340            );
11341        }
11342
11343        let Err(err) =
11344            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11345        else {
11346            panic!("admission should fail once global pool is full");
11347        };
11348        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
11349        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
11350        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11351        assert_eq!(err.peer_inflight, 0);
11352        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11353
11354        drop(held_global_permits);
11355    }
11356
11357    #[tokio::test]
11358    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
11359        let semaphore = Arc::new(Semaphore::new(1));
11360        let inflight = Arc::new(RwLock::new(HashMap::new()));
11361        let peer = test_peer(0xA3);
11362
11363        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
11364            .await
11365            .expect("first responder should be admitted");
11366        assert_eq!(semaphore.available_permits(), 0);
11367        assert_eq!(inflight.read().await.get(&peer), Some(&1));
11368
11369        drop(guard);
11370        assert_eq!(semaphore.available_permits(), 1);
11371        assert!(!inflight.read().await.contains_key(&peer));
11372    }
11373
11374    #[tokio::test]
11375    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
11376        let semaphore = Arc::new(Semaphore::new(1));
11377        let inflight = Arc::new(RwLock::new(HashMap::new()));
11378        let peer = test_peer(0xA4);
11379        let held_map = inflight.write().await;
11380
11381        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
11382        assert!(
11383            tokio::time::timeout(Duration::from_millis(10), waiting)
11384                .await
11385                .is_err(),
11386            "admission should still be waiting for the peer map"
11387        );
11388
11389        drop(held_map);
11390        assert_eq!(semaphore.available_permits(), 1);
11391        assert!(!inflight.read().await.contains_key(&peer));
11392    }
11393
11394    #[test]
11395    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
11396        let timeout = Duration::from_secs(1);
11397        let old_received_at = Instant::now()
11398            .checked_sub(timeout)
11399            .unwrap_or_else(Instant::now);
11400
11401        assert!(request_is_stale(old_received_at, timeout));
11402        assert!(!request_is_stale(Instant::now(), timeout));
11403    }
11404
11405    #[tokio::test]
11406    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
11407        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
11408        let inflight = Arc::new(RwLock::new(HashMap::new()));
11409        let first_peer = test_peer(0xB3);
11410        let second_peer = test_peer(0xB4);
11411
11412        let first_guard = admit_bounded_responder(
11413            &semaphore,
11414            &inflight,
11415            &first_peer,
11416            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11417            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11418        )
11419        .await
11420        .expect("first sync from a peer should be admitted");
11421        let duplicate = admit_bounded_responder(
11422            &semaphore,
11423            &inflight,
11424            &first_peer,
11425            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11426            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11427        )
11428        .await;
11429        let other_peer = admit_bounded_responder(
11430            &semaphore,
11431            &inflight,
11432            &second_peer,
11433            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11434            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11435        )
11436        .await;
11437
11438        assert!(matches!(
11439            duplicate,
11440            Err(ResponderAdmissionFailure {
11441                reason: ResponderRejectReason::PerPeerCapFull,
11442                ..
11443            })
11444        ));
11445        assert!(other_peer.is_ok());
11446        drop(first_guard);
11447        drop(other_peer);
11448    }
11449
11450    /// One flooding peer must not be able to hold every fresh-offer slot.
11451    ///
11452    /// This is the eviction primitive the per-peer share closes: with only a
11453    /// global bound, a single source occupies the pool, every honest offer in
11454    /// that window is refused, and because a refusal reads as absence to the
11455    /// sender's delayed possession check those refusals land as
11456    /// audit-severity penalties on *this* node.
11457    #[tokio::test]
11458    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
11459        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
11460        let inflight = Arc::new(RwLock::new(HashMap::new()));
11461        let flooder = test_peer(0xC1);
11462        let honest = test_peer(0xC2);
11463
11464        let mut held = Vec::new();
11465        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11466            held.push(
11467                admit_bounded_responder(
11468                    &semaphore,
11469                    &inflight,
11470                    &flooder,
11471                    FRESH_OFFER_MAX_OUTSTANDING,
11472                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11473                )
11474                .await
11475                .expect("offers within the per-peer share are admitted"),
11476            );
11477        }
11478
11479        let flooder_excess = admit_bounded_responder(
11480            &semaphore,
11481            &inflight,
11482            &flooder,
11483            FRESH_OFFER_MAX_OUTSTANDING,
11484            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11485        )
11486        .await;
11487        assert!(
11488            matches!(
11489                flooder_excess,
11490                Err(ResponderAdmissionFailure {
11491                    reason: ResponderRejectReason::PerPeerCapFull,
11492                    ..
11493                })
11494            ),
11495            "one source must not exceed its fresh-offer share"
11496        );
11497
11498        let honest_offer = admit_bounded_responder(
11499            &semaphore,
11500            &inflight,
11501            &honest,
11502            FRESH_OFFER_MAX_OUTSTANDING,
11503            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11504        )
11505        .await;
11506        assert!(
11507            honest_offer.is_ok(),
11508            "an honest sender must still be admitted while another peer floods"
11509        );
11510
11511        assert!(
11512            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11513                < FRESH_OFFER_MAX_OUTSTANDING,
11514            "the per-peer share must leave room for other sources"
11515        );
11516
11517        drop(held);
11518        drop(honest_offer);
11519    }
11520
11521    /// Paid notifies get the same per-source treatment as every other class.
11522    #[tokio::test]
11523    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11524        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11525        let inflight = Arc::new(RwLock::new(HashMap::new()));
11526        let flooder = test_peer(0xC3);
11527        let honest = test_peer(0xC4);
11528
11529        let mut held = Vec::new();
11530        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11531            held.push(
11532                admit_bounded_responder(
11533                    &semaphore,
11534                    &inflight,
11535                    &flooder,
11536                    PAID_NOTIFY_MAX_OUTSTANDING,
11537                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11538                )
11539                .await
11540                .expect("notifies within the per-peer share are admitted"),
11541            );
11542        }
11543
11544        assert!(
11545            matches!(
11546                admit_bounded_responder(
11547                    &semaphore,
11548                    &inflight,
11549                    &flooder,
11550                    PAID_NOTIFY_MAX_OUTSTANDING,
11551                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11552                )
11553                .await,
11554                Err(ResponderAdmissionFailure {
11555                    reason: ResponderRejectReason::PerPeerCapFull,
11556                    ..
11557                })
11558            ),
11559            "one source must not exceed its paid-notify share"
11560        );
11561        assert!(
11562            admit_bounded_responder(
11563                &semaphore,
11564                &inflight,
11565                &honest,
11566                PAID_NOTIFY_MAX_OUTSTANDING,
11567                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11568            )
11569            .await
11570            .is_ok(),
11571            "an honest sender must still be admitted while another peer floods"
11572        );
11573
11574        drop(held);
11575    }
11576
11577    /// The fresh-offer per-source bound must guarantee headroom for a peer
11578    /// holding nothing, without throttling a single legitimate fan-out.
11579    ///
11580    /// Sized as a quota rather than a reserve, this bound refused offers during
11581    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11582    /// refusal is charged to THIS node at audit severity because the sender
11583    /// never reads it.
11584    #[test]
11585    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11586        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11587
11588        assert_eq!(
11589            FRESH_OFFER_MAX_OUTSTANDING - share,
11590            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11591            "a source holding none must always find a free slot"
11592        );
11593        assert!(
11594            share < FRESH_OFFER_MAX_OUTSTANDING,
11595            "one peer must not be able to take the whole pool"
11596        );
11597        // The failure this pins: a share sized like the request/response
11598        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11599        // one-way bulk traffic.
11600        assert!(
11601            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11602            "fresh offers are one-way bulk, not request/response — their share \
11603             must not be sized like the request classes'"
11604        );
11605    }
11606
11607    /// A malformed offer must be refused before it can occupy an admission
11608    /// slot, so junk cannot hold capacity for the length of a verification.
11609    #[test]
11610    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11611        let key = test_key(0xC5);
11612
11613        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11614
11615        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11616            .expect("an offer with no proof must be refused");
11617        assert!(
11618            rejection.penalise,
11619            "an honest sender always attaches a proof"
11620        );
11621
11622        // A proof is retained per queued sender, so its size has to be bounded
11623        // here rather than at the verifier, which only sees it on a worker.
11624        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11625        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11626            .expect("an undersized proof must be refused");
11627        assert!(
11628            rejection.penalise,
11629            "no honest sender constructs an undersized proof"
11630        );
11631        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11632        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11633            .expect("an oversized proof must be refused");
11634        assert!(
11635            rejection.penalise,
11636            "no honest sender constructs an oversized proof"
11637        );
11638
11639        let rejection = fresh_offer_structural_rejection(
11640            &key,
11641            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11642            &valid_proof,
11643        )
11644        .expect("an oversized offer must be refused");
11645        assert!(
11646            rejection.penalise,
11647            "no honest sender constructs an oversized offer"
11648        );
11649
11650        let data = vec![0u8; 1];
11651        assert!(
11652            fresh_offer_structural_rejection(
11653                &crate::client::compute_address(&data),
11654                &data,
11655                &valid_proof
11656            )
11657            .is_none(),
11658            "a well-formed offer must reach admission"
11659        );
11660    }
11661
11662    /// Knowing a key must not be enough to enter its entry.
11663    ///
11664    /// Opening an entry on an unverified key/bytes association would let a peer
11665    /// that has only *learned* the key — every recipient of its `PaidNotify`,
11666    /// not just the close group that gets the chunk — seize it with junk.
11667    /// Joining one would be worse: the handler tries each queued proof against
11668    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11669    /// on bytes it never offered.
11670    #[test]
11671    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11672        let genuine_data = vec![0x5Au8; 128];
11673        let key = crate::client::compute_address(&genuine_data);
11674        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11675
11676        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11677            .expect("bytes that do not hash to the advertised key must be refused");
11678        assert!(
11679            rejection.penalise,
11680            "no honest sender offers bytes that do not hash to the advertised key"
11681        );
11682
11683        // Dispatch reaches the entry only past that rejection, so the forged
11684        // offer never touched the key and the genuine one still opens it.
11685        assert!(
11686            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11687            "the offer that actually carries the key's bytes must reach the entry"
11688        );
11689
11690        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11691        assert!(
11692            matches!(
11693                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11694                FreshOfferAdmission::Opened(_)
11695            ),
11696            "an offer refused on payload shape must leave the key openable"
11697        );
11698    }
11699
11700    #[tokio::test]
11701    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11702        let peer = test_peer(0xA5);
11703        let key = test_key(0xA5);
11704        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11705        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11706        let is_bootstrapping = Arc::new(RwLock::new(true));
11707        let bootstrap_complete_notify = Arc::new(Notify::new());
11708
11709        let now = Instant::now();
11710        queues.write().await.add_pending_verify(
11711            key,
11712            VerificationEntry {
11713                state: VerificationState::PendingVerify,
11714                verified_sources: Vec::new(),
11715                tried_sources: HashSet::new(),
11716                created_at: now,
11717                next_verify_at: now,
11718                hint_sources: HashSet::from([peer]),
11719                replica_hint_sources: HashSet::from([peer]),
11720                unresolved_retries: 0,
11721                no_holder_reported: false,
11722            },
11723        );
11724        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11725        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11726        {
11727            let q = queues.read().await;
11728            assert!(
11729                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11730                "capacity rejection should initially block bootstrap drain"
11731            );
11732        }
11733
11734        update_bootstrap_after_peer_removed(
11735            &peer,
11736            &bootstrap_state,
11737            &queues,
11738            &is_bootstrapping,
11739            &bootstrap_complete_notify,
11740        )
11741        .await;
11742
11743        let state = bootstrap_state.read().await;
11744        assert!(state.capacity_rejected_sources.is_empty());
11745        assert!(state.pending_keys.is_empty());
11746        assert!(state.is_drained());
11747        drop(state);
11748        assert!(!*is_bootstrapping.read().await);
11749    }
11750
11751    /// A fairness displacement forfeits the key but must not stamp its former
11752    /// owner: the owner did nothing wrong, and stamping it lets a flooding
11753    /// source block bootstrap drain through an unrelated honest peer.
11754    #[tokio::test]
11755    async fn fairness_displacement_does_not_stamp_its_victim() {
11756        let displaced_owner = test_peer(0xB1);
11757        let incoming_source = test_peer(0xB2);
11758        let displaced_key = test_key(0xB1);
11759        let admitted_key = test_key(0xB2);
11760        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11761        {
11762            let mut state = bootstrap_state.write().await;
11763            state.pending_keys.insert(displaced_key);
11764            state
11765                .capacity_rejected_sources
11766                .insert(incoming_source, Instant::now());
11767        }
11768        let outcomes = [(
11769            incoming_source,
11770            AdmissionOutcome {
11771                discovered: HashSet::from([admitted_key]),
11772                capacity_rejected_count: 0,
11773                displaced: vec![CapacityDisplacement {
11774                    key: displaced_key,
11775                    owner: displaced_owner,
11776                }],
11777            },
11778        )];
11779
11780        publish_bootstrap_admission_outcomes(
11781            &bootstrap_state,
11782            &outcomes,
11783            &HashSet::from([admitted_key]),
11784        )
11785        .await;
11786
11787        let state = bootstrap_state.read().await;
11788        assert!(!state.pending_keys.contains(&displaced_key));
11789        assert!(state.pending_keys.contains(&admitted_key));
11790        assert!(
11791            !state
11792                .capacity_rejected_sources
11793                .contains_key(&displaced_owner),
11794            "the displaced owner must not be charged for our own fairness reclaim"
11795        );
11796        assert!(!state
11797            .capacity_rejected_sources
11798            .contains_key(&incoming_source));
11799    }
11800
11801    /// A source that keeps overflowing us must not keep its own record fresh.
11802    ///
11803    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11804    /// rejection the debt could never age out, so `check_bootstrap_drained`
11805    /// stayed false forever and auditing never started (Invariant 19).
11806    #[tokio::test]
11807    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11808        const REJECTION_ROUNDS: usize = 5;
11809
11810        let source = test_peer(0xB3);
11811        let key = test_key(0xB3);
11812        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11813
11814        let first_seen = {
11815            let outcomes = [(
11816                source,
11817                AdmissionOutcome {
11818                    discovered: HashSet::new(),
11819                    capacity_rejected_count: 1,
11820                    displaced: Vec::new(),
11821                },
11822            )];
11823            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11824                .await;
11825            bootstrap_state
11826                .read()
11827                .await
11828                .capacity_rejected_sources
11829                .get(&source)
11830                .copied()
11831                .expect("first rejection recorded")
11832        };
11833
11834        for _ in 0..REJECTION_ROUNDS {
11835            let outcomes = [(
11836                source,
11837                AdmissionOutcome {
11838                    discovered: HashSet::from([key]),
11839                    capacity_rejected_count: 1,
11840                    displaced: Vec::new(),
11841                },
11842            )];
11843            publish_bootstrap_admission_outcomes(
11844                &bootstrap_state,
11845                &outcomes,
11846                &HashSet::from([key]),
11847            )
11848            .await;
11849        }
11850
11851        let recorded = bootstrap_state
11852            .read()
11853            .await
11854            .capacity_rejected_sources
11855            .get(&source)
11856            .copied()
11857            .expect("debt still outstanding");
11858        assert_eq!(
11859            recorded, first_seen,
11860            "repeat rejections must not restart the expiry clock"
11861        );
11862    }
11863
11864    /// The verification-worker tick's self-heal path: a capacity rejection
11865    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
11866    /// blocks drain until the TTL expires it, at which point the same tick
11867    /// completes bootstrap without any external event.
11868    #[tokio::test]
11869    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
11870        let peer = test_peer(0xA6);
11871        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11872        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11873        let is_bootstrapping = Arc::new(RwLock::new(true));
11874        let bootstrap_complete_notify = Arc::new(Notify::new());
11875
11876        // PeerRemoved was fully processed before the rejection landed, so no
11877        // future event will ever clear this entry.
11878        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11879
11880        // Within the TTL the tick keeps waiting for re-delivery.
11881        expire_and_recheck_bootstrap_drain(
11882            &bootstrap_state,
11883            &queues,
11884            &is_bootstrapping,
11885            &bootstrap_complete_notify,
11886            ReplicationConfig::default().capacity_rejected_max_age(),
11887        )
11888        .await;
11889        assert!(!bootstrap_state.read().await.is_drained());
11890        assert!(*is_bootstrapping.read().await);
11891
11892        // Past the TTL the tick expires the orphan and completes bootstrap.
11893        expire_and_recheck_bootstrap_drain(
11894            &bootstrap_state,
11895            &queues,
11896            &is_bootstrapping,
11897            &bootstrap_complete_notify,
11898            Duration::ZERO,
11899        )
11900        .await;
11901        assert!(bootstrap_state.read().await.is_drained());
11902        assert!(!*is_bootstrapping.read().await);
11903    }
11904
11905    #[test]
11906    fn first_audit_terminal_outcomes_are_stable() {
11907        let peer = test_peer(1);
11908        let passed = AuditTickResult::Passed {
11909            challenged_peer: peer,
11910            keys_checked: 1,
11911        };
11912        let timed_out = AuditTickResult::Failed {
11913            evidence: FailureEvidence::AuditFailure {
11914                challenge_id: 1,
11915                challenged_peer: peer,
11916                confirmed_failed_keys: vec![test_key(1)],
11917                summary: crate::replication::types::AuditFailureSummary::default(),
11918                reason: AuditFailureReason::Timeout,
11919            },
11920            no_response_class: Some("timeout"),
11921        };
11922
11923        assert_eq!(
11924            first_audit_terminal_outcome(&passed),
11925            FirstAuditTerminalOutcome::Passed
11926        );
11927        assert_eq!(
11928            first_audit_terminal_outcome(&timed_out),
11929            FirstAuditTerminalOutcome::Timeout
11930        );
11931        assert_eq!(
11932            first_audit_terminal_outcome(&AuditTickResult::Idle),
11933            FirstAuditTerminalOutcome::Idle
11934        );
11935        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
11936        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
11937        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
11938        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
11939        assert_eq!(
11940            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
11941            "insufficient_keys"
11942        );
11943        assert_eq!(
11944            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
11945            "bootstrap_claim"
11946        );
11947    }
11948
11949    #[test]
11950    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
11951        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
11952        let mut rng = StdRng::seed_from_u64(7);
11953        let peer = test_peer(1);
11954        let base = MonetizedPinEvent {
11955            peer,
11956            pin: [1; 32],
11957            key_count: 100,
11958            quote_ts: SystemTime::now(),
11959        };
11960
11961        // First insert into an empty slot: Queued.
11962        assert_eq!(
11963            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
11964            FirstAuditQueueOutcome::Queued
11965        );
11966
11967        // A strictly LOWER-count same-peer nomination must NOT displace it.
11968        let lower = MonetizedPinEvent {
11969            pin: [2; 32],
11970            key_count: 50,
11971            ..base
11972        };
11973        assert_eq!(
11974            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
11975            FirstAuditQueueOutcome::SuppressedLower
11976        );
11977        assert_eq!(
11978            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11979            Some(([1; 32], 100)),
11980            "the higher-count pin is retained"
11981        );
11982
11983        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
11984        let higher = MonetizedPinEvent {
11985            pin: [3; 32],
11986            key_count: 400,
11987            ..base
11988        };
11989        assert_eq!(
11990            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
11991            FirstAuditQueueOutcome::Coalesced
11992        );
11993        assert_eq!(
11994            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
11995            Some(([3; 32], 400))
11996        );
11997
11998        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
11999        let equal_newer = MonetizedPinEvent {
12000            pin: [4; 32],
12001            key_count: 400,
12002            ..base
12003        };
12004        assert_eq!(
12005            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
12006            FirstAuditQueueOutcome::Coalesced
12007        );
12008        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12009        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
12010        let equal_older = MonetizedPinEvent {
12011            pin: [5; 32],
12012            key_count: 400,
12013            ..base
12014        };
12015        assert_eq!(
12016            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
12017            FirstAuditQueueOutcome::RetainedOnTie
12018        );
12019        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12020
12021        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
12022        let other_peer = MonetizedPinEvent {
12023            peer: test_peer(2),
12024            pin: [6; 32],
12025            key_count: 100,
12026            ..base
12027        };
12028        assert_eq!(
12029            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
12030            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
12031        );
12032        assert_eq!(pending.len(), 1);
12033        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
12034    }
12035
12036    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
12037
12038    #[test]
12039    fn first_audit_limiter_enforces_burst_then_refills() {
12040        let base = Instant::now();
12041        let mut limiter = FirstAuditLimiter::new(base);
12042        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12043
12044        // The full burst is admitted back-to-back (distinct peers).
12045        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12046            let peer = test_peer(u8::try_from(i).expect("small burst"));
12047            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12048            limiter.commit_launch(peer, 10, base);
12049        }
12050        // Bucket empty: the next distinct peer is deferred, never dropped.
12051        let extra = test_peer(0xEE);
12052        assert_eq!(
12053            limiter.assess(&extra, 10, base, 0),
12054            LimiterVerdict::RateDeferred
12055        );
12056
12057        // One full interval later exactly one token is available again.
12058        let later = base + interval;
12059        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
12060        limiter.commit_launch(extra, 10, later);
12061        let extra2 = test_peer(0xEF);
12062        assert_eq!(
12063            limiter.assess(&extra2, 10, later, 0),
12064            LimiterVerdict::RateDeferred
12065        );
12066    }
12067
12068    #[test]
12069    fn first_audit_limiter_refill_keeps_fractional_remainder() {
12070        let base = Instant::now();
12071        let mut limiter = FirstAuditLimiter::new(base);
12072        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12073        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12074            let peer = test_peer(u8::try_from(i).expect("small burst"));
12075            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
12076            limiter.commit_launch(peer, 1, base);
12077        }
12078        // 1.5 intervals later one token is earned and the half interval is
12079        // NOT lost to drift...
12080        let at_1_5 = base + interval + interval / 2;
12081        let p = test_peer(0xAA);
12082        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
12083        limiter.commit_launch(p, 1, at_1_5);
12084        // ...so the next token arrives at 2.0 intervals, not 2.5.
12085        let at_2_0 = base + interval * 2;
12086        let q = test_peer(0xAB);
12087        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
12088    }
12089
12090    #[test]
12091    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
12092        let base = Instant::now();
12093        let mut limiter = FirstAuditLimiter::new(base);
12094        let peer = test_peer(1);
12095        assert_eq!(
12096            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
12097            LimiterVerdict::RateDeferred
12098        );
12099        // A freed slot admits without any clock movement.
12100        assert_eq!(
12101            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
12102            LimiterVerdict::Admit
12103        );
12104    }
12105
12106    #[test]
12107    fn first_audit_limiter_assess_consumes_nothing() {
12108        let base = Instant::now();
12109        let mut limiter = FirstAuditLimiter::new(base);
12110        let peer = test_peer(3);
12111        // Repeated assessment must not burn budget or stamp the window: only
12112        // `commit_launch` consumes (the cooldown gate between assess and
12113        // commit can defer, and that deferral must be free).
12114        for _ in 0..10 {
12115            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
12116        }
12117        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12118            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
12119            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
12120            limiter.commit_launch(p, 5, base);
12121        }
12122    }
12123
12124    #[test]
12125    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
12126        let base = Instant::now();
12127        let mut limiter = FirstAuditLimiter::new(base);
12128        let peer = test_peer(7);
12129        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
12130        limiter.commit_launch(peer, 100, base);
12131
12132        // A rotated pin with a similar count inside the window is dropped...
12133        let soon = base + Duration::from_mins(1);
12134        assert_eq!(
12135            limiter.assess(&peer, 100, soon, 0),
12136            LimiterVerdict::WindowDeduped
12137        );
12138        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
12139        assert_eq!(
12140            limiter.assess(&peer, 150, soon, 0),
12141            LimiterVerdict::WindowDeduped
12142        );
12143        // ...but a >1.5x committed-count jump re-nominates immediately (an
12144        // inflated sidecar-only pin is invisible to the gossip lottery, so
12145        // the window must not shield it).
12146        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
12147
12148        // Window expiry re-admits an unchanged count.
12149        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
12150        assert_eq!(
12151            limiter.assess(&peer, 100, expired, 0),
12152            LimiterVerdict::Admit
12153        );
12154    }
12155
12156    #[test]
12157    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
12158        // A window-deduped nomination must be DROPPED, not kept pending as
12159        // rate-deferred, even when the bucket is also empty: re-queuing a
12160        // suppressed rotation would hold a pending slot for two hours.
12161        let base = Instant::now();
12162        let mut limiter = FirstAuditLimiter::new(base);
12163        let peer = test_peer(9);
12164        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12165        limiter.commit_launch(peer, 10, base);
12166        let other = test_peer(10);
12167        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
12168        limiter.commit_launch(other, 10, base);
12169        assert_eq!(
12170            limiter.assess(&peer, 10, base, 0),
12171            LimiterVerdict::WindowDeduped
12172        );
12173    }
12174
12175    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
12176    /// is answerable now but would age out of the answerability window during
12177    /// the launch jitter, so scheduling state is only ever committed for a pin
12178    /// that can still be challenged when it actually sends.
12179    #[test]
12180    fn first_audit_horizon_prefilter_boundary() {
12181        let now = SystemTime::now();
12182        // C = the too-old cutoff; H = the worst-case send horizon.
12183        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
12184        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
12185        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
12186        let boundary = now
12187            .checked_add(h)
12188            .and_then(|t| t.checked_sub(c))
12189            .expect("boundary time");
12190
12191        // In window at `now` (age = C - H < C)...
12192        assert!(quote_within_audit_window(boundary, now));
12193        // ...but the horizon prefilter rejects it (age == C at now + H).
12194        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
12195
12196        // A hair newer stays answerable through the horizon; a hair older does
12197        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
12198        // a nanosecond step would round to the same instant there.
12199        let newer = boundary
12200            .checked_add(Duration::from_micros(1))
12201            .expect("newer");
12202        let older = boundary
12203            .checked_sub(Duration::from_micros(1))
12204            .expect("older");
12205        assert!(quote_answerable_through_nominal_jitter(newer, now));
12206        assert!(!quote_answerable_through_nominal_jitter(older, now));
12207
12208        // A quote too far in the FUTURE is rejected at `now`, independent of the
12209        // horizon.
12210        let future = now
12211            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
12212            .and_then(|t| t.checked_add(Duration::from_mins(1)))
12213            .expect("future");
12214        assert!(!quote_answerable_through_nominal_jitter(future, now));
12215    }
12216
12217    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
12218    /// answerability check fails at promotion is fully state-neutral — it stamps
12219    /// no `first_audited`, no per-peer window, refunds its token, releases its
12220    /// in-flight slot, does not flip the lane, and does not count a launch — and
12221    /// a same-peer, same-count successor enqueued DURING the reservation is
12222    /// retained and becomes the next reservation after the cancel. This is the
12223    /// exact hole the reviewer flagged: suppression must never outlive a launch
12224    /// that did not send.
12225    /// A pending pin that has aged past the answerability horizon must not
12226    /// suppress a live lower-count nomination for the same peer: under token
12227    /// starvation no reserve scan ever collects the dead entry, so without the
12228    /// enqueue-time check the peer would stay unauditable through this path
12229    /// indefinitely (e.g. after a prune legitimately lowered its key count).
12230    #[test]
12231    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
12232        let obs = Arc::new(FirstAuditObservability::default());
12233        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12234        let peer = test_peer(1);
12235
12236        let dead_quote = SystemTime::now()
12237            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12238            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12239            .expect("past wall time");
12240        let stale_high = MonetizedPinEvent {
12241            peer,
12242            pin: [1; 32],
12243            key_count: 400,
12244            quote_ts: dead_quote,
12245        };
12246        scheduler.enqueue(stale_high, &obs);
12247        assert_eq!(scheduler.pending_len(), 1);
12248
12249        // A fresh, lower-count nomination (a post-prune commitment).
12250        let fresh_lower = MonetizedPinEvent {
12251            peer,
12252            pin: [2; 32],
12253            key_count: 100,
12254            quote_ts: SystemTime::now(),
12255        };
12256        scheduler.enqueue(fresh_lower, &obs);
12257
12258        assert_eq!(scheduler.pending_len(), 1);
12259        assert_eq!(
12260            scheduler.pending.peek(&peer).map(|e| e.pin),
12261            Some([2; 32]),
12262            "the live nomination replaced the dead incumbent"
12263        );
12264        assert_eq!(
12265            obs.suppressed_lower.load(Ordering::Relaxed),
12266            0,
12267            "no self-erasure signal for displacing a dead pin"
12268        );
12269        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
12270        assert_eq!(
12271            obs.outside_answerability_window.load(Ordering::Relaxed),
12272            1,
12273            "the dead incumbent is accounted as an expiry"
12274        );
12275    }
12276
12277    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
12278    /// nomination still loses to an answerable higher-count pending pin.
12279    #[test]
12280    fn first_audit_live_incumbent_still_suppresses_lower_count() {
12281        let obs = Arc::new(FirstAuditObservability::default());
12282        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12283        let peer = test_peer(1);
12284
12285        let live_high = MonetizedPinEvent {
12286            peer,
12287            pin: [1; 32],
12288            key_count: 400,
12289            quote_ts: SystemTime::now(),
12290        };
12291        scheduler.enqueue(live_high, &obs);
12292        let cheaper = MonetizedPinEvent {
12293            peer,
12294            pin: [2; 32],
12295            key_count: 100,
12296            quote_ts: SystemTime::now(),
12297        };
12298        scheduler.enqueue(cheaper, &obs);
12299
12300        assert_eq!(scheduler.pending_len(), 1);
12301        assert_eq!(
12302            scheduler.pending.peek(&peer).map(|e| e.pin),
12303            Some([1; 32]),
12304            "the higher-count live pin is retained"
12305        );
12306        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
12307        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
12308    }
12309
12310    /// A fresh nomination for peer `b` (distinct pin per peer).
12311    fn live_nomination(b: u8) -> MonetizedPinEvent {
12312        MonetizedPinEvent {
12313            peer: test_peer(b),
12314            pin: [b; 32],
12315            key_count: 100,
12316            quote_ts: SystemTime::now(),
12317        }
12318    }
12319
12320    /// The pending admission cap must equal the number of usable launches the
12321    /// token budget can perform inside one answerability window, counted by
12322    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
12323    /// tokens at age zero, one refill per launch interval), not by repeating
12324    /// the derivation formula. Any larger and admitted work is guaranteed to
12325    /// expire unlaunched; any smaller and the budget idles while nominations
12326    /// are displaced.
12327    #[test]
12328    fn first_audit_pending_cap_matches_strict_launch_horizon() {
12329        let quote_ts = SystemTime::now();
12330        // Burst launches fire at age zero and must pass the reserve predicate.
12331        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
12332        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
12333        let mut refill = 1u32;
12334        loop {
12335            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
12336            let at = quote_ts + age;
12337            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
12338                break;
12339            }
12340            usable += 1;
12341            refill += 1;
12342            assert!(refill < 10_000, "runaway horizon simulation");
12343        }
12344        assert_eq!(
12345            FIRST_AUDIT_PENDING_CAP, usable,
12346            "cap must match the simulated strict launch horizon"
12347        );
12348    }
12349
12350    /// The pending queue is sized to the launch budget while the dedup set
12351    /// keeps the commitment-cache bound: shrinking `first_audited` would
12352    /// forget audited pins and re-admit duplicates.
12353    #[test]
12354    fn first_audit_pending_cap_independent_of_dedup_cap() {
12355        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12356        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
12357        assert_eq!(
12358            scheduler.first_audited.cap().get(),
12359            MAX_LAST_COMMITMENT_BY_PEER
12360        );
12361    }
12362
12363    /// Admission beyond the cap displaces exactly one incumbent per overflow
12364    /// and every displacement is accounted as `capacity_evicted` — the steady
12365    /// overload signal — never silent loss, and never an admission refusal.
12366    #[test]
12367    fn first_audit_admission_beyond_cap_displaces_and_counts() {
12368        let obs = Arc::new(FirstAuditObservability::default());
12369        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12370        let overflow: usize = 5;
12371        let total = FIRST_AUDIT_PENDING_CAP + overflow;
12372
12373        for i in 0..total {
12374            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12375            scheduler.enqueue(live_nomination(b), &obs);
12376        }
12377
12378        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12379        assert_eq!(
12380            obs.capacity_evicted.load(Ordering::Relaxed),
12381            u64::try_from(overflow).expect("overflow fits u64"),
12382            "each admission past the cap displaces exactly one entry"
12383        );
12384        assert_eq!(
12385            obs.queued.load(Ordering::Relaxed),
12386            u64::try_from(total).expect("total fits u64"),
12387            "displacement is not an admission refusal"
12388        );
12389        // Every arrival was admitted (the newest always enters the sample).
12390        let last = u8::try_from(total).expect("test peer count fits u8");
12391        assert!(
12392            scheduler.pending.peek(&test_peer(last)).is_some(),
12393            "the newest arrival always enters the sample"
12394        );
12395    }
12396
12397    /// The reviewer-demonstrated suppression route: a target followed by an
12398    /// ordered batch of distinct-peer nominations, all inside one ingress
12399    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
12400    /// the token bucket EMPTY so no reservation can intervene. Under the old
12401    /// keep-newest LRU the target was evicted with certainty; under random
12402    /// displacement its per-overflow eviction probability is `1/cap`, so
12403    /// across repeated trials the target must survive some runs and be
12404    /// displaced in others — never deterministically flushed, and every
12405    /// displacement accounted.
12406    #[test]
12407    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
12408        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
12409        assert!(FIRST_AUDIT_PENDING_CAP < flood);
12410        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
12411
12412        let trials = 100u64;
12413        let mut survived = 0u32;
12414        let mut evicted = 0u32;
12415        for trial in 0..trials {
12416            let obs = Arc::new(FirstAuditObservability::default());
12417            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12418            // Deterministic per-trial seed: the run is fully reproducible (no
12419            // flake budget at all) while still exercising 100 distinct
12420            // eviction sequences.
12421            scheduler.rng = StdRng::seed_from_u64(trial);
12422            // Drain the burst tokens so the pre-overflow reservation
12423            // opportunity cannot fire: this isolates pure retention.
12424            scheduler.limiter.reserve_token();
12425            scheduler.limiter.reserve_token();
12426
12427            let target = test_peer(200);
12428            scheduler.enqueue(live_nomination(200), &obs);
12429            for i in 0..flood {
12430                let b = u8::try_from(i + 1).expect("flood peer fits u8");
12431                scheduler.enqueue(live_nomination(b), &obs);
12432            }
12433
12434            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12435            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
12436                .expect("overflow count fits u64");
12437            assert_eq!(
12438                obs.capacity_evicted.load(Ordering::Relaxed),
12439                overflows,
12440                "every overflow past the cap is accounted, none silent"
12441            );
12442            if scheduler.pending.peek(&target).is_some() {
12443                survived += 1;
12444            } else {
12445                evicted += 1;
12446            }
12447        }
12448        // With eviction probability 1/cap per overflow, P(target survives one
12449        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
12450        // 100 seeded trials — and the seeds make the split exactly
12451        // reproducible rather than a (vanishingly small) flake budget.
12452        assert!(
12453            survived > 0,
12454            "target must survive some ordered floods — deterministic eviction \
12455             would mean keep-newest retention regressed"
12456        );
12457        assert!(
12458            evicted > 0,
12459            "target must also be displaceable — otherwise overflow is refusing \
12460             admissions instead of sampling"
12461        );
12462    }
12463
12464    /// With a token AVAILABLE, an overflowing arrival must first give pending
12465    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12466    /// one entry out of the queue, so admission proceeds without any eviction.
12467    #[test]
12468    fn first_audit_overflow_reserves_before_destructive_eviction() {
12469        let obs = Arc::new(FirstAuditObservability::default());
12470        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12471        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12472
12473        for i in 0..FIRST_AUDIT_PENDING_CAP {
12474            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12475            scheduler.enqueue(live_nomination(b), &obs);
12476        }
12477        let overflowing = live_nomination(250);
12478        assert!(scheduler.would_displace(&overflowing));
12479
12480        // The drainer's pre-overflow sequence: reserve, then enqueue.
12481        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12482        assert!(
12483            !scheduler.would_displace(&overflowing),
12484            "a successful reservation frees the slot"
12485        );
12486        scheduler.enqueue(overflowing, &obs);
12487
12488        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12489        assert_eq!(
12490            obs.capacity_evicted.load(Ordering::Relaxed),
12491            0,
12492            "no destructive eviction when a launch opportunity existed"
12493        );
12494    }
12495
12496    /// Displacement stamps no suppression state: a displaced peer's next
12497    /// nomination re-enters like any newcomer (it is NOT window-deduped or
12498    /// treated as a duplicate), so under overload every peer keeps an
12499    /// unpredictable chance of prompt first audit.
12500    #[test]
12501    fn first_audit_displaced_peer_may_be_renominated() {
12502        let obs = Arc::new(FirstAuditObservability::default());
12503        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12504        let total = FIRST_AUDIT_PENDING_CAP + 1;
12505
12506        for i in 0..total {
12507            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12508            scheduler.enqueue(live_nomination(b), &obs);
12509        }
12510        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12511        // Find whichever peer the random displacement removed.
12512        let displaced = (1..=total)
12513            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12514            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12515            .expect("exactly one admitted peer was displaced");
12516
12517        scheduler.enqueue(live_nomination(displaced), &obs);
12518
12519        assert!(
12520            scheduler.pending.peek(&test_peer(displaced)).is_some(),
12521            "the displaced peer re-enters the sample"
12522        );
12523        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12524        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12525        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12526        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12527    }
12528
12529    /// The periodic sweep collects expired pending entries even when the token
12530    /// bucket is empty — the reserve path returns at the budget gate and never
12531    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12532    /// honest under fleet-wide starvation.
12533    #[test]
12534    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12535        let obs = Arc::new(FirstAuditObservability::default());
12536        let mono = Instant::now();
12537        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12538
12539        let dead_quote = SystemTime::now()
12540            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12541            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12542            .expect("past wall time");
12543        scheduler.enqueue(
12544            MonetizedPinEvent {
12545                peer: test_peer(1),
12546                pin: [1; 32],
12547                key_count: 100,
12548                quote_ts: dead_quote,
12549            },
12550            &obs,
12551        );
12552        scheduler.enqueue(
12553            MonetizedPinEvent {
12554                peer: test_peer(2),
12555                pin: [2; 32],
12556                key_count: 100,
12557                quote_ts: SystemTime::now(),
12558            },
12559            &obs,
12560        );
12561        assert_eq!(scheduler.pending_len(), 2);
12562
12563        // Empty the bucket so the reserve path is budget-gated (fleet-wide
12564        // starvation) and cannot collect the dead entry itself.
12565        scheduler.limiter.tokens = 0;
12566        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12567        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12568        assert_eq!(
12569            scheduler.pending_len(),
12570            2,
12571            "budget-gated reserve scans nothing"
12572        );
12573
12574        let wall_now = SystemTime::now();
12575        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12576        assert_eq!(scheduler.pending_len(), 1);
12577        assert!(
12578            scheduler.pending.peek(&test_peer(2)).is_some(),
12579            "the live entry survives the sweep"
12580        );
12581        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12582        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12583        assert!(
12584            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12585            "the age gauge reflects only live work after the sweep"
12586        );
12587    }
12588
12589    #[test]
12590    #[allow(clippy::too_many_lines)]
12591    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12592        let obs = Arc::new(FirstAuditObservability::default());
12593        let mono = Instant::now();
12594        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12595
12596        // A pre-existing window sentinel for an UNRELATED peer must survive the
12597        // cancel byte-for-byte (cancel never touches `recent`).
12598        let sentinel_peer = test_peer(0xAA);
12599        scheduler.limiter.promote(sentinel_peer, 500, mono);
12600        let sentinel_before = scheduler
12601            .limiter
12602            .recent
12603            .peek(&sentinel_peer)
12604            .copied()
12605            .expect("sentinel present");
12606
12607        let peer = test_peer(1);
12608        let a = MonetizedPinEvent {
12609            peer,
12610            pin: [1; 32],
12611            key_count: 100,
12612            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12613        };
12614        scheduler.enqueue(a, &obs);
12615
12616        let tokens_before = scheduler.tokens();
12617        let lane_before = scheduler.oldest_first_lane;
12618        let launched_before = obs.launched.load(Ordering::Relaxed);
12619        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12620
12621        // Reserve A (jitter 0 so it is immediately due).
12622        let inflight0 = obs.inflight.load(Ordering::Relaxed);
12623        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12624        assert_eq!(scheduler.reserved_peer(), Some(peer));
12625        assert_eq!(
12626            scheduler.tokens(),
12627            tokens_before - 1,
12628            "reserve consumes a token"
12629        );
12630        assert_eq!(
12631            obs.inflight.load(Ordering::Relaxed),
12632            1,
12633            "reserve holds a slot"
12634        );
12635
12636        // A same-peer, same-count successor arrives DURING the reservation. It
12637        // must be retained (bypasses the window for the reserved peer) and must
12638        // NOT create a second reservation.
12639        let b = MonetizedPinEvent {
12640            peer,
12641            pin: [2; 32],
12642            key_count: 100,
12643            quote_ts: SystemTime::now(),
12644        };
12645        scheduler.enqueue(b, &obs);
12646        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12647        assert!(
12648            !scheduler.try_reserve(
12649                mono,
12650                obs.inflight.load(Ordering::Relaxed),
12651                Duration::ZERO,
12652                &cooldown,
12653                &obs
12654            ),
12655            "no second reservation while one is outstanding"
12656        );
12657
12658        // Resolve A with an injected wall time PAST A's answerability cutoff.
12659        let reservation = scheduler
12660            .take_due_reservation(mono)
12661            .expect("A is due at jitter 0");
12662        let wall_fail = a
12663            .quote_ts
12664            .checked_add(GOSSIP_ANSWERABILITY_TTL)
12665            .and_then(|t| t.checked_add(Duration::from_secs(1)))
12666            .expect("past-cutoff wall time");
12667        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12668        assert!(
12669            promoted.is_none(),
12670            "answerability lapsed -> cancelled, not promoted"
12671        );
12672
12673        // State-neutral cancel.
12674        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12675        assert!(
12676            scheduler.limiter.recent.peek(&peer).is_none(),
12677            "cancel stamps no per-peer window"
12678        );
12679        assert_eq!(
12680            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12681            Some(sentinel_before),
12682            "unrelated window sentinel untouched"
12683        );
12684        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12685        assert_eq!(
12686            scheduler.tokens(),
12687            tokens_before,
12688            "token refunded on cancel"
12689        );
12690        assert_eq!(
12691            obs.inflight.load(Ordering::Relaxed),
12692            0,
12693            "in-flight slot released"
12694        );
12695        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12696        assert_eq!(
12697            obs.launched.load(Ordering::Relaxed),
12698            launched_before,
12699            "no launch counted"
12700        );
12701        assert_eq!(
12702            obs.outside_answerability_window.load(Ordering::Relaxed),
12703            1,
12704            "the cancel reason is recorded"
12705        );
12706
12707        // The successor is still pending and is now fully schedulable: a fresh
12708        // reserve makes B the next reservation (proving eligibility, not merely
12709        // that the limiter would admit it).
12710        assert_eq!(
12711            scheduler.pending_len(),
12712            1,
12713            "successor still pending after cancel"
12714        );
12715        assert!(scheduler.reserved.is_none());
12716        assert!(scheduler.try_reserve(
12717            mono,
12718            obs.inflight.load(Ordering::Relaxed),
12719            Duration::ZERO,
12720            &cooldown,
12721            &obs
12722        ));
12723        assert_eq!(
12724            scheduler.reserved_peer(),
12725            Some(peer),
12726            "the retained successor becomes the next reservation"
12727        );
12728    }
12729
12730    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12731    /// race, the reserved event is requeued ONLY if no same-peer successor is
12732    /// already pending. A successor arrived after the reservation, so it is the
12733    /// newer nomination (e.g. a count jump) and must not be overwritten by the
12734    /// older reserved event.
12735    #[test]
12736    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12737        let obs = Arc::new(FirstAuditObservability::default());
12738        let mono = Instant::now();
12739        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12740        let peer = test_peer(1);
12741
12742        // Reserve A.
12743        let a = MonetizedPinEvent {
12744            peer,
12745            pin: [1; 32],
12746            key_count: 100,
12747            quote_ts: SystemTime::now(),
12748        };
12749        scheduler.enqueue(a, &obs);
12750        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12751        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12752
12753        // A newer same-peer successor B (a count jump) arrives during the
12754        // reservation and is retained.
12755        let b = MonetizedPinEvent {
12756            peer,
12757            pin: [2; 32],
12758            key_count: 400,
12759            quote_ts: SystemTime::now(),
12760        };
12761        scheduler.enqueue(b, &obs);
12762        assert_eq!(scheduler.pending_len(), 1);
12763
12764        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12765        // is already stamped for the peer, so promotion loses the race.
12766        let reservation = scheduler.take_due_reservation(mono).expect("due");
12767        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12768        cooldown.insert(peer, mono); // freshly on cooldown
12769        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12770        assert!(promoted.is_none(), "cooldown race -> not promoted");
12771
12772        // B (newer) is preserved; A did NOT overwrite it.
12773        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12774        assert_eq!(
12775            scheduler.pending.peek(&peer).map(|e| e.pin),
12776            Some([2; 32]),
12777            "the newer successor B is retained, not the older reserved A"
12778        );
12779        assert!(scheduler.first_audited.is_empty());
12780        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12781    }
12782
12783    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12784    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12785    /// and saturates to `0` for a future-dated quote (clock skew) without
12786    /// panicking. A climbing value is the pending-work-aging-out signal.
12787    #[test]
12788    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12789        let now = SystemTime::now();
12790        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12791        assert_eq!(
12792            scheduler.oldest_pending_quote_age_ms(now),
12793            0,
12794            "empty pending -> zero"
12795        );
12796
12797        // Two peers: quotes 10s and 2s old. The gauge must track the older.
12798        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12799            let _ = coalesce_first_audit_event(
12800                &mut scheduler.pending,
12801                MonetizedPinEvent {
12802                    peer: test_peer(peer_id),
12803                    pin,
12804                    key_count: 100,
12805                    quote_ts: now - Duration::from_secs(secs),
12806                },
12807                true,
12808                &mut scheduler.rng,
12809            );
12810        }
12811        assert_eq!(
12812            scheduler.oldest_pending_quote_age_ms(now),
12813            10_000,
12814            "tracks the oldest (10s), not the newest (2s)"
12815        );
12816
12817        // A future-dated quote (clock skew) saturates to zero, never panics.
12818        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12819        let _ = coalesce_first_audit_event(
12820            &mut skewed.pending,
12821            MonetizedPinEvent {
12822                peer: test_peer(3),
12823                pin: [3; 32],
12824                key_count: 100,
12825                quote_ts: now + Duration::from_secs(5),
12826            },
12827            true,
12828            &mut skewed.rng,
12829        );
12830        assert_eq!(
12831            skewed.oldest_pending_quote_age_ms(now),
12832            0,
12833            "future quote_ts saturates to zero"
12834        );
12835    }
12836
12837    /// A flood of strictly-lower-count same-peer nominations must neither
12838    /// displace the retained higher pin NOR disturb its recency position (each
12839    /// is suppressed via `peek`, no `push`), and each must be counted as
12840    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12841    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12842    /// (the documented `lru` contract that also drives the reserve scan's lane
12843    /// ordering), deliberately independent of the overflow policy: eviction is
12844    /// random-victim, so no assertion may require a particular peer to be
12845    /// displaced.
12846    #[test]
12847    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12848        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12849            LruCache::new(NonZeroUsize::new(2).unwrap());
12850        let mut rng = StdRng::seed_from_u64(11);
12851        let victim = test_peer(1);
12852        let other = test_peer(2);
12853        // Victim (high count) inserted first (older), then `other` (newer/MRU).
12854        let _ = coalesce_first_audit_event(
12855            &mut pending,
12856            MonetizedPinEvent {
12857                peer: victim,
12858                pin: [1; 32],
12859                key_count: 400,
12860                quote_ts: SystemTime::now(),
12861            },
12862            true,
12863            &mut rng,
12864        );
12865        let _ = coalesce_first_audit_event(
12866            &mut pending,
12867            MonetizedPinEvent {
12868                peer: other,
12869                pin: [9; 32],
12870                key_count: 100,
12871                quote_ts: SystemTime::now(),
12872            },
12873            true,
12874            &mut rng,
12875        );
12876        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12877        assert_eq!(
12878            order_before,
12879            vec![other, victim],
12880            "sanity: `other` is MRU, the victim is LRU"
12881        );
12882
12883        // Flood the victim with cheaper nominations.
12884        let mut suppressed = 0u64;
12885        for i in 0..8u8 {
12886            let out = coalesce_first_audit_event(
12887                &mut pending,
12888                MonetizedPinEvent {
12889                    peer: victim,
12890                    pin: [i; 32],
12891                    key_count: 50,
12892                    quote_ts: SystemTime::now(),
12893                },
12894                true,
12895                &mut rng,
12896            );
12897            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
12898            suppressed += 1;
12899        }
12900        assert_eq!(suppressed, 8);
12901        // Victim pin/count unchanged.
12902        assert_eq!(
12903            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
12904            Some(([1; 32], 400))
12905        );
12906        // Recency untouched: the iteration order (which the reserve lanes
12907        // consume) is byte-for-byte what it was before the flood.
12908        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
12909        assert_eq!(
12910            order_after, order_before,
12911            "the suppressed-lower flood must not have changed any recency position"
12912        );
12913    }
12914
12915    /// The cooldown-race requeue counts a genuine different-peer capacity
12916    /// eviction (the ADR promises capacity loss is observable).
12917    #[test]
12918    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
12919        let obs = Arc::new(FirstAuditObservability::default());
12920        let mono = Instant::now();
12921        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12922        // Pending capacity 1 so a requeue of a different peer must evict.
12923        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12924        let reserved_peer = test_peer(1);
12925        let other_peer = test_peer(2);
12926
12927        // Reserve peer 1.
12928        scheduler.enqueue(
12929            MonetizedPinEvent {
12930                peer: reserved_peer,
12931                pin: [1; 32],
12932                key_count: 100,
12933                quote_ts: SystemTime::now(),
12934            },
12935            &obs,
12936        );
12937        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
12938        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
12939
12940        // A DIFFERENT peer fills the single pending slot during the reservation.
12941        scheduler.enqueue(
12942            MonetizedPinEvent {
12943                peer: other_peer,
12944                pin: [2; 32],
12945                key_count: 100,
12946                quote_ts: SystemTime::now(),
12947            },
12948            &obs,
12949        );
12950        assert_eq!(scheduler.pending_len(), 1);
12951
12952        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
12953        let reservation = scheduler.take_due_reservation(mono).expect("due");
12954        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12955        cooldown.insert(reserved_peer, mono);
12956        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
12957        assert!(scheduler
12958            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
12959            .is_none());
12960        assert_eq!(
12961            obs.capacity_evicted.load(Ordering::Relaxed),
12962            cap_before + 1,
12963            "the requeue eviction of a different peer is counted"
12964        );
12965        assert_eq!(
12966            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
12967            Some([1; 32])
12968        );
12969    }
12970
12971    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
12972    /// nomination arriving while an inflated pin is PENDING must not displace it.
12973    /// The inflated pin stays and is the one launched.
12974    #[test]
12975    fn first_audit_pending_lower_count_does_not_replace_higher() {
12976        let obs = Arc::new(FirstAuditObservability::default());
12977        let mono = Instant::now();
12978        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12979        let peer = test_peer(1);
12980
12981        // Inflated (high-count) sidecar pin lands in pending.
12982        scheduler.enqueue(
12983            MonetizedPinEvent {
12984                peer,
12985                pin: [1; 32],
12986                key_count: 400,
12987                quote_ts: SystemTime::now(),
12988            },
12989            &obs,
12990        );
12991        // A cheaper same-peer settlement arrives right after.
12992        scheduler.enqueue(
12993            MonetizedPinEvent {
12994                peer,
12995                pin: [2; 32],
12996                key_count: 100,
12997                quote_ts: SystemTime::now(),
12998            },
12999            &obs,
13000        );
13001
13002        assert_eq!(scheduler.pending_len(), 1);
13003        assert_eq!(
13004            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13005            Some(([1; 32], 400)),
13006            "the inflated pin must not be erased by the cheaper successor"
13007        );
13008        // The dropped cheaper nomination is counted through the enqueue path.
13009        assert_eq!(
13010            obs.suppressed_lower.load(Ordering::Relaxed),
13011            1,
13012            "the attempted cheaper-pin self-erasure is observable"
13013        );
13014
13015        // It reserves and promotes as the inflated pin/count.
13016        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13017        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13018        let reservation = scheduler.take_due_reservation(mono).expect("due");
13019        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13020        let (event, _slot) = scheduler
13021            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13022            .expect("promotes");
13023        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13024    }
13025
13026    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
13027    /// loses the cooldown race must be requeued OVER a lower-count same-peer
13028    /// successor that arrived during its jitter, and must remain launchable once
13029    /// the shared cooldown expires — the cheaper successor cannot suppress it.
13030    #[test]
13031    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
13032        let obs = Arc::new(FirstAuditObservability::default());
13033        let mono = Instant::now();
13034        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13035        let peer = test_peer(1);
13036
13037        // Reserve the inflated pin.
13038        scheduler.enqueue(
13039            MonetizedPinEvent {
13040                peer,
13041                pin: [1; 32],
13042                key_count: 400,
13043                quote_ts: SystemTime::now(),
13044            },
13045            &obs,
13046        );
13047        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13048        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13049
13050        // A cheaper successor arrives during the reservation (bypasses the
13051        // window as the reserved peer) and sits in pending.
13052        scheduler.enqueue(
13053            MonetizedPinEvent {
13054                peer,
13055                pin: [2; 32],
13056                key_count: 100,
13057                quote_ts: SystemTime::now(),
13058            },
13059            &obs,
13060        );
13061        assert_eq!(scheduler.pending_len(), 1);
13062
13063        // Resolve: answerability passes but the shared cooldown is already
13064        // stamped, so the reservation loses the race and requeues.
13065        let reservation = scheduler.take_due_reservation(mono).expect("due");
13066        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13067        cooldown.insert(peer, mono);
13068        assert!(scheduler
13069            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13070            .is_none());
13071
13072        // The inflated pin (400) replaced the cheaper successor (100).
13073        assert_eq!(scheduler.pending_len(), 1);
13074        assert_eq!(
13075            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13076            Some(([1; 32], 400)),
13077            "the inflated reserved pin must survive the requeue over the cheaper successor"
13078        );
13079        assert!(scheduler.first_audited.is_empty());
13080        assert!(scheduler.limiter.recent.peek(&peer).is_none());
13081
13082        // Once the shared cooldown expires, the inflated pin reserves and
13083        // promotes with its intended pin/count.
13084        let later = mono
13085            .checked_add(Duration::from_secs(
13086                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
13087            ))
13088            .expect("later");
13089        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
13090        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
13091        let reservation = scheduler.take_due_reservation(later).expect("due");
13092        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
13093        let (event, _slot) = scheduler
13094            .resolve(
13095                reservation,
13096                SystemTime::now(),
13097                later,
13098                &mut cooldown_later,
13099                &obs,
13100            )
13101            .expect("promotes after cooldown");
13102        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13103    }
13104
13105    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
13106    /// launch lane, driven through the real scheduler (reserve -> resolve ->
13107    /// promote), so a stream of fresh nominations cannot keep every launch on
13108    /// the newest lane and starve the oldest.
13109    #[test]
13110    fn first_audit_lane_alternates_across_promotions() {
13111        let obs = Arc::new(FirstAuditObservability::default());
13112        let mono = Instant::now();
13113        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13114        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13115
13116        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
13117        let oldest_peer = test_peer(1);
13118        let newest_peer = test_peer(2);
13119        scheduler.enqueue(
13120            MonetizedPinEvent {
13121                peer: oldest_peer,
13122                pin: [1; 32],
13123                key_count: 100,
13124                quote_ts: SystemTime::now(),
13125            },
13126            &obs,
13127        );
13128        scheduler.enqueue(
13129            MonetizedPinEvent {
13130                peer: newest_peer,
13131                pin: [2; 32],
13132                key_count: 100,
13133                quote_ts: SystemTime::now(),
13134            },
13135            &obs,
13136        );
13137
13138        let mut launched_peers = Vec::new();
13139        for _ in 0..2 {
13140            assert!(scheduler.try_reserve(
13141                mono,
13142                obs.inflight.load(Ordering::Relaxed),
13143                Duration::ZERO,
13144                &cooldown,
13145                &obs
13146            ));
13147            let reservation = scheduler.take_due_reservation(mono).expect("due");
13148            // Answerable wall time == the quote's own time (age 0).
13149            let (event, _slot) = scheduler
13150                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13151                .expect("fresh in-window quote promotes");
13152            launched_peers.push(event.peer);
13153        }
13154
13155        // First launch takes the newest lane (lane starts false = newest), the
13156        // second takes the oldest lane: strict alternation.
13157        assert_eq!(
13158            launched_peers,
13159            vec![newest_peer, oldest_peer],
13160            "consecutive promotions alternate newest-then-oldest lane"
13161        );
13162    }
13163
13164    #[test]
13165    fn first_audit_count_jump_boundaries() {
13166        // Exactly 1.5x is NOT a jump; strictly above is.
13167        assert!(!first_audit_count_jump(100, 150));
13168        assert!(first_audit_count_jump(100, 151));
13169        // Anything beats an audited zero; zero never jumps.
13170        assert!(first_audit_count_jump(0, 1));
13171        assert!(!first_audit_count_jump(0, 0));
13172        // Equal max counts must not jump (and must not overflow).
13173        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
13174    }
13175
13176    /// A verified payment's quote list includes the local node's own quote, so
13177    /// the verifier emits a monetized-pin event for the local peer on every
13178    /// payment it verifies. The node cannot network-audit itself, so the
13179    /// scheduler must drop such an event at ingress: never queued, and hence
13180    /// never launched nor marked first-audited.
13181    #[test]
13182    fn first_audit_queue_drops_self_targeting_events() {
13183        let obs = Arc::new(FirstAuditObservability::default());
13184        let self_peer = test_peer(1);
13185        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
13186        let self_event = MonetizedPinEvent {
13187            peer: self_peer,
13188            pin: [7; 32],
13189            key_count: 1,
13190            quote_ts: SystemTime::now(),
13191        };
13192
13193        scheduler.enqueue(self_event, &obs);
13194        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
13195        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
13196        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
13197
13198        // A remote peer's event still queues normally under the same filter.
13199        let remote_event = MonetizedPinEvent {
13200            peer: test_peer(2),
13201            pin: [8; 32],
13202            ..self_event
13203        };
13204        scheduler.enqueue(remote_event, &obs);
13205        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
13206        assert_eq!(scheduler.pending_len(), 1);
13207        assert_eq!(
13208            obs.self_target_skipped.load(Ordering::Relaxed),
13209            1,
13210            "remote event must not count as a self-target skip"
13211        );
13212    }
13213
13214    #[test]
13215    fn fresh_offer_runs_store_admission_payment_checks() {
13216        let context = fresh_offer_payment_context();
13217        assert_eq!(context, VerificationContext::FreshReplication);
13218        // Fresh replication must keep verifying exactly like a direct client
13219        // PUT (store-strength cache, same live checks); the variant only
13220        // exists so price-floor telemetry can tell the two paths apart.
13221        assert!(context.is_store_admission());
13222    }
13223
13224    #[test]
13225    fn paid_notify_uses_paid_list_admission_payment_checks() {
13226        assert_eq!(
13227            paid_notify_payment_context(),
13228            VerificationContext::PaidListAdmission
13229        );
13230    }
13231
13232    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
13233    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
13234    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
13235    #[test]
13236    fn monetized_quote_audit_window_fails_closed_both_ends() {
13237        let now = SystemTime::now();
13238        // Fresh (just quoted) and small future/past skew -> audited.
13239        assert!(quote_within_audit_window(now, now));
13240        assert!(quote_within_audit_window(now + Duration::from_mins(1), now));
13241        assert!(quote_within_audit_window(
13242            now - Duration::from_hours(1),
13243            now
13244        ));
13245        // Far future (badly-skewed / replayed) -> skipped.
13246        assert!(!quote_within_audit_window(
13247            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_mins(1),
13248            now
13249        ));
13250        // Older than the window -> skipped (pin may have aged out).
13251        assert!(!quote_within_audit_window(
13252            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
13253            now
13254        ));
13255    }
13256
13257    #[tokio::test]
13258    async fn replication_branch_lagged_events_are_counted() {
13259        let before = audit_metrics::replication_event_lagged_total();
13260        let flow = handle_replication_event_recv_error(
13261            &tokio::sync::broadcast::error::RecvError::Lagged(3),
13262        );
13263        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
13264        let after = audit_metrics::replication_event_lagged_total();
13265        assert_eq!(after.saturating_sub(before), 3);
13266    }
13267
13268    #[tokio::test]
13269    async fn replication_branch_closed_events_stop_the_loop() {
13270        let flow =
13271            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
13272        assert_eq!(flow, std::ops::ControlFlow::Break(()));
13273    }
13274
13275    #[tokio::test]
13276    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
13277        let (sender, mut receiver) = mpsc::channel(1);
13278        let dropped_body =
13279            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
13280                keys: Vec::new(),
13281                paid_list_check_indices: Vec::new(),
13282            });
13283        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13284        let first = InboundReplicationMessage {
13285            source: test_peer(0xC1),
13286            msg: ReplicationMessage {
13287                request_id: 1,
13288                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
13289                    key: test_key(1),
13290                }),
13291            },
13292            rr_message_id: None,
13293            received_at: Instant::now(),
13294        };
13295        let second = InboundReplicationMessage {
13296            source: test_peer(0xC2),
13297            msg: ReplicationMessage {
13298                request_id: 2,
13299                body: dropped_body.clone(),
13300            },
13301            rr_message_id: None,
13302            received_at: Instant::now(),
13303        };
13304
13305        assert!(try_enqueue_serial_message(&sender, first).is_ok());
13306        let dropped = try_enqueue_serial_message(&sender, second)
13307            .expect_err("a full serial queue must refuse the second message");
13308        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
13309        assert_eq!(dropped.message_class, "verification_request");
13310        assert_eq!(dropped.queue_depth, 1);
13311        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13312        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
13313
13314        let queued = receiver
13315            .recv()
13316            .await
13317            .expect("first message should remain queued");
13318        assert_eq!(queued.msg.request_id, 1);
13319        assert!(receiver.try_recv().is_err());
13320    }
13321
13322    #[tokio::test]
13323    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
13324        let peer = test_peer(0x44);
13325        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
13326
13327        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
13328        let mut digest_guards = Vec::new();
13329        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
13330            let guard = admit_audit_responder(
13331                &semaphore,
13332                &digest_inflight,
13333                &peer,
13334                AuditResponderClass::Digest,
13335            )
13336            .await;
13337            assert!(guard.is_ok());
13338            digest_guards.push(guard);
13339        }
13340        assert!(
13341            admit_audit_responder(
13342                &semaphore,
13343                &digest_inflight,
13344                &peer,
13345                AuditResponderClass::Digest,
13346            )
13347            .await
13348            .is_err(),
13349            "digest class must stop at its documented per-source cap"
13350        );
13351        drop(digest_guards);
13352
13353        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
13354        let mut subtree_guards = Vec::new();
13355        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
13356            let guard = admit_audit_responder(
13357                &semaphore,
13358                &subtree_inflight,
13359                &peer,
13360                AuditResponderClass::Subtree,
13361            )
13362            .await;
13363            assert!(guard.is_ok());
13364            subtree_guards.push(guard);
13365        }
13366        assert!(
13367            admit_audit_responder(
13368                &semaphore,
13369                &subtree_inflight,
13370                &peer,
13371                AuditResponderClass::Subtree,
13372            )
13373            .await
13374            .is_err(),
13375            "subtree class must retain the deployed cap of two"
13376        );
13377        drop(subtree_guards);
13378    }
13379
13380    #[test]
13381    fn in_scope_audit_deadlines_share_one_formula() {
13382        let config = config::ReplicationConfig::default();
13383        for key_count in [1, 4, 16] {
13384            assert_eq!(
13385                audit::responsible_audit_response_timeout(&config, key_count),
13386                config.audit_response_timeout(key_count)
13387            );
13388            assert_eq!(
13389                pruning::prune_audit_response_timeout(&config, key_count),
13390                config.audit_response_timeout(key_count)
13391            );
13392        }
13393        assert_eq!(
13394            possession::possession_probe_response_timeout(&config),
13395            config.audit_response_timeout(1)
13396        );
13397    }
13398
13399    #[test]
13400    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
13401        const EXISTING_SOURCE_ID: u8 = 1;
13402        const HINT_SENDER_ID: u8 = 2;
13403
13404        let existing_source = test_peer(EXISTING_SOURCE_ID);
13405        let hint_sender = test_peer(HINT_SENDER_ID);
13406        let mut sources = vec![existing_source];
13407
13408        let hint_sources = HashSet::from([hint_sender]);
13409        add_replica_hint_sources(&mut sources, &hint_sources);
13410        add_replica_hint_sources(&mut sources, &hint_sources);
13411
13412        // A paid-only advertiser leaves the claim set empty (see
13413        // `queue_admitted_hints`), so it contributes no fetch source.
13414        add_replica_hint_sources(&mut sources, &HashSet::new());
13415
13416        assert_eq!(sources, vec![existing_source, hint_sender]);
13417    }
13418
13419    #[test]
13420    fn audit_timeout_preserves_active_bootstrap_claim() {
13421        assert!(!audit_failure_clears_bootstrap_claim(
13422            &AuditFailureReason::Timeout
13423        ));
13424    }
13425
13426    fn strike_peer(b: u8) -> PeerId {
13427        let mut bytes = [0u8; 32];
13428        bytes[0] = b;
13429        PeerId::from_bytes(bytes)
13430    }
13431
13432    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
13433    // cooldown must collapse a gossip flood into at most one audit per window.
13434
13435    #[test]
13436    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
13437        let peer = strike_peer(1);
13438        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13439        let t0 = Instant::now();
13440        // First gossip in the window passes; a burst of further gossips at the
13441        // same instant are all suppressed.
13442        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13443        let mut passed = 1;
13444        for _ in 0..100 {
13445            if cooldown_allows_audit(&mut map, &peer, t0) {
13446                passed += 1;
13447            }
13448        }
13449        assert_eq!(
13450            passed, 1,
13451            "a flood at one instant must trigger exactly one audit"
13452        );
13453    }
13454
13455    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
13456    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
13457    // consumes the window. This is the property the isolated cooldown tests above
13458    // cannot see: they never sample the lottery, so a regression that reordered
13459    // the gates (sample probability first, only stamp the cooldown on a win)
13460    // would still pass them while breaking flood-resistance: a flood would then
13461    // re-roll the lottery on EVERY message until one won, multiplying audits.
13462    //
13463    // We model the exact production gate order (attempt-window, lottery,
13464    // shared cooldown) with a lottery driven by a fixed outcome instead of
13465    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13466    // messages all WIN. With the production order, the losing first ticket
13467    // burns the ATTEMPT window and every later winner in the same window is
13468    // blocked, so there are 0 audits this window. If the gates were flipped,
13469    // the second message's winning ticket would slip through. The window only
13470    // reopens after it elapses.
13471    //
13472    // FLIPS IF: the lottery is sampled before the attempt-window
13473    // check-and-stamp (a losing ticket no longer consumes the window),
13474    // re-enabling a flood-amplified audit storm.
13475    #[test]
13476    fn losing_lottery_still_consumes_attempt_window() {
13477        // Calls the SHIPPED `audit_launch_decision` (the same function
13478        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13479        // production fails this test — not a local reimplementation.
13480        let peer = strike_peer(3);
13481        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13482        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13483        let t0 = Instant::now();
13484
13485        // First flooded message at t0 LOSES the lottery, but the attempt window
13486        // is stamped BEFORE the lottery is consulted, so the window is consumed.
13487        assert!(
13488            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13489            "a losing ticket launches no audit"
13490        );
13491
13492        // 99 more flooded messages at the same instant would all WIN the lottery,
13493        // yet every one must be blocked by the attempt window the loser stamped.
13494        // (If production sampled the lottery FIRST, these would each get a fresh
13495        // roll and audits would multiply — this assertion catches that reorder.)
13496        let mut audits = 0;
13497        for _ in 0..99 {
13498            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13499                audits += 1;
13500            }
13501        }
13502        assert_eq!(
13503            audits, 0,
13504            "a losing first ticket must consume the attempt window so no later \
13505             flooded message in the same window can audit"
13506        );
13507
13508        // The window only reopens after it elapses; the next winning ticket
13509        // then launches exactly one audit and stamps the SHARED cooldown.
13510        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13511        assert!(
13512            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13513            "after the window a winning ticket audits again"
13514        );
13515        assert!(
13516            launched.contains_key(&peer),
13517            "a real launch stamps the shared cooldown"
13518        );
13519    }
13520
13521    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13522    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13523    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13524    /// first audit deferred until its answerability window expires.
13525    ///
13526    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13527    /// loss (the pre-split behavior, where both paths shared one map).
13528    #[test]
13529    fn losing_lottery_does_not_suppress_monetized_first_audit() {
13530        let peer = strike_peer(4);
13531        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13532        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13533        let t0 = Instant::now();
13534
13535        // A losing ticket consumes the gossip attempt window...
13536        assert!(!audit_launch_decision(
13537            &mut attempts,
13538            &mut launched,
13539            &peer,
13540            t0,
13541            false
13542        ));
13543        // ...but leaves the shared map untouched, so the first-audit reserve
13544        // gate (read-only) and the authoritative promotion check-and-stamp both
13545        // still allow the paid audit to launch immediately.
13546        assert!(
13547            cooldown_would_allow(&launched, &peer, t0),
13548            "reserve gate must not see a losing ticket as audit coverage"
13549        );
13550        assert!(
13551            cooldown_allows_audit(&mut launched, &peer, t0),
13552            "promotion must not be deferred by a losing ticket"
13553        );
13554
13555        // Conversely a WINNING ticket (real audit sent) does suppress the
13556        // first audit for the window, which is the intended shared semantics.
13557        let peer_won = strike_peer(5);
13558        assert!(audit_launch_decision(
13559            &mut attempts,
13560            &mut launched,
13561            &peer_won,
13562            t0,
13563            true
13564        ));
13565        assert!(
13566            !cooldown_would_allow(&launched, &peer_won, t0),
13567            "a real gossip audit still covers the peer for the window"
13568        );
13569    }
13570
13571    #[test]
13572    fn cooldown_lets_audit_through_after_the_window() {
13573        let peer = strike_peer(2);
13574        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13575        let t0 = Instant::now();
13576        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13577        // Within the window: suppressed.
13578        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13579        assert!(!cooldown_allows_audit(&mut map, &peer, within));
13580        // Past the window: allowed again.
13581        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13582        assert!(cooldown_allows_audit(&mut map, &peer, after));
13583    }
13584
13585    #[test]
13586    fn cooldown_is_per_peer_independent() {
13587        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13588        let t0 = Instant::now();
13589        // Different peers each get their own first-audit pass at the same instant.
13590        for i in 0..20u8 {
13591            assert!(
13592                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13593                "peer {i} should be auditable independently"
13594            );
13595        }
13596    }
13597
13598    #[test]
13599    fn audit_on_gossip_constants_match_adr() {
13600        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13601        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13602        // values above 5 would silently never be requested).
13603        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13604        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13605        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13606    }
13607
13608    // (d) A confirmed storage-integrity failure penalizes immediately and
13609    // revokes credit; it is not a timeout.
13610    #[test]
13611    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13612        assert!(audit_failure_clears_bootstrap_claim(
13613            &AuditFailureReason::DigestMismatch
13614        ));
13615        assert!(audit_failure_revokes_holder_credit(
13616            &AuditFailureReason::DigestMismatch
13617        ));
13618    }
13619
13620    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13621    /// uses: confirmed failures revoke credit, `Timeout` does not.
13622    #[test]
13623    fn confirmed_failures_revoke_credit_timeout_does_not() {
13624        for reason in [
13625            AuditFailureReason::MalformedResponse,
13626            AuditFailureReason::DigestMismatch,
13627            AuditFailureReason::KeyAbsent,
13628            AuditFailureReason::Rejected,
13629        ] {
13630            assert!(
13631                audit_failure_revokes_holder_credit(&reason),
13632                "confirmed failure {reason:?} must revoke holder credit"
13633            );
13634        }
13635        assert!(
13636            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13637            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13638        );
13639    }
13640
13641    /// Wiring test for the security fix: the helper the handler calls
13642    /// actually strips a credited peer on a confirmed failure
13643    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13644    /// Records genuine credit first so neither assertion is vacuous;
13645    /// this fails if `forget_peer` stops being called, or if the
13646    /// `Timeout` exclusion is dropped (both verified by mutation).
13647    #[test]
13648    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13649        let peer = test_peer(0xAB);
13650        let key = test_key(1);
13651        let hash = [0xCD; 32];
13652
13653        // Confirmed failure -> credit revoked.
13654        let mut provers = RecentProvers::new();
13655        provers.record_proof(key, peer, hash, Instant::now());
13656        assert!(
13657            provers.is_credited_holder(&key, &peer, &hash),
13658            "precondition: peer credited before failure"
13659        );
13660        apply_audit_failure_credit_revocation(
13661            &mut provers,
13662            &peer,
13663            &AuditFailureReason::DigestMismatch,
13664        );
13665        assert!(
13666            !provers.is_credited_holder(&key, &peer, &hash),
13667            "DigestMismatch must strip the peer's holder credit"
13668        );
13669
13670        // Timeout -> credit retained.
13671        let mut provers_timeout = RecentProvers::new();
13672        provers_timeout.record_proof(key, peer, hash, Instant::now());
13673        apply_audit_failure_credit_revocation(
13674            &mut provers_timeout,
13675            &peer,
13676            &AuditFailureReason::Timeout,
13677        );
13678        assert!(
13679            provers_timeout.is_credited_holder(&key, &peer, &hash),
13680            "Timeout must retain holder credit (deliberate liveness cushion)"
13681        );
13682    }
13683
13684    #[test]
13685    fn decoded_audit_failures_clear_active_bootstrap_claim() {
13686        for reason in [
13687            AuditFailureReason::MalformedResponse,
13688            AuditFailureReason::DigestMismatch,
13689            AuditFailureReason::KeyAbsent,
13690            AuditFailureReason::Rejected,
13691        ] {
13692            assert!(
13693                audit_failure_clears_bootstrap_claim(&reason),
13694                "decoded non-bootstrap failure {reason:?} should clear active claim"
13695            );
13696        }
13697    }
13698
13699    #[test]
13700    fn first_failed_key_label_truncates_to_16_hex_chars() {
13701        // The high-order 8 bytes of the XorName determine the label so an
13702        // operator can group audit-failures on the same chunk prefix.
13703        let mut key = [0u8; 32];
13704        key[0] = 0x18;
13705        key[7] = 0xff;
13706        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13707        // to verify they are NOT included in the label.
13708        for byte in &mut key[8..] {
13709            *byte = 0xAA;
13710        }
13711        let label = first_failed_key_label(&[key]);
13712        // Only the first 8 bytes are encoded, low-order bytes are dropped.
13713        assert_eq!(label, "0x18000000000000ff");
13714        assert_eq!(label.len(), "0x".len() + 16);
13715    }
13716
13717    #[test]
13718    fn first_failed_key_label_falls_back_when_empty() {
13719        // Should never happen in production (audit failure handling rejects
13720        // empty sets), but the formatter must still produce a valid label
13721        // so the log line doesn't contain a misleading default.
13722        assert_eq!(first_failed_key_label(&[]), "0x");
13723    }
13724
13725    #[test]
13726    fn first_failed_key_label_uses_first_key_only() {
13727        let first = [0x11u8; 32];
13728        let second = [0x22u8; 32];
13729        assert_eq!(
13730            first_failed_key_label(&[first, second]),
13731            format!("0x{}", hex::encode(&first[..8]))
13732        );
13733    }
13734
13735    // -- apply_fetch_result --------------------------------------------------
13736    //
13737    // The worker's disposition of a fetch outcome. Note there is no trust
13738    // handle in `apply_fetch_result`'s signature: the worker cannot report a
13739    // trust event for ANY outcome, and `execute_single_fetch` returns
13740    // `NoLongerResponsible` before its trust-reporting paths — the source did
13741    // nothing wrong when this node's own responsibility lapsed.
13742
13743    /// Route `key` through the real pipeline stages (pending → promoted →
13744    /// dequeued → in-flight) so it carries a verification retry-slot
13745    /// reservation, exactly as a worker-dequeued key does. Returns the
13746    /// in-flight source.
13747    fn drive_key_in_flight(
13748        q: &mut ReplicationQueues,
13749        key: XorName,
13750        sources: Vec<PeerId>,
13751    ) -> PeerId {
13752        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13753        let now = Instant::now();
13754        let entry = VerificationEntry {
13755            state: VerificationState::PendingVerify,
13756            verified_sources: Vec::new(),
13757            tried_sources: HashSet::new(),
13758            created_at: now,
13759            next_verify_at: now,
13760            hint_sources: HashSet::from([hinter]),
13761            replica_hint_sources: HashSet::from([hinter]),
13762            unresolved_retries: 0,
13763            no_holder_reported: false,
13764        };
13765        assert!(q.add_pending_verify(key, entry).admitted());
13766        assert!(q.promote_pending_to_fetch(key, key, sources));
13767        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13768        let source = *candidate.sources.first().expect("candidate has a source");
13769        q.start_dequeued_fetch(candidate, source);
13770        source
13771    }
13772
13773    #[test]
13774    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13775        const RETRY_AFTER: Duration = Duration::from_mins(1);
13776
13777        let mut q = ReplicationQueues::new();
13778        let key = test_key(0xAB);
13779        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13780        assert_eq!(q.retry_reserved_slot_count(), 1);
13781
13782        let follow_up =
13783            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13784
13785        assert_eq!(
13786            follow_up,
13787            FetchFollowUp::Terminal,
13788            "lapsed responsibility must run the caller's terminal bootstrap accounting"
13789        );
13790        assert!(
13791            !q.contains_key(&key),
13792            "the key must leave every pipeline stage — alternate sources included"
13793        );
13794        assert_eq!(
13795            q.pending_count(),
13796            0,
13797            "a lapsed-responsibility key must not be requeued for verification"
13798        );
13799        assert_eq!(
13800            q.retry_reserved_slot_count(),
13801            0,
13802            "terminal exit must release the verification retry-slot reservation"
13803        );
13804    }
13805
13806    #[test]
13807    fn no_longer_responsible_shares_the_stored_terminal_path() {
13808        const RETRY_AFTER: Duration = Duration::from_mins(1);
13809
13810        // Both variants must walk the identical terminal gate so the
13811        // battle-tested Stored accounting (retry-slot release + bootstrap
13812        // pending-set shrink in the caller) covers lapsed responsibility too.
13813        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13814            let mut q = ReplicationQueues::new();
13815            let key = test_key(0xCD);
13816            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13817
13818            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13819
13820            assert_eq!(follow_up, FetchFollowUp::Terminal);
13821            assert!(!q.contains_key(&key));
13822            assert_eq!(q.retry_reserved_slot_count(), 0);
13823        }
13824    }
13825
13826    #[test]
13827    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13828        const RETRY_AFTER: Duration = Duration::from_mins(1);
13829
13830        let mut q = ReplicationQueues::new();
13831        let key = test_key(0xEF);
13832        let first = test_peer(0x04);
13833        let second = test_peer(0x05);
13834        drive_key_in_flight(&mut q, key, vec![first, second]);
13835
13836        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13837        assert_eq!(
13838            follow_up,
13839            FetchFollowUp::RetryFrom(second),
13840            "a failed source must not abandon the remaining verified sources"
13841        );
13842        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13843
13844        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13845        assert_eq!(
13846            follow_up,
13847            FetchFollowUp::RequeuedForVerification,
13848            "exhausted sources must restore the reserved verification entry"
13849        );
13850        assert_eq!(q.pending_count(), 1);
13851        assert_eq!(
13852            q.retry_reserved_slot_count(),
13853            0,
13854            "the reservation converts back into the pending entry itself"
13855        );
13856    }
13857
13858    #[test]
13859    fn source_failure_without_retry_metadata_is_terminal() {
13860        const RETRY_AFTER: Duration = Duration::from_mins(1);
13861
13862        // Direct enqueue (no pending entry) models a fetch with no
13863        // verification retry reservation to restore.
13864        let mut q = ReplicationQueues::new();
13865        let key = test_key(0x1F);
13866        let source = test_peer(0x06);
13867        assert!(q.enqueue_fetch(key, key, vec![source]));
13868        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13869        q.start_dequeued_fetch(candidate, source);
13870
13871        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13872
13873        assert_eq!(follow_up, FetchFollowUp::Terminal);
13874        assert!(!q.contains_key(&key));
13875    }
13876
13877    #[test]
13878    fn already_held_key_leaves_the_pipeline_terminally() {
13879        const RETRY_AFTER: Duration = Duration::from_mins(1);
13880
13881        let mut q = ReplicationQueues::new();
13882        let key = test_key(0x4C);
13883        let source = test_peer(0x0B);
13884        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
13885
13886        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
13887
13888        assert_eq!(
13889            follow_up,
13890            FetchFollowUp::Terminal,
13891            "holding the key already discharges the duty, so the key must leave \
13892             the pipeline exactly as a completed fetch does — requeueing it \
13893             would re-verify a key that needs nothing"
13894        );
13895        assert!(!q.contains_key(&key));
13896        assert_eq!(
13897            q.retry_reserved_slot_count(),
13898            0,
13899            "the terminal path must release the retry-slot reservation, or the \
13900             owner's verification budget leaks"
13901        );
13902    }
13903
13904    #[test]
13905    fn local_write_failure_does_not_conscript_the_remaining_sources() {
13906        const RETRY_AFTER: Duration = Duration::from_mins(1);
13907
13908        let mut q = ReplicationQueues::new();
13909        let key = test_key(0x2A);
13910        let first = test_peer(0x07);
13911        let second = test_peer(0x08);
13912        let third = test_peer(0x09);
13913        drive_key_in_flight(&mut q, key, vec![first, second, third]);
13914
13915        let follow_up =
13916            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13917
13918        assert_eq!(
13919            follow_up,
13920            FetchFollowUp::RequeuedForVerification,
13921            "a local write failure must go straight back to verification: the two \
13922             untried sources would each re-upload the same chunk into the same \
13923             full disk, and neither of them did anything wrong"
13924        );
13925        assert_eq!(q.in_flight_count(), 0);
13926        assert_eq!(
13927            q.pending_count(),
13928            1,
13929            "the key must come back — capacity frees up, and a stranded key is \
13930             a replica this node silently stops owing"
13931        );
13932        assert_eq!(q.retry_reserved_slot_count(), 0);
13933    }
13934
13935    #[test]
13936    fn local_write_failure_without_retry_metadata_is_terminal() {
13937        const RETRY_AFTER: Duration = Duration::from_mins(1);
13938
13939        // No pending entry to restore, so the only way not to strand the key
13940        // in `in_flight_fetch` forever — which would also stall bootstrap
13941        // drain — is the terminal path.
13942        let mut q = ReplicationQueues::new();
13943        let key = test_key(0x3B);
13944        let source = test_peer(0x0A);
13945        assert!(q.enqueue_fetch(key, key, vec![source]));
13946        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
13947        q.start_dequeued_fetch(candidate, source);
13948
13949        let follow_up =
13950            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
13951
13952        assert_eq!(follow_up, FetchFollowUp::Terminal);
13953        assert!(!q.contains_key(&key));
13954        assert_eq!(q.retry_reserved_slot_count(), 0);
13955    }
13956}