Skip to main content

ant_node/replication/
mod.rs

1//! Replication subsystem for the Autonomi network.
2//!
3//! Implements Kademlia-style replication with:
4//! - Fresh replication with `PoP` verification
5//! - Neighbor sync with round-robin cycle management
6//! - Batched quorum verification
7//! - Storage audit protocol (anti-outsourcing)
8//! - `PaidForList` persistence and convergence
9//! - Responsibility pruning with hysteresis
10
11// The replication engine intentionally holds `RwLock` read guards across await
12// boundaries (e.g. reading sync_history while calling audit_tick). Clippy's
13// nursery lint `significant_drop_tightening` flags these, but the guards must
14// remain live for the duration of the call.
15#![allow(clippy::significant_drop_tightening)]
16
17pub mod admission;
18pub mod audit;
19pub mod audit_coordinator;
20pub(crate) mod audit_metrics;
21pub mod bootstrap;
22pub mod commitment;
23pub mod commitment_state;
24pub mod config;
25pub mod fresh;
26pub mod neighbor_sync;
27pub mod paid_list;
28pub mod pointer;
29pub mod possession;
30pub mod protocol;
31pub mod pruning;
32pub mod quorum;
33pub mod recent_provers;
34pub mod scheduling;
35pub mod slice;
36pub mod storage_commitment_audit;
37pub mod subtree;
38pub mod types;
39
40use std::collections::{HashMap, HashSet, VecDeque};
41use std::fmt;
42use std::num::NonZeroUsize;
43use std::ops::ControlFlow;
44use std::path::{Path, PathBuf};
45use std::sync::atomic::{AtomicU64, Ordering};
46use std::sync::Arc;
47use std::time::{Duration, Instant, SystemTime};
48
49use lru::LruCache;
50use std::pin::Pin;
51
52use crate::logging::{debug, error, info, warn};
53use futures::stream::FuturesUnordered;
54use futures::{future::join_all, Future, StreamExt};
55use parking_lot::Mutex;
56use rand::rngs::StdRng;
57use rand::{Rng, SeedableRng};
58use tokio::sync::broadcast::error::RecvError;
59use tokio::sync::{mpsc, Notify, RwLock, Semaphore};
60use tokio::task::JoinHandle;
61use tokio_util::sync::CancellationToken;
62use tokio_util::task::TaskTracker;
63
64use crate::ant_protocol::XorName;
65use crate::error::{Error, Result};
66use crate::payment::{
67    PaymentVerifier, VerificationContext, MAX_PAYMENT_PROOF_SIZE_BYTES,
68    MIN_PAYMENT_PROOF_SIZE_BYTES,
69};
70use crate::pointer::store::PointerStore;
71use crate::replication::audit::AuditTickResult;
72use crate::replication::audit_coordinator::AuditChallengeCoordinator;
73use crate::replication::audit_metrics::{
74    AuditResponderClass, AuditResponderDropReason, AuditResponderMetrics,
75    ReplicationResponderClass, ResponderAdmissionCeiling,
76};
77use crate::replication::commitment::{commitment_hash, StorageCommitment};
78use crate::replication::commitment_state::{
79    PeerCommitmentRecord, PersistedRetention, ResponderCommitmentState, GOSSIP_ANSWERABILITY_TTL,
80};
81use crate::replication::config::{
82    fresh_read_retry_delay, max_parallel_fetch, storage_admission_width, ReplicationConfig,
83    MAX_AUDIT_RESPONSES_PER_PEER, MAX_CONCURRENT_AUDIT_RESPONSES, MAX_CONCURRENT_REPLICATION_SENDS,
84    MAX_DIGEST_AUDIT_RESPONSES_PER_PEER, MAX_FRESH_READ_ATTEMPTS, MAX_INCOMING_VERIFICATION_KEYS,
85    MAX_PENDING_FRESH_OFFERS, MAX_SESSION_POINTER_BINDINGS, MAX_SUBTREE_ROUND1_PER_PEER,
86    MAX_SUBTREE_SESSIONS, MAX_VERIFICATION_KEYS_PER_CYCLE, REPLICATION_PROTOCOL_ID,
87    SUBTREE_AUDIT_PROTOCOL_ID, SUBTREE_ROUND1_WORK_BURST_BYTES,
88    SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, SUBTREE_SESSION_TTL,
89};
90use crate::replication::paid_list::PaidList;
91use crate::replication::protocol::{
92    FreshReplicationResponse, NeighborSyncResponse, ReplicationMessage, ReplicationMessageBody,
93    VerificationResponse,
94};
95use crate::replication::quorum::KeyVerificationOutcome;
96use crate::replication::recent_provers::RecentProvers;
97use crate::replication::scheduling::{CapacityDisplacement, DeferralOutcome, ReplicationQueues};
98use crate::replication::storage_commitment_audit::PointerBindings;
99use crate::replication::types::{
100    AuditFailureReason, BootstrapClaimObservation, BootstrapState, FailureEvidence,
101    NeighborSyncState, PeerSyncRecord, PresenceEvidence, RepairProofs, VerificationEntry,
102    VerificationState,
103};
104use crate::storage::{CapacityVerdict, ChunkStore};
105use saorsa_core::identity::{NodeIdentity, PeerId};
106use saorsa_core::{DhtNetworkEvent, P2PEvent, P2PNode, TrustEvent};
107use saorsa_pqc::api::sig::{MlDsaSecretKey, MlDsaVariant};
108
109/// Count of monetized-pin nominations DROPPED at the bounded ingress channel
110/// because it was full (Amendment 2). Process-global because the producer is
111/// the payment verifier (a different module) and the drop happens before the
112/// per-drainer `received` counter. A non-zero value is the rollout signal that
113/// nomination ingress is saturating — benign (penalty-free, lottery/next-
114/// payment covered) but worth watching. `Closed` (engine shut down) is not
115/// counted: it is not a saturation signal.
116static FIRST_AUDIT_INGRESS_DROPPED: AtomicU64 = AtomicU64::new(0);
117
118/// Record one ingress-full drop. Called by the payment verifier's `try_send`
119/// sites; read by the drainer's periodic summary.
120pub(crate) fn note_monetized_ingress_drop() {
121    FIRST_AUDIT_INGRESS_DROPPED.fetch_add(1, Ordering::Relaxed);
122}
123
124#[derive(Default)]
125struct FirstAuditObservability {
126    received: AtomicU64,
127    queued: AtomicU64,
128    coalesced: AtomicU64,
129    duplicates: AtomicU64,
130    capacity_evicted: AtomicU64,
131    /// An event targeting the local peer itself, dropped at ingress: the node
132    /// cannot network-audit itself (no dialable address for the local peer).
133    self_target_skipped: AtomicU64,
134    /// A strictly-lower-count same-peer nomination that was dropped so a
135    /// higher-count pending pin survived. A sustained rise is the signal of an
136    /// attempted "erase the inflated pin with a cheaper one" self-suppression.
137    suppressed_lower: AtomicU64,
138    cooldown_deferred_attempts: AtomicU64,
139    rate_deferred_attempts: AtomicU64,
140    window_deduped: AtomicU64,
141    launched: AtomicU64,
142    passed: AtomicU64,
143    timed_out: AtomicU64,
144    failed: AtomicU64,
145    bootstrap_claims: AtomicU64,
146    idle: AtomicU64,
147    insufficient_keys: AtomicU64,
148    outside_answerability_window: AtomicU64,
149    inflight: AtomicU64,
150}
151
152/// Test-only snapshot of the first-audit scheduler counters.
153///
154/// Lets e2e tests assert on the scheduler's decisions (e.g. that a
155/// self-targeting monetized pin was dropped and never launched) instead of
156/// scraping log lines.
157#[cfg(any(test, feature = "test-utils"))]
158#[derive(Debug, Clone, Copy)]
159pub struct FirstAuditStats {
160    /// Events ingested from the monetized-pin channel.
161    pub received: u64,
162    /// Events accepted into the pending first-audit queue.
163    pub queued: u64,
164    /// Events dropped because they targeted the local peer.
165    pub self_target_skipped: u64,
166    /// Audits launched.
167    pub launched: u64,
168    /// Launched audits that passed.
169    pub passed: u64,
170    /// Launched audits that timed out (non-response lane).
171    pub timed_out: u64,
172    /// Launched audits that ended in a confirmed failure.
173    pub failed: u64,
174}
175
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum FirstAuditTerminalOutcome {
178    Passed,
179    Timeout,
180    Failed,
181    BootstrapClaim,
182    Idle,
183    InsufficientKeys,
184}
185
186impl FirstAuditTerminalOutcome {
187    #[cfg(any(feature = "logging", test))]
188    const fn as_str(self) -> &'static str {
189        match self {
190            Self::Passed => "passed",
191            Self::Timeout => "timeout",
192            Self::Failed => "failed",
193            Self::BootstrapClaim => "bootstrap_claim",
194            Self::Idle => "idle",
195            Self::InsufficientKeys => "insufficient_keys",
196        }
197    }
198}
199
200fn first_audit_terminal_outcome(result: &AuditTickResult) -> FirstAuditTerminalOutcome {
201    match result {
202        AuditTickResult::Passed { .. } => FirstAuditTerminalOutcome::Passed,
203        AuditTickResult::Failed {
204            evidence:
205                FailureEvidence::AuditFailure {
206                    reason: AuditFailureReason::Timeout,
207                    ..
208                },
209            ..
210        } => FirstAuditTerminalOutcome::Timeout,
211        AuditTickResult::Failed { .. } => FirstAuditTerminalOutcome::Failed,
212        AuditTickResult::BootstrapClaim { .. } => FirstAuditTerminalOutcome::BootstrapClaim,
213        AuditTickResult::Idle => FirstAuditTerminalOutcome::Idle,
214        AuditTickResult::InsufficientKeys => FirstAuditTerminalOutcome::InsufficientKeys,
215    }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219enum FirstAuditQueueOutcome {
220    /// New peer inserted with free capacity.
221    Queued,
222    /// Collapsed with an existing same-peer entry; the incoming won (higher
223    /// count, or equal count and newer) and replaced it.
224    Coalesced,
225    /// Collapsed with an existing same-peer entry; the incoming LOST because it
226    /// had a STRICTLY LOWER count and was dropped, leaving the higher-count pin
227    /// in place. This is the attempted cheaper-pin self-erasure signal.
228    SuppressedLower,
229    /// Collapsed with an existing same-peer entry of EQUAL count; the incoming
230    /// lost the freshness tie (it was not the newer of the two) and the
231    /// existing entry was retained. Benign, not an attack signal.
232    RetainedOnTie,
233    /// A DIFFERENT peer's entry was displaced from the capped pending queue
234    /// (random victim) to make room.
235    CapacityEvicted { peer: PeerId, pin: [u8; 32] },
236}
237
238/// Coalesce a monetized nomination into the per-peer pending queue with a
239/// SECURITY-AWARE rule (ADR-0004 Amendment 2): keep the pin that most needs
240/// auditing — the HIGHEST committed key count for that peer, newest on a tie.
241///
242/// A strictly-lower-count incoming must NOT displace a higher-count pending pin,
243/// otherwise a peer can erase an inflated (audit-worthy) commitment by simply
244/// monetizing a cheaper one right after — and a sidecar-only inflated pin has no
245/// gossip-lottery backstop. When the incoming loses, the retained entry's LRU
246/// recency is left UNTOUCHED (via `peek`), so a flood of low-count nominations
247/// cannot promote the retained pin's lane position.
248///
249/// `incoming_is_newer` distinguishes ordinary enqueue (the incoming arrived
250/// last, so it wins an equal-count tie for freshness) from a cooldown-race
251/// requeue of an older reserved event (the pending successor is newer, so it
252/// wins the tie).
253fn coalesce_first_audit_event(
254    pending: &mut LruCache<PeerId, MonetizedPinEvent>,
255    incoming: MonetizedPinEvent,
256    incoming_is_newer: bool,
257    rng: &mut StdRng,
258) -> FirstAuditQueueOutcome {
259    if let Some(existing) = pending.peek(&incoming.peer) {
260        // Strictly lower -> the incoming loses and is dropped WITHOUT touching
261        // the retained pin's recency (the security-relevant self-erasure case).
262        if incoming.key_count < existing.key_count {
263            return FirstAuditQueueOutcome::SuppressedLower;
264        }
265        // Equal count -> keep the fresher; an older incoming loses a benign tie.
266        if incoming.key_count == existing.key_count && !incoming_is_newer {
267            return FirstAuditQueueOutcome::RetainedOnTie;
268        }
269        // Strictly higher, or equal-and-newer: the incoming wins. `push` updates
270        // the value and bumps MRU; replacing an existing key never evicts a
271        // different peer.
272        let _ = pending.push(incoming.peer, incoming);
273        return FirstAuditQueueOutcome::Coalesced;
274    }
275    // No same-peer entry. At capacity, displace a UNIFORMLY RANDOM incumbent,
276    // never the LRU: deterministic keep-newest would let an ordered batch of
277    // `cap` distinct-peer nominations flush a chosen target before any launch
278    // lane sees it, cutting the eviction cost from probabilistic to exact. A
279    // random victim caps an attacker's per-nomination eviction probability at
280    // `1/cap` regardless of arrival order or timing, so suppressing a specific
281    // target with confidence `1-e` costs ~`cap*ln(1/e)` distinct-peer paid
282    // nominations and is never certain (ADR-0004 Amendment 4).
283    if pending.len() >= pending.cap().get() {
284        let victim = {
285            let idx = rng.gen_range(0..pending.len());
286            pending.iter().nth(idx).map(|(p, _)| *p)
287        };
288        if let Some(victim_peer) = victim {
289            if let Some(evicted) = pending.pop(&victim_peer) {
290                let _ = pending.push(incoming.peer, incoming);
291                return FirstAuditQueueOutcome::CapacityEvicted {
292                    peer: victim_peer,
293                    pin: evicted.pin,
294                };
295            }
296        }
297    }
298    match pending.push(incoming.peer, incoming) {
299        None => FirstAuditQueueOutcome::Queued,
300        // Unreachable: the random-displacement branch above guarantees
301        // `len < cap` here (the caller holds `&mut`, so no concurrent insert
302        // exists). Kept so any future logic error surfaces as an ACCOUNTED
303        // eviction rather than silent loss — but note this arm would be
304        // LRU-order, not random, so it must stay unreachable.
305        Some((evicted_peer, evicted)) => FirstAuditQueueOutcome::CapacityEvicted {
306            peer: evicted_peer,
307            pin: evicted.pin,
308        },
309    }
310}
311
312/// ADR-0004 Amendment 2 (E′): slack added to the max launch jitter when
313/// prefiltering a nomination's answerability at schedule time, covering the
314/// spawn/dispatch latency between the timer firing and the wire challenge so a
315/// jitter==MAX pin is not admitted only to fail the authoritative check by a
316/// few milliseconds. Tiny against the multi-hour answerability window.
317const FIRST_AUDIT_SEND_LATENCY_SLACK: Duration = Duration::from_secs(1);
318
319/// A first audit the limiter recently launched at a peer: when, and the
320/// committed key count that was audited (for the count-jump override).
321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
322struct RecentFirstAudit {
323    launched_at: Instant,
324    key_count: u32,
325}
326
327/// Holds one first-audit in-flight slot; decrements the gauge on drop so a
328/// panicking or cancelled audit task can never leak a slot and wedge the
329/// [`config::FIRST_AUDIT_MAX_INFLIGHT`] cap shut.
330struct FirstAuditInflightSlot(Arc<FirstAuditObservability>);
331
332impl FirstAuditInflightSlot {
333    fn acquire(observability: &Arc<FirstAuditObservability>) -> Self {
334        observability.inflight.fetch_add(1, Ordering::Relaxed);
335        Self(Arc::clone(observability))
336    }
337}
338
339impl Drop for FirstAuditInflightSlot {
340    fn drop(&mut self) {
341        self.0.inflight.fetch_sub(1, Ordering::Relaxed);
342    }
343}
344
345/// ADR-0004 Amendment 2: whether `new_count` exceeds `audited_count` by more
346/// than the [`config::FIRST_AUDIT_COUNT_JUMP_NUM`]/
347/// [`config::FIRST_AUDIT_COUNT_JUMP_DEN`] ratio (`new > old * NUM / DEN`,
348/// overflow-free integer math). A jump re-nominates a peer despite a recent
349/// first audit: an inflated SIDECAR-ONLY pin is visible to payment verifiers
350/// only, so no gossip-lottery audit can ever cover it.
351const fn first_audit_count_jump(audited_count: u32, new_count: u32) -> bool {
352    (new_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_DEN
353        > (audited_count as u64) * config::FIRST_AUDIT_COUNT_JUMP_NUM
354}
355
356/// The launch limiter's verdict for one pending monetized pin.
357#[derive(Debug, Clone, Copy, PartialEq, Eq)]
358enum LimiterVerdict {
359    /// Within budget and window: the caller may reserve a launch (and consumes
360    /// a token via [`FirstAuditLimiter::reserve_token`] only if it does).
361    Admit,
362    /// Launch-rate budget or in-flight cap exhausted. Penalty-free: keep the
363    /// pin pending and retry on a later tick.
364    RateDeferred,
365    /// The peer had a first audit within
366    /// [`config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL`] and the new pin's count
367    /// shows no [`first_audit_count_jump`]. Drop the nomination (the
368    /// gossip-lottery re-audit path is unaffected).
369    WindowDeduped,
370}
371
372/// ADR-0004 Amendment 2: the first-audit launch limiter — a token bucket
373/// (launch rate), an in-flight cap, and a per-peer re-audit window that
374/// survives pin rotation.
375///
376/// This is the load-bearing aggregate bound the original scheduler lacked:
377/// fleet-wide first-audit pressure becomes `nodes x refill-rate` instead of
378/// `uploads x pinned-quotes-per-proof x verifying-storers`. Pure over passed
379/// `now`/`inflight` values so every decision is unit-testable without a
380/// runtime.
381struct FirstAuditLimiter {
382    /// Launch tokens available, at most [`config::FIRST_AUDIT_BUDGET_BURST`].
383    tokens: u32,
384    /// Refill anchor. While the bucket is full this tracks `now` (a full
385    /// bucket accrues nothing); while below capacity it advances only by
386    /// whole refill intervals so fractional elapsed time is never lost.
387    last_refill: Instant,
388    /// Peers given a first audit recently, with the audited key count.
389    /// Bounded like the drainer's other per-peer maps.
390    recent: LruCache<PeerId, RecentFirstAudit>,
391}
392
393impl FirstAuditLimiter {
394    fn new(now: Instant) -> Self {
395        Self {
396            tokens: config::FIRST_AUDIT_BUDGET_BURST,
397            last_refill: now,
398            recent: LruCache::new(
399                NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN),
400            ),
401        }
402    }
403
404    /// Whether the per-peer re-audit window admits a nomination for `peer`
405    /// carrying `key_count` at `now`. Read-only (`peek`), so it is safe to
406    /// call at ENQUEUE time — suppressed nominations never occupy pending
407    /// slots — without disturbing LRU recency.
408    fn window_allows(&self, peer: &PeerId, key_count: u32, now: Instant) -> bool {
409        self.recent.peek(peer).is_none_or(|prev| {
410            now.saturating_duration_since(prev.launched_at)
411                >= config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL
412                || first_audit_count_jump(prev.key_count, key_count)
413        })
414    }
415
416    /// Refill the token bucket for the time elapsed up to `now`.
417    fn refill(&mut self, now: Instant) {
418        if self.tokens >= config::FIRST_AUDIT_BUDGET_BURST {
419            // Full bucket accrues nothing; keep the anchor current so the
420            // next consumption starts its interval from here.
421            self.last_refill = now;
422            return;
423        }
424        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
425        let elapsed = now.saturating_duration_since(self.last_refill);
426        let earned = elapsed.as_nanos() / interval.as_nanos().max(1);
427        if earned == 0 {
428            return;
429        }
430        let capacity_gap = u128::from(config::FIRST_AUDIT_BUDGET_BURST - self.tokens);
431        if earned >= capacity_gap {
432            self.tokens = config::FIRST_AUDIT_BUDGET_BURST;
433            self.last_refill = now;
434        } else {
435            // earned < capacity_gap <= u32::MAX, so both casts are lossless.
436            self.tokens = self
437                .tokens
438                .saturating_add(u32::try_from(earned).unwrap_or(u32::MAX));
439            let advance = interval.saturating_mul(u32::try_from(earned).unwrap_or(u32::MAX));
440            self.last_refill = self.last_refill.checked_add(advance).unwrap_or(now);
441        }
442    }
443
444    /// Decide whether a pending pin may launch now. Consumes NOTHING: the
445    /// caller runs the remaining (per-peer cooldown) gate and calls
446    /// [`Self::commit_launch`] only for a launch that actually happens, so a
447    /// deferral elsewhere never burns budget or stamps the window.
448    fn assess(
449        &mut self,
450        peer: &PeerId,
451        key_count: u32,
452        now: Instant,
453        inflight: u64,
454    ) -> LimiterVerdict {
455        if !self.window_allows(peer, key_count, now) {
456            return LimiterVerdict::WindowDeduped;
457        }
458        self.refill(now);
459        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.tokens == 0 {
460            return LimiterVerdict::RateDeferred;
461        }
462        LimiterVerdict::Admit
463    }
464
465    /// Consume one launch token for a RESERVATION (ADR-0004 Amendment 2 E′).
466    /// Does NOT stamp the per-peer window: the durable `recent` stamp happens
467    /// only at [`Self::promote`], after the authoritative post-jitter
468    /// answerability check, so a reservation that is later cancelled leaves no
469    /// suppression behind.
470    fn reserve_token(&mut self) {
471        self.tokens = self.tokens.saturating_sub(1);
472    }
473
474    /// Return a token consumed by a reservation that was cancelled before it
475    /// launched (answerability lapsed or a concurrent gossip audit won the
476    /// cooldown). Capped at the burst so a spurious double-refund cannot exceed
477    /// the bucket.
478    fn refund_token(&mut self) {
479        self.tokens = (self.tokens + 1).min(config::FIRST_AUDIT_BUDGET_BURST);
480    }
481
482    /// Stamp the per-peer re-audit window for a launch that is ACTUALLY firing
483    /// (promotion). Separated from token consumption so suppression is only
484    /// ever recorded for a real send.
485    fn promote(&mut self, peer: PeerId, key_count: u32, now: Instant) {
486        self.recent.put(
487            peer,
488            RecentFirstAudit {
489                launched_at: now,
490                key_count,
491            },
492        );
493    }
494
495    /// Test convenience: the pre-E′ atomic "a launch happened" — consume a token
496    /// and stamp the window in one call. Production splits these across
497    /// reservation and promotion; the limiter's own budget/window unit tests do
498    /// not model the jitter reservation and use this shorthand.
499    #[cfg(test)]
500    fn commit_launch(&mut self, peer: PeerId, key_count: u32, now: Instant) {
501        self.reserve_token();
502        self.promote(peer, key_count, now);
503    }
504}
505
506/// ADR-0004 Amendment 2 (E′ B-prefilter): whether a monetized pin is answerable
507/// across the ENTIRE launch-jitter window ending at
508/// `now + FIRST_AUDIT_LAUNCH_JITTER_MAX + slack`, so committing scheduling state
509/// for it cannot later require aborting an out-of-window challenge. The
510/// too-future bound is enforced at `now` (a jitter delay only ages a pin
511/// forward, never toward the future); the too-old bound is enforced at the
512/// latest possible send time. This is a conservative admission prefilter; the
513/// authoritative answerability check still runs at promotion against the real
514/// send-time wall clock, so A1 (no false conviction) holds regardless of how
515/// jitter and the answerability margin are sized. `checked_add` overflow fails
516/// closed (skip the pin).
517fn quote_answerable_through_nominal_jitter(quote_ts: SystemTime, now: SystemTime) -> bool {
518    let Some(latest_send) = now
519        .checked_add(config::FIRST_AUDIT_LAUNCH_JITTER_MAX)
520        .and_then(|t| t.checked_add(FIRST_AUDIT_SEND_LATENCY_SLACK))
521    else {
522        return false;
523    };
524    quote_within_audit_window(quote_ts, now) && quote_within_audit_window(quote_ts, latest_send)
525}
526
527/// Open the single first-audit reservation from `pending` if none is
528/// outstanding: samples the launch jitter, snapshots the shared cooldown
529/// read-only, and delegates to [`FirstAuditScheduler::try_reserve`]. One
530/// shared implementation for both drainer call sites — the per-wake launch
531/// phase and the pre-overflow opportunity inside the ingress batch — so the
532/// two cannot drift.
533async fn open_first_audit_reservation(
534    scheduler: &mut FirstAuditScheduler,
535    cooldown: &RwLock<HashMap<PeerId, Instant>>,
536    observability: &Arc<FirstAuditObservability>,
537) {
538    if scheduler.has_reservation() {
539        return;
540    }
541    let jitter = Duration::from_millis(rand::thread_rng().gen_range(
542        0..=u64::try_from(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_millis()).unwrap_or(u64::MAX),
543    ));
544    let inflight = observability.inflight.load(Ordering::Relaxed);
545    let reserved = {
546        let cooldown = cooldown.read().await;
547        scheduler.try_reserve(Instant::now(), inflight, jitter, &cooldown, observability)
548    };
549    if reserved {
550        if let Some(peer) = scheduler.reserved_peer() {
551            debug!(
552                "First-audit scheduler: audit_trigger=first_monetized outcome=reserved peer={peer} pending={}",
553                scheduler.pending_len()
554            );
555        }
556    }
557}
558
559/// A far-future `Instant` used to effectively DISABLE the promotion-timer
560/// select arm when no reservation is outstanding. The drainer still wakes at
561/// least every [`config::FIRST_AUDIT_RETRY_INTERVAL`] via its tick, so this only
562/// needs to be comfortably past the next tick.
563fn first_audit_far_future() -> Instant {
564    Instant::now()
565        .checked_add(Duration::from_hours(1))
566        .unwrap_or_else(Instant::now)
567}
568
569/// ADR-0004 Amendment 2 (E′): one outstanding first-audit reservation. Holds
570/// its in-flight slot and launch token from schedule time until the jitter
571/// timer fires; the durable suppression (`recent` + `first_audited`) is stamped
572/// only if the authoritative post-jitter answerability + cooldown checks pass at
573/// promotion, so a cancelled reservation leaves NO suppression behind.
574struct FirstAuditReservation {
575    event: MonetizedPinEvent,
576    ready_at: Instant,
577    inflight: FirstAuditInflightSlot,
578}
579
580/// ADR-0004 Amendment 2 (E′): the drainer-owned first-audit scheduler. Owns the
581/// pending queue, the dedup set, the launch limiter, the alternating lane, and
582/// the single outstanding reservation. All mutation is single-threaded in the
583/// drainer task; the only asynchrony is the spawned audit I/O (which just holds
584/// the moved-in in-flight slot). Kept as a struct so the reserve/promote/cancel
585/// state machine is unit-testable with injected clocks.
586struct FirstAuditScheduler {
587    /// Pins already given a first audit (dedup). A pin enters only at PROMOTION
588    /// (a real send), never at reservation, so a cancelled reservation can be
589    /// re-nominated.
590    first_audited: LruCache<[u8; 32], ()>,
591    /// Highest-count-per-peer pending nominations not yet launched. Capped at
592    /// [`FIRST_AUDIT_PENDING_CAP`] (what the token budget can launch within
593    /// one effective answerability window); at capacity a uniformly RANDOM
594    /// incumbent is displaced and counted as `capacity_evicted`, so eviction
595    /// of a specific entry can never be forced deterministically. One further
596    /// entry may be held in `reserved` outside this queue — a deliberate
597    /// one-entry guard slot, so total schedulable occupancy is at most
598    /// `cap + 1`; the summary line reports both (`pending`/`reserved`).
599    pending: LruCache<PeerId, MonetizedPinEvent>,
600    /// Token bucket + per-peer re-audit window.
601    limiter: FirstAuditLimiter,
602    /// The single outstanding reservation (E′ serializes reservations so the
603    /// per-launch lane alternation is preserved and at most one jitter timer is
604    /// live).
605    reserved: Option<FirstAuditReservation>,
606    /// Alternating launch lane, flipped on every PROMOTION (real launch).
607    oldest_first_lane: bool,
608    /// The local node's own peer ID. A verified payment's quote list includes
609    /// the node's own quote, so the verifier emits a monetized-pin event for
610    /// the local peer on every payment it verifies. The node cannot
611    /// network-audit itself (there is no dialable address for the local peer,
612    /// so the challenge fails instantly and is miscounted as a timeout), while
613    /// any other payee that verifies the same payment schedules its own first
614    /// audit of this node's pin — a self-dial adds no coverage either way.
615    /// Such an event is dropped at ingress: never queued, and hence never
616    /// launched nor marked first-audited.
617    self_peer: PeerId,
618    /// RNG for random-victim displacement (ADR-0004 Amendment 4). Owned by the
619    /// scheduler so tests can seed it and reproduce eviction sequences exactly;
620    /// production seeds from OS entropy at construction.
621    rng: StdRng,
622}
623
624impl FirstAuditScheduler {
625    fn new(now: Instant, self_peer: PeerId) -> Self {
626        let dedup_cap = NonZeroUsize::new(MAX_LAST_COMMITMENT_BY_PEER).unwrap_or(NonZeroUsize::MIN);
627        let pending_cap = NonZeroUsize::new(FIRST_AUDIT_PENDING_CAP).unwrap_or(NonZeroUsize::MIN);
628        Self {
629            first_audited: LruCache::new(dedup_cap),
630            pending: LruCache::new(pending_cap),
631            limiter: FirstAuditLimiter::new(now),
632            reserved: None,
633            oldest_first_lane: false,
634            self_peer,
635            rng: StdRng::from_entropy(),
636        }
637    }
638
639    /// Observability getter: used by the scheduler summary log and unit tests,
640    /// both absent from a release `--no-default-features` build, so it is dead
641    /// only in that configuration.
642    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
643    fn pending_len(&self) -> usize {
644        self.pending.len()
645    }
646
647    /// Observability getter (see [`Self::pending_len`]).
648    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
649    fn tokens(&self) -> u32 {
650        self.limiter.tokens
651    }
652
653    /// Observability getter (see [`Self::pending_len`]). Milliseconds since the
654    /// signed quote timestamp of the oldest pin still awaiting a first audit:
655    /// how close the longest-waiting pending pin is to aging out of the
656    /// answerability window. A value climbing toward the window means pending
657    /// work is expiring unaudited instead of launching; a small, steady value
658    /// means the queue is draining promptly. Returns `0` when `pending` is empty
659    /// and saturates to `0` for a future-dated quote (clock skew), never panics.
660    #[cfg_attr(not(feature = "logging"), allow(dead_code))]
661    fn oldest_pending_quote_age_ms(&self, now: SystemTime) -> u64 {
662        self.pending
663            .iter()
664            .map(|(_, e)| e.quote_ts)
665            .min()
666            .and_then(|oldest| now.duration_since(oldest).ok())
667            .map_or(0, |age| u64::try_from(age.as_millis()).unwrap_or(u64::MAX))
668    }
669
670    /// Drop every pending nomination that has aged past the answerability
671    /// horizon. `try_reserve` collects expired entries only while it can scan —
672    /// under token starvation it returns at the budget gate first — so without
673    /// a periodic sweep dead entries squat the capped pending queue (displacing
674    /// at capacity) and inflate the `pending`/`oldest_pending_quote_age_ms`
675    /// telemetry. Each removal is accounted as `outside_answerability_window`,
676    /// exactly like a scan-time expiry. Returns how many entries were dropped;
677    /// survivor recency is untouched.
678    fn sweep_expired(&mut self, wall_now: SystemTime, obs: &Arc<FirstAuditObservability>) -> usize {
679        let expired: Vec<PeerId> = self
680            .pending
681            .iter()
682            .filter(|(_, event)| !quote_answerable_through_nominal_jitter(event.quote_ts, wall_now))
683            .map(|(peer, _)| *peer)
684            .collect();
685        for peer in &expired {
686            self.pending.pop(peer);
687        }
688        if !expired.is_empty() {
689            obs.outside_answerability_window.fetch_add(
690                u64::try_from(expired.len()).unwrap_or(u64::MAX),
691                Ordering::Relaxed,
692            );
693        }
694        expired.len()
695    }
696
697    fn has_reservation(&self) -> bool {
698        self.reserved.is_some()
699    }
700
701    /// Whether admitting `event` would displace a DIFFERENT peer's pending
702    /// entry: the queue is at capacity and `event.peer` has no incumbent to
703    /// coalesce into. The drainer checks this before enqueueing so pending
704    /// work gets a reservation opportunity BEFORE destructive overflow
705    /// (ADR-0004 Amendment 4) — a successful reservation moves one entry out
706    /// of `pending`, freeing the slot without any eviction.
707    fn would_displace(&self, event: &MonetizedPinEvent) -> bool {
708        self.pending.len() >= self.pending.cap().get() && self.pending.peek(&event.peer).is_none()
709    }
710
711    /// When the outstanding reservation becomes eligible for promotion.
712    fn reserved_ready_at(&self) -> Option<Instant> {
713        self.reserved.as_ref().map(|r| r.ready_at)
714    }
715
716    /// The peer of the outstanding reservation, if any.
717    fn reserved_peer(&self) -> Option<PeerId> {
718        self.reserved.as_ref().map(|r| r.event.peer)
719    }
720
721    /// Admit a monetized nomination into `pending`. Dropped at ingress if it
722    /// targets the local peer (see [`Self::self_peer`]); dropped as a duplicate
723    /// if already first-audited; the window screen is bypassed for the currently
724    /// reserved peer (so a successor is retained across the reservation, never
725    /// window-dropped); otherwise window-screened. Coalescing is
726    /// highest-count-per-peer (newest on a tie) — a lower-count successor never
727    /// displaces a higher-count pending pin. An incumbent that has aged past
728    /// the answerability horizon is dropped (and accounted as an expiry) before
729    /// coalescing, so a dead pin never vetoes a live nomination. Admission for
730    /// a NEW peer at capacity displaces a uniformly RANDOM incumbent (see
731    /// [`FIRST_AUDIT_PENDING_CAP`] and [`coalesce_first_audit_event`]):
732    /// displacement is accounted as `capacity_evicted` and stamps no
733    /// suppression, so a displaced peer's next nomination is judged like any
734    /// newcomer. The drainer additionally offers a reservation opportunity
735    /// via [`Self::would_displace`] before calling this on an overflowing
736    /// arrival.
737    fn enqueue(&mut self, event: MonetizedPinEvent, obs: &Arc<FirstAuditObservability>) {
738        if event.peer == self.self_peer {
739            obs.self_target_skipped.fetch_add(1, Ordering::Relaxed);
740            return;
741        }
742        if self.first_audited.contains(&event.pin) {
743            obs.duplicates.fetch_add(1, Ordering::Relaxed);
744            return;
745        }
746        let reserved_peer = self.reserved_peer();
747        let is_reserved_peer = reserved_peer == Some(event.peer);
748        if !is_reserved_peer
749            && !self
750                .limiter
751                .window_allows(&event.peer, event.key_count, Instant::now())
752        {
753            obs.window_deduped.fetch_add(1, Ordering::Relaxed);
754            return;
755        }
756        // A pending incumbent past the answerability horizon can never launch,
757        // yet its (possibly higher) key count would still win the coalesce
758        // against a live incoming — e.g. a fresh post-prune lower-count pin —
759        // and under token starvation no reserve scan runs to collect it. Drop
760        // it first so the incoming is judged on its own merits.
761        let stale_incumbent = self.pending.peek(&event.peer).is_some_and(|existing| {
762            !quote_answerable_through_nominal_jitter(existing.quote_ts, SystemTime::now())
763        });
764        if stale_incumbent {
765            self.pending.pop(&event.peer);
766            obs.outside_answerability_window
767                .fetch_add(1, Ordering::Relaxed);
768        }
769        // Ordinary enqueue: the incoming arrived last, so it wins an equal-count
770        // tie.
771        match coalesce_first_audit_event(&mut self.pending, event, true, &mut self.rng) {
772            FirstAuditQueueOutcome::Queued => {
773                obs.queued.fetch_add(1, Ordering::Relaxed);
774            }
775            FirstAuditQueueOutcome::Coalesced | FirstAuditQueueOutcome::RetainedOnTie => {
776                obs.coalesced.fetch_add(1, Ordering::Relaxed);
777            }
778            FirstAuditQueueOutcome::SuppressedLower => {
779                obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
780            }
781            FirstAuditQueueOutcome::CapacityEvicted { .. } => {
782                obs.queued.fetch_add(1, Ordering::Relaxed);
783                obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
784            }
785        }
786    }
787
788    /// Attempt to create the single reservation from `pending` (E′ reserve).
789    /// Scans in the current lane order and reserves the FIRST eligible pin:
790    /// consumes one token, acquires one in-flight slot, and sets `ready_at =
791    /// mono_now + jitter`. Does NOT stamp `recent`/`first_audited` and does NOT
792    /// flip the lane — those happen only at promotion. Returns whether a
793    /// reservation was made. `cooldown` is a read-only snapshot (the
794    /// authoritative check-and-stamp is at promotion).
795    fn try_reserve(
796        &mut self,
797        mono_now: Instant,
798        inflight: u64,
799        jitter: Duration,
800        cooldown: &HashMap<PeerId, Instant>,
801        obs: &Arc<FirstAuditObservability>,
802    ) -> bool {
803        if self.reserved.is_some() || self.pending.is_empty() {
804            return false;
805        }
806        self.limiter.refill(mono_now);
807        if inflight >= config::FIRST_AUDIT_MAX_INFLIGHT || self.limiter.tokens == 0 {
808            obs.rate_deferred_attempts.fetch_add(1, Ordering::Relaxed);
809            return false;
810        }
811        // MRU->LRU order; reverse for the oldest-first lane so the preferred
812        // end is at the front.
813        let mut ordered: Vec<(usize, PeerId, MonetizedPinEvent)> = self
814            .pending
815            .iter()
816            .enumerate()
817            .map(|(i, (p, e))| (i, *p, *e))
818            .collect();
819        self.pending.clear();
820        if self.oldest_first_lane {
821            ordered.reverse();
822        }
823        let mut chosen: Option<MonetizedPinEvent> = None;
824        let mut kept: Vec<(usize, PeerId, MonetizedPinEvent)> = Vec::new();
825        for (idx, peer, event) in ordered {
826            if chosen.is_some() {
827                kept.push((idx, peer, event));
828                continue;
829            }
830            if self.first_audited.contains(&event.pin) {
831                obs.duplicates.fetch_add(1, Ordering::Relaxed);
832                continue; // drop: already audited
833            }
834            if !quote_answerable_through_nominal_jitter(event.quote_ts, SystemTime::now()) {
835                obs.outside_answerability_window
836                    .fetch_add(1, Ordering::Relaxed);
837                continue; // drop: cannot stay answerable through the jitter
838            }
839            // Window + budget + inflight. Tokens do not decrease during the
840            // scan (reserve happens after the loop) and `inflight` is fixed, so
841            // after the upfront budget gate `assess` never returns RateDeferred
842            // here; a defensive RateDeferred keeps the pin.
843            match self
844                .limiter
845                .assess(&peer, event.key_count, mono_now, inflight)
846            {
847                LimiterVerdict::WindowDeduped => {
848                    obs.window_deduped.fetch_add(1, Ordering::Relaxed);
849                    continue; // drop: recently first-audited, no count jump
850                }
851                LimiterVerdict::RateDeferred => {
852                    kept.push((idx, peer, event));
853                    continue; // keep (defensive; unreachable after upfront gate)
854                }
855                LimiterVerdict::Admit => {}
856            }
857            if !cooldown_would_allow(cooldown, &peer, mono_now) {
858                obs.cooldown_deferred_attempts
859                    .fetch_add(1, Ordering::Relaxed);
860                kept.push((idx, peer, event));
861                continue; // keep: on shared cooldown, retry later
862            }
863            chosen = Some(event);
864        }
865        // Restore relative recency (oldest re-put first -> newest stays MRU).
866        kept.sort_unstable_by_key(|(idx, _, _)| std::cmp::Reverse(*idx));
867        for (_, peer, event) in kept {
868            self.pending.put(peer, event);
869        }
870        let Some(event) = chosen else {
871            return false;
872        };
873        self.limiter.reserve_token();
874        let inflight_slot = FirstAuditInflightSlot::acquire(obs);
875        let ready_at = mono_now.checked_add(jitter).unwrap_or(mono_now);
876        self.reserved = Some(FirstAuditReservation {
877            event,
878            ready_at,
879            inflight: inflight_slot,
880        });
881        true
882    }
883
884    /// Take the outstanding reservation if its jitter has elapsed at `mono_now`.
885    fn take_due_reservation(&mut self, mono_now: Instant) -> Option<FirstAuditReservation> {
886        if self
887            .reserved
888            .as_ref()
889            .is_some_and(|r| mono_now >= r.ready_at)
890        {
891            self.reserved.take()
892        } else {
893            None
894        }
895    }
896
897    /// Authoritative promotion of a due reservation (E′). The caller holds the
898    /// shared cooldown write lock and passes the real send-time `wall_now` and
899    /// `mono_now`. Returns `Some((event, slot))` to spawn the audit on a real
900    /// launch, or `None` when the launch was cancelled (answerability lapsed
901    /// during jitter) or requeued (a concurrent gossip audit won the cooldown).
902    /// On both `None` paths the token is refunded, the in-flight slot released,
903    /// and NO suppression is recorded.
904    ///
905    /// Known operational residual: suppression is stamped here, at promotion,
906    /// while the wire challenge is sent by the detached task the caller spawns
907    /// with the returned event. A task-start or encoding failure between the
908    /// two therefore leaves a stamped-but-unsent window. No remote input can
909    /// force that failure (it requires local task-spawn/alloc failure), so it
910    /// is accepted rather than closed; closing it would require stamping from
911    /// inside the spawned task and re-introduce the cancel-leaves-suppression
912    /// race this design exists to prevent.
913    fn resolve(
914        &mut self,
915        reservation: FirstAuditReservation,
916        wall_now: SystemTime,
917        mono_now: Instant,
918        cooldown: &mut HashMap<PeerId, Instant>,
919        obs: &Arc<FirstAuditObservability>,
920    ) -> Option<(MonetizedPinEvent, FirstAuditInflightSlot)> {
921        let FirstAuditReservation {
922            event, inflight, ..
923        } = reservation;
924        // Authoritative answerability at the REAL send time.
925        if !quote_within_audit_window(event.quote_ts, wall_now) {
926            self.limiter.refund_token();
927            obs.outside_answerability_window
928                .fetch_add(1, Ordering::Relaxed);
929            drop(inflight);
930            return None; // cancelled; nothing stamped, nothing to roll back
931        }
932        // Authoritative shared-cooldown check-and-stamp. Losing this race to a
933        // concurrent gossip audit requeues the reserved event through the SAME
934        // security-aware coalescing: the reserved event is OLDER than any
935        // same-peer successor (`incoming_is_newer = false`), so a higher-count
936        // reserved event still wins over a lower-count successor (the inflated
937        // pin must be audited), while an equal/higher successor is preserved.
938        if !cooldown_allows_audit(cooldown, &event.peer, mono_now) {
939            self.limiter.refund_token();
940            obs.cooldown_deferred_attempts
941                .fetch_add(1, Ordering::Relaxed);
942            drop(inflight);
943            // Account for the requeue outcome (the nomination itself was already
944            // counted at ingress, so `queued` is not re-incremented): a capacity
945            // eviction of a DIFFERENT peer and a suppressed reserved event are
946            // both observable per the ADR funnel.
947            match coalesce_first_audit_event(&mut self.pending, event, false, &mut self.rng) {
948                FirstAuditQueueOutcome::CapacityEvicted { .. } => {
949                    obs.capacity_evicted.fetch_add(1, Ordering::Relaxed);
950                }
951                FirstAuditQueueOutcome::SuppressedLower => {
952                    obs.suppressed_lower.fetch_add(1, Ordering::Relaxed);
953                }
954                FirstAuditQueueOutcome::Queued
955                | FirstAuditQueueOutcome::Coalesced
956                | FirstAuditQueueOutcome::RetainedOnTie => {}
957            }
958            return None;
959        }
960        // Promote: stamp durable suppression, flip the lane, count the launch.
961        self.limiter.promote(event.peer, event.key_count, mono_now);
962        self.first_audited.put(event.pin, ());
963        self.oldest_first_lane = !self.oldest_first_lane;
964        obs.launched.fetch_add(1, Ordering::Relaxed);
965        Some((event, inflight))
966    }
967}
968
969// ---------------------------------------------------------------------------
970// Constants
971// ---------------------------------------------------------------------------
972
973/// Prefix used by saorsa-core's request-response mechanism.
974const RR_PREFIX: &str = "/rr/";
975
976/// Bounded handoff from the P2P broadcast receiver to serial non-audit
977/// replication processing.
978///
979/// The receiver fast-paths digest `AuditChallenge`s immediately and queues
980/// bulk/non-audit messages here. If this fills, the message is **dropped** —
981/// `start_message_handler` must never block on a full queue, because a stalled
982/// receiver laps the P2P broadcast ring and silently loses messages it never
983/// observed. Every serial-lane class has protocol recovery, so a drop costs a
984/// retry rather than the message.
985///
986/// This bounds a message COUNT, but a queued item is an owned decoded message
987/// of up to [`config::MAX_REPLICATION_MESSAGE_SIZE`], so the resident worst
988/// case is 64 × 10 MiB = 640 MiB. That ceiling is acknowledged, not designed
989/// for: the lane carries small requests and challenges alongside
990/// `FreshReplicationOffer`, its one multi-MiB class, so no single count is
991/// right for both. Responses never reach here — `replication_payload_from_event`
992/// filters them out and their requesters correlate them. ADR-0005 decision 12
993/// records the trade and why byte accounting is the correct eventual fix.
994const INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY: usize = 64;
995
996/// Maximum fresh-replication offers processed concurrently, away from the
997/// serial non-audit loop.
998///
999/// Fresh offers can perform an on-chain payment verification and a 4 MiB LMDB
1000/// write. Four workers keep that latency off the responder dispatch path while
1001/// keeping concurrent EVM/storage pressure small and predictable.
1002const FRESH_OFFER_WORKER_LIMIT: usize = 4;
1003
1004/// Maximum fresh offers admitted at once, counting both those running on a
1005/// worker and those queued for one.
1006///
1007/// An admitted offer holds its payload until it completes, so this bounds
1008/// memory rather than latency: at 4 MiB each, sixteen is a 64 MiB ceiling.
1009/// Offers past the bound are refused rather than queued or handled inline —
1010/// handling one on the message loop stalls every other non-audit message behind
1011/// a payment verification and a multi-MiB write. A refusal is not free: the
1012/// sender does not read it, so it resurfaces as a missing key at the delayed
1013/// possession check (5-15 min, ADR-0003) and is charged to this node at audit
1014/// severity. Only neighbor sync (10-20 min) actually refills the gap, so the
1015/// bound is sized to make refusal rare rather than cheap.
1016const FRESH_OFFER_MAX_OUTSTANDING: usize = 16;
1017
1018/// Distinct payment proofs queued for one fresh-offer key.
1019///
1020/// Duplicate offers for a key are routine rather than adversarial: a client PUT
1021/// is confirmed by `CLOSE_GROUP_MAJORITY` nodes, and *each* of them fans the
1022/// chunk out to the close group, so a receiver sees the same key from about that
1023/// many senders. They differ only in their proof — the bytes are provably
1024/// identical, since `fresh_offer_structural_rejection` has confirmed
1025/// `key == BLAKE3(data)` before any of them is queued.
1026///
1027/// Sizing the queue to the number of legitimate senders is what lets a failing
1028/// proof fall through to the next one instead of costing the node the record.
1029///
1030/// This is a **lifetime budget per entry**, not a queue depth: it counts proofs
1031/// admitted, and a proof the handler has popped has spent its slot rather than
1032/// returned it. That distinction is what bounds the work an attacker can buy —
1033/// at most this many on-chain verifications per key, after which the entry
1034/// refuses everyone until it closes. Gating on the queue's instantaneous length
1035/// instead would let a stream of distinct sources refill each popped slot and
1036/// run unbounded sequential verifications while holding one of the four worker
1037/// slots. One attempt per source additionally means a single peer can only ever
1038/// consume one of these.
1039const MAX_FRESH_OFFER_ATTEMPTS_PER_KEY: usize = crate::ant_protocol::CLOSE_GROUP_MAJORITY;
1040
1041/// Fresh-offer slots kept reachable by sources that hold none.
1042///
1043/// The property worth guaranteeing is that one peer cannot *starve* others, not
1044/// that any peer is held to a small quota. Expressing the bound as a reserve
1045/// rather than a quota is what keeps those two apart.
1046const FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES: usize = 4;
1047
1048/// Maximum fresh offers admitted from one source peer.
1049///
1050/// Without a per-source bound, one peer can hold every slot in the global pool
1051/// and every honest offer arriving in that window is refused — and because a
1052/// refusal is later read as absence by the sender's delayed possession check,
1053/// those refusals land as audit-severity trust penalties on the *refuser*.
1054/// That makes an unbounded global pool a targeted eviction primitive.
1055///
1056/// The bound is deliberately far looser than the other responder classes'
1057/// (fetch 2, verification 1, neighbor sync 1), because the traffic pattern is
1058/// the opposite shape. Those are request/response: a requester needs only a
1059/// couple in flight, so a small quota costs it nothing. Fresh offers are a
1060/// one-way bulk fan-out, and in the ordinary case a node's offers come almost
1061/// entirely from ONE peer — whichever node took the client's PUT. A quota sized
1062/// for request/response traffic therefore binds on completely legitimate
1063/// uploads: at 2, an ordinary 48-chunk upload had offers refused (see
1064/// `tests/e2e/fresh_offer_capacity.rs`), every one of them attributed to this
1065/// ceiling and none to the global pool.
1066///
1067/// Sizing it as "the pool minus a reserve" keeps the anti-starvation guarantee
1068/// exact — [`FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES`] slots always remain for a
1069/// peer holding none — while leaving a single legitimate fan-out unthrottled.
1070// The cast is from a compile-time constant difference of two small literals
1071// (16 - 4), so truncation is impossible; deriving the share keeps the reserve
1072// relationship visible in the code rather than only in a test.
1073#[allow(clippy::cast_possible_truncation)]
1074const FRESH_OFFER_MAX_OUTSTANDING_PER_PEER: u32 =
1075    (FRESH_OFFER_MAX_OUTSTANDING - FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES) as u32;
1076
1077/// Maximum paid-list notifications served concurrently.
1078///
1079/// A `PaidNotify` runs the same on-chain proof verification as a fresh offer
1080/// but stores only paid-list metadata, so it needs no chunk-write headroom.
1081/// Two workers keep cross-peer progress without multiplying concurrent EVM
1082/// and DHT lookup pressure.
1083const PAID_NOTIFY_WORKER_LIMIT: usize = 2;
1084
1085/// Maximum paid-list notifications admitted across workers and their waiters.
1086///
1087/// Sized as a **memory** ceiling, not a fairness device, because `PaidNotify`
1088/// is one-way: the protocol defines no response and the sender never retries,
1089/// so a refused notify is information permanently lost to this node until a
1090/// later verification cycle happens to re-derive the key's paid status from a
1091/// paid-list quorum. A tight admission bound therefore does not shed load, it
1092/// discards durable state — which is why the class's real protection is
1093/// [`PAID_NOTIFY_WORKER_LIMIT`], bounding the concurrent EVM and DHT work that
1094/// is actually expensive, rather than this queue depth.
1095///
1096/// A client PUT fans one notify per key out to the whole paid close group, so
1097/// a single upload legitimately arrives as a burst of tens. At the 512 KiB
1098/// `MAX_PAYMENT_PROOF_SIZE_BYTES` worst case, sixty-four outstanding is a
1099/// 32 MiB ceiling — half the fresh-offer admission ceiling, for messages that
1100/// carry no chunk payload.
1101const PAID_NOTIFY_MAX_OUTSTANDING: usize = 64;
1102
1103/// Maximum admitted paid-list notifications from one source peer.
1104///
1105/// A quarter of the pool. One peer legitimately supplies a whole upload's
1106/// worth of notifies, so this must comfortably exceed a typical file's chunk
1107/// count in flight; it exists to stop a single source evicting every other
1108/// peer's durable paid-list evidence, not to ration ordinary traffic.
1109const PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER: u32 = 16;
1110
1111/// Maximum fetch responses served concurrently.
1112///
1113/// Each successful response can upload a 4 MiB chunk. Matching
1114/// [`MAX_CONCURRENT_REPLICATION_SENDS`] keeps fetch serving to about 12 MiB of
1115/// simultaneous chunk data, which avoids saturating typical home upload links.
1116const FETCH_RESPONDER_WORKER_LIMIT: usize = 3;
1117
1118/// Maximum fetch requests admitted across workers and their bounded waiters.
1119///
1120/// Four worker waves absorb short bursts without retaining chunk bytes—the
1121/// request contains only a key—while the dequeue deadline sheds work before a
1122/// sustained flood can keep the node serving requests whose callers timed out.
1123const FETCH_RESPONDER_MAX_OUTSTANDING: usize = FETCH_RESPONDER_WORKER_LIMIT * 4;
1124
1125/// Maximum admitted fetch requests from one source peer.
1126///
1127/// Two requests let one peer pipeline useful reads while leaving at least one
1128/// of the three workers available to other peers under a single-source flood.
1129const FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 2;
1130
1131/// Maximum verification batches served concurrently.
1132///
1133/// LMDB point lookups are fast, but a batch can contain 8,192 of them. Two
1134/// workers isolate that synchronous work from message dispatch without turning
1135/// large batches into an I/O fan-out throughput contest.
1136const VERIFICATION_RESPONDER_WORKER_LIMIT: usize = 2;
1137
1138/// Maximum verification batches admitted across workers and bounded waiters.
1139///
1140/// Four worker waves absorb ordinary cross-peer bursts while the dequeue
1141/// deadline prevents queued batches from consuming lookup capacity after their
1142/// requesters have stopped waiting.
1143const VERIFICATION_RESPONDER_MAX_OUTSTANDING: usize = VERIFICATION_RESPONDER_WORKER_LIMIT * 4;
1144
1145/// Maximum admitted verification batches from one source peer.
1146///
1147/// Senders already aggregate a peer's keys into one batch. One outstanding
1148/// batch therefore preserves useful work while reserving the other worker and
1149/// the bounded queue for different peers.
1150const VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1151
1152/// Maximum neighbor-sync requests served concurrently across source peers.
1153///
1154/// Building a response scans local keys and performs DHT lookups, so two
1155/// workers allow cross-peer progress without multiplying that expensive scan
1156/// into broad network and storage contention.
1157const NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT: usize = 2;
1158
1159/// Maximum neighbor-sync requests admitted across workers and bounded waiters.
1160///
1161/// Four worker waves cover ordinary cadence overlap while keeping retained sync
1162/// payloads bounded; expired waiters are shed before any key scan begins.
1163const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING: usize = NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT * 4;
1164
1165/// Maximum admitted neighbor-sync requests from one source peer.
1166///
1167/// Sync history must be updated before repair proofs for the same peer. A
1168/// single slot preserves that ordering while independent peers remain parallel.
1169const NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER: u32 = 1;
1170
1171/// Match an inbound topic against the replication protocol ids, in both the bare
1172/// gossip form and the `/rr/<id>` request-response form.
1173///
1174/// Returns the matched core or [`SUBTREE_AUDIT_PROTOCOL_ID`] id and whether it
1175/// was the RR form. The matched id is carried into the handler so it can enforce
1176/// that subtree messages only arrive on the subtree id.
1177fn match_replication_protocol(topic: &str) -> Option<(&'static str, bool)> {
1178    for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
1179        if topic == id {
1180            return Some((id, false));
1181        }
1182        if let Some(rest) = topic.strip_prefix(RR_PREFIX) {
1183            if rest == id {
1184                return Some((id, true));
1185            }
1186        }
1187    }
1188    None
1189}
1190
1191/// Whether a decoded body belongs on the protocol id it arrived on:
1192/// subtree-audit bodies on [`SUBTREE_AUDIT_PROTOCOL_ID`] and every other body,
1193/// including digest audits, on [`REPLICATION_PROTOCOL_ID`].
1194///
1195/// The receive guard drops any mismatch (a cross-version or misrouted message);
1196/// sharing this one predicate between the guard and its regression test means a
1197/// change to the rule cannot pass the test unnoticed.
1198fn body_matches_protocol(body: &ReplicationMessageBody, protocol: &str) -> bool {
1199    protocol == response_protocol_for(body)
1200}
1201
1202/// The protocol id a body belongs on — the single source of truth for BOTH
1203/// directions: the receive guard ([`body_matches_protocol`]) and the outbound
1204/// response selector in `send_replication_response_checked`.
1205///
1206/// Sharing one function makes the subtree/core isolation symmetric.
1207fn response_protocol_for(body: &ReplicationMessageBody) -> &'static str {
1208    if body.is_subtree_audit() {
1209        SUBTREE_AUDIT_PROTOCOL_ID
1210    } else {
1211        REPLICATION_PROTOCOL_ID
1212    }
1213}
1214
1215fn fresh_offer_payment_context() -> VerificationContext {
1216    VerificationContext::FreshReplication
1217}
1218
1219fn paid_notify_payment_context() -> VerificationContext {
1220    VerificationContext::PaidListAdmission
1221}
1222
1223/// Boxed future type for in-flight fetch tasks.
1224type FetchFuture = Pin<Box<dyn Future<Output = (XorName, Option<FetchOutcome>)> + Send>>;
1225
1226/// Fresh-offer keys currently being handled, each with the proofs still to try.
1227///
1228/// Concurrent duplicates are routine: a client PUT is confirmed by
1229/// `CLOSE_GROUP_MAJORITY` nodes and each of them fans the chunk out, so one key
1230/// commonly arrives from several senders at once. Collapsing them onto one
1231/// handler is what keeps a burst of PUTs from costing a permit, a worker slot,
1232/// and an on-chain verification per copy.
1233///
1234/// What they collapse *onto* is the load-bearing part. Keeping only the key and
1235/// refusing every later offer outright made the first arrival the only arrival:
1236/// if its proof failed, the record was lost even though a valid proof for the
1237/// same bytes was queued behind it, and the resulting absence was charged to
1238/// this node by the delayed possession check. So the entry holds the bytes once
1239/// and queues each sender's proof, and the handler works down that queue. A
1240/// later offer therefore costs a proof, not a payload — sound only because
1241/// `fresh_offer_structural_rejection` has confirmed `key == BLAKE3(data)` for
1242/// every one of them before it is queued, which is what makes their bytes
1243/// provably identical.
1244///
1245/// Entries are exact keys rather than hash shards. A node only receives offers
1246/// for keys it is close to, so the accepted key set clusters tightly around its
1247/// own ID — any index derived from the key would land nearly every offer on one
1248/// shard and serialize unrelated keys behind each other. Exact keys keep them
1249/// independent, and the map stays bounded by [`FRESH_OFFER_MAX_OUTSTANDING`],
1250/// each entry by [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`].
1251///
1252/// The critical section is a map insert, pop, or remove and is never held across
1253/// an await, so this is a blocking mutex rather than an async one.
1254type FreshOfferInFlight = Arc<Mutex<HashMap<XorName, FreshOfferEntry>>>;
1255
1256/// One sender's unverified claim to have paid for a key already in flight.
1257///
1258/// Carries no payload: the bytes live once in [`FreshOfferEntryGuard`], and the
1259/// content-address check ran before this attempt was queued.
1260struct FreshOfferAttempt {
1261    source: PeerId,
1262    proof_of_payment: Vec<u8>,
1263    request_id: u64,
1264    rr_message_id: Option<String>,
1265}
1266
1267/// Proofs still to try for one in-flight key, and who supplied them.
1268///
1269/// Deliberately holds neither the bytes nor an arrival time: both belong to the
1270/// handler that owns the key, and live once in [`FreshOfferEntryGuard`].
1271struct FreshOfferEntry {
1272    /// Untried proofs in arrival order. The handler holds the current one.
1273    pending: VecDeque<FreshOfferAttempt>,
1274    /// Sources already represented, so one peer cannot fill the queue alone.
1275    sources: HashSet<PeerId>,
1276    /// Proofs admitted over this entry's whole life, **never decremented**.
1277    ///
1278    /// The budget has to be spent by admissions rather than held by the queue.
1279    /// The handler pops a proof before verifying it, so gating on
1280    /// `pending.len()` would let a fresh source refill the slot that pop just
1281    /// freed, and a stream of distinct sources could then run unbounded
1282    /// sequential payment verifications while holding one of only four worker
1283    /// slots. Counting admissions makes the cap a lifetime budget instead.
1284    admitted: usize,
1285}
1286
1287/// How an arriving fresh offer joined the work already in flight for its key.
1288enum FreshOfferAdmission {
1289    /// Opened the entry. This offer's handler owns the key and drives every
1290    /// queued proof, including proofs that arrive later.
1291    Opened(Box<FreshOfferEntryGuard>),
1292    /// Merged into an entry another offer opened; its handler reaches this proof
1293    /// if the ones ahead of it fail.
1294    Joined,
1295    /// The entry already holds [`MAX_FRESH_OFFER_ATTEMPTS_PER_KEY`] proofs.
1296    Full,
1297    /// This source already has a proof queued for this key.
1298    DuplicateSource,
1299}
1300
1301// Gated on `logging` like `SerialQueueDropReason::as_str`: the only caller is a
1302// `debug!`, which compiles to nothing without the feature.
1303#[cfg(feature = "logging")]
1304impl FreshOfferAdmission {
1305    /// Why the offer added nothing to the work already queued for its key.
1306    ///
1307    /// Local logging only — the wire reason stays uniform so a probing peer
1308    /// cannot tell a full queue from a repeat of its own proof.
1309    const fn surplus_reason(&self) -> &'static str {
1310        match self {
1311            Self::DuplicateSource => "this source already has a proof queued",
1312            Self::Full => "the key already holds its full complement of proofs",
1313            Self::Opened(_) | Self::Joined => "not surplus",
1314        }
1315    }
1316}
1317
1318/// RAII ownership of one in-flight fresh-offer key.
1319///
1320/// Clears the entry on drop, so an early return, an error, or a panic cannot
1321/// strand a key as permanently in flight. Also owns the single copy of the
1322/// offered bytes that every queued proof is tried against.
1323struct FreshOfferEntryGuard {
1324    in_flight: FreshOfferInFlight,
1325    key: XorName,
1326    /// The bytes every attempt for this key shares, held exactly once.
1327    data: Vec<u8>,
1328    /// Arrival of the offer that opened the entry.
1329    received_at: Instant,
1330    /// Cleared once the entry has been removed, so `drop` cannot delete an entry
1331    /// a *later* offer has since opened for the same key.
1332    holds_entry: bool,
1333}
1334
1335impl FreshOfferEntryGuard {
1336    /// Open an entry for this offer's key, or queue its proof behind the entry
1337    /// already open.
1338    ///
1339    /// Takes the offer by value: on `Opened` its bytes move into the guard, and
1340    /// on every other outcome they are dropped here rather than held for the
1341    /// lifetime of the entry.
1342    fn admit(
1343        in_flight: &FreshOfferInFlight,
1344        offer: protocol::FreshReplicationOffer,
1345        source: PeerId,
1346        request_id: u64,
1347        rr_message_id: Option<String>,
1348        received_at: Instant,
1349    ) -> FreshOfferAdmission {
1350        let key = offer.key;
1351        let attempt = FreshOfferAttempt {
1352            source,
1353            proof_of_payment: offer.proof_of_payment,
1354            request_id,
1355            rr_message_id,
1356        };
1357
1358        let mut in_flight_map = in_flight.lock();
1359        if let Some(entry) = in_flight_map.get_mut(&key) {
1360            if entry.sources.contains(&source) {
1361                return FreshOfferAdmission::DuplicateSource;
1362            }
1363            // Lifetime budget, not queue depth: a proof the handler has already
1364            // popped has spent its slot, not returned it.
1365            if entry.admitted >= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
1366                return FreshOfferAdmission::Full;
1367            }
1368            entry.admitted = entry.admitted.saturating_add(1);
1369            entry.sources.insert(source);
1370            entry.pending.push_back(attempt);
1371            return FreshOfferAdmission::Joined;
1372        }
1373
1374        let mut sources = HashSet::new();
1375        sources.insert(source);
1376        let mut pending = VecDeque::new();
1377        pending.push_back(attempt);
1378        in_flight_map.insert(
1379            key,
1380            FreshOfferEntry {
1381                pending,
1382                sources,
1383                admitted: 1,
1384            },
1385        );
1386        drop(in_flight_map);
1387        FreshOfferAdmission::Opened(Box::new(Self {
1388            in_flight: Arc::clone(in_flight),
1389            key,
1390            data: offer.data,
1391            received_at,
1392            holds_entry: true,
1393        }))
1394    }
1395
1396    /// The bytes every proof for this key is tried against.
1397    fn data(&self) -> &[u8] {
1398        &self.data
1399    }
1400
1401    /// When the first offer for this key arrived.
1402    fn received_at(&self) -> Instant {
1403        self.received_at
1404    }
1405
1406    /// Take the next untried proof, releasing the key when none remain.
1407    ///
1408    /// Popping and releasing happen under one lock so a proof arriving exactly
1409    /// as the queue empties is never silently discarded: it either lands in this
1410    /// entry and is returned here, or finds no entry and opens its own.
1411    fn next_attempt(&mut self) -> Option<FreshOfferAttempt> {
1412        let mut in_flight = self.in_flight.lock();
1413        let Some(entry) = in_flight.get_mut(&self.key) else {
1414            self.holds_entry = false;
1415            return None;
1416        };
1417        if let Some(attempt) = entry.pending.pop_front() {
1418            return Some(attempt);
1419        }
1420        in_flight.remove(&self.key);
1421        self.holds_entry = false;
1422        None
1423    }
1424
1425    /// Release the key and return the proofs that were never tried, so their
1426    /// senders can be told the outcome the key reached without them.
1427    fn release(&mut self) -> Vec<FreshOfferAttempt> {
1428        let mut in_flight = self.in_flight.lock();
1429        self.holds_entry = false;
1430        in_flight
1431            .remove(&self.key)
1432            .map(|entry| entry.pending.into_iter().collect())
1433            .unwrap_or_default()
1434    }
1435}
1436
1437impl Drop for FreshOfferEntryGuard {
1438    fn drop(&mut self) {
1439        if self.holds_entry {
1440            self.in_flight.lock().remove(&self.key);
1441        }
1442    }
1443}
1444
1445/// Shared dependencies for one verification worker cycle.
1446struct VerificationCycleContext<'a> {
1447    p2p_node: &'a Arc<P2PNode>,
1448    paid_list: &'a Arc<PaidList>,
1449    storage: &'a Arc<ChunkStore>,
1450    queues: &'a Arc<RwLock<ReplicationQueues>>,
1451    config: &'a ReplicationConfig,
1452    bootstrap_state: &'a Arc<RwLock<BootstrapState>>,
1453    is_bootstrapping: &'a Arc<RwLock<bool>>,
1454    bootstrap_complete_notify: &'a Arc<Notify>,
1455    /// v12 §6 holder-eligibility inputs. The verifier downgrades a
1456    /// peer's Present claim to Unresolved unless they're a credited
1457    /// holder of the key (i.e. they recently passed a commitment-bound
1458    /// audit on it under their currently-credited commitment hash).
1459    last_commitment_by_peer: &'a Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1460    ever_capable_peers: &'a Arc<RwLock<HashSet<PeerId>>>,
1461    recent_provers: &'a Arc<RwLock<RecentProvers>>,
1462}
1463
1464/// Fetch worker polling interval in milliseconds.
1465const FETCH_WORKER_POLL_MS: u64 = 100;
1466
1467/// Verification worker polling interval in milliseconds.
1468const VERIFICATION_WORKER_POLL_MS: u64 = 250;
1469
1470/// Verification cycle duration that is worth surfacing at info level.
1471const VERIFICATION_CYCLE_SLOW_LOG_MS: u128 = 500;
1472
1473/// Standard trust event weight for per-operation success/failure signals.
1474///
1475/// Used for individual replication fetch outcomes, integrity check failures,
1476/// and bootstrap claim abuse. Distinct from `AUDIT_FAILURE_TRUST_WEIGHT` which
1477/// is reserved for confirmed audit failures.
1478const REPLICATION_TRUST_WEIGHT: f64 = 1.0;
1479/// Bound trust updates from one verification cycle. A malicious peer can
1480/// advertise thousands of bad singleton keys at once; a few independent
1481/// contradictions are enough for the trust engine without flooding it.
1482const MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE: usize = 3;
1483
1484/// Bootstrap drain check interval in seconds.
1485const BOOTSTRAP_DRAIN_CHECK_SECS: u64 = 5;
1486
1487/// Grace period `shutdown()` waits for each long-lived background task to
1488/// observe the cancellation token and terminate before aborting it.
1489///
1490/// Detached tasks are drained without a timeout because storage-capable work
1491/// may be awaiting a `spawn_blocking` LMDB operation, which continues running
1492/// if its async waiter is dropped.
1493const SHUTDOWN_TASK_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
1494
1495/// How often the responder rebuilds + rotates its storage commitment.
1496///
1497/// Each rebuild scans LMDB to compute leaf hashes; for ~10k keys this is
1498/// sub-100ms (BLAKE3 + tree build). Retention is gossip-anchored, NOT
1499/// rotation-anchored: the responder stays answerable for the current
1500/// commitment plus every root it recently gossiped that is still in-window
1501/// (~2 in steady state), each kept for `GOSSIP_ANSWERABILITY_TTL` (3 h) after
1502/// its last emission (see `commitment_state`). So the rotation cadence does
1503/// not by itself bound answerability — a gossiped commitment stays
1504/// answerable across rotations until its gossip TTL lapses.
1505///
1506/// Default: 1 hour, aligned with the worst-case neighbor-sync cooldown
1507/// (`NEIGHBOR_SYNC_COOLDOWN_SECS = 3600`). Because the gossip TTL (3 h)
1508/// comfortably exceeds the gap between our rotation and the next gossip
1509/// arrival at a remote peer, this prevents the "unknown commitment hash" ->
1510/// Idle audit-skip pattern from being the common case.
1511///
1512/// Why not faster: the v12 pin is bound to a specific point-in-time
1513/// commitment, so rotation isn't security-critical for pin freshness —
1514/// only for keeping the committed key set current as the responder
1515/// writes new keys. 1 hour is plenty for that, and slow enough that
1516/// honest auditors mostly hit `current` or `previous` rather than the
1517/// "rotated past" case.
1518const COMMITMENT_ROTATION_INTERVAL_SECS: u64 = 3600;
1519
1520/// How often the responder retention snapshot is flushed to disk (ADR-0004 A1).
1521/// Short relative to the answerability TTL (3 h) so a gossip-stamp refresh is
1522/// durable well before it could matter to a restart, while the write-on-change
1523/// guard keeps idle nodes from needless disk writes.
1524const RETENTION_PERSIST_INTERVAL_SECS: u64 = 30;
1525
1526/// Cadence of the `replication traffic summary (cumulative)` INFO lines
1527/// (V2-623). A `const` so testnets can drop it to 60s; 300s is the production
1528/// default that keeps log volume negligible.
1529const TRAFFIC_SUMMARY_INTERVAL_SECS: u64 = 300;
1530
1531/// Cadence of the read-only bootstrap state snapshot used to separate drain
1532/// debt from cache and broader connectivity failures in fleet logs.
1533#[cfg(feature = "logging")]
1534const BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS: u64 = 60;
1535
1536/// Maximum tolerated auditor↔responder wall-clock skew for the first-audit
1537/// in-window screen (ADR-0004 A1 guardrail A). The screen accepts a monetized pin
1538/// for first audit only if its SIGNED `quote_ts` lands in
1539/// `[now - (GOSSIP_ANSWERABILITY_TTL - MONETIZED_AUDIT_SKEW_MARGIN), now + MONETIZED_AUDIT_SKEW_MARGIN]`
1540/// — fail-closed on BOTH ends: a quote dated too far in the future (a
1541/// badly-skewed or replayed quote) and one too old (the responder may have aged
1542/// the pin out) are both skipped, so — with grace removed — a stale/skewed quote
1543/// cannot frame an honest node. This assumes bounded clock skew (nodes NTP-synced
1544/// within this margin); a legit first audit fires moments after payment
1545/// (`quote_ts ≈ now`), far from either bound. The gossip-lottery path (which pins
1546/// the responder's OWN freshly-gossiped root) is the clock-skew-immune backstop.
1547/// 30 min dwarfs any realistic honest skew while leaving a wide audit window.
1548const MONETIZED_AUDIT_SKEW_MARGIN: Duration = Duration::from_mins(30);
1549
1550/// ADR-0004 A1 (guardrail A): whether a monetized pin's SIGNED `quote_ts` lands
1551/// inside the answerability window relative to `now`, so first-auditing it cannot
1552/// false-convict once grace is removed. Fail-closed on BOTH ends (see
1553/// [`MONETIZED_AUDIT_SKEW_MARGIN`]): a quote more than the skew margin in the
1554/// future, or older than `GOSSIP_ANSWERABILITY_TTL - margin`, is out of window.
1555/// All comparisons use `duration_since` (no `Duration` overflow).
1556fn quote_within_audit_window(quote_ts: SystemTime, now: SystemTime) -> bool {
1557    let too_future = quote_ts
1558        .duration_since(now)
1559        .is_ok_and(|ahead| ahead > MONETIZED_AUDIT_SKEW_MARGIN);
1560    let audit_cutoff = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
1561    let too_old = now
1562        .duration_since(quote_ts)
1563        .is_ok_and(|age| age >= audit_cutoff);
1564    !(too_future || too_old)
1565}
1566
1567/// Minimum interval between commitment signature verifications for a
1568/// single peer (v10/v12 §2 step 3 + §11 `DoS`).
1569///
1570/// A sybil that bypasses the routing-table gate (e.g. by transient
1571/// bucket pollution) could otherwise force one ML-DSA-65 verify (~1 ms)
1572/// per gossip message. This rate limit caps the verify-per-peer rate
1573/// at 1/min, which is comfortably above the legitimate gossip cadence
1574/// (the 10-20 min neighbor-sync round on each peer).
1575const COMMITMENT_SIG_VERIFY_MIN_INTERVAL: Duration = Duration::from_mins(1);
1576
1577/// Hard cap on the size of `last_commitment_by_peer`.
1578///
1579/// Bounds the per-process memory cost of the auditor's per-peer
1580/// commitment cache. Each entry holds a `StorageCommitment`
1581/// (~5 KiB: 1952-byte pubkey + 3293-byte signature + small fields).
1582/// At 4096 entries the cache is ~20 MiB, which comfortably covers a
1583/// realistic close-group neighborhood. When the cap is hit, one
1584/// arbitrary existing entry is evicted on insert (`HashMap` iteration
1585/// order is unspecified; we do not track insertion order). The
1586/// `PeerRemoved` handler proactively drops entries as the DHT
1587/// detects departures, and `ingest_peer_commitment` only admits
1588/// commitments from peers currently in the routing table — together
1589/// the cap is the third line of defence against sybil/churn flooding.
1590const MAX_LAST_COMMITMENT_BY_PEER: usize = 4096;
1591
1592/// ADR-0004 Amendment 4: admission cap for the first-audit pending queue,
1593/// sized to the launch budget instead of the commitment cache.
1594///
1595/// The token bucket can launch at most one audit per
1596/// [`config::FIRST_AUDIT_LAUNCH_INTERVAL`] (plus the
1597/// [`config::FIRST_AUDIT_BUDGET_BURST`] allowance), and a pending pin stays
1598/// launchable for at most the effective answerability window
1599/// ([`GOSSIP_ANSWERABILITY_TTL`] − [`MONETIZED_AUDIT_SKEW_MARGIN`]). Any
1600/// occupancy beyond `window / interval + burst` is work that cannot launch
1601/// before it expires, so admitting it only builds an aging backlog whose
1602/// telemetry measures the backlog instead of schedulable work.
1603///
1604/// At capacity, admission displaces a uniformly RANDOM incumbent (counted as
1605/// `capacity_evicted`), so under overload `pending` degrades to a budget-sized
1606/// rolling sample in which no arrival order lets an attacker deterministically
1607/// flush a chosen target; a fresh pin always enters the sample with an
1608/// unpredictable chance of near-immediate audit, whereas refusing at the door
1609/// would let a sustained payment flood guarantee that every later pin is never
1610/// admitted. See [`coalesce_first_audit_event`] for the displacement rule and
1611/// ADR-0004 Amendment 4 for the eviction-cost math.
1612///
1613/// Derivation uses the STRICT reserve-time horizon: a launch at quote age `a`
1614/// is usable only if the quote stays answerable through `a` plus the maximum
1615/// launch jitter and send slack, so the last usable refill is the largest
1616/// `k` with `k * interval < cutoff - jitter_max - slack`. The unit test
1617/// simulates the shipped predicate instant-by-instant and must agree.
1618#[allow(clippy::cast_possible_truncation)] // bounded by TTL-secs/interval-secs + burst (~31)
1619const FIRST_AUDIT_PENDING_CAP: usize = {
1620    let strict_horizon_secs = GOSSIP_ANSWERABILITY_TTL
1621        .as_secs()
1622        .saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN.as_secs())
1623        .saturating_sub(config::FIRST_AUDIT_LAUNCH_JITTER_MAX.as_secs())
1624        .saturating_sub(FIRST_AUDIT_SEND_LATENCY_SLACK.as_secs());
1625    // Strictly-inside count: a refill landing exactly ON the horizon is dead
1626    // (`age >= cutoff` rejects), hence the `- 1`. Compile-time division-by-zero
1627    // if the launch interval is ever zeroed: a zero interval makes the budget
1628    // (and this cap) meaningless.
1629    let refills =
1630        strict_horizon_secs.saturating_sub(1) / config::FIRST_AUDIT_LAUNCH_INTERVAL.as_secs();
1631    (refills + config::FIRST_AUDIT_BUDGET_BURST as u64) as usize
1632};
1633
1634// Compile-time guardrails: the cap must be a usable `LruCache` capacity and
1635// strictly tighter than the commitment-cache bound it replaced.
1636const _: () = {
1637    assert!(FIRST_AUDIT_PENDING_CAP >= 1);
1638    assert!(FIRST_AUDIT_PENDING_CAP < MAX_LAST_COMMITMENT_BY_PEER);
1639};
1640
1641/// Cap on the sticky `ever_capable_peers` set. Bounds memory so a
1642/// long-running bootstrap node cannot have the set grow without limit
1643/// from peer-id churn. Sized at 4x `MAX_LAST_COMMITMENT_BY_PEER` so
1644/// the set comfortably outlives normal LRU churn but still caps the
1645/// blast radius of identity-rotation attacks. Once full we refuse new
1646/// inserts (no eviction) — keeps the historic set stable; new v12
1647/// peers above the cap are treated as legacy on rejoin, which matches
1648/// the behaviour before this set existed, not a security regression.
1649const MAX_EVER_CAPABLE_PEERS: usize = 4 * MAX_LAST_COMMITMENT_BY_PEER;
1650
1651// ---------------------------------------------------------------------------
1652// ReplicationEngine
1653// ---------------------------------------------------------------------------
1654
1655/// The replication engine manages all replication background tasks and state.
1656pub struct ReplicationEngine {
1657    /// Replication configuration (shared across spawned tasks).
1658    config: Arc<ReplicationConfig>,
1659    /// P2P networking node.
1660    p2p_node: Arc<P2PNode>,
1661    /// Local chunk storage.
1662    storage: Arc<ChunkStore>,
1663    /// Persistent paid-for-list.
1664    paid_list: Arc<PaidList>,
1665    /// Payment verifier for `PoP` validation.
1666    payment_verifier: Arc<PaymentVerifier>,
1667    /// Replication pipeline queues.
1668    queues: Arc<RwLock<ReplicationQueues>>,
1669    /// Neighbor sync cycle state.
1670    sync_state: Arc<RwLock<NeighborSyncState>>,
1671    /// Per-peer sync history (for `RepairOpportunity`).
1672    ///
1673    /// This map grows with peer churn and is intentionally unbounded: entries
1674    /// are lightweight (`PeerSyncRecord` is two fields) and peer IDs are
1675    /// naturally bounded by the routing table's k-bucket capacity.
1676    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
1677    /// Per-peer cooldown for gossip-triggered subtree audits (ADR-0002).
1678    ///
1679    /// Records when each peer was last audited so a burst of gossiped
1680    /// commitment changes cannot spawn back-to-back audits of the same peer.
1681    /// Bounded by routing-table membership and cleaned on `PeerRemoved`.
1682    audit_on_gossip_cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
1683    /// Gossip-private lottery attempt window (one roll per peer per window,
1684    /// win or lose). Kept separate from `audit_on_gossip_cooldown` so a losing
1685    /// ticket never stamps the shared map and thus never defers a monetized
1686    /// first audit. Bounded like its sibling and cleaned on `PeerRemoved`.
1687    gossip_lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1688    /// Completed local neighbor-sync cycle epoch for proof maturity.
1689    sync_cycle_epoch: Arc<RwLock<u64>>,
1690    /// Per-key repair proof tracking for audit eligibility.
1691    repair_proofs: Arc<RwLock<RepairProofs>>,
1692    /// Bootstrap state tracking.
1693    bootstrap_state: Arc<RwLock<BootstrapState>>,
1694    /// Whether this node is currently bootstrapping.
1695    is_bootstrapping: Arc<RwLock<bool>>,
1696    /// Trigger for early neighbor sync (signalled on topology changes).
1697    sync_trigger: Arc<Notify>,
1698    /// Notified when `is_bootstrapping` transitions from `true` to `false`.
1699    bootstrap_complete_notify: Arc<Notify>,
1700    /// Node identity (for signing storage commitments).
1701    ///
1702    /// Phase 3 of the v12 storage-bound audit design. The responder
1703    /// uses this to sign its periodically-built `StorageCommitment`.
1704    identity: Arc<NodeIdentity>,
1705    /// Responder-side commitment state (two-slot atomic rotation).
1706    ///
1707    /// Periodically rebuilt from the live LMDB key set; gossiped on
1708    /// outbound `NeighborSyncRequest`/`Response`; consulted by the
1709    /// commitment-bound audit handler.
1710    commitment_state: Arc<ResponderCommitmentState>,
1711    /// Path to the persisted responder retention snapshot
1712    /// (`{root_dir}/commitment_retention.bin`): reloaded on startup so an honest
1713    /// node's answerability survives restart (ADR-0004 A1), which is what makes
1714    /// removing audit grace safe (an unanswerable in-window pin is then provable
1715    /// misbehaviour, not an honest crash-restart).
1716    retention_path: PathBuf,
1717    /// Auditor-side per-peer commitment record (last known commitment +
1718    /// sticky `commitment_capable` flag).
1719    ///
1720    /// Populated whenever an inbound gossip carries a verified
1721    /// commitment from the sender. Used by `audit_tick` to snapshot
1722    /// `expected_commitment_hash` into outbound challenges, and by
1723    /// holder-eligibility (§6) to decide whether a peer's `recent_provers`
1724    /// proof should be honoured. The sticky `commitment_capable` flag
1725    /// flips true on first successful ingest and never reverts (§2
1726    /// step 5).
1727    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
1728    /// Sticky set of peer IDs we have EVER seen carrying a v12
1729    /// commitment, independent of whether their commitment bytes are
1730    /// still in `last_commitment_by_peer`. The §6 holder-eligibility
1731    /// closure consults this set to keep treating churned-out
1732    /// previously-v12 peers as v12-capable (rather than degrading them
1733    /// to "legacy" credit-unconditionally) when they re-appear on the
1734    /// network before their next gossip arrives. Bounded growth: even
1735    /// at one million peers seen over the node's lifetime, the set is
1736    /// 32 MB.
1737    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
1738    /// Auditor-side holder-eligibility cache (v12 §6).
1739    ///
1740    /// Recorded on successful commitment-bound audit; read by future
1741    /// quorum / paid-list eligibility checks (phase-3 stretch).
1742    recent_provers: Arc<RwLock<RecentProvers>>,
1743    /// Per-peer last sig-verify attempt timestamp for the §2 step 3 /
1744    /// §11 `DoS` rate limit. Bumped on EVERY verify attempt (success or
1745    /// failure) so a peer we've never successfully verified can't burn
1746    /// CPU on a flood of structurally-plausible-but-invalid gossips.
1747    /// Lives separately from `last_commitment_by_peer` because that
1748    /// map's records only exist after a successful verify.
1749    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
1750    /// Limits concurrent outbound replication sends to prevent bandwidth
1751    /// saturation on home broadband connections.
1752    send_semaphore: Arc<Semaphore>,
1753    /// Bounds how many encoded fresh offers can wait behind `send_semaphore`;
1754    /// see [`MAX_PENDING_FRESH_OFFERS`].
1755    pending_offer_semaphore: Arc<Semaphore>,
1756    /// Fresh offers encoded and handed to their per-peer sends.
1757    fresh_offers_dispatched: Arc<AtomicU64>,
1758    /// Bounds concurrent IN-FLIGHT LIGHT audit-responder tasks (responsible-chunk
1759    /// audits + subtree slice round 2). The heavy subtree round 1 has its own
1760    /// tighter pool ([`SubtreeRound1Limiter`]). Those are spawned off the serial
1761    /// message loop so disk
1762    /// reads don't block replication; the semaphore restores a global
1763    /// backpressure ceiling so the node can't fan out unbounded `get_raw` reads
1764    /// / multi-MiB byte serves.
1765    audit_responder_semaphore: Arc<Semaphore>,
1766    /// Per-source in-flight audit-responder counts, capped at
1767    /// [`MAX_AUDIT_RESPONSES_PER_PEER`]. The GLOBAL semaphore alone is not
1768    /// flood-fair: one peer spamming challenges could occupy every slot and
1769    /// starve honest auditors, whose dropped challenges then convert to
1770    /// audit timeouts against HONEST peers (codex-r2 A). This
1771    /// per-peer cap guarantees no single source can hold more than its share,
1772    /// so a flood self-throttles without denying service to everyone else.
1773    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1774    /// Windowed per-origin capacity and processing-time telemetry for every
1775    /// request sharing the audit responder pool.
1776    audit_responder_metrics: Arc<AuditResponderMetrics>,
1777    /// Shared auditor-side limiter for outbound digest `AuditChallenge`s.
1778    ///
1779    /// Responsible-chunk audits, prune confirmations, and possession checks
1780    /// all use this before sending so local bursts wait instead of breaching
1781    /// the responder's deployed per-source admission cap.
1782    audit_challenge_coordinator: Arc<AuditChallengeCoordinator>,
1783    /// Worker permits for bandwidth-bound fetch responses.
1784    fetch_responder_worker_semaphore: Arc<Semaphore>,
1785    /// Admission permits bounding fetch workers and queued waiters together.
1786    fetch_responder_admission_semaphore: Arc<Semaphore>,
1787    /// Per-source fetch responder counts for flood-fair admission.
1788    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1789    /// Worker permits for lookup-heavy verification batches.
1790    verification_responder_worker_semaphore: Arc<Semaphore>,
1791    /// Admission permits bounding verification workers and queued waiters.
1792    verification_responder_admission_semaphore: Arc<Semaphore>,
1793    /// Per-source verification responder counts for flood-fair admission.
1794    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1795    /// Worker permits for expensive inbound neighbor-sync requests.
1796    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
1797    /// Admission permits bounding sync workers and queued waiters together.
1798    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
1799    /// Per-source sync responder counts; capped at one to preserve ordering.
1800    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1801    /// Bounded worker permits for expensive fresh-offer handling.
1802    fresh_offer_worker_semaphore: Arc<Semaphore>,
1803    /// Admission permits bounding offers running on a worker or queued for one.
1804    fresh_offer_admission_semaphore: Arc<Semaphore>,
1805    /// Per-source fresh-offer counts, so one sender cannot hold the whole pool
1806    /// and turn honest senders' refusals into trust penalties on this node.
1807    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1808    /// Keys claimed by an in-flight fresh-offer handler, so concurrent
1809    /// duplicates collapse onto one verification and one write.
1810    fresh_offer_in_flight: FreshOfferInFlight,
1811    /// Bounded worker permits for paid-list notification proof verification.
1812    paid_notify_worker_semaphore: Arc<Semaphore>,
1813    /// Admission permits bounding notifies on a worker or queued for one.
1814    paid_notify_admission_semaphore: Arc<Semaphore>,
1815    /// Per-source paid-notify counts for flood-fair admission.
1816    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
1817    /// Resource controls for the HEAVY subtree-audit round 1: its own
1818    /// tight admission pool (so a burst of full-subtree hashing can't starve the
1819    /// light audits), a per-peer rate cooldown, and single-use round-1 → round-2
1820    /// sessions binding a slice challenge to a matching round 1.
1821    subtree_round1: SubtreeRound1Limiter,
1822    /// Receiver for fresh-write events from the chunk PUT handler.
1823    ///
1824    /// When present, `start()` spawns the fresh-write drainer, which records
1825    /// paid-list evidence for each event immediately and forwards it to the
1826    /// offer dispatcher.
1827    fresh_write_rx: Option<mpsc::UnboundedReceiver<fresh::FreshWriteEvent>>,
1828    /// Pointer replication (ADR-0016), when this node stores pointers.
1829    pointers: Option<Arc<pointer::PointerReplication>>,
1830    /// Receiver for fresh pointer writes, taken by `start()`.
1831    pointer_fresh_rx: Option<mpsc::UnboundedReceiver<pointer::PointerFreshWrite>>,
1832    /// Sender for delayed possession-check events (ADR-0003). Sending a write's
1833    /// fresh offers (`fresh::send_fresh_offers`) pushes its responsible
1834    /// close-group peers here; the possession-check scheduler drains the paired
1835    /// receiver.
1836    possession_check_tx: mpsc::UnboundedSender<possession::PossessionCheckEvent>,
1837    /// Receiver paired with `possession_check_tx`; taken by the scheduler task.
1838    possession_check_rx: Option<mpsc::UnboundedReceiver<possession::PossessionCheckEvent>>,
1839    /// ADR-0004: sender the payment verifier clones to surface monetized pins
1840    /// for a deterministic first audit. The matching receiver is drained by
1841    /// `start_first_audit_drainer`. BOUNDED (Amendment 2): the producer
1842    /// `try_send`s and drops on a full queue, so ingress memory is capped just
1843    /// like launches; a dropped nomination is penalty-free — the peer's
1844    /// gossiped commitments stay lottery-covered and its next settled payment
1845    /// re-nominates the paid pin.
1846    monetized_pin_tx: mpsc::Sender<MonetizedPinEvent>,
1847    /// ADR-0004: receiver half of the monetized-pin channel, taken by
1848    /// `start_first_audit_drainer`.
1849    monetized_pin_rx: Option<mpsc::Receiver<MonetizedPinEvent>>,
1850    /// Counters shared with the first-audit drainer task, so the scheduler's
1851    /// decisions (queued / launched / self-target skipped / outcome) stay
1852    /// observable from the engine after the drainer takes the receiver.
1853    first_audit_observability: Arc<FirstAuditObservability>,
1854    /// Shutdown token.
1855    shutdown: CancellationToken,
1856    /// Background task handles.
1857    task_handles: Vec<JoinHandle<()>>,
1858    /// Tracks detached, short-lived work spawned by background producers.
1859    ///
1860    /// Fresh-offer and bounded responder workers, audit launches, per-fetch
1861    /// tasks, and delayed possession checks may retain storage or P2P state
1862    /// after their producer exits, so shutdown drains them before those
1863    /// resources may be reopened.
1864    detached_task_tracker: TaskTracker,
1865}
1866
1867impl ReplicationEngine {
1868    /// Create a new replication engine.
1869    ///
1870    /// # Errors
1871    ///
1872    /// Returns an error if the `PaidList` LMDB environment cannot be opened
1873    /// or if the configuration fails validation.
1874    #[allow(clippy::too_many_arguments)]
1875    pub async fn new(
1876        config: ReplicationConfig,
1877        p2p_node: Arc<P2PNode>,
1878        storage: Arc<ChunkStore>,
1879        payment_verifier: Arc<PaymentVerifier>,
1880        identity: Arc<NodeIdentity>,
1881        root_dir: &Path,
1882        fresh_write_rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
1883        shutdown: CancellationToken,
1884    ) -> Result<Self> {
1885        config.validate().map_err(Error::Config)?;
1886
1887        let paid_list = Arc::new(
1888            PaidList::new(root_dir)
1889                .await
1890                .map_err(|e| Error::Storage(format!("Failed to open PaidList: {e}")))?,
1891        );
1892
1893        let initial_neighbors = NeighborSyncState::new_cycle(Vec::new());
1894        let config = Arc::new(config);
1895        let (possession_check_tx, possession_check_rx) = mpsc::unbounded_channel();
1896
1897        // ADR-0004: monetized-pin channel (verifier -> first-audit drainer).
1898        // Bounded (Amendment 2): every stage of the first-audit pipeline is
1899        // now capacity-limited — ingress queue here, pending set (LRU), and
1900        // launch rate (token bucket).
1901        let (monetized_pin_tx, monetized_pin_rx) =
1902            mpsc::channel(config::FIRST_AUDIT_INGRESS_CAPACITY);
1903
1904        let engine = Self {
1905            config: Arc::clone(&config),
1906            p2p_node,
1907            storage,
1908            paid_list,
1909            payment_verifier,
1910            queues: Arc::new(RwLock::new(ReplicationQueues::new())),
1911            sync_state: Arc::new(RwLock::new(initial_neighbors)),
1912            sync_history: Arc::new(RwLock::new(HashMap::new())),
1913            audit_on_gossip_cooldown: Arc::new(RwLock::new(HashMap::new())),
1914            gossip_lottery_attempts: Arc::new(RwLock::new(HashMap::new())),
1915            sync_cycle_epoch: Arc::new(RwLock::new(0)),
1916            repair_proofs: Arc::new(RwLock::new(RepairProofs::new())),
1917            bootstrap_state: Arc::new(RwLock::new(BootstrapState::new())),
1918            is_bootstrapping: Arc::new(RwLock::new(true)),
1919            sync_trigger: Arc::new(Notify::new()),
1920            bootstrap_complete_notify: Arc::new(Notify::new()),
1921            identity,
1922            commitment_state: Arc::new(ResponderCommitmentState::new()),
1923            retention_path: root_dir.join("commitment_retention.bin"),
1924            last_commitment_by_peer: Arc::new(RwLock::new(HashMap::new())),
1925            ever_capable_peers: Arc::new(RwLock::new(HashSet::new())),
1926            recent_provers: Arc::new(RwLock::new(RecentProvers::new())),
1927            sig_verify_attempts: Arc::new(RwLock::new(HashMap::new())),
1928            send_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_REPLICATION_SENDS)),
1929            pending_offer_semaphore: Arc::new(Semaphore::new(MAX_PENDING_FRESH_OFFERS)),
1930            fresh_offers_dispatched: Arc::new(AtomicU64::new(0)),
1931            audit_responder_semaphore: Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES)),
1932            audit_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1933            audit_responder_metrics: Arc::new(AuditResponderMetrics::default()),
1934            audit_challenge_coordinator: Arc::new(AuditChallengeCoordinator::new()),
1935            fetch_responder_worker_semaphore: Arc::new(Semaphore::new(
1936                FETCH_RESPONDER_WORKER_LIMIT,
1937            )),
1938            fetch_responder_admission_semaphore: Arc::new(Semaphore::new(
1939                FETCH_RESPONDER_MAX_OUTSTANDING,
1940            )),
1941            fetch_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1942            verification_responder_worker_semaphore: Arc::new(Semaphore::new(
1943                VERIFICATION_RESPONDER_WORKER_LIMIT,
1944            )),
1945            verification_responder_admission_semaphore: Arc::new(Semaphore::new(
1946                VERIFICATION_RESPONDER_MAX_OUTSTANDING,
1947            )),
1948            verification_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1949            neighbor_sync_responder_worker_semaphore: Arc::new(Semaphore::new(
1950                NEIGHBOR_SYNC_RESPONDER_WORKER_LIMIT,
1951            )),
1952            neighbor_sync_responder_admission_semaphore: Arc::new(Semaphore::new(
1953                NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
1954            )),
1955            neighbor_sync_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1956            fresh_offer_worker_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_WORKER_LIMIT)),
1957            fresh_offer_admission_semaphore: Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING)),
1958            fresh_offer_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1959            fresh_offer_in_flight: Arc::new(Mutex::new(HashMap::new())),
1960            paid_notify_worker_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_WORKER_LIMIT)),
1961            paid_notify_admission_semaphore: Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING)),
1962            paid_notify_responder_inflight: Arc::new(RwLock::new(HashMap::new())),
1963            subtree_round1: SubtreeRound1Limiter::new(
1964                config.subtree_round1_responder_cooldown,
1965                config.subtree_round1_max_concurrent,
1966            ),
1967            fresh_write_rx: Some(fresh_write_rx),
1968            pointers: None,
1969            pointer_fresh_rx: None,
1970            possession_check_tx,
1971            possession_check_rx: Some(possession_check_rx),
1972            monetized_pin_tx,
1973            monetized_pin_rx: Some(monetized_pin_rx),
1974            first_audit_observability: Arc::new(FirstAuditObservability::default()),
1975            shutdown,
1976            task_handles: Vec::new(),
1977            detached_task_tracker: TaskTracker::new(),
1978        };
1979        // ADR-0004 A1: reload persisted responder retention BEFORE any task
1980        // spawns, so an honest restarted node is answerable for its pre-restart
1981        // pins from the first audit it serves, and the persist loop never races
1982        // an empty snapshot over the good on-disk file.
1983        load_commitment_retention(&engine.commitment_state, &engine.retention_path).await;
1984        Ok(engine)
1985    }
1986
1987    /// ADR-0004: a sender the payment verifier uses to surface monetized pins
1988    /// (commitments that backed a payment) for a first audit. Cloneable; the
1989    /// engine drains the matching receiver. Bounded: senders must `try_send`
1990    /// and treat a full queue as a benign drop (Amendment 2 best-effort).
1991    #[must_use]
1992    pub fn monetized_pin_sender(&self) -> mpsc::Sender<MonetizedPinEvent> {
1993        self.monetized_pin_tx.clone()
1994    }
1995
1996    /// Get a reference to the `PaidList`.
1997    #[must_use]
1998    pub fn paid_list(&self) -> &Arc<PaidList> {
1999        &self.paid_list
2000    }
2001
2002    /// Get a reference to the responder's commitment state. Used by audit
2003    /// handlers to look up commitments by hash; used by the rotation tick
2004    /// to install fresh ones.
2005    #[must_use]
2006    pub fn commitment_state(&self) -> &Arc<ResponderCommitmentState> {
2007        &self.commitment_state
2008    }
2009
2010    /// Neighbour-sync state, for the storage migration's possession challenges.
2011    #[must_use]
2012    pub fn sync_state(&self) -> &Arc<RwLock<NeighborSyncState>> {
2013        &self.sync_state
2014    }
2015
2016    /// The audit-challenge coordinator, for the storage migration's possession challenges.
2017    #[must_use]
2018    pub fn audit_challenge_coordinator(&self) -> &Arc<AuditChallengeCoordinator> {
2019        &self.audit_challenge_coordinator
2020    }
2021
2022    /// Replication settings, for the storage migration's possession challenges.
2023    #[must_use]
2024    pub fn config(&self) -> &Arc<ReplicationConfig> {
2025        &self.config
2026    }
2027
2028    /// Get a reference to the auditor's last-commitment-by-peer table.
2029    #[must_use]
2030    pub fn last_commitment_by_peer(&self) -> &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>> {
2031        &self.last_commitment_by_peer
2032    }
2033
2034    /// Get a reference to the holder-eligibility cache. Phase-3 stretch:
2035    /// will be read by quorum / paid-list eligibility checks.
2036    #[must_use]
2037    pub fn recent_provers(&self) -> &Arc<RwLock<RecentProvers>> {
2038        &self.recent_provers
2039    }
2040
2041    /// Test-only: rebuild + rotate this node's storage commitment now over its
2042    /// current key set (normally on a 1h timer). Lets a test commit to chunks it
2043    /// just stored without waiting for the rotation cadence.
2044    ///
2045    /// # Errors
2046    ///
2047    /// Propagates any error from reading the local key set or building/signing
2048    /// the commitment.
2049    #[cfg(any(test, feature = "test-utils"))]
2050    pub async fn rebuild_commitment_now(&self) -> Result<()> {
2051        rebuild_and_rotate_commitment(
2052            &self.storage,
2053            self.pointers.as_ref().map(|p| p.store()),
2054            &self.identity,
2055            &self.commitment_state,
2056            &self.p2p_node,
2057            &self.config,
2058        )
2059        .await
2060    }
2061
2062    /// Test-only: directly seed this node's cached commitment for `peer`,
2063    /// simulating "we received `peer`'s gossiped commitment" without depending
2064    /// on neighbor-sync propagation timing. Lets a two-node audit test pin the
2065    /// peer's commitment deterministically.
2066    #[cfg(any(feature = "test-utils", test))]
2067    pub async fn inject_peer_commitment_for_test(
2068        &self,
2069        peer: &PeerId,
2070        commitment: StorageCommitment,
2071    ) {
2072        let now = Instant::now();
2073        self.last_commitment_by_peer
2074            .write()
2075            .await
2076            .insert(*peer, PeerCommitmentRecord::from_verified(commitment, now));
2077        self.ever_capable_peers.write().await.insert(*peer);
2078    }
2079
2080    /// Test-only: isolate a monetized first audit of `peer` from live gossip
2081    /// audits. Suppresses new gossip lottery attempts for the current cooldown
2082    /// window and clears any shared cooldown stamped by an earlier gossip
2083    /// launch. The locks follow the production gossip-audit lock order.
2084    #[cfg(any(test, feature = "test-utils"))]
2085    pub async fn isolate_first_audit_for_test(&self, peer: &PeerId) {
2086        let now = Instant::now();
2087        let mut lottery_attempts = self.gossip_lottery_attempts.write().await;
2088        let mut launched = self.audit_on_gossip_cooldown.write().await;
2089        lottery_attempts.insert(*peer, now);
2090        launched.remove(peer);
2091    }
2092
2093    /// Test-only: run ONE subtree audit against `peer` right now, pinned to the
2094    /// commitment this node has cached for it (from gossip), over the live wire.
2095    /// Returns the audit outcome so tests can assert honest-pass / adversary-fail
2096    /// in a real two-node setting without waiting for the gossip cadence.
2097    ///
2098    /// Returns `AuditTickResult::Idle` if we have no cached commitment for the
2099    /// peer yet (gossip hasn't reached us). Gated to test builds.
2100    #[cfg(any(test, feature = "test-utils"))]
2101    pub async fn audit_peer_now(&self, peer: &PeerId) -> audit::AuditTickResult {
2102        let target = {
2103            let map = self.last_commitment_by_peer.read().await;
2104            map.get(peer)
2105                .and_then(PeerCommitmentRecord::last_commitment)
2106                .and_then(|c| commitment_hash(c).map(|h| (h, c.key_count)))
2107        };
2108        let Some((pin, key_count)) = target else {
2109            return audit::AuditTickResult::Idle;
2110        };
2111        let credit = storage_commitment_audit::AuditCredit {
2112            recent_provers: &self.recent_provers,
2113        };
2114        storage_commitment_audit::run_subtree_audit(
2115            &self.p2p_node,
2116            &self.config,
2117            peer,
2118            pin,
2119            key_count,
2120            Some(&credit),
2121        )
2122        .await
2123    }
2124
2125    /// Test-only: snapshot the first-audit scheduler's counters. Lets e2e
2126    /// tests assert what the live drainer decided for an injected
2127    /// [`MonetizedPinEvent`] (dropped as self-target vs queued and launched).
2128    #[cfg(any(test, feature = "test-utils"))]
2129    #[must_use]
2130    pub fn first_audit_stats(&self) -> FirstAuditStats {
2131        let o = &self.first_audit_observability;
2132        FirstAuditStats {
2133            received: o.received.load(Ordering::Relaxed),
2134            queued: o.queued.load(Ordering::Relaxed),
2135            self_target_skipped: o.self_target_skipped.load(Ordering::Relaxed),
2136            launched: o.launched.load(Ordering::Relaxed),
2137            passed: o.passed.load(Ordering::Relaxed),
2138            timed_out: o.timed_out.load(Ordering::Relaxed),
2139            failed: o.failed.load(Ordering::Relaxed),
2140        }
2141    }
2142
2143    /// Test-only: run the possession check immediately for `key` against
2144    /// `peers`, bypassing the scheduler's randomised 5-15 minute settle delay.
2145    ///
2146    /// Penalises any peer that does not hold `key` at `AuditChallenge`
2147    /// severity (ADR-0003). Lets e2e tests assert the detection+penalty path
2148    /// deterministically without waiting for the scheduled check.
2149    #[cfg(any(test, feature = "test-utils"))]
2150    pub async fn run_possession_check_now(&self, key: XorName, peers: Vec<PeerId>) {
2151        possession::run_possession_check(
2152            key,
2153            peers,
2154            &self.p2p_node,
2155            &self.storage,
2156            &self.config,
2157            &self.sync_state,
2158            &self.audit_challenge_coordinator,
2159            &self.shutdown,
2160        )
2161        .await;
2162    }
2163
2164    /// Test-only: place `key` directly into the fetch queue as though a
2165    /// verification cycle had just promoted it, with `sources` as its
2166    /// verified holders. Returns whether the key was enqueued.
2167    ///
2168    /// Bypasses admission, verification, and the promotion-time
2169    /// responsibility pre-filter, modelling a promotion decision that has
2170    /// since gone stale (topology churn between promotion and download).
2171    /// The only guard left standing is the per-attempt recheck inside
2172    /// `execute_single_fetch` — exactly the gate e2e tests use this seam to
2173    /// exercise.
2174    #[cfg(any(test, feature = "test-utils"))]
2175    pub async fn enqueue_fetch_for_test(&self, key: XorName, sources: Vec<PeerId>) -> bool {
2176        let distance = crate::client::xor_distance(&key, self.p2p_node.peer_id().as_bytes());
2177        self.queues
2178            .write()
2179            .await
2180            .enqueue_fetch(key, distance, sources)
2181    }
2182
2183    /// Test-only: whether `key` is still tracked in any fetch-pipeline stage
2184    /// (pending verification, fetch queue, or in-flight fetch).
2185    #[cfg(any(test, feature = "test-utils"))]
2186    pub async fn fetch_pipeline_contains_for_test(&self, key: &XorName) -> bool {
2187        self.queues.read().await.contains_key(key)
2188    }
2189
2190    /// Test-only: place `key` into pending verification as though `hinter` had
2191    /// just advertised it with a replica hint. Returns whether it was admitted.
2192    ///
2193    /// Enters the pipeline one stage earlier than
2194    /// [`Self::enqueue_fetch_for_test`], so what the verification cycle itself
2195    /// decides about the key is observable.
2196    #[cfg(any(test, feature = "test-utils"))]
2197    pub async fn enqueue_pending_verify_for_test(&self, key: XorName, hinter: PeerId) -> bool {
2198        let now = Instant::now();
2199        let entry = VerificationEntry {
2200            state: VerificationState::PendingVerify,
2201            verified_sources: Vec::new(),
2202            tried_sources: HashSet::new(),
2203            created_at: now,
2204            next_verify_at: now,
2205            hint_sources: HashSet::from([hinter]),
2206            replica_hint_sources: HashSet::from([hinter]),
2207            unresolved_retries: 0,
2208            no_holder_reported: false,
2209        };
2210        self.queues
2211            .write()
2212            .await
2213            .add_pending_verify(key, entry)
2214            .admitted()
2215    }
2216
2217    /// Test-only: how far ahead `key`'s next verification round is scheduled,
2218    /// or `None` when the key is not pending verification.
2219    #[cfg(any(test, feature = "test-utils"))]
2220    pub async fn pending_verify_delay_for_test(&self, key: &XorName) -> Option<Duration> {
2221        self.queues.read().await.get_pending(key).map(|entry| {
2222            entry
2223                .next_verify_at
2224                .saturating_duration_since(Instant::now())
2225        })
2226    }
2227
2228    /// Replicate pointers too (ADR-0016): the records in `store`, and the
2229    /// fresh writes the pointer PUT handler sends on `fresh_writes`.
2230    ///
2231    /// Call before [`Self::start`].
2232    pub fn with_pointers(
2233        &mut self,
2234        store: PointerStore,
2235        fresh_writes: mpsc::UnboundedReceiver<pointer::PointerFreshWrite>,
2236    ) {
2237        self.pointers = Some(Arc::new(pointer::PointerReplication::new(
2238            store,
2239            Arc::clone(&self.storage),
2240            Arc::clone(&self.p2p_node),
2241            Arc::clone(&self.payment_verifier),
2242            Arc::clone(&self.config),
2243            Arc::clone(&self.is_bootstrapping),
2244            Arc::clone(&self.send_semaphore),
2245            self.shutdown.clone(),
2246            self.detached_task_tracker.clone(),
2247        )));
2248        self.pointer_fresh_rx = Some(fresh_writes);
2249    }
2250
2251    /// The pointer replication, when enabled. Tests use it to drive rounds.
2252    #[cfg(any(test, feature = "test-utils"))]
2253    #[must_use]
2254    pub fn pointer_replication(&self) -> Option<&Arc<pointer::PointerReplication>> {
2255        self.pointers.as_ref()
2256    }
2257
2258    /// Test-only: pending-offer permits not currently held by an encoded
2259    /// fresh offer. Equals [`MAX_PENDING_FRESH_OFFERS`] when no fresh
2260    /// replication is in flight, which is how tests prove a burst of writes
2261    /// drained without leaking a permit.
2262    #[cfg(any(test, feature = "test-utils"))]
2263    #[must_use]
2264    pub fn pending_offer_permits_available(&self) -> usize {
2265        self.pending_offer_semaphore.available_permits()
2266    }
2267
2268    /// Test-only: fresh offers encoded and handed to their per-peer sends
2269    /// since the engine was created. A write skipped because its chunk is gone
2270    /// is not counted.
2271    #[cfg(any(test, feature = "test-utils"))]
2272    #[must_use]
2273    pub fn fresh_offers_dispatched(&self) -> u64 {
2274        self.fresh_offers_dispatched.load(Ordering::Relaxed)
2275    }
2276
2277    /// Test-only: take every outbound replication send permit. Until the
2278    /// returned permit is dropped, encoded fresh offers wait behind the send
2279    /// stage, so a test can fill the pending-offer budget deterministically.
2280    /// The send semaphore is never closed, so this returns `Some`.
2281    #[cfg(any(test, feature = "test-utils"))]
2282    pub async fn hold_replication_sends(&self) -> Option<tokio::sync::OwnedSemaphorePermit> {
2283        let all = u32::try_from(MAX_CONCURRENT_REPLICATION_SENDS).ok()?;
2284        Arc::clone(&self.send_semaphore)
2285            .acquire_many_owned(all)
2286            .await
2287            .ok()
2288    }
2289
2290    /// Start all background tasks.
2291    ///
2292    /// `dht_events` must be subscribed **before** `P2PNode::start()` so that
2293    /// the `BootstrapComplete` event emitted during DHT bootstrap is not
2294    /// missed by the bootstrap-sync gate.
2295    pub fn start(&mut self, dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>) {
2296        if !self.task_handles.is_empty() {
2297            error!("ReplicationEngine::start() called while already running — ignoring");
2298            return;
2299        }
2300        info!("Starting replication engine");
2301
2302        self.start_message_handler();
2303        // Takes out of service the rotted chunks that round-1 proofs report.
2304        self.start_corrupt_recheck_worker();
2305        self.start_neighbor_sync_loop();
2306        self.start_self_lookup_loop();
2307        // Audit #2 (responsible-chunk): periodic tick auditing peers for the
2308        // chunks they SHOULD store (responsibility + prior hint).
2309        self.start_audit_loop();
2310        // Audit #1 (storage-commitment) is gossip-triggered in the message
2311        // handler when a peer's commitment is ingested, not on a periodic tick.
2312        self.start_commitment_rotation_loop();
2313        self.start_retention_persist_loop();
2314        self.start_fetch_worker();
2315        self.start_verification_worker();
2316        self.start_bootstrap_sync(dht_events);
2317        self.start_fresh_replication();
2318        self.start_possession_check_scheduler();
2319        if let Some(pointers) = &self.pointers {
2320            self.task_handles.push(pointers.start_verification_loop());
2321            if let Some(writes) = self.pointer_fresh_rx.take() {
2322                self.task_handles.push(pointers.start_fresh_drainer(writes));
2323            }
2324        }
2325        // ADR-0004: deterministic first audit of commitments that backed a
2326        // payment (surfaced by the verifier cross-check).
2327        self.start_first_audit_drainer();
2328        // V2-623: periodic cumulative per-variant traffic accounting.
2329        self.start_traffic_summary_loop();
2330        // V2-884: read-only bootstrap state for cache/drain/connectivity triage.
2331        #[cfg(feature = "logging")]
2332        self.start_bootstrap_state_snapshot_loop();
2333        #[cfg(feature = "logging")]
2334        self.start_audit_responder_summary_loop();
2335
2336        info!(
2337            "Replication engine started with {} background tasks",
2338            self.task_handles.len()
2339        );
2340    }
2341
2342    /// Returns `true` if the node is still in the replication bootstrap phase.
2343    ///
2344    /// During bootstrap, audit challenges return `Bootstrapping` instead of
2345    /// digests, and neighbor sync responses carry `bootstrapping: true`.
2346    pub async fn is_bootstrapping(&self) -> bool {
2347        *self.is_bootstrapping.read().await
2348    }
2349
2350    /// Wait until the replication bootstrap phase completes.
2351    ///
2352    /// Returns immediately if bootstrap has already completed. Useful for
2353    /// readiness probes, health checks, and test harnesses that need the
2354    /// node to be fully operational before proceeding.
2355    ///
2356    /// Returns `true` if bootstrap completed within the timeout, `false`
2357    /// if the timeout elapsed first.
2358    pub async fn wait_for_bootstrap_complete(&self, timeout: Duration) -> bool {
2359        // Register the notification future *before* checking the flag so that
2360        // a transition between the read and the await is not missed.
2361        let notified = self.bootstrap_complete_notify.notified();
2362        tokio::pin!(notified);
2363        notified.as_mut().enable();
2364
2365        if !*self.is_bootstrapping.read().await {
2366            return true;
2367        }
2368
2369        tokio::time::timeout(timeout, notified).await.is_ok()
2370    }
2371
2372    /// Cancel all background tasks and wait for them to terminate.
2373    ///
2374    /// This must be awaited before dropping the engine when the caller needs
2375    /// the `Arc<ChunkStore>` references held by background tasks to be
2376    /// released (e.g. before reopening the same LMDB environment).
2377    ///
2378    /// When this returns, no engine-spawned task still holds
2379    /// `Arc<ChunkStore>` or `Arc<PaidList>`, and no LMDB blocking operation
2380    /// (read or write, on either the chunk store or the paid-list
2381    /// environment) is still running.  Engine tasks race their work against
2382    /// the shutdown token; a dropped future may leave a `spawn_blocking`
2383    /// LMDB transaction running detached, so this method additionally waits
2384    /// for both storage layers to go quiescent before returning.
2385    pub async fn shutdown(&mut self) {
2386        self.shutdown.cancel();
2387        for (i, mut handle) in self.task_handles.drain(..).enumerate() {
2388            match tokio::time::timeout(SHUTDOWN_TASK_DRAIN_TIMEOUT, &mut handle).await {
2389                Ok(Ok(())) => {}
2390                Ok(Err(e)) if e.is_cancelled() => {}
2391                Ok(Err(e)) => warn!("Replication task {i} panicked during shutdown: {e}"),
2392                Err(_) => {
2393                    warn!(
2394                        "Replication task {i} did not stop within {}s, aborting",
2395                        SHUTDOWN_TASK_DRAIN_TIMEOUT.as_secs()
2396                    );
2397                    handle.abort();
2398                    // `abort` only requests cancellation. Await the handle so
2399                    // synchronous sections finish and the task drops every
2400                    // storage/P2P clone before we claim producer quiescence.
2401                    match handle.await {
2402                        Ok(()) => {}
2403                        Err(e) if e.is_cancelled() => {}
2404                        Err(e) => warn!("Replication task {i} panicked after abort: {e}"),
2405                    }
2406                }
2407            }
2408        }
2409
2410        // Close the responder worker pools. Detached tasks still queued for a
2411        // worker take the `Err` arm of `acquire_owned()` and exit immediately
2412        // rather than waiting for a slot that will never free up — without
2413        // this, work admitted just before shutdown would queue behind the last
2414        // in-flight batch and hold the drain below open for its full duration.
2415        self.fresh_offer_worker_semaphore.close();
2416        self.paid_notify_worker_semaphore.close();
2417        self.fetch_responder_worker_semaphore.close();
2418        self.verification_responder_worker_semaphore.close();
2419        self.neighbor_sync_responder_worker_semaphore.close();
2420
2421        // All producers have stopped, so close and drain their detached work.
2422        // A started storage operation must run to completion: dropping an async
2423        // waiter does not cancel `spawn_blocking`, and would let shutdown return
2424        // while an LMDB transaction still owns the environment.
2425        //
2426        // Deliberately unbounded: the LMDB contract requires every worker to
2427        // release its `Arc<ChunkStore>` before the caller may reopen the
2428        // environment, and a timeout here could return with one still held.
2429        // What makes that safe is that every detached task is now guaranteed to
2430        // finish — the pools above are closed, stale work is shed at dequeue,
2431        // and the one genuinely unbounded await (payment verification) races
2432        // `self.shutdown` via `verify_payment_until_shutdown`.
2433        self.detached_task_tracker.close();
2434        self.detached_task_tracker.wait().await;
2435
2436        // Every producer is gone, but a select! racing the shutdown token may
2437        // have dropped a future while it awaited an LMDB `spawn_blocking` op
2438        // (fetch `storage.put`, prune `storage.delete` /
2439        // `paid_list.remove_batch`, verification `paid_list.insert`).  The
2440        // detached blocking closure owns a cloned `Env`; wait for both
2441        // environments to go quiescent — bounded by one in-flight transaction
2442        // per op — so the caller may reopen them.
2443        self.storage.wait_idle().await;
2444        self.paid_list.wait_idle().await;
2445    }
2446
2447    /// Trigger an early neighbor sync round.
2448    ///
2449    /// Useful after topology changes (new nodes joining, network heal after
2450    /// partition) when the caller wants replication to converge faster than
2451    /// the regular 10-20 minute cadence.
2452    pub fn trigger_neighbor_sync(&self) {
2453        self.sync_trigger.notify_one();
2454    }
2455
2456    /// Execute fresh replication for a newly stored record: announce it, then
2457    /// send its offers and schedule the delayed possession check for the
2458    /// responsible close-group peers (ADR-0003), as the PUT path does.
2459    ///
2460    /// Unlike the PUT path, this waits for a pending-offer permit before
2461    /// returning, and it offers the caller's bytes rather than reading them
2462    /// back from storage.
2463    pub async fn replicate_fresh(&self, key: &XorName, data: &[u8], proof_of_payment: &[u8]) {
2464        fresh::announce_paid_write(
2465            key,
2466            proof_of_payment,
2467            &self.paid_list,
2468            &self.p2p_node,
2469            &self.config,
2470        )
2471        .await;
2472        // Never closed, so this cannot fail; the arm keeps the call panic-free.
2473        let Ok(pending_offer) = Arc::clone(&self.pending_offer_semaphore)
2474            .acquire_owned()
2475            .await
2476        else {
2477            return;
2478        };
2479        fresh::send_fresh_offers(
2480            &self.fresh_offer_context(),
2481            key,
2482            data.to_vec(),
2483            proof_of_payment.to_vec(),
2484            pending_offer,
2485        )
2486        .await;
2487    }
2488
2489    /// Handles the offer dispatcher and the direct entry point share.
2490    fn fresh_offer_context(&self) -> fresh::FreshOfferContext {
2491        fresh::FreshOfferContext {
2492            p2p_node: Arc::clone(&self.p2p_node),
2493            config: Arc::clone(&self.config),
2494            send_semaphore: Arc::clone(&self.send_semaphore),
2495            possession_check_tx: self.possession_check_tx.clone(),
2496            dispatched: Arc::clone(&self.fresh_offers_dispatched),
2497        }
2498    }
2499
2500    // =======================================================================
2501    // Background task launchers
2502    // =======================================================================
2503
2504    /// Spawn fresh replication's two stages, joined by an unbounded FIFO of
2505    /// key + proof events: the drainer, which announces every write at arrival
2506    /// rate, and the offer dispatcher, the only permit-gated stage.
2507    fn start_fresh_replication(&mut self) {
2508        let Some(writes) = self.fresh_write_rx.take() else {
2509            return;
2510        };
2511        let (offer_tx, offer_rx) = mpsc::unbounded_channel();
2512        self.start_fresh_write_drainer(writes, offer_tx.clone());
2513        self.start_fresh_offer_dispatcher(offer_rx, offer_tx);
2514    }
2515
2516    /// Spawn a task that drains the fresh-write channel: it announces each
2517    /// newly-stored chunk and hands it to the offer dispatcher.
2518    fn start_fresh_write_drainer(
2519        &mut self,
2520        mut rx: mpsc::UnboundedReceiver<fresh::FreshWriteEvent>,
2521        offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2522    ) {
2523        let p2p = Arc::clone(&self.p2p_node);
2524        let paid_list = Arc::clone(&self.paid_list);
2525        let config = Arc::clone(&self.config);
2526        let shutdown = self.shutdown.clone();
2527
2528        let handle = tokio::spawn(async move {
2529            loop {
2530                let event = tokio::select! {
2531                    () = shutdown.cancelled() => break,
2532                    event = rx.recv() => {
2533                        let Some(event) = event else { break };
2534                        event
2535                    }
2536                };
2537                // Stage one never waits for chunk back-pressure: the paid-list
2538                // entry and PaidNotify are what let peers repair the key later,
2539                // so every queued write gets them at arrival rate.
2540                fresh::announce_paid_write(
2541                    &event.key,
2542                    &event.payment_proof,
2543                    &paid_list,
2544                    &p2p,
2545                    &config,
2546                )
2547                .await;
2548                if offer_tx
2549                    .send(fresh::FreshOfferEvent {
2550                        key: event.key,
2551                        payment_proof: event.payment_proof,
2552                        read_attempts: 0,
2553                    })
2554                    .is_err()
2555                {
2556                    break;
2557                }
2558            }
2559            debug!("Fresh-write drainer shut down");
2560        });
2561        self.task_handles.push(handle);
2562    }
2563
2564    /// Spawn the fresh-offer dispatcher: the only stage of fresh replication
2565    /// that waits for a pending-offer permit.
2566    ///
2567    /// For each forwarded write it acquires a permit, reads the chunk back
2568    /// from storage and dispatches the offers. A missing chunk is skipped; a
2569    /// failed read is retried up to `MAX_FRESH_READ_ATTEMPTS` times, backing
2570    /// off over about a minute with the permit released in between, so a
2571    /// transient I/O fault does not lose the write's replication. The retry
2572    /// waits on its own task, never on the dispatcher.
2573    fn start_fresh_offer_dispatcher(
2574        &mut self,
2575        mut rx: mpsc::UnboundedReceiver<fresh::FreshOfferEvent>,
2576        offer_tx: mpsc::UnboundedSender<fresh::FreshOfferEvent>,
2577    ) {
2578        let storage = Arc::clone(&self.storage);
2579        let pending_offer_semaphore = Arc::clone(&self.pending_offer_semaphore);
2580        let ctx = self.fresh_offer_context();
2581        let shutdown = self.shutdown.clone();
2582        let retries = self.detached_task_tracker.clone();
2583
2584        let handle = tokio::spawn(async move {
2585            loop {
2586                let event = tokio::select! {
2587                    () = shutdown.cancelled() => break,
2588                    event = rx.recv() => {
2589                        let Some(event) = event else { break };
2590                        event
2591                    }
2592                };
2593                // Wait for a pending-offer permit before touching the chunk so a
2594                // send backlog holds queued events, not encoded chunk buffers.
2595                let pending_offer = tokio::select! {
2596                    () = shutdown.cancelled() => break,
2597                    permit = Arc::clone(&pending_offer_semaphore).acquire_owned() => {
2598                        let Ok(permit) = permit else { break };
2599                        permit
2600                    }
2601                };
2602                let key_hex = hex::encode(event.key);
2603                // The same verified read the fetch path serves from. The bytes
2604                // were content-checked when they were stored, but they come
2605                // off disk now, possibly long after, and every receiver
2606                // charges the sender for an offer that does not hash to its
2607                // key. A chunk that fails verification is quarantined by this
2608                // read, so its retry finds it gone and skips it.
2609                let data = match storage.get(&event.key).await {
2610                    Ok(Some(data)) => data,
2611                    Ok(None) => {
2612                        debug!("Chunk {key_hex} no longer stored, skipping fresh replication");
2613                        continue;
2614                    }
2615                    Err(e) => {
2616                        // The permit is released as this iteration ends, well
2617                        // before any retry is due.
2618                        let attempts = event.read_attempts + 1;
2619                        if attempts >= MAX_FRESH_READ_ATTEMPTS {
2620                            warn!(
2621                                "Giving up fresh replication of {key_hex} after {attempts} failed reads: {e}"
2622                            );
2623                            continue;
2624                        }
2625                        // One warning per write: a store-wide fault fails the
2626                        // whole backlog, once per retry.
2627                        if attempts == 1 {
2628                            warn!(
2629                                "Failed to read chunk {key_hex} for fresh replication; will retry: {e}"
2630                            );
2631                        } else {
2632                            debug!(
2633                                "Failed to read chunk {key_hex} for fresh replication (attempt {attempts}): {e}"
2634                            );
2635                        }
2636                        // Wait on a task of its own: a read fault is often
2637                        // shared (exhausted descriptors), and sleeping here
2638                        // would hold every healthy write queued behind this
2639                        // one for the whole delay, once per failed read. The
2640                        // delay grows, so a store-wide fault spends a write's
2641                        // attempts over about a minute rather than seconds.
2642                        let retry_tx = offer_tx.clone();
2643                        let retry_shutdown = shutdown.clone();
2644                        let delay = fresh_read_retry_delay(attempts);
2645                        retries.spawn(async move {
2646                            tokio::select! {
2647                                () = retry_shutdown.cancelled() => {}
2648                                () = tokio::time::sleep(delay) => {
2649                                    let _ = retry_tx.send(fresh::FreshOfferEvent {
2650                                        read_attempts: attempts,
2651                                        ..event
2652                                    });
2653                                }
2654                            }
2655                        });
2656                        continue;
2657                    }
2658                };
2659                fresh::send_fresh_offers(
2660                    &ctx,
2661                    &event.key,
2662                    data,
2663                    event.payment_proof,
2664                    pending_offer,
2665                )
2666                .await;
2667            }
2668            debug!("Fresh-offer dispatcher shut down");
2669        });
2670        self.task_handles.push(handle);
2671    }
2672
2673    /// Spawn the possession-check scheduler (ADR-0003).
2674    ///
2675    /// Drains scheduled possession-check events and, for each, waits a
2676    /// randomised 5-15 minute settle delay before probing every responsible
2677    /// peer for actual possession. A peer that fails to prove possession or does
2678    /// not answer is penalised at `AuditChallenge` severity.
2679    fn start_possession_check_scheduler(&mut self) {
2680        let Some(mut rx) = self.possession_check_rx.take() else {
2681            return;
2682        };
2683        let p2p = Arc::clone(&self.p2p_node);
2684        let storage = Arc::clone(&self.storage);
2685        let config = Arc::clone(&self.config);
2686        let sync_state = Arc::clone(&self.sync_state);
2687        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
2688        let shutdown = self.shutdown.clone();
2689        let detached_task_tracker = self.detached_task_tracker.clone();
2690
2691        let handle = tokio::spawn(async move {
2692            loop {
2693                tokio::select! {
2694                    () = shutdown.cancelled() => break,
2695                    event = rx.recv() => {
2696                        let Some(event) = event else { break };
2697                        // Spawn a per-chunk delayed check so the drain loop
2698                        // keeps pace with the write rate. Each check sleeps the
2699                        // randomised settle delay, then probes every peer.
2700                        let p2p = Arc::clone(&p2p);
2701                        let storage = Arc::clone(&storage);
2702                        let config = Arc::clone(&config);
2703                        let sync_state = Arc::clone(&sync_state);
2704                        let audit_challenge_coordinator = Arc::clone(&audit_challenge_coordinator);
2705                        let shutdown = shutdown.clone();
2706                        let delay_min = config.possession_check_delay_min;
2707                        let delay_max = config.possession_check_delay_max;
2708                        detached_task_tracker.spawn(async move {
2709                            let delay = possession::random_delay(delay_min, delay_max);
2710                            // Race shutdown against the whole settle-then-probe
2711                            // sequence, not just the sleep. Once a check starts it
2712                            // may park on the per-target audit coordinator, which
2713                            // has no deadline of its own: with the settle delay
2714                            // inside the branch BODY the select is already resolved,
2715                            // so those waiters would drain only at the probe timeout
2716                            // (roughly `queued / per-target-limit` probes deep) while
2717                            // `detached_task_tracker.wait()` — deliberately unbounded
2718                            // for the LMDB contract — held shutdown open.
2719                            //
2720                            // Dropping this future mid-probe is safe and is the same
2721                            // shape the neighbor-sync round uses: a parked coordinator
2722                            // acquire releases its counted reference via
2723                            // `ReferenceGuard`, and a dropped LMDB `spawn_blocking` is
2724                            // covered by the storage-quiescence wait in `shutdown`.
2725                            tokio::select! {
2726                                () = shutdown.cancelled() => {}
2727                                () = async {
2728                                    tokio::time::sleep(delay).await;
2729                                    possession::run_possession_check(
2730                                        event.key,
2731                                        event.peers,
2732                                        &p2p,
2733                                        &storage,
2734                                        &config,
2735                                        &sync_state,
2736                                        &audit_challenge_coordinator,
2737                                        &shutdown,
2738                                    )
2739                                    .await;
2740                                } => {}
2741                            }
2742                        });
2743                    }
2744                }
2745            }
2746            debug!("Possession-check scheduler shut down");
2747        });
2748        self.task_handles.push(handle);
2749    }
2750
2751    /// ADR-0004: drain monetized pins surfaced by the verifier cross-check and
2752    /// run a **deterministic first audit** of each — the same `run_subtree_audit`
2753    /// as the gossip path, under the same per-peer cooldown and concurrency
2754    /// caps, but with the probability lottery BYPASSED (the lottery governs
2755    /// re-audits only). Deduped by pin via a bounded set so a pin gets one
2756    /// deterministic first audit; a peer minting fresh pins faster than the
2757    /// cooldown forfeits the older ones' coverage, never the newest's (the
2758    /// channel surfaces newest pins as they are monetized).
2759    #[allow(clippy::too_many_lines)]
2760    fn start_first_audit_drainer(&mut self) {
2761        let Some(mut rx) = self.monetized_pin_rx.take() else {
2762            return;
2763        };
2764        let gossip_audit = GossipAuditTrigger {
2765            p2p_node: Arc::clone(&self.p2p_node),
2766            config: Arc::clone(&self.config),
2767            recent_provers: Arc::clone(&self.recent_provers),
2768            sync_state: Arc::clone(&self.sync_state),
2769            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
2770            detached_task_tracker: self.detached_task_tracker.clone(),
2771            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
2772        };
2773        let shutdown = self.shutdown.clone();
2774        let observability = Arc::clone(&self.first_audit_observability);
2775        let self_peer = *self.p2p_node.peer_id();
2776
2777        let handle = tokio::spawn(async move {
2778            // ADR-0004 Amendment 2 (E'): the drainer-owned first-audit
2779            // scheduler. Payments only NOMINATE pins; the token bucket launches
2780            // them at a fixed per-node rate, and durable suppression is stamped
2781            // only at PROMOTION (after an authoritative post-jitter answerability
2782            // + cooldown check), so a cancelled reservation leaves nothing behind.
2783            let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
2784            // Periodic retry tick so budget/cooldown-deferred pins get retried
2785            // even when no new nomination arrives. `Skip` collapses a backlog.
2786            let mut tick = tokio::time::interval(config::FIRST_AUDIT_RETRY_INTERVAL);
2787            tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2788            let mut last_summary = Instant::now();
2789            loop {
2790                // The reservation's jitter deadline is a wake source: if a
2791                // reservation is outstanding, sleep until it is due; otherwise
2792                // a far-future deadline effectively disables that arm and only
2793                // shutdown/rx/tick wake the loop. Recreated each iteration so a
2794                // newly reserved (earlier) deadline is honoured next turn.
2795                let promotion_due = scheduler
2796                    .reserved_ready_at()
2797                    .unwrap_or_else(first_audit_far_future);
2798                tokio::select! {
2799                    () = shutdown.cancelled() => break,
2800                    event = rx.recv() => match event {
2801                        Some(e) => {
2802                            observability.received.fetch_add(1, Ordering::Relaxed);
2803                            // Pre-overflow reservation opportunity: before an
2804                            // arrival may displace a DIFFERENT peer, let the
2805                            // queue launch — a successful reservation frees the
2806                            // slot without eviction. One reservation can be
2807                            // outstanding at a time, so this consumes at most
2808                            // one slot per jitter window; arrivals beyond it
2809                            // fall through to random displacement (ADR-0004
2810                            // Amendment 4).
2811                            if scheduler.would_displace(&e) {
2812                                open_first_audit_reservation(
2813                                    &mut scheduler,
2814                                    &gossip_audit.cooldown,
2815                                    &observability,
2816                                )
2817                                .await;
2818                            }
2819                            scheduler.enqueue(e, &observability);
2820                            // Drain a bounded burst so a flood cannot starve the
2821                            // launch phase.
2822                            let mut drained = 1usize;
2823                            while drained < config::FIRST_AUDIT_DRAIN_BATCH {
2824                                match rx.try_recv() {
2825                                    Ok(e) => {
2826                                        observability.received.fetch_add(1, Ordering::Relaxed);
2827                                        if scheduler.would_displace(&e) {
2828                                            open_first_audit_reservation(
2829                                                &mut scheduler,
2830                                                &gossip_audit.cooldown,
2831                                                &observability,
2832                                            )
2833                                            .await;
2834                                        }
2835                                        scheduler.enqueue(e, &observability);
2836                                        drained += 1;
2837                                    }
2838                                    Err(_) => break,
2839                                }
2840                            }
2841                        }
2842                        None => break,
2843                    },
2844                    _ = tick.tick() => {}
2845                    () = tokio::time::sleep_until(promotion_due.into()) => {}
2846                }
2847
2848                // 1) Promote a due reservation. Resolved after EVERY wake (not
2849                //    only when the timer arm wins) so a continuously-ready `rx`
2850                //    cannot indefinitely delay a due promotion. The authoritative
2851                //    answerability + cooldown check-and-stamp happens here under
2852                //    the shared cooldown write lock, immediately before the send.
2853                if let Some(reservation) = scheduler.take_due_reservation(Instant::now()) {
2854                    let promoted = {
2855                        let mut cooldown = gossip_audit.cooldown.write().await;
2856                        scheduler.resolve(
2857                            reservation,
2858                            SystemTime::now(),
2859                            Instant::now(),
2860                            &mut cooldown,
2861                            &observability,
2862                        )
2863                    };
2864                    if let Some((event, inflight_slot)) = promoted {
2865                        debug!(
2866                            "First-audit scheduler: audit_trigger=first_monetized outcome=launched peer={} pin={} key_count={} inflight={}",
2867                            event.peer, hex::encode(event.pin), event.key_count,
2868                            observability.inflight.load(Ordering::Relaxed)
2869                        );
2870                        let trigger = gossip_audit.clone();
2871                        let audit_observability = Arc::clone(&observability);
2872                        // Track the launch so `shutdown()`'s detached drain
2873                        // covers it. This task outlives the drainer loop that
2874                        // spawned it — the loop breaks on the shutdown token
2875                        // while the audit is still awaiting its response — so a
2876                        // bare spawn would let an in-flight subtree audit keep
2877                        // running, and keep its `Arc<P2PNode>`, past the point
2878                        // `shutdown()` claims every engine task has stopped.
2879                        let tracker = trigger.detached_task_tracker.clone();
2880                        tracker.spawn(async move {
2881                            // The jitter already elapsed as the reservation's
2882                            // timer; the slot is held for the audit's duration
2883                            // and released on drop (panic-safe).
2884                            let inflight_slot = inflight_slot;
2885                            let started = Instant::now();
2886                            let credit = storage_commitment_audit::AuditCredit {
2887                                recent_provers: &trigger.recent_provers,
2888                            };
2889                            let result = storage_commitment_audit::run_subtree_audit(
2890                                &trigger.p2p_node,
2891                                &trigger.config,
2892                                &event.peer,
2893                                event.pin,
2894                                event.key_count,
2895                                Some(&credit),
2896                            )
2897                            .await;
2898                            let outcome = first_audit_terminal_outcome(&result);
2899                            match outcome {
2900                                FirstAuditTerminalOutcome::Passed => {
2901                                    audit_observability.passed.fetch_add(1, Ordering::Relaxed);
2902                                }
2903                                FirstAuditTerminalOutcome::Timeout => {
2904                                    audit_observability
2905                                        .timed_out
2906                                        .fetch_add(1, Ordering::Relaxed);
2907                                }
2908                                FirstAuditTerminalOutcome::Failed => {
2909                                    audit_observability.failed.fetch_add(1, Ordering::Relaxed);
2910                                }
2911                                FirstAuditTerminalOutcome::BootstrapClaim => {
2912                                    audit_observability
2913                                        .bootstrap_claims
2914                                        .fetch_add(1, Ordering::Relaxed);
2915                                }
2916                                FirstAuditTerminalOutcome::Idle => {
2917                                    audit_observability.idle.fetch_add(1, Ordering::Relaxed);
2918                                }
2919                                FirstAuditTerminalOutcome::InsufficientKeys => {
2920                                    audit_observability
2921                                        .insufficient_keys
2922                                        .fetch_add(1, Ordering::Relaxed);
2923                                }
2924                            }
2925                            drop(inflight_slot);
2926                            debug!(
2927                                "First-audit scheduler: audit_trigger=first_monetized outcome={} peer={} pin={} key_count={} elapsed_ms={} inflight={}",
2928                                outcome.as_str(),
2929                                event.peer, hex::encode(event.pin), event.key_count,
2930                                started.elapsed().as_millis(),
2931                                audit_observability.inflight.load(Ordering::Relaxed)
2932                            );
2933                            handle_subtree_audit_result(
2934                                &result,
2935                                &trigger.p2p_node,
2936                                &trigger.sync_state,
2937                                &trigger.recent_provers,
2938                                &trigger.config,
2939                            )
2940                            .await;
2941                        });
2942                    }
2943                }
2944
2945                // 2) Open the single reservation from the pending queue if none
2946                //    is outstanding (read-only cooldown snapshot; the
2947                //    authoritative stamp is at promotion). Serializing
2948                //    reservations preserves per-launch lane alternation and keeps
2949                //    at most one jitter timer live.
2950                open_first_audit_reservation(
2951                    &mut scheduler,
2952                    &gossip_audit.cooldown,
2953                    &observability,
2954                )
2955                .await;
2956
2957                if last_summary.elapsed() >= config::FIRST_AUDIT_SUMMARY_INTERVAL {
2958                    // Token-independent hygiene: collect entries that aged past
2959                    // the answerability horizon while the budget gate kept the
2960                    // reserve scan from running, so the summary below reports
2961                    // only live work.
2962                    let swept = scheduler.sweep_expired(SystemTime::now(), &observability);
2963                    if swept > 0 {
2964                        debug!(
2965                            "First-audit scheduler: audit_trigger=first_monetized outcome=expired_swept count={swept} pending={}",
2966                            scheduler.pending_len()
2967                        );
2968                    }
2969                    info!(
2970                        "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={}",
2971                        FIRST_AUDIT_INGRESS_DROPPED.load(Ordering::Relaxed),
2972                        observability.received.load(Ordering::Relaxed),
2973                        observability.queued.load(Ordering::Relaxed),
2974                        observability.coalesced.load(Ordering::Relaxed),
2975                        observability.suppressed_lower.load(Ordering::Relaxed),
2976                        observability.duplicates.load(Ordering::Relaxed),
2977                        observability.capacity_evicted.load(Ordering::Relaxed),
2978                        observability.self_target_skipped.load(Ordering::Relaxed),
2979                        observability.cooldown_deferred_attempts.load(Ordering::Relaxed),
2980                        observability.rate_deferred_attempts.load(Ordering::Relaxed),
2981                        observability.window_deduped.load(Ordering::Relaxed),
2982                        observability.launched.load(Ordering::Relaxed),
2983                        observability.passed.load(Ordering::Relaxed),
2984                        observability.timed_out.load(Ordering::Relaxed),
2985                        observability.failed.load(Ordering::Relaxed),
2986                        observability.bootstrap_claims.load(Ordering::Relaxed),
2987                        observability.idle.load(Ordering::Relaxed),
2988                        observability.insufficient_keys.load(Ordering::Relaxed),
2989                        observability.outside_answerability_window.load(Ordering::Relaxed),
2990                        scheduler.pending_len(),
2991                        FIRST_AUDIT_PENDING_CAP,
2992                        u8::from(scheduler.has_reservation()),
2993                        scheduler.oldest_pending_quote_age_ms(SystemTime::now()),
2994                        observability.inflight.load(Ordering::Relaxed),
2995                        scheduler.tokens(),
2996                    );
2997                    last_summary = Instant::now();
2998                }
2999            }
3000            debug!("First-audit drainer shut down");
3001        });
3002        self.task_handles.push(handle);
3003    }
3004
3005    #[allow(clippy::too_many_lines)]
3006    fn start_message_handler(&mut self) {
3007        let mut p2p_events = self.p2p_node.subscribe_events();
3008        let mut dht_events = self.p2p_node.dht_manager().subscribe_events();
3009        let p2p = Arc::clone(&self.p2p_node);
3010        let storage = Arc::clone(&self.storage);
3011        let paid_list = Arc::clone(&self.paid_list);
3012        let payment_verifier = Arc::clone(&self.payment_verifier);
3013        let queues = Arc::clone(&self.queues);
3014        let config = Arc::clone(&self.config);
3015        let shutdown = self.shutdown.clone();
3016        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3017        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3018        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3019        let sync_history = Arc::clone(&self.sync_history);
3020        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3021        let repair_proofs = Arc::clone(&self.repair_proofs);
3022        let sync_trigger = Arc::clone(&self.sync_trigger);
3023        let my_commitment_state = Arc::clone(&self.commitment_state);
3024        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3025        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3026        let recent_provers = Arc::clone(&self.recent_provers);
3027        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3028        let audit_on_gossip_cooldown = Arc::clone(&self.audit_on_gossip_cooldown);
3029        let gossip_lottery_attempts = Arc::clone(&self.gossip_lottery_attempts);
3030        let sync_state = Arc::clone(&self.sync_state);
3031        let audit_responder_semaphore = Arc::clone(&self.audit_responder_semaphore);
3032        let audit_responder_inflight = Arc::clone(&self.audit_responder_inflight);
3033        let audit_responder_metrics = Arc::clone(&self.audit_responder_metrics);
3034        let fetch_responder_worker_semaphore = Arc::clone(&self.fetch_responder_worker_semaphore);
3035        let fetch_responder_admission_semaphore =
3036            Arc::clone(&self.fetch_responder_admission_semaphore);
3037        let fetch_responder_inflight = Arc::clone(&self.fetch_responder_inflight);
3038        let verification_responder_worker_semaphore =
3039            Arc::clone(&self.verification_responder_worker_semaphore);
3040        let verification_responder_admission_semaphore =
3041            Arc::clone(&self.verification_responder_admission_semaphore);
3042        let verification_responder_inflight = Arc::clone(&self.verification_responder_inflight);
3043        let neighbor_sync_responder_worker_semaphore =
3044            Arc::clone(&self.neighbor_sync_responder_worker_semaphore);
3045        let neighbor_sync_responder_admission_semaphore =
3046            Arc::clone(&self.neighbor_sync_responder_admission_semaphore);
3047        let neighbor_sync_responder_inflight = Arc::clone(&self.neighbor_sync_responder_inflight);
3048        let fresh_offer_worker_semaphore = Arc::clone(&self.fresh_offer_worker_semaphore);
3049        let fresh_offer_admission_semaphore = Arc::clone(&self.fresh_offer_admission_semaphore);
3050        let fresh_offer_responder_inflight = Arc::clone(&self.fresh_offer_responder_inflight);
3051        let fresh_offer_in_flight = Arc::clone(&self.fresh_offer_in_flight);
3052        let paid_notify_worker_semaphore = Arc::clone(&self.paid_notify_worker_semaphore);
3053        let paid_notify_admission_semaphore = Arc::clone(&self.paid_notify_admission_semaphore);
3054        let paid_notify_responder_inflight = Arc::clone(&self.paid_notify_responder_inflight);
3055        let detached_task_tracker = self.detached_task_tracker.clone();
3056        let subtree_round1 = self.subtree_round1.clone();
3057
3058        // ADR-0002 gossip-audit trigger: bundled state so an ingested *changed*
3059        // commitment can spawn a probabilistic, cooldown-gated subtree audit.
3060        let gossip_audit = GossipAuditTrigger {
3061            p2p_node: Arc::clone(&p2p),
3062            config: Arc::clone(&config),
3063            recent_provers: Arc::clone(&recent_provers),
3064            sync_state: Arc::clone(&sync_state),
3065            cooldown: Arc::clone(&audit_on_gossip_cooldown),
3066            detached_task_tracker: detached_task_tracker.clone(),
3067            lottery_attempts: Arc::clone(&gossip_lottery_attempts),
3068        };
3069
3070        let handler_context = ReplicationMessageHandlerContext {
3071            p2p_node: Arc::clone(&p2p),
3072            storage,
3073            paid_list,
3074            payment_verifier,
3075            queues,
3076            config: Arc::clone(&config),
3077            is_bootstrapping,
3078            bootstrap_state,
3079            sync_history,
3080            sync_cycle_epoch,
3081            repair_proofs: Arc::clone(&repair_proofs),
3082            last_commitment_by_peer: Arc::clone(&last_commitment_by_peer),
3083            ever_capable_peers,
3084            sig_verify_attempts: Arc::clone(&sig_verify_attempts),
3085            my_commitment_state,
3086            gossip_audit,
3087            audit_responder_semaphore,
3088            audit_responder_inflight,
3089            audit_responder_metrics,
3090            subtree_round1,
3091            fetch_responder_worker_semaphore,
3092            fetch_responder_admission_semaphore,
3093            fetch_responder_inflight,
3094            verification_responder_worker_semaphore,
3095            verification_responder_admission_semaphore,
3096            verification_responder_inflight,
3097            neighbor_sync_responder_worker_semaphore,
3098            neighbor_sync_responder_admission_semaphore,
3099            neighbor_sync_responder_inflight,
3100            fresh_offer_worker_semaphore,
3101            fresh_offer_admission_semaphore,
3102            fresh_offer_responder_inflight,
3103            fresh_offer_in_flight,
3104            paid_notify_worker_semaphore,
3105            paid_notify_admission_semaphore,
3106            paid_notify_responder_inflight,
3107            pointers: self.pointers.clone(),
3108            shutdown: shutdown.clone(),
3109            detached_task_tracker,
3110        };
3111
3112        let (replication_tx, mut replication_rx) =
3113            mpsc::channel::<InboundReplicationMessage>(INBOUND_REPLICATION_SERIAL_QUEUE_CAPACITY);
3114        let serial_context = handler_context.clone();
3115        let serial_shutdown = shutdown.clone();
3116        let serial_handle = tokio::spawn(async move {
3117            loop {
3118                tokio::select! {
3119                    () = serial_shutdown.cancelled() => break,
3120                    inbound = replication_rx.recv() => {
3121                        let Some(inbound) = inbound else { break };
3122                        let source = inbound.source;
3123                        match handle_replication_message(
3124                            &source,
3125                            inbound.msg,
3126                            &serial_context,
3127                            inbound.received_at,
3128                            inbound.rr_message_id.as_deref(),
3129                        )
3130                        .await
3131                        {
3132                            Ok(()) => {}
3133                            Err(e) => {
3134                                debug!("Replication message from {source} error: {e}");
3135                            }
3136                        }
3137                    }
3138                }
3139            }
3140            debug!("Replication non-audit serial handler shut down");
3141        });
3142        self.task_handles.push(serial_handle);
3143
3144        let handle = tokio::spawn(async move {
3145            loop {
3146                tokio::select! {
3147                    () = shutdown.cancelled() => break,
3148                    event = p2p_events.recv() => {
3149                        let event = match event {
3150                            Ok(event) => event,
3151                            Err(error) => match handle_replication_event_recv_error(&error) {
3152                                ControlFlow::Continue(()) => continue,
3153                                ControlFlow::Break(()) => break,
3154                            },
3155                        };
3156                        let Some((source, payload, inbound_protocol, rr_message_id)) =
3157                            replication_payload_from_event(event)
3158                        else {
3159                            continue;
3160                        };
3161                        let received_at = Instant::now();
3162                        let msg = match ReplicationMessage::decode(&payload) {
3163                            Ok(msg) => msg,
3164                            Err(e) => {
3165                                debug!("Replication message from {source} decode error: {e}");
3166                                continue;
3167                            }
3168                        };
3169                        if !body_matches_protocol(&msg.body, inbound_protocol) {
3170                            debug!(
3171                                "Dropping replication body (variant {}) on protocol \
3172                                 {inbound_protocol}: wrong id for its family \
3173                                 (cross-version or misrouted)",
3174                                msg.body.variant_index()
3175                            );
3176                            continue;
3177                        }
3178                        if let Some(class) = audit_responder_class(&msg.body) {
3179                            handler_context
3180                                .audit_responder_metrics
3181                                .record_received(source, class);
3182                        }
3183                        let inbound = InboundReplicationMessage {
3184                            source,
3185                            msg,
3186                            rr_message_id,
3187                            received_at,
3188                        };
3189                        if matches!(
3190                            inbound.msg.body,
3191                            ReplicationMessageBody::AuditChallenge(_)
3192                                | ReplicationMessageBody::SubtreeAuditChallenge(_)
3193                                | ReplicationMessageBody::SubtreeSliceChallenge(_)
3194                        ) {
3195                            let source = inbound.source;
3196                            match handle_replication_message(
3197                                &source,
3198                                inbound.msg,
3199                                &handler_context,
3200                                inbound.received_at,
3201                                inbound.rr_message_id.as_deref(),
3202                            )
3203                            .await
3204                            {
3205                                Ok(()) => {}
3206                                Err(e) => {
3207                                    debug!("Replication message from {source} error: {e}");
3208                                }
3209                            }
3210                            continue;
3211                        }
3212                        if let Err(dropped) = try_enqueue_serial_message(&replication_tx, inbound) {
3213                            if dropped.audit_responder_class.is_some() {
3214                                handler_context
3215                                    .audit_responder_metrics
3216                                    .record_serial_queue_drop(dropped.source);
3217                            }
3218                            // Every serial-lane class has protocol recovery: syncs rerun,
3219                            // fetches retry, verification re-asks, and a dropped fresh
3220                            // offer is refilled by neighbor sync (the possession check
3221                            // penalises the absence but never re-offers). Responses are
3222                            // covered by their requester's deadline/retry path. Never run
3223                            // a bulk handler here: event receipt must remain non-blocking.
3224                            warn!(
3225                                message_class = dropped.message_class,
3226                                source = %dropped.source,
3227                                queue_depth = dropped.queue_depth,
3228                                reason = dropped.reason.as_str(),
3229                                "Replication serial-queue message dropped"
3230                            );
3231                        }
3232                    }
3233                    // Gap 4: Topology churn handling (Section 13).
3234                    //
3235                    // The DHT routing table emits KClosestPeersChanged when the
3236                    // K-closest peer set actually changes, which is the precise
3237                    // signal for triggering neighbor sync. This replaces the
3238                    // previous approach of checking every PeerConnected /
3239                    // PeerDisconnected event against the close group.
3240                    dht_event = dht_events.recv() => {
3241                        let dht_event = match dht_event {
3242                            Ok(event) => event,
3243                            Err(RecvError::Lagged(missed)) => {
3244                                // Under heavy churn the broadcast buffer can overflow
3245                                // and drop routing-table events — the moment
3246                                // convergence matters most. A dropped
3247                                // KClosestPeersChanged means its entrants were never
3248                                // queued and its departures were never pruned, so
3249                                // draining priority_order cannot recover either.
3250                                // Resync from ground truth instead: snapshot the
3251                                // current close-peer set, prune pending peers that
3252                                // left it during the lost window (retain_sync_peers,
3253                                // as the normal topology-change path does), and queue
3254                                // every member. Dedup (queue_priority_peers) and
3255                                // per-peer cooldown (select_next_sync_peer) drop peers
3256                                // already queued or recently synced, so only genuine
3257                                // entrants surface.
3258                                warn!(
3259                                    "Missed {missed} DHT routing events (broadcast lag); resynchronizing close-peer set for neighbor sync"
3260                                );
3261                                let self_id = *p2p.peer_id();
3262                                let neighbors = neighbor_sync::snapshot_close_neighbors(
3263                                    &p2p,
3264                                    &self_id,
3265                                    config.neighbor_sync_scope,
3266                                )
3267                                .await;
3268                                let neighbor_set =
3269                                    neighbors.iter().copied().collect::<HashSet<_>>();
3270                                let (requeued, sync_removals) = {
3271                                    let mut state = sync_state.write().await;
3272                                    let sync_removals =
3273                                        state.retain_sync_peers(&neighbor_set);
3274                                    let requeued = state.queue_priority_peers(neighbors);
3275                                    (requeued, sync_removals)
3276                                };
3277                                if sync_removals > 0 {
3278                                    debug!(
3279                                        "Resync after broadcast lag pruned {sync_removals} departed pending sync entries"
3280                                    );
3281                                }
3282                                if requeued > 0 {
3283                                    debug!(
3284                                        "Resync after broadcast lag queued {requeued} close peers for priority neighbor sync"
3285                                    );
3286                                    sync_trigger.notify_one();
3287                                }
3288                                continue;
3289                            }
3290                            Err(RecvError::Closed) => {
3291                                // A closed broadcast channel never yields again;
3292                                // continuing would spin the select! loop forever.
3293                                warn!(
3294                                    "DHT event stream closed on replication branch; stopping message handler"
3295                                );
3296                                break;
3297                            }
3298                        };
3299                        match dht_event {
3300                            DhtNetworkEvent::KClosestPeersChanged { old, new, .. } => {
3301                                let old_peers = old
3302                                    .iter()
3303                                    .take(config.neighbor_sync_scope)
3304                                    .copied()
3305                                    .collect::<HashSet<_>>();
3306                                let new_scoped = new
3307                                    .iter()
3308                                    .take(config.neighbor_sync_scope)
3309                                    .copied()
3310                                    .collect::<Vec<_>>();
3311                                let new_peers =
3312                                    new_scoped.iter().copied().collect::<HashSet<_>>();
3313                                let entrants = new_scoped
3314                                    .iter()
3315                                    .copied()
3316                                    .filter(|peer| !old_peers.contains(peer))
3317                                    .collect::<Vec<_>>();
3318                                let entrant_count = entrants.len();
3319                                let (priority_insertions, sync_removals) = {
3320                                    let mut state = sync_state.write().await;
3321                                    let sync_removals = state.retain_sync_peers(&new_peers);
3322                                    let priority_insertions = state.queue_priority_peers(entrants);
3323                                    (priority_insertions, sync_removals)
3324                                };
3325                                if priority_insertions > 0 {
3326                                    debug!(
3327                                        "K-closest peers changed, queued {priority_insertions}/{entrant_count} new close peers for priority neighbor sync and pruned {sync_removals} departed pending sync entries"
3328                                    );
3329                                } else {
3330                                    debug!(
3331                                        "K-closest peers changed, no additional close peers queued, pruned {sync_removals} departed pending sync entries, triggering early neighbor sync"
3332                                    );
3333                                }
3334                                sync_trigger.notify_one();
3335                            }
3336                            DhtNetworkEvent::PeerRemoved { peer_id } => {
3337                                sync_state.write().await.remove_peer(&peer_id);
3338                                repair_proofs.write().await.remove_peer(&peer_id);
3339                                if let Some(pointers) = &handler_context.pointers {
3340                                    pointers.forget_peer(&peer_id);
3341                                }
3342                                update_bootstrap_after_peer_removed(
3343                                    &peer_id,
3344                                    &handler_context.bootstrap_state,
3345                                    &handler_context.queues,
3346                                    &handler_context.is_bootstrapping,
3347                                    &bootstrap_complete_notify,
3348                                )
3349                                .await;
3350                                // v12: drop the commitment bytes and the
3351                                // recent-prover credit so a churn / sybil
3352                                // attacker cannot leave behind one
3353                                // StorageCommitment per identity in
3354                                // `last_commitment_by_peer`. Also drop the
3355                                // sig-verify rate-limit timestamp.
3356                                last_commitment_by_peer.write().await.remove(&peer_id);
3357                                recent_provers.write().await.forget_peer(&peer_id);
3358                                sig_verify_attempts.write().await.remove(&peer_id);
3359                                // Same for the gossip-audit cooldown (ADR-0002)
3360                                // and the lottery-attempt window.
3361                                audit_on_gossip_cooldown.write().await.remove(&peer_id);
3362                                gossip_lottery_attempts.write().await.remove(&peer_id);
3363                                // The sticky `commitment_capable` flag is
3364                                // preserved orthogonally via
3365                                // `ever_capable_peers` — even after this
3366                                // removal, a re-joining peer continues to
3367                                // be treated as v12-capable rather than
3368                                // legacy (§3 shield).
3369                            }
3370                            _ => {}
3371                        }
3372                    }
3373                }
3374            }
3375            debug!("Replication message handler shut down");
3376        });
3377        self.task_handles.push(handle);
3378    }
3379
3380    fn start_neighbor_sync_loop(&mut self) {
3381        let pointers = self.pointers.clone();
3382        let p2p = Arc::clone(&self.p2p_node);
3383        let storage = Arc::clone(&self.storage);
3384        let paid_list = Arc::clone(&self.paid_list);
3385        let queues = Arc::clone(&self.queues);
3386        let config = Arc::clone(&self.config);
3387        let shutdown = self.shutdown.clone();
3388        let sync_state = Arc::clone(&self.sync_state);
3389        let sync_history = Arc::clone(&self.sync_history);
3390        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3391        let repair_proofs = Arc::clone(&self.repair_proofs);
3392        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3393        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3394        let sync_trigger = Arc::clone(&self.sync_trigger);
3395        let commitment_state = Arc::clone(&self.commitment_state);
3396        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
3397        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
3398        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
3399        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3400        let detached_task_tracker = self.detached_task_tracker.clone();
3401        // ADR-0002: a peer's commitment also arrives on the sync RESPONSE path
3402        // (we initiated, they piggybacked theirs). Carry a gossip-audit trigger
3403        // here too so a peer that only ever answers — never initiates sync —
3404        // is still audited; otherwise it could fully evade auditing.
3405        let gossip_audit = GossipAuditTrigger {
3406            p2p_node: Arc::clone(&p2p),
3407            config: Arc::clone(&config),
3408            recent_provers: Arc::clone(&self.recent_provers),
3409            sync_state: Arc::clone(&sync_state),
3410            cooldown: Arc::clone(&self.audit_on_gossip_cooldown),
3411            detached_task_tracker,
3412            lottery_attempts: Arc::clone(&self.gossip_lottery_attempts),
3413        };
3414
3415        let handle = tokio::spawn(async move {
3416            loop {
3417                // Park for the periodic tick or an explicit trigger ONLY when no
3418                // priority (topology-change) peers are queued. `sync_trigger` is a
3419                // coalescing `Notify`, so a churn burst that queues many entrants
3420                // produces a single wakeup; parking after draining one batch would
3421                // leave the rest waiting up to a full periodic tick. `priority_order`
3422                // is the durable record of pending work, so drain it back-to-back —
3423                // each round removes the peers it selects (`select_next_sync_peer`),
3424                // so the drain terminates once the queue empties.
3425                if !sync_state.read().await.has_priority_peers() {
3426                    let interval = config.random_neighbor_sync_interval();
3427                    tokio::select! {
3428                        () = shutdown.cancelled() => break,
3429                        () = tokio::time::sleep(interval) => {}
3430                        () = sync_trigger.notified() => {
3431                            debug!("Neighbor sync triggered by topology change");
3432                        }
3433                    }
3434                }
3435                // Wrap the sync round in a select so shutdown cancels
3436                // in-progress network operations rather than waiting for
3437                // the full round to complete.
3438                tokio::select! {
3439                    () = shutdown.cancelled() => break,
3440                    () = run_neighbor_sync_round(
3441                        &p2p,
3442                        &storage,
3443                        &paid_list,
3444                        &queues,
3445                        &config,
3446                        &sync_state,
3447                        &sync_history,
3448                        &sync_cycle_epoch,
3449                        &repair_proofs,
3450                        &is_bootstrapping,
3451                        &bootstrap_state,
3452                        &commitment_state,
3453                        &last_commitment_by_peer,
3454                        &ever_capable_peers,
3455                        &sig_verify_attempts,
3456                        &audit_challenge_coordinator,
3457                        &gossip_audit,
3458                        pointers.as_ref(),
3459                    ) => {}
3460                }
3461            }
3462            debug!("Neighbor sync loop shut down");
3463        });
3464        self.task_handles.push(handle);
3465    }
3466
3467    fn start_self_lookup_loop(&mut self) {
3468        let p2p = Arc::clone(&self.p2p_node);
3469        let config = Arc::clone(&self.config);
3470        let shutdown = self.shutdown.clone();
3471
3472        let handle = tokio::spawn(async move {
3473            loop {
3474                let interval = config.random_self_lookup_interval();
3475                tokio::select! {
3476                    () = shutdown.cancelled() => break,
3477                    () = tokio::time::sleep(interval) => {
3478                        if let Err(e) = p2p.dht_manager().trigger_self_lookup().await {
3479                            debug!("Self-lookup failed: {e}");
3480                        }
3481                    }
3482                }
3483            }
3484            debug!("Self-lookup loop shut down");
3485        });
3486        self.task_handles.push(handle);
3487    }
3488
3489    /// Spawn the one task that takes chunks audits found rotted out of service.
3490    ///
3491    /// One, so that the rechecks hold at most one blocking thread between them however
3492    /// many audits report rot; see [`ChunkStore::run_corrupt_rechecks`]. Tracked with
3493    /// the detached storage work rather than the engine's loops, because shutdown aborts
3494    /// a loop that outlasts its drain timeout and a recheck must not be dropped part-way.
3495    /// The worker itself stops at the shutdown token, between rechecks.
3496    fn start_corrupt_recheck_worker(&self) {
3497        let storage = Arc::clone(&self.storage);
3498        let shutdown = self.shutdown.clone();
3499        self.detached_task_tracker.spawn(async move {
3500            storage.run_corrupt_rechecks(&shutdown).await;
3501            debug!("Corrupt-chunk recheck worker shut down");
3502        });
3503    }
3504
3505    /// Periodic responsible-chunk audit loop (audit #2): every
3506    /// [`ReplicationConfig::random_audit_tick_interval`] (~10-20 min), audit one
3507    /// eligible close peer for the chunks it *should* be storing (by
3508    /// responsibility and prior repair hint), independent of the gossip-triggered
3509    /// storage-commitment audit. Waits for bootstrap to drain, then runs one tick
3510    /// immediately and periodically thereafter.
3511    fn start_audit_loop(&mut self) {
3512        let p2p = Arc::clone(&self.p2p_node);
3513        let storage = Arc::clone(&self.storage);
3514        let config = Arc::clone(&self.config);
3515        let shutdown = self.shutdown.clone();
3516        let sync_history = Arc::clone(&self.sync_history);
3517        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
3518        let repair_proofs = Arc::clone(&self.repair_proofs);
3519        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3520        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3521        let sync_state = Arc::clone(&self.sync_state);
3522        let audit_challenge_coordinator = Arc::clone(&self.audit_challenge_coordinator);
3523
3524        let handle = tokio::spawn(async move {
3525            // Invariant 19: wait for bootstrap to drain before starting audits.
3526            loop {
3527                tokio::select! {
3528                    () = shutdown.cancelled() => return,
3529                    () = tokio::time::sleep(
3530                        std::time::Duration::from_secs(BOOTSTRAP_DRAIN_CHECK_SECS)
3531                    ) => {
3532                        if bootstrap_state.read().await.is_drained() {
3533                            break;
3534                        }
3535                    }
3536                }
3537            }
3538
3539            // Run one audit tick immediately after bootstrap drain.
3540            {
3541                let bootstrapping = *is_bootstrapping.read().await;
3542                let result = {
3543                    let history = sync_history.read().await;
3544                    let current_sync_epoch = *sync_cycle_epoch.read().await;
3545                    audit::audit_tick_with_repair_proofs(
3546                        &p2p,
3547                        &storage,
3548                        &config,
3549                        &history,
3550                        &repair_proofs,
3551                        &audit_challenge_coordinator,
3552                        current_sync_epoch,
3553                        bootstrapping,
3554                    )
3555                    .await
3556                };
3557                handle_audit_result(&result, &p2p, &sync_state, &config).await;
3558            }
3559
3560            // Then run periodically.
3561            loop {
3562                let interval = config.random_audit_tick_interval();
3563                tokio::select! {
3564                    () = shutdown.cancelled() => break,
3565                    () = tokio::time::sleep(interval) => {
3566                        let bootstrapping = *is_bootstrapping.read().await;
3567                        let result = {
3568                            let history = sync_history.read().await;
3569                            let current_sync_epoch = *sync_cycle_epoch.read().await;
3570                            audit::audit_tick_with_repair_proofs(
3571                                &p2p,
3572                                &storage,
3573                                &config,
3574                                &history,
3575                                &repair_proofs,
3576                                &audit_challenge_coordinator,
3577                                current_sync_epoch,
3578                                bootstrapping,
3579                            )
3580                            .await
3581                        };
3582                        handle_audit_result(&result, &p2p, &sync_state, &config).await;
3583                    }
3584                }
3585            }
3586            debug!("Audit loop shut down");
3587        });
3588        self.task_handles.push(handle);
3589    }
3590
3591    /// Periodically rebuild + sign + rotate the responder's storage
3592    /// commitment.
3593    ///
3594    /// Phase 3 of the v12 storage-bound audit. Once per
3595    /// [`COMMITMENT_ROTATION_INTERVAL_SECS`], the responder reads the
3596    /// current LMDB key set, builds a Merkle tree (for content-addressed
3597    /// chunks `bytes_hash == key`, so no chunk re-read is needed), signs
3598    /// the root with the node's `MlDsaSecretKey`, and rotates the result
3599    /// into `commitment_state`. Old `previous` slot is dropped by the
3600    /// rotate (per `ResponderCommitmentState::rotate`).
3601    ///
3602    /// Skips if the key set is empty (no commitment to make) — the
3603    /// auditor side falls back to the legacy plain-digest path for
3604    /// peers that have never gossiped a commitment.
3605    fn start_commitment_rotation_loop(&mut self) {
3606        let storage = Arc::clone(&self.storage);
3607        let identity = Arc::clone(&self.identity);
3608        let commitment_state = Arc::clone(&self.commitment_state);
3609        let shutdown = self.shutdown.clone();
3610        let p2p = Arc::clone(&self.p2p_node);
3611        let config = Arc::clone(&self.config);
3612        let sync_trigger = Arc::clone(&self.sync_trigger);
3613        let recent_provers = Arc::clone(&self.recent_provers);
3614        let pointer_store = self.pointers.as_ref().map(|p| p.store().clone());
3615
3616        let handle = tokio::spawn(async move {
3617            // Build the first commitment immediately on startup so a
3618            // restarted node can answer commitment-bound audits right
3619            // away — otherwise current() stays None for a full rotation
3620            // interval and audits silently fall back to legacy.
3621            //
3622            // After the first build, trigger an immediate neighbor-sync
3623            // round so the new commitment gossips out within seconds.
3624            // Without this, after a restart remote auditors keep pinning
3625            // the pre-restart (rotated-away) hash until their normal
3626            // sync cadence elapses — up to 1 h in the worst case,
3627            // during which time commitment-bound audits hit "unknown
3628            // commitment hash" -> Idle no-ops.
3629            // ML-DSA signatures are randomized so we cannot reproduce
3630            // the pre-restart hash; the only honest path to recovery
3631            // is fast re-gossip.
3632            // ADR-0004 A1: retention was reloaded in `new()` (before any task
3633            // spawned), so this initial rebuild no-ops when the key set is
3634            // unchanged — preserving the reloaded current pin; otherwise the
3635            // reloaded roots stay answerable as retained slots until their gossip
3636            // TTL lapses. Persistence is handled by the retention-persist loop.
3637            if let Err(e) = rebuild_and_rotate_commitment(
3638                &storage,
3639                pointer_store.as_ref(),
3640                &identity,
3641                &commitment_state,
3642                &p2p,
3643                &config,
3644            )
3645            .await
3646            {
3647                warn!("Initial commitment build failed: {e}");
3648            } else {
3649                sync_trigger.notify_one();
3650            }
3651            loop {
3652                tokio::select! {
3653                    () = shutdown.cancelled() => break,
3654                    () = tokio::time::sleep(
3655                        std::time::Duration::from_secs(COMMITMENT_ROTATION_INTERVAL_SECS)
3656                    ) => {
3657                        if let Err(e) = rebuild_and_rotate_commitment(
3658                            &storage,
3659                            pointer_store.as_ref(),
3660                            &identity,
3661                            &commitment_state,
3662                            &p2p,
3663                            &config,
3664                        ).await {
3665                            warn!("Commitment rotation failed: {e}");
3666                        }
3667                        // Piggyback a sweep of expired recent_provers
3668                        // entries on the rotation tick (same cadence,
3669                        // 1 h). is_credited_holder already honours the
3670                        // TTL on read, but the sweep reclaims memory
3671                        // for entries we'll never re-read.
3672                        let dropped = recent_provers.write().await.sweep_expired(
3673                            std::time::Instant::now()
3674                        );
3675                        if dropped > 0 {
3676                            debug!("recent_provers: swept {dropped} expired entries");
3677                        }
3678                    }
3679                }
3680            }
3681            debug!("Commitment rotation loop shut down");
3682        });
3683        self.task_handles.push(handle);
3684    }
3685
3686    /// ADR-0004 A1: periodically flush the responder retention snapshot to disk
3687    /// (write-on-change) so answerability — including gossip-stamp refreshes and
3688    /// rotations — survives a restart. Flushes once immediately, then every
3689    /// `RETENTION_PERSIST_INTERVAL_SECS`, and once more on shutdown.
3690    fn start_retention_persist_loop(&mut self) {
3691        let commitment_state = Arc::clone(&self.commitment_state);
3692        let retention_path = self.retention_path.clone();
3693        let shutdown = self.shutdown.clone();
3694        let handle = tokio::spawn(async move {
3695            let mut last: Option<Vec<u8>> = None;
3696            persist_retention_if_changed(&commitment_state, &retention_path, &mut last).await;
3697            loop {
3698                tokio::select! {
3699                    () = shutdown.cancelled() => {
3700                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3701                            .await;
3702                        break;
3703                    }
3704                    () = tokio::time::sleep(std::time::Duration::from_secs(
3705                        RETENTION_PERSIST_INTERVAL_SECS,
3706                    )) => {
3707                        persist_retention_if_changed(&commitment_state, &retention_path, &mut last)
3708                            .await;
3709                    }
3710                }
3711            }
3712            debug!("Commitment retention persist loop shut down");
3713        });
3714        self.task_handles.push(handle);
3715    }
3716
3717    /// Periodically emit the cumulative replication traffic summaries: the
3718    /// per-variant line (V2-623) and the per-peer top-10 served-bytes line
3719    /// (V2-684). Both read process-global counter tables maintained by the
3720    /// encode/decode and serve choke points in [`protocol`]; needs no engine
3721    /// state.
3722    fn start_traffic_summary_loop(&mut self) {
3723        let shutdown = self.shutdown.clone();
3724        let handle = tokio::spawn(async move {
3725            loop {
3726                tokio::select! {
3727                    () = shutdown.cancelled() => break,
3728                    () = tokio::time::sleep(std::time::Duration::from_secs(
3729                        TRAFFIC_SUMMARY_INTERVAL_SECS,
3730                    )) => {
3731                        protocol::log_traffic_summary();
3732                        protocol::log_served_peers_summary();
3733                        protocol::log_audit_outcome_summary();
3734                        audit_metrics::log_responder_admission_summary();
3735                        // V2-834 Part D: chunk RPC, upgrade and EVM RPC attribution
3736                        // ride the same cadence.
3737                        crate::storage::traffic::log_chunk_rpc_traffic_summary();
3738                        crate::upgrade::traffic::log_upgrade_traffic_summary();
3739                        crate::payment::traffic::log_evm_rpc_summary();
3740                    }
3741                }
3742            }
3743            debug!("Replication traffic summary loop shut down");
3744        });
3745        self.task_handles.push(handle);
3746    }
3747
3748    /// Periodically expose the state that gates bootstrap completion and prune
3749    /// admission. The state counts are copied before reading `is_bootstrapping`
3750    /// so this diagnostic path never nests async locks.
3751    #[cfg(feature = "logging")]
3752    fn start_bootstrap_state_snapshot_loop(&mut self) {
3753        let shutdown = self.shutdown.clone();
3754        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3755        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3756        let started_at = Instant::now();
3757        let handle = tokio::spawn(async move {
3758            loop {
3759                tokio::select! {
3760                    () = shutdown.cancelled() => break,
3761                    () = tokio::time::sleep(Duration::from_secs(
3762                        BOOTSTRAP_STATE_SNAPSHOT_INTERVAL_SECS,
3763                    )) => {
3764                        let (
3765                            drained,
3766                            pending_peer_requests,
3767                            pending_keys,
3768                            capacity_rejected_sources,
3769                        ) = {
3770                            let state = bootstrap_state.read().await;
3771                            (
3772                                state.drained,
3773                                state.pending_peer_requests,
3774                                state.pending_keys.len(),
3775                                state.capacity_rejected_sources.len(),
3776                            )
3777                        };
3778                        let bootstrapping = *is_bootstrapping.read().await;
3779                        let snapshot_state = if drained && !bootstrapping {
3780                            "healthy"
3781                        } else if drained {
3782                            "drained_waiting_for_bootstrap_flag"
3783                        } else {
3784                            "pending"
3785                        };
3786                        info!(
3787                            drained,
3788                            pending_peer_requests,
3789                            pending_keys,
3790                            capacity_rejected_sources,
3791                            is_bootstrapping = bootstrapping,
3792                            snapshot_state,
3793                            uptime_secs = started_at.elapsed().as_secs(),
3794                            "Replication bootstrap state snapshot"
3795                        );
3796                        if drained && !bootstrapping {
3797                            info!(
3798                                "Replication bootstrap diagnostics reached healthy state; stopping periodic snapshots"
3799                            );
3800                            break;
3801                        }
3802                    }
3803                }
3804            }
3805            debug!("Bootstrap state snapshot loop shut down");
3806        });
3807        self.task_handles.push(handle);
3808    }
3809
3810    /// Periodically rank remote peers using the shared audit responder pool and
3811    /// report handler-only versus end-to-end latency. Windowed values make a
3812    /// burst visible even after a long-running node has accumulated traffic.
3813    #[cfg(feature = "logging")]
3814    fn start_audit_responder_summary_loop(&mut self) {
3815        let shutdown = self.shutdown.clone();
3816        let metrics = Arc::clone(&self.audit_responder_metrics);
3817        let semaphore = Arc::clone(&self.audit_responder_semaphore);
3818        let handle = tokio::spawn(async move {
3819            let mut window_started = Instant::now();
3820            loop {
3821                tokio::select! {
3822                    () = shutdown.cancelled() => {
3823                        log_audit_responder_summary(
3824                            &metrics,
3825                            &semaphore,
3826                            window_started.elapsed(),
3827                        );
3828                        break;
3829                    }
3830                    () = tokio::time::sleep(config::AUDIT_RESPONDER_SUMMARY_INTERVAL) => {
3831                        log_audit_responder_summary(
3832                            &metrics,
3833                            &semaphore,
3834                            window_started.elapsed(),
3835                        );
3836                        window_started = Instant::now();
3837                    }
3838                }
3839            }
3840            debug!("Audit responder summary loop shut down");
3841        });
3842        self.task_handles.push(handle);
3843    }
3844
3845    #[allow(clippy::too_many_lines, clippy::option_if_let_else)]
3846    fn start_fetch_worker(&mut self) {
3847        let p2p = Arc::clone(&self.p2p_node);
3848        let storage = Arc::clone(&self.storage);
3849        let queues = Arc::clone(&self.queues);
3850        let config = Arc::clone(&self.config);
3851        let shutdown = self.shutdown.clone();
3852        let bootstrap_state = Arc::clone(&self.bootstrap_state);
3853        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
3854        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
3855        let detached_task_tracker = self.detached_task_tracker.clone();
3856        let concurrency = max_parallel_fetch();
3857
3858        info!("Fetch worker concurrency set to {concurrency} (hardware threads)");
3859
3860        let handle = tokio::spawn(async move {
3861            // Each in-flight future yields (key, Option<FetchOutcome>) so we
3862            // always recover the key — even if the inner task panics.
3863            let mut in_flight = FuturesUnordered::<FetchFuture>::new();
3864
3865            loop {
3866                // Fill up to `concurrency` slots from the queue.
3867                {
3868                    let mut q = queues.write().await;
3869                    while in_flight.len() < concurrency {
3870                        let Some(candidate) = q.dequeue_fetch() else {
3871                            break;
3872                        };
3873                        let fetch_key = candidate.key;
3874                        let Some(&source) = candidate.sources.first() else {
3875                            warn!(
3876                                "Fetch candidate {} has no sources; requeueing for verification",
3877                                hex::encode(fetch_key)
3878                            );
3879                            let _ = q.requeue_candidate_for_verification(
3880                                candidate,
3881                                config.verification_request_timeout,
3882                            );
3883                            continue;
3884                        };
3885                        q.start_dequeued_fetch(candidate, source);
3886
3887                        let p2p = Arc::clone(&p2p);
3888                        let storage = Arc::clone(&storage);
3889                        let config = Arc::clone(&config);
3890                        let token = shutdown.clone();
3891                        let tracker = detached_task_tracker.clone();
3892                        in_flight.push(Box::pin(async move {
3893                            // Tracked so shutdown() still awaits the task if
3894                            // this awaiter is dropped (e.g. the worker is
3895                            // aborted): it holds Arc<ChunkStore> and must
3896                            // not outlive the engine.
3897                            let handle = tracker.spawn(async move {
3898                                // Cancel-aware: abort when the engine shuts down.
3899                                tokio::select! {
3900                                    () = token.cancelled() => FetchOutcome {
3901                                        key: fetch_key,
3902                                        result: FetchResult::SourceFailed,
3903                                    },
3904                                    outcome = execute_single_fetch(
3905                                        p2p, storage, config, fetch_key, source,
3906                                    ) => outcome,
3907                                }
3908                            });
3909                            match handle.await {
3910                                Ok(outcome) => (outcome.key, Some(outcome)),
3911                                Err(e) => {
3912                                    error!(
3913                                        "Fetch task for {} panicked: {e}",
3914                                        hex::encode(fetch_key)
3915                                    );
3916                                    (fetch_key, None)
3917                                }
3918                            }
3919                        }));
3920                    }
3921                } // release queues write lock
3922
3923                if in_flight.is_empty() {
3924                    // No work — wait for new items or shutdown.
3925                    tokio::select! {
3926                        () = shutdown.cancelled() => break,
3927                        () = tokio::time::sleep(
3928                            std::time::Duration::from_millis(FETCH_WORKER_POLL_MS)
3929                        ) => continue,
3930                    }
3931                }
3932
3933                // Wait for the next fetch to complete and process the result.
3934                tokio::select! {
3935                    () = shutdown.cancelled() => break,
3936                    Some((key, maybe_outcome)) = in_flight.next() => {
3937                        let mut q = queues.write().await;
3938                        let terminal = if let Some(outcome) = maybe_outcome {
3939                            match apply_fetch_result(
3940                                &mut q,
3941                                &key,
3942                                &outcome.result,
3943                                config.verification_request_timeout,
3944                            ) {
3945                                FetchFollowUp::Terminal => true,
3946                                FetchFollowUp::RequeuedForVerification => false,
3947                                FetchFollowUp::RetryFrom(next_peer) => {
3948                                    // Spawn a new fetch task for the next source.
3949                                    let p2p = Arc::clone(&p2p);
3950                                    let storage = Arc::clone(&storage);
3951                                    let config = Arc::clone(&config);
3952                                    let token = shutdown.clone();
3953                                    let tracker = detached_task_tracker.clone();
3954                                    let fetch_key = key;
3955                                    in_flight.push(Box::pin(async move {
3956                                        // Tracked for the same reason as the
3957                                        // initial fetch spawn above.
3958                                        let handle = tracker.spawn(async move {
3959                                            tokio::select! {
3960                                                () = token.cancelled() => FetchOutcome {
3961                                                    key: fetch_key,
3962                                                    result: FetchResult::SourceFailed,
3963                                                },
3964                                                outcome = execute_single_fetch(
3965                                                    p2p, storage, config, fetch_key, next_peer,
3966                                                ) => outcome,
3967                                            }
3968                                        });
3969                                        match handle.await {
3970                                            Ok(outcome) => (outcome.key, Some(outcome)),
3971                                            Err(e) => {
3972                                                error!(
3973                                                    "Fetch task for {} panicked: {e}",
3974                                                    hex::encode(fetch_key)
3975                                                );
3976                                                (fetch_key, None)
3977                                            }
3978                                        }
3979                                    }));
3980                                    false
3981                                }
3982                            }
3983                        } else {
3984                            // Task panicked — retry verification when this was
3985                            // a verified repair, otherwise reclaim the slot.
3986                            !q.requeue_fetch_for_verification(
3987                                &key,
3988                                config.verification_request_timeout,
3989                            )
3990                        };
3991
3992                        // Shrink bootstrap pending set on terminal exit.
3993                        if terminal {
3994                            drop(q); // release queues lock before acquiring bootstrap_state
3995                            if !bootstrap_state.read().await.is_drained() {
3996                                bootstrap_state.write().await.remove_key(&key);
3997                                let q = queues.read().await;
3998                                if bootstrap::check_bootstrap_drained(
3999                                    &bootstrap_state,
4000                                    &q,
4001                                )
4002                                .await
4003                                {
4004                                    complete_bootstrap(
4005                                        &is_bootstrapping,
4006                                        &bootstrap_complete_notify,
4007                                    ).await;
4008                                }
4009                            }
4010                        }
4011                    }
4012                }
4013            }
4014
4015            // Cancel and drain remaining in-flight fetches on shutdown.
4016            // The CancellationToken is already cancelled by this point, so
4017            // spawned tasks will see cancellation via their select! branches.
4018            while in_flight.next().await.is_some() {}
4019            debug!("Fetch worker shut down");
4020        });
4021        self.task_handles.push(handle);
4022    }
4023
4024    fn start_verification_worker(&mut self) {
4025        let p2p = Arc::clone(&self.p2p_node);
4026        let storage = Arc::clone(&self.storage);
4027        let queues = Arc::clone(&self.queues);
4028        let paid_list = Arc::clone(&self.paid_list);
4029        let config = Arc::clone(&self.config);
4030        let shutdown = self.shutdown.clone();
4031        let bootstrap_state = Arc::clone(&self.bootstrap_state);
4032        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4033        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4034        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4035        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4036        let recent_provers = Arc::clone(&self.recent_provers);
4037
4038        let handle = tokio::spawn(async move {
4039            loop {
4040                tokio::select! {
4041                    () = shutdown.cancelled() => break,
4042                    () = tokio::time::sleep(
4043                        std::time::Duration::from_millis(VERIFICATION_WORKER_POLL_MS)
4044                    ) => {
4045                        let ctx = VerificationCycleContext {
4046                            p2p_node: &p2p,
4047                            paid_list: &paid_list,
4048                            storage: &storage,
4049                            queues: &queues,
4050                            config: &config,
4051                            bootstrap_state: &bootstrap_state,
4052                            is_bootstrapping: &is_bootstrapping,
4053                            bootstrap_complete_notify: &bootstrap_complete_notify,
4054                            last_commitment_by_peer: &last_commitment_by_peer,
4055                            ever_capable_peers: &ever_capable_peers,
4056                            recent_provers: &recent_provers,
4057                        };
4058                        run_verification_cycle(ctx).await;
4059                    }
4060                }
4061            }
4062            debug!("Verification worker shut down");
4063        });
4064        self.task_handles.push(handle);
4065    }
4066
4067    /// Gap 3: Run a one-shot bootstrap sync on startup.
4068    ///
4069    /// Waits for saorsa-core to emit `DhtNetworkEvent::BootstrapComplete`
4070    /// (indicating the routing table is populated) before snapshotting
4071    /// close neighbors. Falls back after a timeout so bootstrap nodes
4072    /// (which have no peers and therefore never receive the event) still
4073    /// proceed.
4074    ///
4075    /// After the gate, finds close neighbors, syncs with each in
4076    /// round-robin batches, admits returned hints into the verification
4077    /// pipeline, and tracks discovered keys for bootstrap drain detection.
4078    #[allow(clippy::too_many_lines)]
4079    fn start_bootstrap_sync(
4080        &mut self,
4081        dht_events: tokio::sync::broadcast::Receiver<DhtNetworkEvent>,
4082    ) {
4083        let p2p = Arc::clone(&self.p2p_node);
4084        let storage = Arc::clone(&self.storage);
4085        let paid_list = Arc::clone(&self.paid_list);
4086        let queues = Arc::clone(&self.queues);
4087        let config = Arc::clone(&self.config);
4088        let shutdown = self.shutdown.clone();
4089        let is_bootstrapping = Arc::clone(&self.is_bootstrapping);
4090        let bootstrap_state = Arc::clone(&self.bootstrap_state);
4091        let bootstrap_complete_notify = Arc::clone(&self.bootstrap_complete_notify);
4092        let sync_cycle_epoch = Arc::clone(&self.sync_cycle_epoch);
4093        let repair_proofs = Arc::clone(&self.repair_proofs);
4094        let my_commitment_state = Arc::clone(&self.commitment_state);
4095        let last_commitment_by_peer = Arc::clone(&self.last_commitment_by_peer);
4096        let ever_capable_peers = Arc::clone(&self.ever_capable_peers);
4097        let sig_verify_attempts = Arc::clone(&self.sig_verify_attempts);
4098
4099        let handle = tokio::spawn(async move {
4100            // Wait for DHT bootstrap to complete before snapshotting
4101            // neighbors. The routing table is empty until saorsa-core
4102            // finishes its FIND_NODE rounds and bucket refreshes.
4103            let gate = bootstrap::wait_for_bootstrap_complete(
4104                dht_events,
4105                config.bootstrap_complete_timeout_secs,
4106                &shutdown,
4107            )
4108            .await;
4109
4110            if gate == bootstrap::BootstrapGateResult::Shutdown {
4111                return;
4112            }
4113
4114            let self_id = *p2p.peer_id();
4115            let neighbors =
4116                neighbor_sync::snapshot_close_neighbors(&p2p, &self_id, config.neighbor_sync_scope)
4117                    .await;
4118
4119            if neighbors.is_empty() {
4120                info!("Bootstrap sync: no close neighbors found, marking drained");
4121                bootstrap::mark_bootstrap_drained(&bootstrap_state).await;
4122                complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4123                return;
4124            }
4125
4126            let neighbor_count = neighbors.len();
4127            info!("Bootstrap sync: syncing with {neighbor_count} close neighbors");
4128
4129            // Process neighbors in batches of NEIGHBOR_SYNC_PEER_COUNT.
4130            for batch in neighbors.chunks(config.neighbor_sync_peer_count) {
4131                if shutdown.is_cancelled() {
4132                    break;
4133                }
4134
4135                let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
4136                    batch,
4137                    &storage,
4138                    &paid_list,
4139                    &p2p,
4140                    config.close_group_size,
4141                    config.paid_list_close_group_size,
4142                )
4143                .await;
4144
4145                // Keep the batch outstanding until every response has been
4146                // admitted and bootstrap accounting is updated. The verification
4147                // worker uses this counter as a batch barrier, so it cannot race
4148                // the source aggregation below.
4149                bootstrap::increment_pending_requests(&bootstrap_state, batch.len()).await;
4150                let bootstrapping = *is_bootstrapping.read().await;
4151
4152                let sync_futures = batch.iter().map(|peer| {
4153                    let peer = *peer;
4154                    let hints = hints_by_peer.remove(&peer).unwrap_or_default();
4155                    // Atomically snapshot + mark-gossiped for each emitted
4156                    // bootstrap request so we remain answerable for it.
4157                    let commitment = my_commitment_state
4158                        .current_for_gossip()
4159                        .map(|binding| binding.commitment().clone());
4160                    let p2p = &p2p;
4161                    let config = &config;
4162                    async move {
4163                        let outcome = neighbor_sync::sync_with_peer_with_hints(
4164                            &peer,
4165                            p2p,
4166                            config,
4167                            bootstrapping,
4168                            hints,
4169                            commitment,
4170                        )
4171                        .await;
4172                        (peer, outcome)
4173                    }
4174                });
4175                let completed = join_all(sync_futures).await;
4176
4177                // Process response metadata before exposing any of this batch's
4178                // hints to verification.
4179                for (peer, outcome) in &completed {
4180                    if let Some(outcome) = outcome {
4181                        // Ingest the peer's piggybacked commitment from the
4182                        // response (same verification as the request path).
4183                        // Bootstrap is the FIRST gossip we receive from most
4184                        // peers, so this populates last_commitment_by_peer.
4185                        //
4186                        // We intentionally do NOT trigger a gossip-audit here:
4187                        // during bootstrap this node may itself still be
4188                        // bootstrapping (audits are gated on that), and the
4189                        // close-group/RT view is not yet stable. The peer is
4190                        // audited on the first STEADY-STATE neighbor-sync round
4191                        // after bootstrap drains (request + response paths both
4192                        // trigger), which is within one sync cycle — so caching
4193                        // the commitment here is sufficient and there is no
4194                        // coverage gap (ADR-0002).
4195                        ingest_peer_commitment(
4196                            peer,
4197                            outcome.response.commitment.as_ref(),
4198                            &p2p,
4199                            &last_commitment_by_peer,
4200                            &ever_capable_peers,
4201                            &sig_verify_attempts,
4202                        )
4203                        .await; // sig_verify_attempts in scope from line ~1080
4204
4205                        if !outcome.response.bootstrapping {
4206                            record_sent_replica_hints(
4207                                peer,
4208                                &outcome.sent_replica_hints,
4209                                &repair_proofs,
4210                                &sync_cycle_epoch,
4211                            )
4212                            .await;
4213                        }
4214                    }
4215                }
4216
4217                let pending_keys: HashSet<XorName> = {
4218                    let q = queues.read().await;
4219                    q.pending_keys().into_iter().collect()
4220                };
4221                let admission_futures = completed.iter().map(async |(_, outcome)| match outcome {
4222                    Some(outcome) if !outcome.response.bootstrapping => Some(
4223                        admission::admit_hints(
4224                            &self_id,
4225                            &outcome.response.replica_hints,
4226                            &outcome.response.paid_hints,
4227                            &p2p,
4228                            &config,
4229                            &storage,
4230                            &paid_list,
4231                            &pending_keys,
4232                        )
4233                        .await,
4234                    ),
4235                    _ => None,
4236                });
4237                let admitted = join_all(admission_futures).await;
4238
4239                // Queue every peer's admitted hints under one write lock. Once
4240                // released, source-count ordering sees the complete batch.
4241                let (batch_outcomes, batch_discovered) = {
4242                    let mut q = queues.write().await;
4243                    let outcomes = completed
4244                        .iter()
4245                        .zip(admitted)
4246                        .filter_map(|((peer, _), admitted)| {
4247                            admitted.map(|admitted| {
4248                                (
4249                                    *peer,
4250                                    queue_admitted_hints(peer, admitted, &storage, &mut q),
4251                                )
4252                            })
4253                        })
4254                        .collect::<Vec<_>>();
4255                    let live_discovered = outcomes
4256                        .iter()
4257                        .flat_map(|(_, outcome)| outcome.discovered.iter().copied())
4258                        .filter(|key| q.contains_key(key))
4259                        .collect::<HashSet<_>>();
4260                    (outcomes, live_discovered)
4261                };
4262
4263                publish_bootstrap_admission_outcomes(
4264                    &bootstrap_state,
4265                    &batch_outcomes,
4266                    &batch_discovered,
4267                )
4268                .await;
4269
4270                bootstrap::decrement_pending_requests(&bootstrap_state, batch.len()).await;
4271            }
4272
4273            // Check drain condition.
4274            {
4275                let q = queues.read().await;
4276                if bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await {
4277                    complete_bootstrap(&is_bootstrapping, &bootstrap_complete_notify).await;
4278                }
4279            }
4280
4281            info!("Bootstrap sync completed");
4282        });
4283        self.task_handles.push(handle);
4284    }
4285}
4286
4287// ===========================================================================
4288// Free functions for background tasks
4289// ===========================================================================
4290
4291#[cfg(feature = "logging")]
4292fn log_audit_responder_summary(
4293    metrics: &AuditResponderMetrics,
4294    semaphore: &Semaphore,
4295    window: Duration,
4296) {
4297    let snapshot = metrics.take_snapshot();
4298    if snapshot.origins.is_empty() {
4299        return;
4300    }
4301
4302    let total = snapshot.total;
4303    let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4304        total.received_by_class;
4305    let global_inflight =
4306        MAX_CONCURRENT_AUDIT_RESPONSES.saturating_sub(semaphore.available_permits());
4307    info!(
4308        target: "ant_node::replication::audit_responder",
4309        window_ms = window.as_millis(),
4310        source_count = snapshot.origins.len(),
4311        received = total.received(),
4312        digest_received,
4313        subtree_received,
4314        byte_received,
4315        commitment_pin_received,
4316        admitted = total.admitted,
4317        global_pool_drops = total.global_pool_drops,
4318        per_peer_cap_drops = total.per_peer_cap_drops,
4319        serial_queue_drops = total.serial_queue_drops,
4320        completed = total.completed,
4321        send_failures = total.send_failures,
4322        processing_avg_ms = total.processing_avg_ms(),
4323        processing_max_ms = total.processing_max_ms,
4324        total_avg_ms = total.total_avg_ms(),
4325        total_max_ms = total.total_max_ms,
4326        global_inflight,
4327        global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
4328        peak_global_inflight = total.peak_global_inflight,
4329        "Audit responder summary"
4330    );
4331
4332    for (index, origin) in snapshot
4333        .origins
4334        .iter()
4335        .take(config::AUDIT_RESPONDER_TOP_ORIGINS)
4336        .enumerate()
4337    {
4338        let Some(source) = origin.source else {
4339            continue;
4340        };
4341        let [digest_received, subtree_received, byte_received, commitment_pin_received] =
4342            origin.received_by_class;
4343        info!(
4344            target: "ant_node::replication::audit_responder",
4345            rank = index + 1,
4346            source = %source,
4347            received = origin.received(),
4348            digest_received,
4349            subtree_received,
4350            byte_received,
4351            commitment_pin_received,
4352            admitted = origin.admitted,
4353            global_pool_drops = origin.global_pool_drops,
4354            per_peer_cap_drops = origin.per_peer_cap_drops,
4355            serial_queue_drops = origin.serial_queue_drops,
4356            completed = origin.completed,
4357            send_failures = origin.send_failures,
4358            processing_avg_ms = origin.processing_avg_ms(),
4359            processing_max_ms = origin.processing_max_ms,
4360            total_avg_ms = origin.total_avg_ms(),
4361            total_max_ms = origin.total_max_ms,
4362            peak_global_inflight = origin.peak_global_inflight,
4363            peak_peer_inflight = origin.peak_peer_inflight,
4364            "Audit responder top origin"
4365        );
4366    }
4367}
4368
4369/// Which ceiling rejected an audit-responder admission attempt.
4370///
4371/// Stable, machine-readable so a production log-scrape can bucket drops by
4372/// cause. A 24 h node log collapsed 117 dropped responsible replies into a
4373/// single opaque "capacity reached" line; this splits the two distinct causes
4374/// so the next such investigation can tell a global-pool exhaustion (the whole
4375/// node is saturated) from a per-peer cap hit (one source is self-throttling)
4376/// without re-instrumenting.
4377///
4378/// This branch runs a SINGLE shared audit-responder pool for all challenge
4379/// kinds (responsible / subtree / byte), so there is no separate slow/fast
4380/// pool to distinguish here — the `kind=` log field already separates the
4381/// responsible (fast-path) challenge from the heavier subtree/byte ones. If a
4382/// dedicated slow pool is later split out, add its variants here.
4383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4384enum ResponderRejectReason {
4385    /// The global [`MAX_CONCURRENT_AUDIT_RESPONSES`] semaphore had no permit
4386    /// free; the per-peer cap was not the binding constraint.
4387    GlobalPoolFull,
4388    /// `source` already held its [`MAX_AUDIT_RESPONSES_PER_PEER`] in-flight
4389    /// share, so the global permit was never attempted.
4390    PerPeerCapFull,
4391}
4392
4393impl ResponderRejectReason {
4394    /// Stable token emitted as `reason=<token>` in drop logs. Keep these values
4395    /// frozen — production log tooling greps for them.
4396    fn as_str(self) -> &'static str {
4397        match self {
4398            Self::GlobalPoolFull => "global_pool_full",
4399            Self::PerPeerCapFull => "per_peer_cap_full",
4400        }
4401    }
4402}
4403
4404impl From<ResponderRejectReason> for AuditResponderDropReason {
4405    fn from(reason: ResponderRejectReason) -> Self {
4406        match reason {
4407            ResponderRejectReason::GlobalPoolFull => Self::GlobalPoolFull,
4408            ResponderRejectReason::PerPeerCapFull => Self::PerPeerCapFull,
4409        }
4410    }
4411}
4412
4413impl From<ResponderRejectReason> for ResponderAdmissionCeiling {
4414    fn from(reason: ResponderRejectReason) -> Self {
4415        match reason {
4416            ResponderRejectReason::GlobalPoolFull => Self::GlobalPool,
4417            ResponderRejectReason::PerPeerCapFull => Self::PerPeerShare,
4418        }
4419    }
4420}
4421
4422/// Cumulative fresh-offer admission refusals in this process.
4423///
4424/// **Expected value in healthy operation is zero.** A node that refuses a
4425/// legitimate fresh offer does not merely shed load: the sender transmits
4426/// offers one-way and never reads the refusal, so the chunk's absence
4427/// resurfaces at the sender's delayed possession check and is charged to the
4428/// refusing node at audit severity (ADR-0003). Reaching this ceiling therefore
4429/// means the node is either under-provisioned for its offered load or its
4430/// admission share is mis-sized — and is accruing unearned trust damage either
4431/// way. Operators should alarm on any sustained non-zero rate.
4432///
4433/// Process-global rather than per-engine, which is exactly right in production
4434/// (one node per process) and adequate in multi-node test harnesses, where the
4435/// useful assertion is that *no* node in the fleet refused.
4436#[must_use]
4437pub fn fresh_offer_admission_refusals() -> u64 {
4438    audit_metrics::responder_admission_drops(ReplicationResponderClass::FreshOffer)
4439}
4440
4441/// Cumulative paid-list notification admission refusals in this process.
4442///
4443/// As with [`fresh_offer_admission_refusals`], zero is the expected value.
4444/// `PaidNotify` is one-way with no retry, so a refusal discards durable
4445/// paid-list evidence outright rather than pushing work back onto a requester.
4446#[must_use]
4447pub fn paid_notify_admission_refusals() -> u64 {
4448    audit_metrics::responder_admission_drops(ReplicationResponderClass::PaidNotify)
4449}
4450
4451/// Fresh-offer refusals caused by the class-wide pool being exhausted.
4452///
4453/// Split from [`fresh_offer_refusals_per_peer_share`] because the two indict
4454/// different things: this one says the node was saturated across all sources
4455/// and is genuinely under-provisioned for its offered load.
4456#[must_use]
4457pub fn fresh_offer_refusals_global_pool() -> u64 {
4458    audit_metrics::responder_admission_drops_by_ceiling(
4459        ReplicationResponderClass::FreshOffer,
4460        ResponderAdmissionCeiling::GlobalPool,
4461    )
4462}
4463
4464/// Fresh-offer refusals caused by one source exhausting its per-peer share.
4465///
4466/// For fresh offers this usually indicts the *share's size* rather than the
4467/// sender: the legitimate traffic pattern is bulk from a single peer — the one
4468/// node handling a client's PUT and fanning it out — so a share sized for
4469/// request/response traffic will refuse ordinary uploads.
4470#[must_use]
4471pub fn fresh_offer_refusals_per_peer_share() -> u64 {
4472    audit_metrics::responder_admission_drops_by_ceiling(
4473        ReplicationResponderClass::FreshOffer,
4474        ResponderAdmissionCeiling::PerPeerShare,
4475    )
4476}
4477
4478/// Why an audit-responder admission attempt failed, with the decision-time
4479/// capacity counters that let a drop be logged with full context.
4480///
4481/// `global_inflight`/`peer_inflight` are best-effort snapshots taken as the
4482/// decision was made (the two ceilings are read under different locks, so they
4483/// are not a single atomic view), but they are exact enough to tell a saturated
4484/// node from a single self-throttling flooder.
4485#[derive(Debug, Clone, Copy)]
4486struct ResponderAdmissionFailure {
4487    reason: ResponderRejectReason,
4488    /// Global permits in use across the whole engine at decision time.
4489    global_inflight: usize,
4490    /// Configured global ceiling ([`MAX_CONCURRENT_AUDIT_RESPONSES`]).
4491    global_limit: usize,
4492    /// In-flight audit responders already held for `source` at decision time.
4493    peer_inflight: u32,
4494    /// Configured per-peer ceiling ([`MAX_AUDIT_RESPONSES_PER_PEER`]).
4495    peer_limit: u32,
4496}
4497
4498impl fmt::Display for ResponderAdmissionFailure {
4499    /// Renders the stable `reason=... global_inflight=... global_limit=...
4500    /// peer_inflight=... peer_limit=...` suffix appended to every drop log.
4501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4502        write!(
4503            f,
4504            "reason={} global_inflight={} global_limit={} peer_inflight={} peer_limit={}",
4505            self.reason.as_str(),
4506            self.global_inflight,
4507            self.global_limit,
4508            self.peer_inflight,
4509            self.peer_limit,
4510        )
4511    }
4512}
4513
4514/// RAII admission for one audit-responder task: holds the GLOBAL permit and,
4515/// on drop, decrements the PER-PEER in-flight count. Moving this into the
4516/// spawned task ties both bounds to the task's exact lifetime — no manual
4517/// decrement to forget on an early return or panic.
4518struct ResponderGuard {
4519    _permit: tokio::sync::OwnedSemaphorePermit,
4520    _peer_slot: PeerResponderSlot,
4521    global_inflight: usize,
4522    peer_inflight: u32,
4523}
4524
4525type AuditResponderGuard = ResponderGuard;
4526type AuditResponderAdmissionFailure = ResponderAdmissionFailure;
4527
4528/// Provisional or admitted per-peer responder slot.
4529///
4530/// The slot is claimed before the global permit is attempted. Keeping that
4531/// claim under RAII means cancellation while rolling a failed admission back
4532/// cannot strand a peer at its cap. Once admission succeeds this guard moves
4533/// into [`ResponderGuard`] and remains held for the worker's exact lifetime.
4534struct PeerResponderSlot {
4535    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4536    peer: PeerId,
4537}
4538
4539#[derive(Clone)]
4540struct ReplicationMessageHandlerContext {
4541    p2p_node: Arc<P2PNode>,
4542    storage: Arc<ChunkStore>,
4543    paid_list: Arc<PaidList>,
4544    payment_verifier: Arc<PaymentVerifier>,
4545    queues: Arc<RwLock<ReplicationQueues>>,
4546    config: Arc<ReplicationConfig>,
4547    is_bootstrapping: Arc<RwLock<bool>>,
4548    bootstrap_state: Arc<RwLock<BootstrapState>>,
4549    sync_history: Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
4550    sync_cycle_epoch: Arc<RwLock<u64>>,
4551    repair_proofs: Arc<RwLock<RepairProofs>>,
4552    last_commitment_by_peer: Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
4553    ever_capable_peers: Arc<RwLock<HashSet<PeerId>>>,
4554    sig_verify_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
4555    my_commitment_state: Arc<ResponderCommitmentState>,
4556    gossip_audit: GossipAuditTrigger,
4557    audit_responder_semaphore: Arc<Semaphore>,
4558    audit_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4559    audit_responder_metrics: Arc<AuditResponderMetrics>,
4560    subtree_round1: SubtreeRound1Limiter,
4561    fetch_responder_worker_semaphore: Arc<Semaphore>,
4562    fetch_responder_admission_semaphore: Arc<Semaphore>,
4563    fetch_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4564    verification_responder_worker_semaphore: Arc<Semaphore>,
4565    verification_responder_admission_semaphore: Arc<Semaphore>,
4566    verification_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4567    neighbor_sync_responder_worker_semaphore: Arc<Semaphore>,
4568    neighbor_sync_responder_admission_semaphore: Arc<Semaphore>,
4569    neighbor_sync_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4570    fresh_offer_worker_semaphore: Arc<Semaphore>,
4571    fresh_offer_admission_semaphore: Arc<Semaphore>,
4572    fresh_offer_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4573    fresh_offer_in_flight: FreshOfferInFlight,
4574    paid_notify_worker_semaphore: Arc<Semaphore>,
4575    paid_notify_admission_semaphore: Arc<Semaphore>,
4576    paid_notify_responder_inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4577    /// Pointer replication, when this node stores pointers.
4578    pointers: Option<Arc<pointer::PointerReplication>>,
4579    /// The engine's shutdown token, for detached responder work.
4580    ///
4581    /// Workers on [`Self::detached_task_tracker`] race this around their
4582    /// *network* phase only — never around an LMDB `spawn_blocking` await,
4583    /// where dropping the awaiter would detach a live transaction. This is
4584    /// what lets `shutdown()` keep its unbounded `tracker.wait()` and still
4585    /// terminate: the wait stays safe because it is now guaranteed finite.
4586    shutdown: CancellationToken,
4587    /// Shared tracker for detached work so `shutdown()` can await release of
4588    /// storage and P2P resources after all producer tasks have stopped.
4589    detached_task_tracker: TaskTracker,
4590}
4591
4592struct InboundReplicationMessage {
4593    source: PeerId,
4594    msg: ReplicationMessage,
4595    rr_message_id: Option<String>,
4596    received_at: Instant,
4597}
4598
4599#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4600enum SerialQueueDropReason {
4601    Full,
4602    Closed,
4603}
4604
4605#[cfg(feature = "logging")]
4606impl SerialQueueDropReason {
4607    const fn as_str(self) -> &'static str {
4608        match self {
4609            Self::Full => "full",
4610            Self::Closed => "closed",
4611        }
4612    }
4613}
4614
4615#[derive(Debug, Clone, Copy)]
4616#[cfg_attr(not(any(feature = "logging", test)), allow(dead_code))]
4617struct SerialQueueDrop {
4618    source: PeerId,
4619    message_class: &'static str,
4620    audit_responder_class: Option<AuditResponderClass>,
4621    queue_depth: usize,
4622    reason: SerialQueueDropReason,
4623}
4624
4625fn try_enqueue_serial_message(
4626    sender: &mpsc::Sender<InboundReplicationMessage>,
4627    inbound: InboundReplicationMessage,
4628) -> std::result::Result<(), SerialQueueDrop> {
4629    let source = inbound.source;
4630    let message_class = replication_message_class(&inbound.msg.body);
4631    let audit_responder_class = audit_responder_class(&inbound.msg.body);
4632    let queue_depth = sender.max_capacity().saturating_sub(sender.capacity());
4633    sender.try_send(inbound).map_err(|error| {
4634        let (reason, dropped) = match error {
4635            mpsc::error::TrySendError::Full(dropped) => (SerialQueueDropReason::Full, dropped),
4636            mpsc::error::TrySendError::Closed(dropped) => (SerialQueueDropReason::Closed, dropped),
4637        };
4638        audit_metrics::record_serial_queue_overflow_drop(&dropped.msg.body);
4639        SerialQueueDrop {
4640            source,
4641            message_class,
4642            audit_responder_class,
4643            queue_depth,
4644            reason,
4645        }
4646    })
4647}
4648
4649const fn replication_message_class(body: &ReplicationMessageBody) -> &'static str {
4650    match body {
4651        ReplicationMessageBody::FreshReplicationOffer(_) => "fresh_offer",
4652        ReplicationMessageBody::FreshReplicationResponse(_) => "fresh_response",
4653        ReplicationMessageBody::PaidNotify(_) => "paid_notify",
4654        ReplicationMessageBody::NeighborSyncRequest(_) => "neighbor_sync_request",
4655        ReplicationMessageBody::NeighborSyncResponse(_) => "neighbor_sync_response",
4656        ReplicationMessageBody::VerificationRequest(_) => "verification_request",
4657        ReplicationMessageBody::VerificationResponse(_) => "verification_response",
4658        ReplicationMessageBody::FetchRequest(_) => "fetch_request",
4659        ReplicationMessageBody::FetchResponse(_) => "fetch_response",
4660        ReplicationMessageBody::AuditChallenge(_) => "audit_challenge",
4661        ReplicationMessageBody::AuditResponse(_) => "audit_response",
4662        ReplicationMessageBody::SubtreeAuditChallenge(_) => "subtree_audit_challenge",
4663        ReplicationMessageBody::SubtreeAuditResponse(_) => "subtree_audit_response",
4664        ReplicationMessageBody::SubtreeSliceChallenge(_) => "subtree_slice_challenge",
4665        ReplicationMessageBody::SubtreeSliceResponse(_) => "subtree_slice_response",
4666        ReplicationMessageBody::GetCommitmentByPin(_) => "commitment_pin_request",
4667        ReplicationMessageBody::GetCommitmentByPinResponse(_) => "commitment_pin_response",
4668        ReplicationMessageBody::PointerFreshOffer(_) => "pointer_fresh_offer",
4669        ReplicationMessageBody::PointerHints(_) => "pointer_hints",
4670        ReplicationMessageBody::PointerFetchRequest(_) => "pointer_fetch_request",
4671        ReplicationMessageBody::PointerFetchResponse(_) => "pointer_fetch_response",
4672        ReplicationMessageBody::PointerStateRequest(_) => "pointer_state_request",
4673        ReplicationMessageBody::PointerStateResponse(_) => "pointer_state_response",
4674    }
4675}
4676
4677const fn audit_responder_class(body: &ReplicationMessageBody) -> Option<AuditResponderClass> {
4678    match body {
4679        ReplicationMessageBody::AuditChallenge(_) => Some(AuditResponderClass::Digest),
4680        ReplicationMessageBody::SubtreeAuditChallenge(_) => Some(AuditResponderClass::Subtree),
4681        ReplicationMessageBody::SubtreeSliceChallenge(_) => Some(AuditResponderClass::Byte),
4682        ReplicationMessageBody::GetCommitmentByPin(_) => Some(AuditResponderClass::CommitmentPin),
4683        _ => None,
4684    }
4685}
4686
4687impl AuditResponderClass {
4688    const fn per_peer_limit(self) -> u32 {
4689        match self {
4690            Self::Digest => MAX_DIGEST_AUDIT_RESPONSES_PER_PEER,
4691            Self::Subtree | Self::Byte | Self::CommitmentPin => MAX_AUDIT_RESPONSES_PER_PEER,
4692        }
4693    }
4694}
4695
4696fn handle_replication_event_recv_error(error: &RecvError) -> ControlFlow<()> {
4697    match error {
4698        RecvError::Lagged(missed) => {
4699            audit_metrics::record_replication_event_lagged(*missed);
4700            warn!(
4701                "Missed {missed} P2P events on replication branch (broadcast lag); \
4702                 replication messages may have been dropped before dispatch"
4703            );
4704            ControlFlow::Continue(())
4705        }
4706        RecvError::Closed => {
4707            // A closed broadcast channel never yields again, so the branch
4708            // would otherwise be immediately ready on every select! iteration.
4709            warn!("P2P event stream closed on replication branch; stopping message handler");
4710            ControlFlow::Break(())
4711        }
4712    }
4713}
4714
4715fn replication_payload_from_event(
4716    event: P2PEvent,
4717) -> Option<(PeerId, Vec<u8>, &'static str, Option<String>)> {
4718    let P2PEvent::Message {
4719        topic,
4720        source: Some(source),
4721        data,
4722        ..
4723    } = event
4724    else {
4725        return None;
4726    };
4727
4728    let (matched_id, is_rr) = match_replication_protocol(&topic)?;
4729    if !is_rr {
4730        return Some((source, data, matched_id, None));
4731    }
4732    if is_rr {
4733        return P2PNode::parse_request_envelope(&data)
4734            .filter(|(_, is_resp, _)| !is_resp)
4735            .map(|(msg_id, _, payload)| (source, payload, matched_id, Some(msg_id)));
4736    }
4737    None
4738}
4739
4740impl Drop for PeerResponderSlot {
4741    fn drop(&mut self) {
4742        // Decrement (and prune to keep the map bounded) without blocking the
4743        // async runtime: a short lock on a tiny map.
4744        //
4745        // Fast path: if the (uncontended, tiny) lock is free, decrement inline
4746        // with no spawn. Otherwise defer to a task — but only if a runtime is
4747        // actually current, so `Drop` during shutdown (no runtime) can never
4748        // panic. A missed decrement at shutdown is harmless: the whole map is
4749        // being dropped with the engine.
4750        let peer = self.peer;
4751        if let Ok(mut map) = self.inflight.try_write() {
4752            if let Some(n) = map.get_mut(&peer) {
4753                *n = n.saturating_sub(1);
4754                if *n == 0 {
4755                    map.remove(&peer);
4756                }
4757            }
4758            return;
4759        }
4760        if let Ok(handle) = tokio::runtime::Handle::try_current() {
4761            let inflight = Arc::clone(&self.inflight);
4762            handle.spawn(async move {
4763                let mut map = inflight.write().await;
4764                if let Some(n) = map.get_mut(&peer) {
4765                    *n = n.saturating_sub(1);
4766                    if *n == 0 {
4767                        map.remove(&peer);
4768                    }
4769                }
4770            });
4771        }
4772    }
4773}
4774
4775/// Try to admit one bounded responder task for `source`: claim a per-peer slot
4776/// and then a global permit. The limits are parameters so independent responder
4777/// classes can reuse the same flood-fair admission and cancellation semantics.
4778async fn admit_bounded_responder(
4779    semaphore: &Arc<Semaphore>,
4780    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
4781    source: &PeerId,
4782    global_limit: usize,
4783    peer_limit: u32,
4784) -> std::result::Result<ResponderGuard, ResponderAdmissionFailure> {
4785    let global_inflight = |sem: &Semaphore| global_limit.saturating_sub(sem.available_permits());
4786
4787    let admitted_peer_inflight = {
4788        let mut map = inflight.write().await;
4789        let entry = map.entry(*source).or_insert(0);
4790        if *entry >= peer_limit {
4791            let peer_inflight = *entry;
4792            drop(map);
4793            return Err(ResponderAdmissionFailure {
4794                reason: ResponderRejectReason::PerPeerCapFull,
4795                global_inflight: global_inflight(semaphore),
4796                global_limit,
4797                peer_inflight,
4798                peer_limit,
4799            });
4800        }
4801        *entry += 1;
4802        *entry
4803    };
4804
4805    let peer_slot = PeerResponderSlot {
4806        inflight: Arc::clone(inflight),
4807        peer: *source,
4808    };
4809    let Ok(permit) = Arc::clone(semaphore).try_acquire_owned() else {
4810        return Err(ResponderAdmissionFailure {
4811            reason: ResponderRejectReason::GlobalPoolFull,
4812            global_inflight: global_inflight(semaphore),
4813            global_limit,
4814            peer_inflight: admitted_peer_inflight.saturating_sub(1),
4815            peer_limit,
4816        });
4817    };
4818
4819    Ok(ResponderGuard {
4820        _permit: permit,
4821        _peer_slot: peer_slot,
4822        global_inflight: global_inflight(semaphore),
4823        peer_inflight: admitted_peer_inflight,
4824    })
4825}
4826
4827/// A live round-1 → round-2 subtree-audit session: proof of a matching round 1.
4828struct SubtreeSession {
4829    commitment_hash: [u8; 32],
4830    nonce: [u8; 32],
4831    inserted: Instant,
4832    /// What round 1 bound for each pointer it proved, so round 2 serves that
4833    /// record however many updates land in between (ADR-0019).
4834    pointer_bindings: PointerBindings,
4835}
4836
4837/// Responder-wide token bucket over the chunk bytes round-1 proof building may
4838/// read and hash, refilled continuously at
4839/// [`SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC`] up to
4840/// [`SUBTREE_ROUND1_WORK_BURST_BYTES`].
4841///
4842/// Deliberately keyed by nothing. The per-peer cooldown limits how often one
4843/// identity may ask, so it is refilled by acquiring more identities; this is
4844/// charged for work done regardless of who asked, so it is not.
4845///
4846/// Charged after the fact, with the bytes the proof actually covered: the cost
4847/// of a request is not known until the pinned commitment has been resolved and
4848/// its subtree selected, both of which happen inside the handler. Admission
4849/// therefore asks only whether the balance is positive, and a proof that costs
4850/// more than is left drives the balance NEGATIVE rather than stopping at zero.
4851/// Carrying the debt is what makes the bound real: without it a maximal proof
4852/// would cost the same as a trivial one, since either way the next request only
4853/// has to wait for the balance to climb back above zero. With it, sustained
4854/// throughput settles at refill ÷ cost-per-proof, so expensive proofs are
4855/// admitted proportionally less often.
4856struct Round1WorkBudget {
4857    /// Signed, so an over-large proof leaves debt to work off.
4858    balance: i64,
4859    last_refill: Instant,
4860}
4861
4862impl Round1WorkBudget {
4863    /// Deepest debt carried, so one huge proof cannot lock out honest audits
4864    /// for longer than the burst takes to refill.
4865    const MAX_DEBT: i64 = -SUBTREE_ROUND1_WORK_BURST_BYTES;
4866    /// Nanoseconds per second, for the sub-second part of a refill.
4867    const NANOS_PER_SEC: i64 = 1_000_000_000;
4868
4869    fn new() -> Self {
4870        Self {
4871            balance: SUBTREE_ROUND1_WORK_BURST_BYTES,
4872            last_refill: Instant::now(),
4873        }
4874    }
4875
4876    /// Add the tokens accrued since the last touch, capped at the burst size.
4877    fn refill(&mut self, now: Instant) {
4878        let elapsed = now.saturating_duration_since(self.last_refill);
4879        self.last_refill = now;
4880        let whole_secs = i64::try_from(elapsed.as_secs())
4881            .unwrap_or(i64::MAX)
4882            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC);
4883        let sub_sec = i64::from(elapsed.subsec_nanos())
4884            .saturating_mul(SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC)
4885            / Self::NANOS_PER_SEC;
4886        self.balance = self
4887            .balance
4888            .saturating_add(whole_secs.saturating_add(sub_sec))
4889            .min(SUBTREE_ROUND1_WORK_BURST_BYTES);
4890    }
4891
4892    /// Whether budget remains for a new round-1 proof.
4893    fn has_budget(&mut self, now: Instant) -> bool {
4894        self.refill(now);
4895        self.balance > 0
4896    }
4897
4898    /// Charge `bytes` of completed proof work, carrying debt down to
4899    /// [`Self::MAX_DEBT`].
4900    fn charge(&mut self, bytes: i64, now: Instant) {
4901        self.refill(now);
4902        self.balance = self.balance.saturating_sub(bytes).max(Self::MAX_DEBT);
4903    }
4904}
4905
4906/// Resource controls for the HEAVY subtree-audit round 1: a tight
4907/// admission pool separate from the light responsible/slice audits, a per-peer
4908/// rate cooldown, and single-use round-1 → round-2 sessions so a round-2 slice
4909/// challenge is only served after a matching round 1.
4910///
4911/// It also holds the responder-wide [`Round1WorkBudget`], the only one of those
4912/// bounds not keyed by peer identity, and so the only one that bounds sustained
4913/// work rather than concurrency or per-identity frequency.
4914#[derive(Clone)]
4915struct SubtreeRound1Limiter {
4916    semaphore: Arc<Semaphore>,
4917    /// Global ceiling on concurrent round-1 proofs (config-driven;
4918    /// [`MAX_CONCURRENT_SUBTREE_ROUND1`] in production). Held alongside the
4919    /// semaphore because the per-peer admission helper needs the same number.
4920    max_concurrent: usize,
4921    inflight: Arc<RwLock<HashMap<PeerId, u32>>>,
4922    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
4923    /// Per-peer minimum spacing between served round-1 proofs (config-driven;
4924    /// [`SUBTREE_ROUND1_RESPONDER_COOLDOWN`] in production, near-zero in tests).
4925    cooldown_interval: Duration,
4926    sessions: Arc<RwLock<HashMap<(PeerId, u64), SubtreeSession>>>,
4927    /// Identity-independent ceiling on sustained round-1 work.
4928    work: Arc<RwLock<Round1WorkBudget>>,
4929}
4930
4931impl SubtreeRound1Limiter {
4932    /// `max_concurrent` of 0 would wedge the responder into refusing every
4933    /// round-1 proof, which reads on the auditor side as a silent whole-fleet
4934    /// audit outage. Clamp to at least one so a mis-set config degrades to slow
4935    /// rather than to off.
4936    fn new(cooldown_interval: Duration, max_concurrent: usize) -> Self {
4937        let max_concurrent = max_concurrent.max(1);
4938        Self {
4939            semaphore: Arc::new(Semaphore::new(max_concurrent)),
4940            max_concurrent,
4941            inflight: Arc::new(RwLock::new(HashMap::new())),
4942            cooldown: Arc::new(RwLock::new(HashMap::new())),
4943            cooldown_interval,
4944            sessions: Arc::new(RwLock::new(HashMap::new())),
4945            work: Arc::new(RwLock::new(Round1WorkBudget::new())),
4946        }
4947    }
4948
4949    /// Charge completed round-1 proof work against the responder-wide budget.
4950    async fn charge_work(&self, content_bytes: i64) {
4951        self.work
4952            .write()
4953            .await
4954            .charge(content_bytes, Instant::now());
4955    }
4956
4957    /// Admit one heavy round-1 proof for `source`: take a concurrency permit
4958    /// FIRST (so a full pool never wastes the peer's cooldown allowance), then
4959    /// the responder-wide work budget, then the per-peer rate cooldown. `None`
4960    /// drops the challenge (the remote auditor applies its own graced-timeout
4961    /// policy).
4962    async fn admit(&self, source: &PeerId) -> Option<AuditResponderGuard> {
4963        let guard = admit_bounded_responder(
4964            &self.semaphore,
4965            &self.inflight,
4966            source,
4967            self.max_concurrent,
4968            MAX_SUBTREE_ROUND1_PER_PEER,
4969        )
4970        .await
4971        .ok()?;
4972        // Checked before the per-peer cooldown is stamped, so a peer refused for
4973        // want of budget is not also charged its next allowance.
4974        if !self.work.write().await.has_budget(Instant::now()) {
4975            return None; // guard drops here, releasing the permit + slot
4976        }
4977        let now = Instant::now();
4978        let mut cooldown = self.cooldown.write().await;
4979        if let Some(&last) = cooldown.get(source) {
4980            if now.duration_since(last) < self.cooldown_interval {
4981                return None; // guard drops here, releasing the permit + slot
4982            }
4983        }
4984        // Evict lapsed entries (their cooldown has expired, so they no longer
4985        // limit) and cap capacity, so peer-id churn can't grow this map unbounded.
4986        cooldown.retain(|_, &mut last| now.duration_since(last) < self.cooldown_interval);
4987        if cooldown.len() >= MAX_SUBTREE_SESSIONS {
4988            if let Some(oldest) = cooldown.iter().min_by_key(|(_, &t)| t).map(|(k, _)| *k) {
4989                cooldown.remove(&oldest);
4990            }
4991        }
4992        cooldown.insert(*source, now);
4993        Some(guard)
4994    }
4995
4996    /// Record a single-use session once a round-1 proof is built and about to be
4997    /// sent, so the matching round 2 is admitted exactly once.
4998    ///
4999    /// The session keeps what round 1 bound for each pointer it proved, while
5000    /// every live session together holds no more than
5001    /// [`MAX_SESSION_POINTER_BINDINGS`] of them. A session whose bindings do
5002    /// not fit is not opened and `false` is returned, so its proof is not
5003    /// sent and round 1 is answered `Transient` instead: the bindings of
5004    /// sessions already answered are never given up, because their round 2 is
5005    /// owed them (ADR-0019).
5006    async fn open_session(
5007        &self,
5008        source: PeerId,
5009        challenge_id: u64,
5010        commitment_hash: [u8; 32],
5011        nonce: [u8; 32],
5012        pointer_bindings: PointerBindings,
5013    ) -> bool {
5014        let now = Instant::now();
5015        let mut sessions = self.sessions.write().await;
5016        sessions.retain(|_, e| now.duration_since(e.inserted) < SUBTREE_SESSION_TTL);
5017        // Checked before anything is evicted, so a session refused here costs
5018        // no other session its place.
5019        let held: usize = sessions.values().map(|e| e.pointer_bindings.len()).sum();
5020        if held.saturating_add(pointer_bindings.len()) > MAX_SESSION_POINTER_BINDINGS {
5021            return false;
5022        }
5023        if sessions.len() >= MAX_SUBTREE_SESSIONS {
5024            if let Some(oldest) = sessions
5025                .iter()
5026                .min_by_key(|(_, e)| e.inserted)
5027                .map(|(k, _)| *k)
5028            {
5029                sessions.remove(&oldest);
5030            }
5031        }
5032        sessions.insert(
5033            (source, challenge_id),
5034            SubtreeSession {
5035                commitment_hash,
5036                nonce,
5037                inserted: now,
5038                pointer_bindings,
5039            },
5040        );
5041        true
5042    }
5043
5044    /// Atomically consume the round-2 session for this exchange. `Some` iff a
5045    /// live session matching `(source, challenge_id, commitment_hash, nonce)`
5046    /// existed (and is now removed), carrying what its round 1 bound for each
5047    /// pointer; a miss silently drops round 2 to the graced timeout lane
5048    /// (sessions are ephemeral and can be lost across a restart).
5049    async fn consume_session(
5050        &self,
5051        source: &PeerId,
5052        challenge_id: u64,
5053        commitment_hash: &[u8; 32],
5054        nonce: &[u8; 32],
5055    ) -> Option<PointerBindings> {
5056        let mut sessions = self.sessions.write().await;
5057        let matches = sessions.get(&(*source, challenge_id)).is_some_and(|e| {
5058            Instant::now().duration_since(e.inserted) < SUBTREE_SESSION_TTL
5059                && &e.commitment_hash == commitment_hash
5060                && &e.nonce == nonce
5061        });
5062        if matches {
5063            sessions
5064                .remove(&(*source, challenge_id))
5065                .map(|e| e.pointer_bindings)
5066        } else {
5067            None
5068        }
5069    }
5070}
5071
5072/// Outcome of admitting a round-2 slice challenge.
5073enum SliceAdmission {
5074    /// Admitted: the guard holds the global permit and the per-peer slot, and
5075    /// the single-use round-1 session has been consumed, yielding what its
5076    /// round 1 bound for each pointer.
5077    Admitted(AuditResponderGuard, PointerBindings),
5078    /// Refused at a responder ceiling. The round-1 session is left INTACT.
5079    Capacity(AuditResponderAdmissionFailure),
5080    /// No live round-1 session matched this challenge.
5081    NoSession,
5082}
5083
5084/// Admit a round-2 slice challenge: take the responder permit BEFORE consuming
5085/// the single-use round-1 session.
5086///
5087/// The order is the point: a single-use token must not be spent on work that is
5088/// then refused. Consuming first and testing admission second leaves the session
5089/// destroyed by a purely local capacity drop, so the refusal is not recoverable
5090/// even in principle.
5091///
5092/// Scope of the benefit today, stated honestly: `request_slice_proof` issues one
5093/// `send_request` and maps any failure straight to `SliceRound::Timeout`, so the
5094/// auditor does not currently re-send round 2 within an audit. The preserved
5095/// session is therefore not yet *recovering* an audit — it keeps a refusal
5096/// truthful (temporary means temporary) and keeps the invariant available for a
5097/// retry, rather than baking "capacity drop is permanent" into the state
5098/// machine. If an application-level retry is ruled out for good, this ordering
5099/// still costs nothing over the alternative.
5100///
5101/// Cost of the ordering: the permit and per-peer slot are held across the
5102/// session probe, which is one in-memory map lookup and no chunk work. The
5103/// per-peer cap still bounds a peer sending unsessioned challenges to the same
5104/// share it could already occupy with well-formed ones, so the admission
5105/// surface is unchanged.
5106async fn admit_slice_challenge(
5107    semaphore: &Arc<Semaphore>,
5108    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5109    round1: &SubtreeRound1Limiter,
5110    source: &PeerId,
5111    challenge: &protocol::SubtreeSliceChallenge,
5112) -> SliceAdmission {
5113    let guard =
5114        match admit_audit_responder(semaphore, inflight, source, AuditResponderClass::Byte).await {
5115            Ok(guard) => guard,
5116            Err(failure) => return SliceAdmission::Capacity(failure),
5117        };
5118    let Some(pointer_bindings) = round1
5119        .consume_session(
5120            source,
5121            challenge.challenge_id,
5122            &challenge.expected_commitment_hash,
5123            &challenge.nonce,
5124        )
5125        .await
5126    else {
5127        // Release the permit and per-peer slot before the caller replies: no
5128        // chunk work follows, so holding them would shrink the pool for nothing.
5129        drop(guard);
5130        return SliceAdmission::NoSession;
5131    };
5132    SliceAdmission::Admitted(guard, pointer_bindings)
5133}
5134
5135/// Try to admit one audit-responder task for `source`: take a global permit AND
5136/// a per-peer slot (both bounded). Returns `Err` with the binding ceiling and
5137/// its decision-time counters (caller drops the challenge, leaving the remote
5138/// auditor to apply that audit path's timeout policy) if either ceiling is hit,
5139/// so one flooder can neither exhaust the global pool's effect on others nor
5140/// exceed its own per-peer share (codex-r2 A). The `Err` reason lets the caller
5141/// log exactly WHY the drop happened rather than a single opaque "capacity
5142/// reached".
5143async fn admit_audit_responder(
5144    semaphore: &Arc<Semaphore>,
5145    inflight: &Arc<RwLock<HashMap<PeerId, u32>>>,
5146    source: &PeerId,
5147    class: AuditResponderClass,
5148) -> std::result::Result<AuditResponderGuard, AuditResponderAdmissionFailure> {
5149    let global_limit = MAX_CONCURRENT_AUDIT_RESPONSES;
5150    let peer_limit = class.per_peer_limit();
5151    admit_bounded_responder(semaphore, inflight, source, global_limit, peer_limit).await
5152}
5153
5154/// Handle an incoming replication protocol message.
5155///
5156/// When `rr_message_id` is `Some`, the request arrived via the `/rr/`
5157/// request-response path and the response must be sent via `send_response`
5158/// so saorsa-core can route it back to the waiting `send_request` caller.
5159#[allow(clippy::too_many_lines)]
5160async fn handle_replication_message(
5161    source: &PeerId,
5162    msg: ReplicationMessage,
5163    ctx: &ReplicationMessageHandlerContext,
5164    received_at: Instant,
5165    rr_message_id: Option<&str>,
5166) -> Result<()> {
5167    match msg.body {
5168        ReplicationMessageBody::FreshReplicationOffer(offer) => {
5169            dispatch_fresh_offer(
5170                *source,
5171                offer,
5172                ctx,
5173                msg.request_id,
5174                received_at,
5175                rr_message_id,
5176            )
5177            .await
5178        }
5179        ReplicationMessageBody::PaidNotify(notify) => {
5180            dispatch_paid_notify(*source, notify, ctx, received_at).await
5181        }
5182        ReplicationMessageBody::NeighborSyncRequest(request) => {
5183            let bootstrapping = *ctx.is_bootstrapping.read().await;
5184            // Phase-3 storage-bound audit: store the sender's
5185            // commitment for use as `expected_commitment_hash` in
5186            // future audits. Verify signature before storing so a peer
5187            // cannot inject a forged commitment for someone else.
5188            if let Some(target) = ingest_peer_commitment(
5189                source,
5190                request.commitment.as_ref(),
5191                &ctx.p2p_node,
5192                &ctx.last_commitment_by_peer,
5193                &ctx.ever_capable_peers,
5194                &ctx.sig_verify_attempts,
5195            )
5196            .await
5197            {
5198                maybe_trigger_gossip_audit(&ctx.gossip_audit, source, target).await;
5199            }
5200            dispatch_neighbor_sync_request(
5201                *source,
5202                request,
5203                ctx,
5204                bootstrapping,
5205                // Atomically snapshot + mark-gossiped: emitted in the sync
5206                // response, so we must stay answerable for it (ADR-0002).
5207                ctx.my_commitment_state
5208                    .current_for_gossip()
5209                    .map(|b| b.commitment().clone()),
5210                msg.request_id,
5211                received_at,
5212                rr_message_id,
5213            )
5214            .await
5215        }
5216        ReplicationMessageBody::VerificationRequest(request) => {
5217            dispatch_verification_request(
5218                *source,
5219                request,
5220                ctx,
5221                msg.request_id,
5222                received_at,
5223                rr_message_id,
5224            )
5225            .await
5226        }
5227        ReplicationMessageBody::FetchRequest(request) => {
5228            dispatch_fetch_request(
5229                *source,
5230                request,
5231                ctx,
5232                msg.request_id,
5233                received_at,
5234                rr_message_id,
5235            )
5236            .await
5237        }
5238        ReplicationMessageBody::AuditChallenge(challenge) => {
5239            // Responsible-chunk audit (audit #2) responder: answer with per-key
5240            // possession digests. This same handler also answers the
5241            // prune-confirmation audit, which sends the same `AuditChallenge`
5242            // wire message.
5243            //
5244            // Answering digests the stored bytes of every challenged key, so —
5245            // like the subtree/byte audits below — run it on a detached task off
5246            // this serial message loop. Handling it inline lets one challenge
5247            // block all other replication traffic until its digests complete
5248            // (head-of-line blocking). The same flood-fair admission applies: a
5249            // global ceiling AND a per-peer cap, dropping the challenge if either
5250            // is hit. A dropped challenge reads as a penalised timeout to the
5251            // auditor, so the caps must remain high enough for honest audit load;
5252            // the per-peer share still prevents one flooder from starving others.
5253            let class = AuditResponderClass::Digest;
5254            let guard = match admit_audit_responder(
5255                &ctx.audit_responder_semaphore,
5256                &ctx.audit_responder_inflight,
5257                source,
5258                class,
5259            )
5260            .await
5261            {
5262                Ok(guard) => guard,
5263                Err(failure) => {
5264                    protocol::record_audit_drop(protocol::AuditDropKind::Responsible);
5265                    audit_metrics::record_admission_drop(class);
5266                    ctx.audit_responder_metrics
5267                        .record_drop(*source, failure.reason.into());
5268                    warn!(
5269                        target: "ant_node::replication::audit_responder",
5270                        event = "admission_dropped",
5271                        kind = "responsible",
5272                        responder_class = class.as_str(),
5273                        source = %source,
5274                        challenge_id = challenge.challenge_id,
5275                        key_count = challenge.keys.len(),
5276                        request_response = rr_message_id.is_some(),
5277                        dispatch_ms = received_at.elapsed().as_millis(),
5278                        reason = failure.reason.as_str(),
5279                        global_inflight = failure.global_inflight,
5280                        global_limit = failure.global_limit,
5281                        peer_inflight = failure.peer_inflight,
5282                        peer_limit = failure.peer_limit,
5283                        "Audit responder admission dropped"
5284                    );
5285                    return Ok(());
5286                }
5287            };
5288            let admission_global_inflight = guard.global_inflight;
5289            let admission_peer_inflight = guard.peer_inflight;
5290            ctx.audit_responder_metrics.record_admitted(
5291                *source,
5292                admission_global_inflight,
5293                admission_peer_inflight,
5294            );
5295            info!(
5296                target: "ant_node::replication::audit_responder",
5297                event = "admitted",
5298                kind = "responsible",
5299                responder_class = class.as_str(),
5300                source = %source,
5301                challenge_id = challenge.challenge_id,
5302                key_count = challenge.keys.len(),
5303                request_response = rr_message_id.is_some(),
5304                dispatch_ms = received_at.elapsed().as_millis(),
5305                global_inflight = admission_global_inflight,
5306                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5307                peer_inflight = admission_peer_inflight,
5308                peer_limit = class.per_peer_limit(),
5309                "Audit responder request admitted"
5310            );
5311            let bootstrapping = *ctx.is_bootstrapping.read().await;
5312            let dispatch_latency = received_at.elapsed();
5313            audit_metrics::record_digest_dispatch_latency(dispatch_latency);
5314            debug!(
5315                audit_type = "digest_responder",
5316                dispatch_latency_ms = dispatch_latency.as_millis(),
5317                source = %source,
5318                "Audit challenge dispatch latency measured"
5319            );
5320            let storage = Arc::clone(&ctx.storage);
5321            let p2p_node = Arc::clone(&ctx.p2p_node);
5322            let source = *source;
5323            let request_id = msg.request_id;
5324            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5325            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5326            ctx.detached_task_tracker.spawn(async move {
5327                let _guard = guard; // global permit + per-peer slot, held until done
5328                let worker_started = Instant::now();
5329                match handle_audit_challenge_msg(
5330                    &source,
5331                    &challenge,
5332                    &storage,
5333                    &p2p_node,
5334                    bootstrapping,
5335                    ReplyRoute {
5336                        request_id,
5337                        rr_message_id: rr_message_id.as_deref(),
5338                        protocol: REPLICATION_PROTOCOL_ID,
5339                    },
5340                )
5341                .await
5342                {
5343                    Ok(completion) => log_audit_responder_completion(
5344                        &responder_metrics,
5345                        source,
5346                        class,
5347                        "responsible",
5348                        challenge.challenge_id,
5349                        challenge.keys.len(),
5350                        completion.response_kind,
5351                        completion.sent,
5352                        received_at,
5353                        worker_started,
5354                        completion.processing,
5355                        completion.response_send,
5356                    ),
5357                    Err(e) => debug!("Audit challenge from {source} error: {e}"),
5358                }
5359            });
5360            Ok(())
5361        }
5362        ReplicationMessageBody::SubtreeAuditChallenge(challenge) => {
5363            // Gossip-triggered storage-bound subtree audit (ADR-0002). The
5364            // responder rebuilds the WHOLE nonce-selected subtree, reading every
5365            // leaf's bytes from disk (`get_raw` × ~sqrt(N) leaves). Run it on a
5366            // detached task so this serial message loop is never blocked on disk
5367            // I/O — otherwise one audit stalls all replication traffic (§5).
5368            //
5369            // A bounded, flood-fair admission restores backpressure (codex#1 +
5370            // codex-r2 A): a global ceiling AND a per-peer cap. If either is hit
5371            // we drop this challenge. Subtree auditors grace timeout
5372            // non-responses, so capacity drops throttle flooders without turning
5373            // into trust penalties (and one source cannot starve other peers,
5374            // since its share is capped per-peer).
5375            let class = AuditResponderClass::Subtree;
5376            info!(
5377                "Audit challenge received: kind=subtree source={source} request_response={}",
5378                rr_message_id.is_some(),
5379            );
5380            // Round 1 is the HEAVY path (rebuilds + hashes the whole sqrt-subtree),
5381            // so it uses its own tight admission pool + per-peer rate cooldown,
5382            // separate from the light responsible/slice audits, and a miss silently
5383            // drops (subtree auditors grace timeouts).
5384            let Some(guard) = ctx.subtree_round1.admit(source).await else {
5385                protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5386                warn!(
5387                    target: "ant_node::replication::audit_responder",
5388                    event = "admission_dropped",
5389                    kind = "subtree",
5390                    responder_class = class.as_str(),
5391                    source = %source,
5392                    challenge_id = challenge.challenge_id,
5393                    request_response = rr_message_id.is_some(),
5394                    dispatch_ms = received_at.elapsed().as_millis(),
5395                    reason = "heavy_pool_cooldown_or_work_budget",
5396                    "Audit responder admission dropped"
5397                );
5398                return Ok(());
5399            };
5400            let admission_global_inflight = guard.global_inflight;
5401            let admission_peer_inflight = guard.peer_inflight;
5402            ctx.audit_responder_metrics.record_admitted(
5403                *source,
5404                admission_global_inflight,
5405                admission_peer_inflight,
5406            );
5407            info!(
5408                target: "ant_node::replication::audit_responder",
5409                event = "admitted",
5410                kind = "subtree",
5411                responder_class = class.as_str(),
5412                source = %source,
5413                challenge_id = challenge.challenge_id,
5414                request_response = rr_message_id.is_some(),
5415                dispatch_ms = received_at.elapsed().as_millis(),
5416                global_inflight = admission_global_inflight,
5417                global_limit = ctx.subtree_round1.max_concurrent,
5418                peer_inflight = admission_peer_inflight,
5419                peer_limit = MAX_SUBTREE_ROUND1_PER_PEER,
5420                "Audit responder request admitted"
5421            );
5422            let bootstrapping = *ctx.is_bootstrapping.read().await;
5423            let storage = Arc::clone(&ctx.storage);
5424            let p2p_node = Arc::clone(&ctx.p2p_node);
5425            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5426            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5427            let source = *source;
5428            let request_id = msg.request_id;
5429            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5430            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5431            let subtree_round1 = ctx.subtree_round1.clone();
5432            ctx.detached_task_tracker.spawn(async move {
5433                let _guard = guard; // global permit + per-peer slot, held until done
5434                let worker_started = Instant::now();
5435                let processing_started = Instant::now();
5436                let storage_commitment_audit::Round1Work {
5437                    response,
5438                    content_bytes,
5439                    corrupt_keys,
5440                } = storage_commitment_audit::handle_subtree_challenge_measured_with_pointers(
5441                    &challenge,
5442                    &storage,
5443                    pointer_store.as_ref(),
5444                    p2p_node.peer_id(),
5445                    bootstrapping,
5446                    Some(&my_commitment_state),
5447                )
5448                .await;
5449                let processing = processing_started.elapsed();
5450                // Committed chunks this proof found rotted go to the chunk store's
5451                // single recheck worker. Queueing never waits, so no number of
5452                // audits over a rotted chunk can pile up cleanup work outside this
5453                // task's admission.
5454                storage.report_corrupt(&corrupt_keys);
5455                // Charge the work actually done, on EVERY outcome.
5456                //
5457                // This used to charge only the `Proof` arm, reasoning that the
5458                // rejecting paths either read nothing or reflected this node's
5459                // own broken storage. The second half of that was wrong: a
5460                // retained commitment containing one unreadable key still costs
5461                // a full run of reads and keyed-BLAKE3 passes over every leaf
5462                // before it, and then rejects. An attacker who finds such a
5463                // commitment could replay subtrees over it indefinitely for
5464                // free. The per-peer cooldown does not catch that either, since
5465                // it is escapable by rotating identity — the responder-wide
5466                // budget is the only bound that applies, so it has to see the
5467                // work. A zero charge is a no-op, so the untouched paths are
5468                // unaffected.
5469                subtree_round1.charge_work(content_bytes).await;
5470                // A round-1 proof authorizes exactly one matching round 2: open a
5471                // single-use session so a slice challenge cannot be served without
5472                // a live round-1 exchange.
5473                let mut response = response;
5474                if let crate::replication::protocol::SubtreeAuditResponse::Proof { .. } = &response
5475                {
5476                    let opened = subtree_round1
5477                        .open_session(
5478                            source,
5479                            challenge.challenge_id,
5480                            challenge.expected_commitment_hash,
5481                            challenge.nonce,
5482                            storage_commitment_audit::pointer_bindings(&response),
5483                        )
5484                        .await;
5485                    // A proof round 2 could not be answered for is not sent.
5486                    // The node says so instead, as for a local read error: the
5487                    // auditor's timeout lane, with no trust penalty, where
5488                    // silence would read as a peer that did not answer
5489                    // (ADR-0019).
5490                    if !opened {
5491                        protocol::record_audit_drop(protocol::AuditDropKind::Subtree);
5492                        warn!(
5493                            target: "ant_node::replication::audit_responder",
5494                            event = "admission_dropped",
5495                            kind = "subtree",
5496                            responder_class = class.as_str(),
5497                            source = %source,
5498                            challenge_id = challenge.challenge_id,
5499                            request_response = rr_message_id.is_some(),
5500                            reason = "pointer_binding_budget",
5501                            "Audit responder admission dropped"
5502                        );
5503                        response = crate::replication::protocol::SubtreeAuditResponse::Rejected {
5504                            challenge_id: challenge.challenge_id,
5505                            kind: protocol::RejectKind::Transient,
5506                            reason: "pointer binding budget full".to_string(),
5507                        };
5508                    }
5509                }
5510                let response_kind = subtree_audit_response_kind(&response);
5511                let work_items = subtree_audit_response_work_items(&response);
5512                let response_send_started = Instant::now();
5513                let sent = send_replication_response_checked(
5514                    &source,
5515                    &p2p_node,
5516                    request_id,
5517                    ReplicationMessageBody::SubtreeAuditResponse(response),
5518                    rr_message_id.as_deref(),
5519                    None,
5520                )
5521                .await;
5522                let response_send = response_send_started.elapsed();
5523                log_audit_responder_completion(
5524                    &responder_metrics,
5525                    source,
5526                    class,
5527                    "subtree",
5528                    challenge.challenge_id,
5529                    work_items,
5530                    response_kind,
5531                    sent,
5532                    received_at,
5533                    worker_started,
5534                    processing,
5535                    response_send,
5536                );
5537            });
5538            Ok(())
5539        }
5540        ReplicationMessageBody::SubtreeSliceChallenge(challenge) => {
5541            // Round 2 of the storage audit (ADR-0002 / V2-685): open one 1 KiB
5542            // block of each auditor-selected spot-check key with a Bao verified
5543            // slice + nonced block-tree opening. Reads chunk bytes from disk to
5544            // build the proofs, so it runs off the serial loop under the light
5545            // audit pool's global and per-peer ceilings.
5546            let class = AuditResponderClass::Byte;
5547            info!(
5548                "Audit challenge received: kind=slice source={source} request_response={}",
5549                rr_message_id.is_some(),
5550            );
5551            let (guard, pointer_bindings) = match admit_slice_challenge(
5552                &ctx.audit_responder_semaphore,
5553                &ctx.audit_responder_inflight,
5554                &ctx.subtree_round1,
5555                source,
5556                &challenge,
5557            )
5558            .await
5559            {
5560                SliceAdmission::Admitted(guard, pointer_bindings) => (guard, pointer_bindings),
5561                SliceAdmission::Capacity(failure) => {
5562                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5563                    audit_metrics::record_admission_drop(class);
5564                    ctx.audit_responder_metrics
5565                        .record_drop(*source, failure.reason.into());
5566                    warn!(
5567                        target: "ant_node::replication::audit_responder",
5568                        event = "admission_dropped",
5569                        kind = "byte",
5570                        responder_class = class.as_str(),
5571                        source = %source,
5572                        challenge_id = challenge.challenge_id,
5573                        key_count = challenge.openings.len(),
5574                        request_response = rr_message_id.is_some(),
5575                        dispatch_ms = received_at.elapsed().as_millis(),
5576                        reason = failure.reason.as_str(),
5577                        global_inflight = failure.global_inflight,
5578                        global_limit = failure.global_limit,
5579                        peer_inflight = failure.peer_inflight,
5580                        peer_limit = failure.peer_limit,
5581                        "Audit responder admission dropped"
5582                    );
5583                    return Ok(());
5584                }
5585                // No live round-1 session: reply with a cheap `Transient` rejection
5586                // rather than dropping silently. Sessions are ephemeral (an honest
5587                // responder that restarts between rounds loses its session), and an
5588                // unanswered `send_request` would make saorsa-core record a
5589                // transport trust failure against that honest responder — an
5590                // ongoing effect, not just a rollout-window one. A `Transient`
5591                // reply routes the auditor to the graced timeout lane (no trust
5592                // penalty; the responder re-earns pinned credit on the next audit)
5593                // and does no chunk work, so it is not a DoS lever.
5594                SliceAdmission::NoSession => {
5595                    protocol::record_audit_drop(protocol::AuditDropKind::Slice);
5596                    debug!(
5597                        "Slice challenge without a live round-1 session source={source} \
5598                         challenge_id={} → Transient reject",
5599                        challenge.challenge_id
5600                    );
5601                    send_replication_response_checked(
5602                        source,
5603                        &ctx.p2p_node,
5604                        msg.request_id,
5605                        ReplicationMessageBody::SubtreeSliceResponse(
5606                            protocol::SubtreeSliceResponse::Rejected {
5607                                challenge_id: challenge.challenge_id,
5608                                kind: protocol::RejectKind::Transient,
5609                                reason: "no live round-1 session".to_string(),
5610                            },
5611                        ),
5612                        rr_message_id,
5613                        None,
5614                    )
5615                    .await;
5616                    return Ok(());
5617                }
5618            };
5619            let admission_global_inflight = guard.global_inflight;
5620            let admission_peer_inflight = guard.peer_inflight;
5621            ctx.audit_responder_metrics.record_admitted(
5622                *source,
5623                admission_global_inflight,
5624                admission_peer_inflight,
5625            );
5626            info!(
5627                target: "ant_node::replication::audit_responder",
5628                event = "admitted",
5629                kind = "byte",
5630                responder_class = class.as_str(),
5631                source = %source,
5632                challenge_id = challenge.challenge_id,
5633                key_count = challenge.openings.len(),
5634                request_response = rr_message_id.is_some(),
5635                dispatch_ms = received_at.elapsed().as_millis(),
5636                global_inflight = admission_global_inflight,
5637                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5638                peer_inflight = admission_peer_inflight,
5639                peer_limit = class.per_peer_limit(),
5640                "Audit responder request admitted"
5641            );
5642            let bootstrapping = *ctx.is_bootstrapping.read().await;
5643            let storage = Arc::clone(&ctx.storage);
5644            let p2p_node = Arc::clone(&ctx.p2p_node);
5645            let my_commitment_state = Arc::clone(&ctx.my_commitment_state);
5646            let pointer_store = ctx.pointers.as_ref().map(|p| p.store().clone());
5647            let source = *source;
5648            let request_id = msg.request_id;
5649            let rr_message_id = rr_message_id.map(ToOwned::to_owned);
5650            let responder_metrics = Arc::clone(&ctx.audit_responder_metrics);
5651            ctx.detached_task_tracker.spawn(async move {
5652                let _guard = guard; // global permit + per-peer slot, held until done
5653                let worker_started = Instant::now();
5654                let processing_started = Instant::now();
5655                let response =
5656                    storage_commitment_audit::handle_subtree_slice_challenge_with_pointer_bindings(
5657                        &challenge,
5658                        &storage,
5659                        pointer_store.as_ref(),
5660                        &pointer_bindings,
5661                        p2p_node.peer_id(),
5662                        bootstrapping,
5663                        Some(&my_commitment_state),
5664                    )
5665                    .await;
5666                let processing = processing_started.elapsed();
5667                let response_kind = subtree_slice_response_kind(&response);
5668                let response_send_started = Instant::now();
5669                let sent = send_replication_response_checked(
5670                    &source,
5671                    &p2p_node,
5672                    request_id,
5673                    ReplicationMessageBody::SubtreeSliceResponse(response),
5674                    rr_message_id.as_deref(),
5675                    None,
5676                )
5677                .await;
5678                let response_send = response_send_started.elapsed();
5679                log_audit_responder_completion(
5680                    &responder_metrics,
5681                    source,
5682                    class,
5683                    "byte",
5684                    challenge.challenge_id,
5685                    challenge.openings.len(),
5686                    response_kind,
5687                    sent,
5688                    received_at,
5689                    worker_started,
5690                    processing,
5691                    response_send,
5692                );
5693            });
5694            Ok(())
5695        }
5696        ReplicationMessageBody::GetCommitmentByPin(ref request) => {
5697            // ADR-0004: answer a commitment-by-pin fetch from the retained set
5698            // only. `lookup_by_hash` is an allocation-light read over the
5699            // bounded slot set; it returns the live current commitment or any
5700            // still-answerable recently-gossiped/quoted one. A miss is reported
5701            // as `NotRetained` (graced, never confirmed) rather than an error,
5702            // so an aged-out pin can never brand an honest node.
5703            //
5704            // Reuse the audit-responder admission guard (global ceiling + per-peer
5705            // cap) so a flood of fetches cannot drive unbounded commitment
5706            // clone/encode/send work; over-limit is dropped, which the fetching
5707            // peer graces exactly like a missed audit response.
5708            let class = AuditResponderClass::CommitmentPin;
5709            let guard = match admit_audit_responder(
5710                &ctx.audit_responder_semaphore,
5711                &ctx.audit_responder_inflight,
5712                source,
5713                class,
5714            )
5715            .await
5716            {
5717                Ok(guard) => guard,
5718                Err(failure) => {
5719                    audit_metrics::record_admission_drop(class);
5720                    ctx.audit_responder_metrics
5721                        .record_drop(*source, failure.reason.into());
5722                    warn!(
5723                        target: "ant_node::replication::audit_responder",
5724                        event = "admission_dropped",
5725                        kind = "commitment_pin",
5726                        responder_class = class.as_str(),
5727                        source = %source,
5728                        challenge_id = msg.request_id,
5729                        request_response = rr_message_id.is_some(),
5730                        dispatch_ms = received_at.elapsed().as_millis(),
5731                        reason = failure.reason.as_str(),
5732                        global_inflight = failure.global_inflight,
5733                        global_limit = failure.global_limit,
5734                        peer_inflight = failure.peer_inflight,
5735                        peer_limit = failure.peer_limit,
5736                        "Audit responder admission dropped"
5737                    );
5738                    return Ok(());
5739                }
5740            };
5741            ctx.audit_responder_metrics.record_admitted(
5742                *source,
5743                guard.global_inflight,
5744                guard.peer_inflight,
5745            );
5746            info!(
5747                target: "ant_node::replication::audit_responder",
5748                event = "admitted",
5749                kind = "commitment_pin",
5750                responder_class = class.as_str(),
5751                source = %source,
5752                challenge_id = msg.request_id,
5753                request_response = rr_message_id.is_some(),
5754                dispatch_ms = received_at.elapsed().as_millis(),
5755                global_inflight = guard.global_inflight,
5756                global_limit = MAX_CONCURRENT_AUDIT_RESPONSES,
5757                peer_inflight = guard.peer_inflight,
5758                peer_limit = class.per_peer_limit(),
5759                "Audit responder request admitted"
5760            );
5761            let worker_started = Instant::now();
5762            let processing_started = Instant::now();
5763            let response = ctx.my_commitment_state.lookup_by_hash(&request.pin).map_or(
5764                protocol::GetCommitmentByPinResponse::NotRetained { pin: request.pin },
5765                |built| protocol::GetCommitmentByPinResponse::Found {
5766                    commitment: built.commitment().clone(),
5767                },
5768            );
5769            let processing = processing_started.elapsed();
5770            let response_kind = commitment_pin_response_kind(&response);
5771            let response_send_started = Instant::now();
5772            let sent = send_replication_response_checked(
5773                source,
5774                &ctx.p2p_node,
5775                msg.request_id,
5776                ReplicationMessageBody::GetCommitmentByPinResponse(response),
5777                rr_message_id,
5778                None,
5779            )
5780            .await;
5781            let response_send = response_send_started.elapsed();
5782            log_audit_responder_completion(
5783                &ctx.audit_responder_metrics,
5784                *source,
5785                class,
5786                "commitment_pin",
5787                msg.request_id,
5788                1,
5789                response_kind,
5790                sent,
5791                received_at,
5792                worker_started,
5793                processing,
5794                response_send,
5795            );
5796            drop(guard);
5797            Ok(())
5798        }
5799        // Pointers (ADR-0016). A node that does not store pointers ignores
5800        // them, and so is never marked capable and never asked anything.
5801        ReplicationMessageBody::PointerFreshOffer(offer) => {
5802            if let Some(pointers) = &ctx.pointers {
5803                pointers.accept_offer_detached(*source, offer);
5804            }
5805            Ok(())
5806        }
5807        ReplicationMessageBody::PointerHints(hints) => {
5808            if let Some(pointers) = &ctx.pointers {
5809                pointers.handle_hints(*source, hints.hints).await;
5810            }
5811            Ok(())
5812        }
5813        ReplicationMessageBody::PointerFetchRequest(request) => {
5814            if let Some(pointers) = &ctx.pointers {
5815                pointers
5816                    .serve_fetch_detached(
5817                        *source,
5818                        request,
5819                        msg.request_id,
5820                        rr_message_id.map(ToOwned::to_owned),
5821                    )
5822                    .await;
5823            }
5824            Ok(())
5825        }
5826        ReplicationMessageBody::PointerStateRequest(request) => {
5827            if let Some(pointers) = &ctx.pointers {
5828                pointers
5829                    .serve_state_detached(
5830                        *source,
5831                        request,
5832                        msg.request_id,
5833                        rr_message_id.map(ToOwned::to_owned),
5834                    )
5835                    .await;
5836            }
5837            Ok(())
5838        }
5839        // Response messages are handled by their respective request initiators.
5840        ReplicationMessageBody::FreshReplicationResponse(_)
5841        | ReplicationMessageBody::NeighborSyncResponse(_)
5842        | ReplicationMessageBody::VerificationResponse(_)
5843        | ReplicationMessageBody::FetchResponse(_)
5844        | ReplicationMessageBody::AuditResponse(_)
5845        | ReplicationMessageBody::SubtreeAuditResponse(_)
5846        | ReplicationMessageBody::SubtreeSliceResponse(_)
5847        | ReplicationMessageBody::GetCommitmentByPinResponse(_)
5848        | ReplicationMessageBody::PointerFetchResponse(_)
5849        | ReplicationMessageBody::PointerStateResponse(_) => Ok(()),
5850    }
5851}
5852
5853// ---------------------------------------------------------------------------
5854// Per-message-type handlers
5855// ---------------------------------------------------------------------------
5856
5857/// Verify a payment proof, yielding early if the engine is shutting down.
5858///
5859/// Returns `None` when shutdown won the race, meaning no verdict was reached
5860/// and the caller must abandon the message without storing or penalising.
5861///
5862/// Payment verification is pure network I/O — an EVM round trip and, on the
5863/// merkle path, an iterative Kademlia lookup bounded only by the verifier's
5864/// own `CLOSENESS_LOOKUP_TIMEOUT`. Racing it against the shutdown token is
5865/// what keeps `ReplicationEngine::shutdown()`'s deliberately unbounded
5866/// `detached_task_tracker.wait()` finite: the wait may block only on work that
5867/// is guaranteed to end.
5868///
5869/// Deliberately NOT applied to `storage.put`: that awaits `spawn_blocking`, so
5870/// dropping its awaiter would detach a live LMDB transaction and break the
5871/// very contract the unbounded wait exists to uphold.
5872async fn verify_payment_until_shutdown(
5873    payment_verifier: &Arc<PaymentVerifier>,
5874    key: &XorName,
5875    proof_of_payment: &[u8],
5876    context: VerificationContext,
5877    shutdown: &CancellationToken,
5878) -> Option<Result<crate::payment::PaymentStatus>> {
5879    tokio::select! {
5880        () = shutdown.cancelled() => None,
5881        result = payment_verifier.verify_payment(key, Some(proof_of_payment), context) => {
5882            Some(result)
5883        }
5884    }
5885}
5886
5887/// A fresh offer rejected on payload shape alone.
5888struct FreshOfferRejection {
5889    /// Wire-visible reason returned to the sender.
5890    reason: String,
5891    /// Whether the sender is charged for it. Reserved for offers no honest
5892    /// node would construct, so an ordinary capacity refusal stays free.
5893    penalise: bool,
5894}
5895
5896/// Reject a fresh offer on payload shape, or return `None` to admit it.
5897///
5898/// Pure and non-blocking by construction: these are the checks answerable from
5899/// the payload alone, run on the serial message loop *before* the in-flight
5900/// claim and the admission permit, so a malformed offer can neither lock an
5901/// honest offer out of its key nor occupy one of the scarce
5902/// [`FRESH_OFFER_MAX_OUTSTANDING`] slots for the duration of a payment
5903/// verification. Anything needing I/O — routing lookups, capacity checks, proof
5904/// verification — stays on the worker.
5905///
5906/// The content-address hash is deliberately included despite costing real CPU
5907/// on the loop: it is what makes the entry below *earned* rather than merely
5908/// asserted. Its cost is self-limiting — BLAKE3 runs at GB/s while offers
5909/// arrive at link speed, so a flooder can never make this loop hash faster than
5910/// it can deliver the bytes, and delivering them already cost it more than the
5911/// hash costs us. The receive path has in any case already deserialised the
5912/// same buffer.
5913///
5914/// Every rejection here is penalised. These are the conditions no honest sender
5915/// can produce — an absent, undersized, oversized, or non-matching payload — as
5916/// distinct from a capacity refusal, which is this node's own state and stays
5917/// free. Payment *outcomes* are deliberately not judged here or anywhere: a
5918/// proof that fails to verify may simply have been read against a lagging chain
5919/// view, and penalising that would charge honest senders in correlated bursts.
5920fn fresh_offer_structural_rejection(
5921    key: &XorName,
5922    data: &[u8],
5923    proof_of_payment: &[u8],
5924) -> Option<FreshOfferRejection> {
5925    // Rule 5: reject if PoP is missing. An honest sender always attaches one,
5926    // and an absent proof is the cheapest possible slot-filler, so this is the
5927    // first thing checked.
5928    if proof_of_payment.is_empty() {
5929        return Some(FreshOfferRejection {
5930            reason: "Missing proof of payment".to_string(),
5931            penalise: true,
5932        });
5933    }
5934
5935    // Bound the proof before it can be queued. The verifier applies the same
5936    // limits, but only once the offer reaches a worker — too late here, because
5937    // an entry retains a proof per queued sender, and a proof is capped on the
5938    // wire only by MAX_REPLICATION_MESSAGE_SIZE. Without this an offer carrying
5939    // a byte of data and a 10 MiB "proof" would be admitted, and
5940    // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY of them per key across
5941    // FRESH_OFFER_MAX_OUTSTANDING keys would dwarf the payload ceiling the
5942    // admission bound exists to enforce.
5943    if proof_of_payment.len() < MIN_PAYMENT_PROOF_SIZE_BYTES {
5944        return Some(FreshOfferRejection {
5945            reason: format!(
5946                "Proof of payment {} is below the minimum {MIN_PAYMENT_PROOF_SIZE_BYTES} bytes",
5947                proof_of_payment.len(),
5948            ),
5949            penalise: true,
5950        });
5951    }
5952    if proof_of_payment.len() > MAX_PAYMENT_PROOF_SIZE_BYTES {
5953        return Some(FreshOfferRejection {
5954            reason: format!(
5955                "Proof of payment {} exceeds the maximum {MAX_PAYMENT_PROOF_SIZE_BYTES} bytes",
5956                proof_of_payment.len(),
5957            ),
5958            penalise: true,
5959        });
5960    }
5961
5962    // Enforce chunk size invariant: the normal PUT path rejects data larger
5963    // than MAX_CHUNK_SIZE; the replication receive path must do the same to
5964    // prevent peers from pushing oversized records through replication.
5965    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
5966        return Some(FreshOfferRejection {
5967            reason: format!(
5968                "Data size {} exceeds maximum chunk size {}",
5969                data.len(),
5970                crate::ant_protocol::MAX_CHUNK_SIZE,
5971            ),
5972            penalise: true,
5973        });
5974    }
5975
5976    // Mirror the normal PUT path: the advertised key must be the content
5977    // address of the supplied bytes. Ordered last so an oversized payload is
5978    // refused without being hashed.
5979    //
5980    // This is the check that makes the entry safe to open, and safe for later
5981    // offers to be folded into. Until it passes, the sender has only *asserted*
5982    // an association between the key and the bytes. Opening an entry on an
5983    // assertion would let any peer that knows a key — every recipient of its
5984    // `PaidNotify`, not just the close group — seize it with junk; folding a
5985    // later offer into an entry on an assertion would be worse still, since the
5986    // handler tries each queued proof against the *opener's* bytes and would be
5987    // storing bytes nobody offered for that proof.
5988    let computed_key = crate::client::compute_address(data);
5989    if computed_key != *key {
5990        return Some(FreshOfferRejection {
5991            reason: format!(
5992                "Content address mismatch: expected {}, computed {}",
5993                hex::encode(key),
5994                hex::encode(computed_key),
5995            ),
5996            penalise: true,
5997        });
5998    }
5999
6000    None
6001}
6002
6003/// Tell `source` its offer for `key` was not taken.
6004///
6005/// Note the sender does not currently read this: `fresh::send_fresh_offers` uses
6006/// one-way `send_message`, so the refusal is observed only as a later absence by
6007/// the delayed possession check. Recorded in ADR-0005 as a known gap.
6008async fn refuse_fresh_offer(
6009    source: &PeerId,
6010    key: XorName,
6011    reason: String,
6012    ctx: &ReplicationMessageHandlerContext,
6013    request_id: u64,
6014    rr_message_id: Option<&str>,
6015) {
6016    send_replication_response(
6017        source,
6018        &ctx.p2p_node,
6019        request_id,
6020        ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6021            key,
6022            reason,
6023        }),
6024        rr_message_id,
6025    )
6026    .await;
6027}
6028
6029/// Refuse an offer that failed [`fresh_offer_structural_rejection`], charging
6030/// the sender when the defect is one no honest node could produce.
6031///
6032/// Kept apart from the capacity refusal in `dispatch_fresh_offer` because the
6033/// two say opposite things: this is the sender's fault, that one is ours.
6034async fn refuse_malformed_fresh_offer(
6035    source: &PeerId,
6036    key: XorName,
6037    rejection: FreshOfferRejection,
6038    ctx: &ReplicationMessageHandlerContext,
6039    request_id: u64,
6040    rr_message_id: Option<&str>,
6041) {
6042    if rejection.penalise {
6043        warn!(
6044            "Rejecting fresh offer for key {} from {source}: {}",
6045            hex::encode(key),
6046            rejection.reason
6047        );
6048        ctx.p2p_node
6049            .report_trust_event(
6050                source,
6051                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6052            )
6053            .await;
6054    } else {
6055        debug!(
6056            "Fresh offer for {} from {source} refused before admission: {}",
6057            hex::encode(key),
6058            rejection.reason
6059        );
6060    }
6061    refuse_fresh_offer(
6062        source,
6063        key,
6064        rejection.reason,
6065        ctx,
6066        request_id,
6067        rr_message_id,
6068    )
6069    .await;
6070}
6071
6072/// Tell senders whose proofs joined an entry that was torn down before a handler
6073/// ever ran for it.
6074///
6075/// Only reachable in the window between opening an entry and failing to take an
6076/// admission permit. Their proofs are answered rather than dropped with the
6077/// entry, so the refusal count reflects what actually happened.
6078async fn refuse_stranded_fresh_offers(
6079    key: XorName,
6080    stranded: Vec<FreshOfferAttempt>,
6081    ctx: &ReplicationMessageHandlerContext,
6082) {
6083    for attempt in stranded {
6084        refuse_fresh_offer(
6085            &attempt.source,
6086            key,
6087            "Receiver at fresh-offer capacity".to_string(),
6088            ctx,
6089            attempt.request_id,
6090            attempt.rr_message_id.as_deref(),
6091        )
6092        .await;
6093    }
6094}
6095
6096/// Admit a fresh offer for handling on a worker, or refuse it.
6097///
6098/// This runs on the serial non-audit message loop, so it must stay cheap: every
6099/// path here is a set insert, a permit try, or a small response send. The offer
6100/// itself — an on-chain payment verification and a multi-MiB LMDB write — always
6101/// runs on a tracked worker task, never inline, because stalling this loop backs
6102/// up the inbound queue and ultimately drops replication messages wholesale.
6103///
6104/// Admission is bounded **per source** as well as globally
6105/// ([`FRESH_OFFER_MAX_OUTSTANDING_PER_PEER`]). Without that share one peer can
6106/// hold every slot, and since a refusal is later read as absence by the
6107/// sender's delayed possession check, the resulting refusals land as
6108/// audit-severity penalties on this node rather than on the flooder.
6109///
6110/// The structurally-invalid checks run **before** the entry is opened and before
6111/// the permit is taken, so junk can neither seize a key nor occupy a slot for
6112/// the duration of a payment verification.
6113///
6114/// Only the offer that *opens* an entry costs a permit and a worker. Later
6115/// offers for the same key contribute their proof and are answered by whatever
6116/// the opener's handler concludes, which is what keeps the routine
6117/// `CLOSE_GROUP_MAJORITY`-way duplication of a client PUT down to one permit and
6118/// one verification per key.
6119async fn dispatch_fresh_offer(
6120    source: PeerId,
6121    offer: protocol::FreshReplicationOffer,
6122    ctx: &ReplicationMessageHandlerContext,
6123    request_id: u64,
6124    received_at: Instant,
6125    rr_message_id: Option<&str>,
6126) -> Result<()> {
6127    if let Some(rejection) =
6128        fresh_offer_structural_rejection(&offer.key, &offer.data, &offer.proof_of_payment)
6129    {
6130        refuse_malformed_fresh_offer(
6131            &source,
6132            offer.key,
6133            rejection,
6134            ctx,
6135            request_id,
6136            rr_message_id,
6137        )
6138        .await;
6139        return Ok(());
6140    }
6141
6142    // Join the work already in flight for this key before taking an admission
6143    // permit, so the duplicates a single client PUT produces cost one permit
6144    // between them rather than one each.
6145    //
6146    // Reaching this point means `fresh_offer_structural_rejection` has confirmed
6147    // `key == BLAKE3(data)`, so this offer's bytes are provably identical to any
6148    // already held for the key. That is what lets its payload be dropped here
6149    // and only its proof retained: the handler will try that proof against the
6150    // bytes it already has.
6151    let key = offer.key;
6152    let admission_outcome = FreshOfferEntryGuard::admit(
6153        &ctx.fresh_offer_in_flight,
6154        offer,
6155        source,
6156        request_id,
6157        rr_message_id.map(ToOwned::to_owned),
6158        received_at,
6159    );
6160    let mut entry = match admission_outcome {
6161        FreshOfferAdmission::Opened(entry) => entry,
6162        FreshOfferAdmission::Joined => {
6163            // No response yet: this proof has not been judged. The handler that
6164            // owns the key answers every queued sender once it settles.
6165            debug!(
6166                "Fresh offer for {} from {source} queued behind the handler already \
6167                 holding the key",
6168                hex::encode(key)
6169            );
6170            return Ok(());
6171        }
6172        // Surplus, not suspect: the proofs already queued are enough to place
6173        // the record, so neither case is charged as misbehaviour.
6174        surplus => {
6175            debug!(
6176                "Fresh offer for {} from {source} refused: {}",
6177                hex::encode(key),
6178                surplus.surplus_reason()
6179            );
6180            refuse_fresh_offer(
6181                &source,
6182                key,
6183                "Duplicate offer already in flight".to_string(),
6184                ctx,
6185                request_id,
6186                rr_message_id,
6187            )
6188            .await;
6189            return Ok(());
6190        }
6191    };
6192
6193    let admission = match admit_bounded_responder(
6194        &ctx.fresh_offer_admission_semaphore,
6195        &ctx.fresh_offer_responder_inflight,
6196        &source,
6197        FRESH_OFFER_MAX_OUTSTANDING,
6198        FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
6199    )
6200    .await
6201    {
6202        Ok(guard) => guard,
6203        Err(failure) => {
6204            audit_metrics::record_responder_admission_drop(
6205                ReplicationResponderClass::FreshOffer,
6206                failure.reason.into(),
6207            );
6208            // WARN, not DEBUG: a healthy node should never refuse a legitimate
6209            // fresh offer. The sender does not read this refusal, so it
6210            // resurfaces as a missing key at the delayed possession check and
6211            // is charged to US at audit severity. Log the binding ceiling
6212            // locally; the wire reason stays generic so a probing peer cannot
6213            // map out this node's live occupancy.
6214            warn!(
6215                responder_class = "fresh_offer",
6216                source = %source,
6217                key = %hex::encode(key),
6218                penalty_suspended = config::close_group_storage_penalty_suspended(),
6219                "Fresh offer refused at admission; the resulting absence is recorded \
6220                 against this node, and penalised unless the release withholds it: \
6221                 {failure}"
6222            );
6223            // Release the key explicitly rather than on drop, so the next offer
6224            // opens a fresh entry rather than queueing behind a handler that was
6225            // never spawned — and so any proof that joined in the window between
6226            // opening the entry and failing here is answered rather than
6227            // discarded with it.
6228            let stranded = entry.release();
6229            refuse_fresh_offer(
6230                &source,
6231                key,
6232                "Receiver at fresh-offer capacity".to_string(),
6233                ctx,
6234                request_id,
6235                rr_message_id,
6236            )
6237            .await;
6238            refuse_stranded_fresh_offers(key, stranded, ctx).await;
6239            return Ok(());
6240        }
6241    };
6242
6243    let ctx = ctx.clone();
6244    // Track the worker so `ReplicationEngine::shutdown()` can await it: it holds
6245    // an `Arc<ChunkStore>` while writing, and the shutdown contract requires
6246    // those references be released before the caller reopens the environment.
6247    ctx.detached_task_tracker
6248        .clone()
6249        .spawn(run_fresh_offer_worker(key, entry, ctx, admission));
6250    Ok(())
6251}
6252
6253/// Body of one tracked fresh-offer worker: drive one key to a verdict.
6254///
6255/// Split out so `dispatch_fresh_offer` stays a readable admission decision.
6256/// A started handler is never cancelled: `storage.put()` awaits
6257/// `spawn_blocking`, and dropping that awaiter would detach the live LMDB
6258/// transaction. Shutdown responsiveness comes from the closed worker semaphore
6259/// and from `handle_fresh_offer` racing the token around payment verification.
6260///
6261/// Works down the key's queued proofs rather than judging the key on the first
6262/// one. A proof that fails to establish payment disqualifies its *sender*, not
6263/// the record: the bytes are content-addressed and identical across every offer,
6264/// so the next sender's proof is tried against the copy already in hand — no
6265/// second payload, no second permit, no refetch. Only when a failure is about
6266/// the key itself (not responsible, no capacity, shutting down) does rotating
6267/// become pointless, because every remaining proof would meet the same wall.
6268async fn run_fresh_offer_worker(
6269    key: XorName,
6270    mut entry: Box<FreshOfferEntryGuard>,
6271    ctx: ReplicationMessageHandlerContext,
6272    admission: ResponderGuard,
6273) {
6274    // The admission permit is released on completion, freeing the payload's
6275    // memory budget and the opening source's per-peer share. The entry releases
6276    // the key itself, either as the queue empties or on drop.
6277    let _admission = admission;
6278    let received_at = entry.received_at();
6279    // Wait for a worker slot here rather than in the caller. The worker bound
6280    // caps concurrent EVM and storage pressure; making the message loop wait on
6281    // it is what put that pressure back on the loop.
6282    //
6283    // The semaphore is closed by `shutdown()`, so this arm is the prompt exit
6284    // path for offers still queued behind a worker when the engine stops — not
6285    // dead code.
6286    let Ok(_worker) = Arc::clone(&ctx.fresh_offer_worker_semaphore)
6287        .acquire_owned()
6288        .await
6289    else {
6290        debug!(
6291            "Fresh offer for {} dropped: worker pool shut down",
6292            hex::encode(key)
6293        );
6294        return;
6295    };
6296    // Fresh offers are fire-and-forget (`send_message`), so there is no
6297    // requester deadline to honour and a late store is still genuinely useful.
6298    // The threshold is the point past which the offer has already cost us what
6299    // it was going to cost: the possession check (ADR-0003) has run by then and
6300    // charged the absence to this node, and it does not re-offer the key —
6301    // repair comes later from neighbor sync. Shedding here trades a copy that
6302    // would have arrived after the penalty for the multi-MiB payload it is
6303    // holding, and keeps a backlog from outliving its own admission bound.
6304    //
6305    // Note this is a memory-pressure decision, not a redundancy one: the copy
6306    // is late, not useless, so on a node with headroom finishing it would still
6307    // beat waiting for neighbor sync.
6308    if request_is_stale(received_at, ctx.config.possession_check_delay_min) {
6309        debug!(
6310            responder_class = "fresh_offer",
6311            key = %hex::encode(key),
6312            request_age_ms = received_at.elapsed().as_millis(),
6313            "Superseded fresh offer shed at dequeue"
6314        );
6315        return;
6316    }
6317
6318    let mut verdict = FreshOfferOutcome::Abandoned;
6319    while let Some(attempt) = entry.next_attempt() {
6320        match handle_fresh_offer(&key, entry.data(), &attempt, &ctx).await {
6321            Ok(outcome) => {
6322                verdict = outcome;
6323                match outcome {
6324                    // Settled: the record is down and every remaining sender
6325                    // wanted exactly that. Abandoned: the key cannot be placed
6326                    // by anyone right now, so the proofs behind this one would
6327                    // fail identically. Either way there is nothing left to try.
6328                    FreshOfferOutcome::Settled | FreshOfferOutcome::Abandoned => break,
6329                    // This sender's claim to have paid did not hold up. Say so
6330                    // to that sender alone and try the next proof.
6331                    FreshOfferOutcome::ProofRejected => {}
6332                }
6333            }
6334            Err(e) => {
6335                debug!(
6336                    "Fresh replication offer for {} from {} error: {e}",
6337                    hex::encode(key),
6338                    attempt.source
6339                );
6340                verdict = FreshOfferOutcome::Abandoned;
6341                break;
6342            }
6343        }
6344    }
6345
6346    // Answer the senders whose proofs were never reached. A stored record is
6347    // what they were asking for, so it is an acceptance even though their own
6348    // proof went untested.
6349    let unreached = entry.release();
6350    if unreached.is_empty() {
6351        return;
6352    }
6353    let response = match verdict {
6354        FreshOfferOutcome::Settled => FreshReplicationResponse::Accepted { key },
6355        FreshOfferOutcome::ProofRejected | FreshOfferOutcome::Abandoned => {
6356            FreshReplicationResponse::Rejected {
6357                key,
6358                reason: "Record could not be stored from any offered proof".to_string(),
6359            }
6360        }
6361    };
6362    for attempt in unreached {
6363        send_replication_response(
6364            &attempt.source,
6365            &ctx.p2p_node,
6366            attempt.request_id,
6367            ReplicationMessageBody::FreshReplicationResponse(response.clone()),
6368            attempt.rr_message_id.as_deref(),
6369        )
6370        .await;
6371    }
6372}
6373
6374/// What one proof concluded, and whether another proof for the same key is worth
6375/// trying.
6376///
6377/// The distinction the worker acts on is *what the failure was about*. A
6378/// rejected proof is a statement about its sender; anything else is a statement
6379/// about the key or this node, which no other sender's proof can change.
6380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6381enum FreshOfferOutcome {
6382    /// The record is stored. The key is done.
6383    Settled,
6384    /// This proof did not establish payment. A different sender's proof for the
6385    /// same bytes may still succeed.
6386    ProofRejected,
6387    /// Nothing about this key can succeed right now — not responsible, no disk,
6388    /// shutting down, or a write that failed. Rotating repeats the failure.
6389    Abandoned,
6390}
6391
6392// A linear sequence of protocol steps — structural recheck, responsibility,
6393// capacity, payment, write — each with its own refusal response. Splitting it
6394// would scatter one decision across several functions.
6395#[allow(clippy::too_many_lines)]
6396async fn handle_fresh_offer(
6397    key: &XorName,
6398    data: &[u8],
6399    attempt: &FreshOfferAttempt,
6400    ctx: &ReplicationMessageHandlerContext,
6401) -> Result<FreshOfferOutcome> {
6402    let source = &attempt.source;
6403    let request_id = attempt.request_id;
6404    let rr_message_id = attempt.rr_message_id.as_deref();
6405    let p2p_node = &ctx.p2p_node;
6406    let config = &ctx.config;
6407    let self_id = *p2p_node.peer_id();
6408
6409    // Defence in depth: `dispatch_fresh_offer` already applied these — missing
6410    // proof, bad proof size, oversized payload, content-address mismatch —
6411    // before opening the entry or taking an admission permit, so nothing
6412    // reaching a worker should trip them. Kept so the handler is correct in
6413    // isolation. Note this re-checks the *pairing* actually being used: these
6414    // bytes against this attempt's proof.
6415    if let Some(rejection) = fresh_offer_structural_rejection(key, data, &attempt.proof_of_payment)
6416    {
6417        if rejection.penalise {
6418            warn!(
6419                "Rejecting fresh offer for key {}: {}",
6420                hex::encode(key),
6421                rejection.reason
6422            );
6423            p2p_node
6424                .report_trust_event(
6425                    source,
6426                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
6427                )
6428                .await;
6429        }
6430        send_replication_response(
6431            source,
6432            p2p_node,
6433            request_id,
6434            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6435                key: *key,
6436                reason: rejection.reason,
6437            }),
6438            rr_message_id,
6439        )
6440        .await;
6441        // Structurally invalid is a fact about this attempt, not the key.
6442        return Ok(FreshOfferOutcome::ProofRejected);
6443    }
6444
6445    // Rule 7: check storage admission. Fresh chunk receivers accept across the
6446    // paid-close-group neighbourhood (`paid_list_close_group_size`, = K_BUCKET_SIZE,
6447    // the same width client PUTs use), not just the close group plus a small
6448    // margin (ADR-0003). During full-node shunning a healthy replica's routing
6449    // table may still list closer full nodes it hasn't evicted yet, ranking it
6450    // outside the narrow window in its own view; the wider accept window absorbs
6451    // that transient skew so the chunk still lands. Retention (pruning) stays at
6452    // `storage_admission_width`, so steady-state replication is unchanged.
6453    if !admission::is_responsible(&self_id, key, p2p_node, config.paid_list_close_group_size).await
6454    {
6455        send_replication_response(
6456            source,
6457            p2p_node,
6458            request_id,
6459            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6460                key: *key,
6461                reason: "Not in storage-admission range for this key".to_string(),
6462            }),
6463            rr_message_id,
6464        )
6465        .await;
6466        // About the key and this node's place in the routing table, not about
6467        // the sender: every queued proof would be refused identically.
6468        return Ok(FreshOfferOutcome::Abandoned);
6469    }
6470
6471    // Disk-space pre-check — mirror the PUT handler (V2-411). A full node can
6472    // never store this record, so reject it before the expensive payment
6473    // verification (EVM on-chain query / merkle pool work) rather than verifying
6474    // and only then failing at `storage.put` below. Reuses the cached capacity
6475    // check (passing results only, so freed space is detected promptly), and the
6476    // store path keeps its own check as defence-in-depth.
6477    if let Err(e) = ctx.storage.check_capacity() {
6478        info!(
6479            target: "ant_node::storage::disk_precheck",
6480            key = %hex::encode(key),
6481            "Rejecting fresh replication offer before payment verification: {e}"
6482        );
6483        send_replication_response(
6484            source,
6485            p2p_node,
6486            request_id,
6487            ReplicationMessageBody::FreshReplicationResponse(FreshReplicationResponse::Rejected {
6488                key: *key,
6489                reason: e.to_string(),
6490            }),
6491            rr_message_id,
6492        )
6493        .await;
6494        // A full disk is this node's condition, not the sender's.
6495        return Ok(FreshOfferOutcome::Abandoned);
6496    }
6497
6498    // Gap 1: Validate PoP via PaymentVerifier. Fresh replication is still
6499    // part of the immediate write fan-out: this receiver is about to store the
6500    // record as if the client had PUT it here directly. Storage admission
6501    // was checked above before proof work. FreshReplication verification is
6502    // identical to ClientPut — store-strength cache semantics, paid-quote
6503    // issuer K-closeness checks for single-node proofs, merkle candidate
6504    // closeness for merkle proofs, and the same price-floor policy — the
6505    // distinct context only labels price-floor telemetry.
6506    let Some(verification) = verify_payment_until_shutdown(
6507        &ctx.payment_verifier,
6508        key,
6509        &attempt.proof_of_payment,
6510        fresh_offer_payment_context(),
6511        &ctx.shutdown,
6512    )
6513    .await
6514    else {
6515        debug!(
6516            "Fresh offer for {} from {source} abandoned: engine shutting down \
6517             during payment verification",
6518            hex::encode(key)
6519        );
6520        return Ok(FreshOfferOutcome::Abandoned);
6521    };
6522    match verification {
6523        Ok(status) if status.can_store() => {
6524            debug!("PoP validated for fresh offer key {}", hex::encode(key));
6525        }
6526        // The chain has no record of this payment. That is a statement about
6527        // *this sender's* proof, so the key rotates to the next one rather than
6528        // being written off — the whole point of queueing them.
6529        //
6530        // Deliberately unpenalised. `PaymentRequired` means "no payment found",
6531        // not "definitively unpaid", so a lagging or reorganising chain view
6532        // renders honest senders indistinguishable from forgers, and penalising
6533        // would land on the entire close group at once. The structural checks in
6534        // `fresh_offer_structural_rejection` are where misbehaviour is charged,
6535        // because those cannot be produced by an honest sender at all.
6536        Ok(_) => {
6537            debug!(
6538                "Fresh offer for {} from {source}: no payment found for this proof",
6539                hex::encode(key)
6540            );
6541            send_replication_response(
6542                source,
6543                p2p_node,
6544                request_id,
6545                ReplicationMessageBody::FreshReplicationResponse(
6546                    FreshReplicationResponse::Rejected {
6547                        key: *key,
6548                        reason: "Payment verification failed: payment required".to_string(),
6549                    },
6550                ),
6551                rr_message_id,
6552            )
6553            .await;
6554            return Ok(FreshOfferOutcome::ProofRejected);
6555        }
6556        // A verification *error* is usually ours — an unreachable or failing EVM
6557        // endpoint — so it is neither penalised nor treated as this sender's
6558        // fault. Another proof still gets its turn, since the next call may well
6559        // succeed against a recovered endpoint.
6560        Err(e) => {
6561            warn!("PoP verification error for key {}: {e}", hex::encode(key));
6562            send_replication_response(
6563                source,
6564                p2p_node,
6565                request_id,
6566                ReplicationMessageBody::FreshReplicationResponse(
6567                    FreshReplicationResponse::Rejected {
6568                        key: *key,
6569                        reason: format!("Payment verification error: {e}"),
6570                    },
6571                ),
6572                rr_message_id,
6573            )
6574            .await;
6575            return Ok(FreshOfferOutcome::ProofRejected);
6576        }
6577    }
6578
6579    // Rule 6: add to PaidForList.
6580    if let Err(e) = ctx.paid_list.insert(key).await {
6581        warn!("Failed to add key to PaidForList: {e}");
6582    }
6583
6584    // Store the record.
6585    match ctx.storage.put(key, data).await {
6586        Ok(_) => {
6587            send_replication_response(
6588                source,
6589                p2p_node,
6590                request_id,
6591                ReplicationMessageBody::FreshReplicationResponse(
6592                    FreshReplicationResponse::Accepted { key: *key },
6593                ),
6594                rr_message_id,
6595            )
6596            .await;
6597            Ok(FreshOfferOutcome::Settled)
6598        }
6599        Err(e) => {
6600            send_replication_response(
6601                source,
6602                p2p_node,
6603                request_id,
6604                ReplicationMessageBody::FreshReplicationResponse(
6605                    FreshReplicationResponse::Rejected {
6606                        key: *key,
6607                        reason: e.to_string(),
6608                    },
6609                ),
6610                rr_message_id,
6611            )
6612            .await;
6613            // The payment was good and the write still failed, so this is local
6614            // storage trouble that another proof cannot get around.
6615            Ok(FreshOfferOutcome::Abandoned)
6616        }
6617    }
6618}
6619
6620/// Admit a paid-list notification for handling on a worker, or drop it.
6621///
6622/// `PaidNotify` used to be handled inline on the serial non-audit loop, which
6623/// meant one message could park every other non-audit message behind a full
6624/// payment verification. That verification is not a bounded local computation:
6625/// on the merkle path it performs an iterative Kademlia lookup capped only by
6626/// the verifier's `CLOSENESS_LOOKUP_TIMEOUT`, so a single notify could stall
6627/// the loop for minutes while the bounded inbound queue behind it overflowed
6628/// and dropped unrelated replication traffic wholesale.
6629///
6630/// It now follows the same detached-responder pattern as neighbor sync and
6631/// verification (ADR-0005 decision 2): bounded globally and per source, shed
6632/// when stale, and run on a tracked worker.
6633///
6634/// `PaidNotify` is one-way — the protocol defines no response variant — so a
6635/// refused notify is simply dropped. The sender's own paid-list convergence
6636/// (periodic neighbor sync and the verification cycle's paid-list quorum) is
6637/// the recovery path, exactly as for a notify lost in transit.
6638async fn dispatch_paid_notify(
6639    source: PeerId,
6640    notify: protocol::PaidNotify,
6641    ctx: &ReplicationMessageHandlerContext,
6642    received_at: Instant,
6643) -> Result<()> {
6644    let admission = match admit_bounded_responder(
6645        &ctx.paid_notify_admission_semaphore,
6646        &ctx.paid_notify_responder_inflight,
6647        &source,
6648        PAID_NOTIFY_MAX_OUTSTANDING,
6649        PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
6650    )
6651    .await
6652    {
6653        Ok(guard) => guard,
6654        Err(failure) => {
6655            audit_metrics::record_responder_admission_drop(
6656                ReplicationResponderClass::PaidNotify,
6657                failure.reason.into(),
6658            );
6659            // WARN for the same reason as fresh offers: PaidNotify is one-way,
6660            // so a refusal discards durable paid-list evidence outright rather
6661            // than pushing work back onto a requester.
6662            warn!(
6663                responder_class = "paid_notify",
6664                source = %source,
6665                key = %hex::encode(notify.key),
6666                "Paid notify dropped at admission — paid-list evidence lost                  until a verification cycle re-derives it: {failure}"
6667            );
6668            return Ok(());
6669        }
6670    };
6671
6672    let ctx = ctx.clone();
6673    let worker_semaphore = Arc::clone(&ctx.paid_notify_worker_semaphore);
6674    // Deliberately NOT the verification request deadline used by the
6675    // request/response responders. Nobody is waiting on a notify, and shedding
6676    // one discards durable paid-list evidence rather than a reply a requester
6677    // has already given up on. The threshold is instead the point at which the
6678    // pull path would have learned the same fact anyway: one slow-cadence
6679    // neighbor-sync interval, after which the verification cycle's paid-list
6680    // quorum makes this notify genuinely redundant.
6681    let queue_max_age = ctx.config.neighbor_sync_interval_max;
6682    ctx.detached_task_tracker.clone().spawn(async move {
6683        let _admission = admission;
6684        // Closed by `shutdown()`, so this is the prompt exit path for notifies
6685        // still queued behind a worker when the engine stops.
6686        let Ok(_worker) = worker_semaphore.acquire_owned().await else {
6687            debug!("Paid notify from {source} dropped: worker pool shut down");
6688            return;
6689        };
6690        if request_is_stale(received_at, queue_max_age) {
6691            debug!(
6692                responder_class = "paid_notify",
6693                source = %source,
6694                request_age_ms = received_at.elapsed().as_millis(),
6695                "Redundant paid notify shed at dequeue"
6696            );
6697            return;
6698        }
6699        if let Err(e) = handle_paid_notify(
6700            &source,
6701            &notify,
6702            &ctx.paid_list,
6703            &ctx.payment_verifier,
6704            &ctx.p2p_node,
6705            &ctx.config,
6706            &ctx.shutdown,
6707        )
6708        .await
6709        {
6710            debug!("Paid notify from {source} error: {e}");
6711        }
6712    });
6713
6714    Ok(())
6715}
6716
6717async fn handle_paid_notify(
6718    _source: &PeerId,
6719    notify: &protocol::PaidNotify,
6720    paid_list: &Arc<PaidList>,
6721    payment_verifier: &Arc<PaymentVerifier>,
6722    p2p_node: &Arc<P2PNode>,
6723    config: &ReplicationConfig,
6724    shutdown: &CancellationToken,
6725) -> Result<()> {
6726    let self_id = *p2p_node.peer_id();
6727
6728    // Rule 3: validate PoP presence before adding.
6729    if notify.proof_of_payment.is_empty() {
6730        return Ok(());
6731    }
6732
6733    // Check if we're in PaidCloseGroup for this key.
6734    if !admission::is_in_paid_close_group(
6735        &self_id,
6736        &notify.key,
6737        p2p_node,
6738        config.paid_list_close_group_size,
6739    )
6740    .await
6741    {
6742        return Ok(());
6743    }
6744
6745    // Gap 1: Validate PoP via PaymentVerifier. PaidNotify admits fresh
6746    // paid-list metadata, so local paid-list close-group membership was checked
6747    // above before proof work. The verifier then runs the same payment proof
6748    // checks as ClientPut while writing a paid-list-strength cache entry.
6749    let Some(verification) = verify_payment_until_shutdown(
6750        payment_verifier,
6751        &notify.key,
6752        &notify.proof_of_payment,
6753        paid_notify_payment_context(),
6754        shutdown,
6755    )
6756    .await
6757    else {
6758        debug!(
6759            "Paid notify for {} abandoned: engine shutting down during payment \
6760             verification",
6761            hex::encode(notify.key)
6762        );
6763        return Ok(());
6764    };
6765    match verification {
6766        Ok(status) if status.can_store() => {
6767            debug!(
6768                "PoP validated for paid notify key {}",
6769                hex::encode(notify.key)
6770            );
6771        }
6772        Ok(_) => {
6773            warn!(
6774                "Paid notify rejected: payment required for key {}",
6775                hex::encode(notify.key)
6776            );
6777            return Ok(());
6778        }
6779        Err(e) => {
6780            warn!(
6781                "PoP verification error for paid notify key {}: {e}",
6782                hex::encode(notify.key)
6783            );
6784            return Ok(());
6785        }
6786    }
6787
6788    if let Err(e) = paid_list.insert(&notify.key).await {
6789        warn!("Failed to add paid notify key to PaidForList: {e}");
6790    }
6791
6792    Ok(())
6793}
6794
6795#[allow(clippy::too_many_arguments)]
6796async fn dispatch_neighbor_sync_request(
6797    source: PeerId,
6798    request: protocol::NeighborSyncRequest,
6799    ctx: &ReplicationMessageHandlerContext,
6800    is_bootstrapping: bool,
6801    my_commitment: Option<StorageCommitment>,
6802    request_id: u64,
6803    received_at: Instant,
6804    rr_message_id: Option<&str>,
6805) -> Result<()> {
6806    let guard = match admit_bounded_responder(
6807        &ctx.neighbor_sync_responder_admission_semaphore,
6808        &ctx.neighbor_sync_responder_inflight,
6809        &source,
6810        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
6811        NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
6812    )
6813    .await
6814    {
6815        Ok(guard) => guard,
6816        Err(failure) => {
6817            audit_metrics::record_responder_admission_drop(
6818                ReplicationResponderClass::NeighborSync,
6819                failure.reason.into(),
6820            );
6821            warn!(
6822                responder_class = "neighbor_sync",
6823                source = %source,
6824                "Neighbor-sync response dropped at admission: {failure}"
6825            );
6826            return Ok(());
6827        }
6828    };
6829    let pointers = ctx.pointers.clone();
6830    let worker_semaphore = Arc::clone(&ctx.neighbor_sync_responder_worker_semaphore);
6831    let p2p_node = Arc::clone(&ctx.p2p_node);
6832    let storage = Arc::clone(&ctx.storage);
6833    let paid_list = Arc::clone(&ctx.paid_list);
6834    let queues = Arc::clone(&ctx.queues);
6835    let config = Arc::clone(&ctx.config);
6836    let bootstrap_state = Arc::clone(&ctx.bootstrap_state);
6837    let sync_history = Arc::clone(&ctx.sync_history);
6838    let sync_cycle_epoch = Arc::clone(&ctx.sync_cycle_epoch);
6839    let repair_proofs = Arc::clone(&ctx.repair_proofs);
6840    let request_timeout = ctx.config.verification_request_timeout;
6841    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
6842    ctx.detached_task_tracker.spawn(async move {
6843        let _guard = guard;
6844        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
6845            debug!(
6846                responder_class = "neighbor_sync",
6847                source = %source,
6848                "Neighbor-sync responder worker pool closed before dequeue"
6849            );
6850            return;
6851        };
6852        if request_is_stale(received_at, request_timeout) {
6853            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::NeighborSync);
6854            debug!(
6855                responder_class = "neighbor_sync",
6856                source = %source,
6857                request_age_ms = received_at.elapsed().as_millis(),
6858                "Stale neighbor-sync request shed at dequeue"
6859            );
6860            return;
6861        }
6862        // A peer whose sync request is admitted and fresh gets our pointer
6863        // hints as well, including a node that is bootstrapping, which is how
6864        // it learns the pointers it should hold. Only such a request: each
6865        // answer scans every pointer held, and a refused or stale one must
6866        // cost nothing.
6867        if let Some(pointers) = &pointers {
6868            pointers.answer_sync_with_hints(source);
6869        }
6870        if let Err(e) = handle_neighbor_sync_request(
6871            &source,
6872            &request,
6873            &p2p_node,
6874            &storage,
6875            &paid_list,
6876            &queues,
6877            &config,
6878            is_bootstrapping,
6879            &bootstrap_state,
6880            &sync_history,
6881            &sync_cycle_epoch,
6882            &repair_proofs,
6883            my_commitment,
6884            request_id,
6885            rr_message_id.as_deref(),
6886        )
6887        .await
6888        {
6889            debug!(source = %source, "Neighbor-sync request handling failed: {e}");
6890        }
6891    });
6892
6893    Ok(())
6894}
6895
6896#[allow(clippy::too_many_arguments)]
6897async fn handle_neighbor_sync_request(
6898    source: &PeerId,
6899    request: &protocol::NeighborSyncRequest,
6900    p2p_node: &Arc<P2PNode>,
6901    storage: &Arc<ChunkStore>,
6902    paid_list: &Arc<PaidList>,
6903    queues: &Arc<RwLock<ReplicationQueues>>,
6904    config: &ReplicationConfig,
6905    is_bootstrapping: bool,
6906    bootstrap_state: &Arc<RwLock<BootstrapState>>,
6907    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
6908    sync_cycle_epoch: &Arc<RwLock<u64>>,
6909    repair_proofs: &Arc<RwLock<RepairProofs>>,
6910    my_commitment: Option<StorageCommitment>,
6911    request_id: u64,
6912    rr_message_id: Option<&str>,
6913) -> Result<()> {
6914    let self_id = *p2p_node.peer_id();
6915
6916    // No per-request hint count limit: the wire message size limit
6917    // (MAX_REPLICATION_MESSAGE_SIZE) already caps the payload. Unlike audit
6918    // challenges, sync hints don't drive expensive computation — they just
6919    // enter the verification queue. A per-request limit here would break
6920    // bootstrap replication for newly-joined nodes with 0 stored chunks.
6921
6922    // Build response (outbound hints).
6923    let (response, sent_replica_hints, sender_in_rt) =
6924        neighbor_sync::handle_sync_request_with_proofs(
6925            source,
6926            request,
6927            p2p_node,
6928            storage,
6929            paid_list,
6930            config,
6931            is_bootstrapping,
6932            my_commitment.clone(),
6933        )
6934        .await;
6935
6936    // Send response.
6937    let response_sent = send_replication_response_checked(
6938        source,
6939        p2p_node,
6940        request_id,
6941        ReplicationMessageBody::NeighborSyncResponse(response),
6942        rr_message_id,
6943        None,
6944    )
6945    .await;
6946
6947    // Process inbound hints only if sender is in LocalRT (Rule 4-6).
6948    if !sender_in_rt {
6949        return Ok(());
6950    }
6951
6952    // Update sync history for this peer before recording repair proofs so a
6953    // same-tick audit cannot combine a fresh key proof with stale peer maturity.
6954    {
6955        let mut history = sync_history.write().await;
6956        let record = history.entry(*source).or_insert(PeerSyncRecord {
6957            last_sync: None,
6958            cycles_since_sync: 0,
6959        });
6960        record.last_sync = Some(Instant::now());
6961        record.cycles_since_sync = 0;
6962    }
6963
6964    if response_sent && !request.bootstrapping {
6965        record_sent_replica_hints(source, &sent_replica_hints, repair_proofs, sync_cycle_epoch)
6966            .await;
6967    }
6968
6969    // Admit inbound hints and queue for verification.
6970    let outcome = admit_and_queue_hints(
6971        &self_id,
6972        source,
6973        &request.replica_hints,
6974        &request.paid_hints,
6975        p2p_node,
6976        config,
6977        storage,
6978        paid_list,
6979        queues,
6980    )
6981    .await;
6982
6983    // Track discovered keys for bootstrap drain detection so that hints
6984    // admitted via inbound sync requests are not missed. Capacity-rejected
6985    // hints keep this source on the "not yet drained" list until its next
6986    // sync re-admits them; a clean cycle clears the source.
6987    if is_bootstrapping {
6988        let live_discovered = outcome.discovered.clone();
6989        let outcomes = [(*source, outcome)];
6990        publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered).await;
6991    }
6992
6993    Ok(())
6994}
6995
6996/// Test-only record of who *sent* a verification request covering a watched key.
6997///
6998/// The capacity gate's entire effect is a request that is never sent, and a
6999/// request that was not sent leaves no production counter anywhere — not on the
7000/// sender, whose traffic counters are process-global and so cannot separate one
7001/// node of a single-process testnet from another, and not on the responder,
7002/// which simply never hears from it. Recording who asked is what lets a test
7003/// tell "held the key back" apart from "probed the close group, was refused at
7004/// the dial, and then held the key back", which are otherwise identical from the
7005/// queue's point of view.
7006///
7007/// Arming replaces the previous watch, so the outer map holds exactly the keys
7008/// the current test named, and each inner map holds at most one entry per node
7009/// in the process. Nothing is recorded until a test arms it, and the armed path
7010/// costs one read lock on the sending side.
7011///
7012/// Counting is per key because a node that cannot write legitimately keeps
7013/// sending verification requests for keys it has not yet authorized — that is
7014/// `PaidForList` convergence, which the gate leaves alone — so a per-peer total
7015/// would assert something untrue.
7016///
7017/// It counts *send attempts*, deliberately, recorded immediately before the wire
7018/// call. A responder sheds requests at admission and as stale, so a
7019/// receiver-side count would report zero for probes that were really sent, and
7020/// an assertion that this node asked nobody would pass on the strength of the
7021/// receiver dropping the question. It is not proof of delivery: a send that
7022/// fails immediately, with no route or during shutdown, is still counted.
7023///
7024/// `OnceLock` rather than `LazyLock`, which needs a newer Rust than this crate's
7025/// MSRV.
7026#[cfg(any(test, feature = "test-utils"))]
7027type VerificationWatch = HashMap<XorName, HashMap<PeerId, usize>>;
7028
7029#[cfg(any(test, feature = "test-utils"))]
7030static VERIFICATION_WATCH: std::sync::OnceLock<std::sync::RwLock<VerificationWatch>> =
7031    std::sync::OnceLock::new();
7032
7033#[cfg(any(test, feature = "test-utils"))]
7034fn verification_watch() -> &'static std::sync::RwLock<VerificationWatch> {
7035    VERIFICATION_WATCH.get_or_init(|| std::sync::RwLock::new(HashMap::new()))
7036}
7037
7038/// Test-only: start counting verification requests for `keys`, from zero.
7039///
7040/// Replaces any previous watch rather than adding to it, so the map is bounded
7041/// by the keys of the test that armed it last and nothing accumulates across a
7042/// process running many tests.
7043#[cfg(any(test, feature = "test-utils"))]
7044pub fn watch_verification_requests_for_test(keys: &[XorName]) {
7045    if let Ok(mut watch) = verification_watch().write() {
7046        watch.clear();
7047        for key in keys {
7048            watch.insert(*key, HashMap::new());
7049        }
7050    }
7051}
7052
7053/// Record that `requester` sent a verification request covering `keys`, for
7054/// whichever of them are watched. A poisoned lock is ignored rather than
7055/// propagated: this is observation for tests and must never change behaviour.
7056#[cfg(any(test, feature = "test-utils"))]
7057pub(crate) fn record_verification_request_sent(requester: &PeerId, keys: &[XorName]) {
7058    // Fast path under a read lock: with nothing watched — every production
7059    // build, and every test that did not ask — this is all the sender pays.
7060    match verification_watch().read() {
7061        Ok(watch) if watch.is_empty() => return,
7062        Ok(watch) if !keys.iter().any(|key| watch.contains_key(key)) => return,
7063        Ok(_) => {}
7064        Err(_) => return,
7065    }
7066    if let Ok(mut watch) = verification_watch().write() {
7067        for key in keys {
7068            if let Some(by_peer) = watch.get_mut(key) {
7069                *by_peer.entry(*requester).or_insert(0) += 1;
7070            }
7071        }
7072    }
7073}
7074
7075/// Test-only: how many times `requester` has asked this process about `key`.
7076/// Zero unless the key was registered with `watch_verification_requests_for_test`.
7077#[cfg(any(test, feature = "test-utils"))]
7078#[must_use]
7079pub fn verification_requests_for_key_from_for_test(requester: &PeerId, key: &XorName) -> usize {
7080    verification_watch().read().map_or(0, |watch| {
7081        watch
7082            .get(key)
7083            .and_then(|by_peer| by_peer.get(requester))
7084            .copied()
7085            .unwrap_or(0)
7086    })
7087}
7088
7089async fn handle_verification_request(
7090    source: &PeerId,
7091    request: &protocol::VerificationRequest,
7092    storage: &Arc<ChunkStore>,
7093    paid_list: &Arc<PaidList>,
7094    p2p_node: &Arc<P2PNode>,
7095    request_id: u64,
7096    rr_message_id: Option<&str>,
7097) -> Result<()> {
7098    #[derive(Clone, Copy)]
7099    enum CachedPaidLookup {
7100        NotChecked,
7101        Checked(Option<bool>),
7102    }
7103
7104    #[derive(Clone, Copy)]
7105    struct CachedVerificationLookup {
7106        present: Option<bool>,
7107        paid: CachedPaidLookup,
7108    }
7109
7110    if verification_request_exceeds_limit(request.keys.len()) {
7111        warn!(
7112            "Verification request from {source} has {} keys, exceeding max {MAX_INCOMING_VERIFICATION_KEYS}; rejecting batch",
7113            request.keys.len(),
7114        );
7115        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7116        return Ok(());
7117    }
7118
7119    let requested_keys = request.keys.as_slice();
7120
7121    if request.paid_list_check_indices.len() > request.keys.len() {
7122        warn!(
7123            "Verification request from {source} has {} paid-list indices for {} keys; rejecting batch",
7124            request.paid_list_check_indices.len(),
7125            request.keys.len(),
7126        );
7127        send_verification_results(source, p2p_node, request_id, Vec::new(), rr_message_id).await;
7128        return Ok(());
7129    }
7130
7131    let keys_len = u32::try_from(requested_keys.len()).unwrap_or(u32::MAX);
7132    let paid_check_set: HashSet<u32> = request
7133        .paid_list_check_indices
7134        .iter()
7135        .copied()
7136        .filter(|&idx| {
7137            if idx >= keys_len {
7138                warn!(
7139                    "Verification request from {source}: paid_list_check_index {idx} out of bounds (keys.len() = {})",
7140                    requested_keys.len(),
7141                );
7142                false
7143            } else {
7144                true
7145            }
7146        })
7147        .collect();
7148
7149    let mut results = Vec::with_capacity(requested_keys.len());
7150    let mut lookup_cache: HashMap<XorName, CachedVerificationLookup> = HashMap::new();
7151    for (i, key) in requested_keys.iter().enumerate() {
7152        let needs_paid = paid_check_set.contains(&u32::try_from(i).unwrap_or(u32::MAX));
7153        let cached = lookup_cache.entry(*key).or_insert_with(|| {
7154            let present = match storage.exists(key) {
7155                Ok(present) => Some(present),
7156                Err(e) => {
7157                    warn!(
7158                        "Verification request from {source}: failed to check storage for {}: {e}",
7159                        hex::encode(key)
7160                    );
7161                    None
7162                }
7163            };
7164            CachedVerificationLookup {
7165                present,
7166                paid: CachedPaidLookup::NotChecked,
7167            }
7168        });
7169
7170        if needs_paid && matches!(cached.paid, CachedPaidLookup::NotChecked) {
7171            cached.paid = CachedPaidLookup::Checked(match paid_list.contains(key) {
7172                Ok(paid) => Some(paid),
7173                Err(e) => {
7174                    warn!(
7175                        "Verification request from {source}: failed to check paid-list for {}: {e}",
7176                        hex::encode(key)
7177                    );
7178                    None
7179                }
7180            });
7181        }
7182
7183        let paid = if needs_paid {
7184            match cached.paid {
7185                CachedPaidLookup::Checked(paid) => paid,
7186                CachedPaidLookup::NotChecked => None,
7187            }
7188        } else {
7189            None
7190        };
7191
7192        if cached.present.is_none() && paid.is_none() {
7193            continue;
7194        }
7195
7196        results.push(protocol::KeyVerificationResult {
7197            key: *key,
7198            present: cached.present.unwrap_or(false),
7199            paid,
7200        });
7201    }
7202
7203    send_verification_results(source, p2p_node, request_id, results, rr_message_id).await;
7204
7205    Ok(())
7206}
7207
7208async fn dispatch_verification_request(
7209    source: PeerId,
7210    request: protocol::VerificationRequest,
7211    ctx: &ReplicationMessageHandlerContext,
7212    request_id: u64,
7213    received_at: Instant,
7214    rr_message_id: Option<&str>,
7215) -> Result<()> {
7216    let guard = match admit_bounded_responder(
7217        &ctx.verification_responder_admission_semaphore,
7218        &ctx.verification_responder_inflight,
7219        &source,
7220        VERIFICATION_RESPONDER_MAX_OUTSTANDING,
7221        VERIFICATION_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7222    )
7223    .await
7224    {
7225        Ok(guard) => guard,
7226        Err(failure) => {
7227            audit_metrics::record_responder_admission_drop(
7228                ReplicationResponderClass::Verification,
7229                failure.reason.into(),
7230            );
7231            warn!(
7232                responder_class = "verification",
7233                source = %source,
7234                "Verification response dropped at admission: {failure}"
7235            );
7236            return Ok(());
7237        }
7238    };
7239
7240    let worker_semaphore = Arc::clone(&ctx.verification_responder_worker_semaphore);
7241    let storage = Arc::clone(&ctx.storage);
7242    let paid_list = Arc::clone(&ctx.paid_list);
7243    let p2p_node = Arc::clone(&ctx.p2p_node);
7244    let request_timeout = ctx.config.verification_request_timeout;
7245    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7246    ctx.detached_task_tracker.spawn(async move {
7247        let _guard = guard;
7248        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7249            debug!(
7250                responder_class = "verification",
7251                source = %source,
7252                "Verification responder worker pool closed before dequeue"
7253            );
7254            return;
7255        };
7256        if request_is_stale(received_at, request_timeout) {
7257            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Verification);
7258            debug!(
7259                responder_class = "verification",
7260                source = %source,
7261                request_age_ms = received_at.elapsed().as_millis(),
7262                "Stale verification request shed at dequeue"
7263            );
7264            return;
7265        }
7266        if let Err(e) = handle_verification_request(
7267            &source,
7268            &request,
7269            &storage,
7270            &paid_list,
7271            &p2p_node,
7272            request_id,
7273            rr_message_id.as_deref(),
7274        )
7275        .await
7276        {
7277            debug!(source = %source, "Verification request handling failed: {e}");
7278        }
7279    });
7280
7281    Ok(())
7282}
7283
7284const fn verification_request_exceeds_limit(key_count: usize) -> bool {
7285    key_count > MAX_INCOMING_VERIFICATION_KEYS
7286}
7287
7288async fn send_verification_results(
7289    source: &PeerId,
7290    p2p_node: &Arc<P2PNode>,
7291    request_id: u64,
7292    results: Vec<protocol::KeyVerificationResult>,
7293    rr_message_id: Option<&str>,
7294) {
7295    send_replication_response(
7296        source,
7297        p2p_node,
7298        request_id,
7299        ReplicationMessageBody::VerificationResponse(VerificationResponse { results }),
7300        rr_message_id,
7301    )
7302    .await;
7303}
7304
7305async fn dispatch_fetch_request(
7306    source: PeerId,
7307    request: protocol::FetchRequest,
7308    ctx: &ReplicationMessageHandlerContext,
7309    request_id: u64,
7310    received_at: Instant,
7311    rr_message_id: Option<&str>,
7312) -> Result<()> {
7313    let guard = match admit_bounded_responder(
7314        &ctx.fetch_responder_admission_semaphore,
7315        &ctx.fetch_responder_inflight,
7316        &source,
7317        FETCH_RESPONDER_MAX_OUTSTANDING,
7318        FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER,
7319    )
7320    .await
7321    {
7322        Ok(guard) => guard,
7323        Err(failure) => {
7324            audit_metrics::record_responder_admission_drop(
7325                ReplicationResponderClass::Fetch,
7326                failure.reason.into(),
7327            );
7328            warn!(
7329                responder_class = "fetch",
7330                source = %source,
7331                "Fetch response dropped at admission: {failure}"
7332            );
7333            return Ok(());
7334        }
7335    };
7336
7337    let worker_semaphore = Arc::clone(&ctx.fetch_responder_worker_semaphore);
7338    let storage = Arc::clone(&ctx.storage);
7339    let p2p_node = Arc::clone(&ctx.p2p_node);
7340    let request_timeout = ctx.config.fetch_request_timeout;
7341    let rr_message_id = rr_message_id.map(ToOwned::to_owned);
7342    ctx.detached_task_tracker.spawn(async move {
7343        let _guard = guard;
7344        let Ok(_worker_permit) = worker_semaphore.acquire_owned().await else {
7345            debug!(
7346                responder_class = "fetch",
7347                source = %source,
7348                "Fetch responder worker pool closed before dequeue"
7349            );
7350            return;
7351        };
7352        if request_is_stale(received_at, request_timeout) {
7353            audit_metrics::record_responder_staleness_shed(ReplicationResponderClass::Fetch);
7354            debug!(
7355                responder_class = "fetch",
7356                source = %source,
7357                request_age_ms = received_at.elapsed().as_millis(),
7358                "Stale fetch request shed at dequeue"
7359            );
7360            return;
7361        }
7362        if let Err(e) = handle_fetch_request(
7363            &source,
7364            &request,
7365            &storage,
7366            &p2p_node,
7367            request_id,
7368            rr_message_id.as_deref(),
7369        )
7370        .await
7371        {
7372            debug!(source = %source, "Fetch request handling failed: {e}");
7373        }
7374    });
7375
7376    Ok(())
7377}
7378
7379fn request_is_stale(received_at: Instant, timeout: Duration) -> bool {
7380    received_at.elapsed() >= timeout
7381}
7382
7383/// How a fetch responder's answer is charged against its reputation.
7384#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7385enum FetchFault {
7386    /// The peer does not hold a chunk it was expected to hold.
7387    ///
7388    /// This is the lane the release withholds, because a node part-way through moving
7389    /// off the legacy store answers exactly this way about chunks it has legitimately
7390    /// given up.
7391    UnheldChunk,
7392    /// The peer's own storage failed, or served bytes that no longer hash to their
7393    /// address.
7394    ///
7395    /// Never withheld. `FetchResponse::Error` has one producer, and it is the responder's
7396    /// storage read returning an error: an I/O fault, an exhausted descriptor table, or a
7397    /// failed integrity check. A peer that merely does not hold the chunk answers
7398    /// `NotFound` instead, so nothing about the migration produces this.
7399    ResponderFault,
7400}
7401
7402/// Classify a fetch response that did not carry the chunk.
7403///
7404/// `Success` yields `None`. Every other answer is a fault of one kind or the other, and
7405/// which kind decides whether this release charges for it.
7406fn fetch_fault_for(response: &protocol::FetchResponse) -> Option<FetchFault> {
7407    match response {
7408        protocol::FetchResponse::Success { .. } => None,
7409        protocol::FetchResponse::NotFound { .. } => Some(FetchFault::UnheldChunk),
7410        protocol::FetchResponse::Error { .. } => Some(FetchFault::ResponderFault),
7411    }
7412}
7413
7414/// Charge a fetch fault to the responder.
7415///
7416/// The only place the two kinds are treated differently. An unheld chunk goes through the
7417/// release switch, which is currently withholding it; a responder fault is charged
7418/// directly and is not affected by the switch at all.
7419async fn charge_fetch_fault(
7420    p2p_node: &Arc<P2PNode>,
7421    source: &PeerId,
7422    fault: FetchFault,
7423    lane: &'static str,
7424) {
7425    match fault {
7426        FetchFault::UnheldChunk => {
7427            config::penalise_unheld_close_group_chunk(
7428                p2p_node,
7429                source,
7430                lane,
7431                REPLICATION_TRUST_WEIGHT,
7432            )
7433            .await;
7434        }
7435        FetchFault::ResponderFault => {
7436            p2p_node
7437                .report_trust_event(
7438                    source,
7439                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
7440                )
7441                .await;
7442        }
7443    }
7444}
7445
7446/// Turn the responder's storage read into the answer it sends back.
7447///
7448/// The whole distinction the fetch lanes rest on is made here. A key this node does not
7449/// hold reads as `Ok(None)` and is answered `NotFound`. A read that fails, from an I/O
7450/// fault, an exhausted descriptor table, or a failed integrity check, is answered `Error`.
7451/// Nothing about a node giving chunks up produces the second.
7452fn fetch_response_for(key: XorName, read: Result<Option<Vec<u8>>>) -> protocol::FetchResponse {
7453    match read {
7454        Ok(Some(data)) => protocol::FetchResponse::Success { key, data },
7455        Ok(None) => protocol::FetchResponse::NotFound { key },
7456        Err(e) => protocol::FetchResponse::Error {
7457            key,
7458            reason: format!("{e}"),
7459        },
7460    }
7461}
7462
7463async fn handle_fetch_request(
7464    source: &PeerId,
7465    request: &protocol::FetchRequest,
7466    storage: &Arc<ChunkStore>,
7467    p2p_node: &Arc<P2PNode>,
7468    request_id: u64,
7469    rr_message_id: Option<&str>,
7470) -> Result<()> {
7471    let response = fetch_response_for(request.key, storage.get(&request.key).await);
7472
7473    send_replication_response(
7474        source,
7475        p2p_node,
7476        request_id,
7477        ReplicationMessageBody::FetchResponse(response),
7478        rr_message_id,
7479    )
7480    .await;
7481
7482    Ok(())
7483}
7484
7485/// Responder for an incoming `AuditChallenge` (responsible-chunk audit #2, and
7486/// the prune-confirmation audit, which reuses the same wire message): reply with
7487/// per-key possession digests.
7488struct AuditResponderCompletion {
7489    response_kind: &'static str,
7490    sent: bool,
7491    processing: Duration,
7492    response_send: Duration,
7493}
7494
7495async fn handle_audit_challenge_msg(
7496    source: &PeerId,
7497    challenge: &protocol::AuditChallenge,
7498    storage: &Arc<ChunkStore>,
7499    p2p_node: &Arc<P2PNode>,
7500    is_bootstrapping: bool,
7501    reply: ReplyRoute<'_>,
7502) -> Result<AuditResponderCompletion> {
7503    #[allow(clippy::cast_possible_truncation)]
7504    let stored_chunks = storage.current_chunks().map_or(0, |c| c as usize);
7505    info!(
7506        "Audit challenge received: kind=responsible keys={} bootstrapping={} request_response={}",
7507        challenge.keys.len(),
7508        is_bootstrapping,
7509        reply.rr_message_id.is_some(),
7510    );
7511
7512    let processing_started = Instant::now();
7513    let response = audit::handle_audit_challenge(
7514        challenge,
7515        storage,
7516        p2p_node.peer_id(),
7517        is_bootstrapping,
7518        stored_chunks,
7519    )
7520    .await;
7521    let processing = processing_started.elapsed();
7522    let response_kind = audit_response_kind(&response);
7523
7524    let response_send_started = Instant::now();
7525    let sent = send_replication_response_checked(
7526        source,
7527        p2p_node,
7528        reply.request_id,
7529        ReplicationMessageBody::AuditResponse(response),
7530        reply.rr_message_id,
7531        Some(reply.protocol),
7532    )
7533    .await;
7534    let response_send = response_send_started.elapsed();
7535
7536    Ok(AuditResponderCompletion {
7537        response_kind,
7538        sent,
7539        processing,
7540        response_send,
7541    })
7542}
7543
7544#[allow(clippy::too_many_arguments)]
7545fn log_audit_responder_completion(
7546    metrics: &AuditResponderMetrics,
7547    source: PeerId,
7548    class: AuditResponderClass,
7549    kind: &'static str,
7550    challenge_id: u64,
7551    work_items: usize,
7552    response_kind: &'static str,
7553    sent: bool,
7554    received_at: Instant,
7555    worker_started: Instant,
7556    processing: Duration,
7557    response_send: Duration,
7558) {
7559    let dispatch = worker_started.saturating_duration_since(received_at);
7560    let total = received_at.elapsed();
7561    metrics.record_completed(source, processing, total, sent);
7562    if sent {
7563        info!(
7564            target: "ant_node::replication::audit_responder",
7565            event = "completed",
7566            kind,
7567            responder_class = class.as_str(),
7568            source = %source,
7569            challenge_id,
7570            work_items,
7571            response = response_kind,
7572            sent,
7573            dispatch_ms = dispatch.as_millis(),
7574            processing_ms = processing.as_millis(),
7575            response_send_ms = response_send.as_millis(),
7576            total_ms = total.as_millis(),
7577            "Audit responder request completed"
7578        );
7579    } else {
7580        warn!(
7581            target: "ant_node::replication::audit_responder",
7582            event = "completed",
7583            kind,
7584            responder_class = class.as_str(),
7585            source = %source,
7586            challenge_id,
7587            work_items,
7588            response = response_kind,
7589            sent,
7590            dispatch_ms = dispatch.as_millis(),
7591            processing_ms = processing.as_millis(),
7592            response_send_ms = response_send.as_millis(),
7593            total_ms = total.as_millis(),
7594            "Audit responder request completed without sending a reply"
7595        );
7596    }
7597}
7598
7599/// Where a reply goes and how it is addressed.
7600///
7601/// Grouped because the audit responder needs all three together and one of them
7602/// is not derivable from the body: during the rollout window a possession reply
7603/// may have to go out on the core id rather than its family's own (see
7604/// [`is_legacy_possession_challenge`]).
7605struct ReplyRoute<'a> {
7606    /// Correlates the reply with the challenge, at the replication layer.
7607    request_id: u64,
7608    /// Present when the challenge arrived over request-response, in which case
7609    /// the reply rides the same exchange back.
7610    rr_message_id: Option<&'a str>,
7611    /// The protocol id to answer on.
7612    protocol: &'static str,
7613}
7614
7615fn audit_response_kind(response: &protocol::AuditResponse) -> &'static str {
7616    match response {
7617        protocol::AuditResponse::Digests { .. } => "digests",
7618        protocol::AuditResponse::Bootstrapping { .. } => "bootstrapping",
7619        protocol::AuditResponse::Rejected { .. } => "rejected",
7620    }
7621}
7622
7623fn subtree_audit_response_kind(response: &protocol::SubtreeAuditResponse) -> &'static str {
7624    match response {
7625        protocol::SubtreeAuditResponse::Proof { .. } => "proof",
7626        protocol::SubtreeAuditResponse::Bootstrapping { .. } => "bootstrapping",
7627        protocol::SubtreeAuditResponse::Rejected { .. } => "rejected",
7628    }
7629}
7630
7631fn subtree_audit_response_work_items(response: &protocol::SubtreeAuditResponse) -> usize {
7632    match response {
7633        protocol::SubtreeAuditResponse::Proof { proof, .. } => proof.leaves.len(),
7634        protocol::SubtreeAuditResponse::Bootstrapping { .. }
7635        | protocol::SubtreeAuditResponse::Rejected { .. } => 0,
7636    }
7637}
7638
7639fn subtree_slice_response_kind(response: &protocol::SubtreeSliceResponse) -> &'static str {
7640    match response {
7641        protocol::SubtreeSliceResponse::Items { .. } => "items",
7642        protocol::SubtreeSliceResponse::Bootstrapping { .. } => "bootstrapping",
7643        protocol::SubtreeSliceResponse::Rejected { .. } => "rejected",
7644    }
7645}
7646
7647fn commitment_pin_response_kind(response: &protocol::GetCommitmentByPinResponse) -> &'static str {
7648    match response {
7649        protocol::GetCommitmentByPinResponse::Found { .. } => "found",
7650        protocol::GetCommitmentByPinResponse::NotRetained { .. } => "not_retained",
7651    }
7652}
7653
7654// ---------------------------------------------------------------------------
7655// Message sending helper
7656// ---------------------------------------------------------------------------
7657
7658/// Send a replication response message as a best-effort reply.
7659///
7660/// Encode and send failures are logged by the checked helper. Most response
7661/// paths do not need to branch on send success, so this wrapper keeps those
7662/// call sites explicit about their best-effort behavior.
7663async fn send_replication_response(
7664    peer: &PeerId,
7665    p2p_node: &Arc<P2PNode>,
7666    request_id: u64,
7667    body: ReplicationMessageBody,
7668    rr_message_id: Option<&str>,
7669) {
7670    let _ =
7671        send_replication_response_checked(peer, p2p_node, request_id, body, rr_message_id, None)
7672            .await;
7673}
7674
7675/// Send a replication response message and report whether it was accepted.
7676///
7677/// Returns `true` after the message is encoded and accepted by the P2P send
7678/// path. Returns `false` after logging an encode or send failure. Repair-proof
7679/// recording uses this to avoid trusting hints that were not actually sent.
7680///
7681/// When `rr_message_id` is `Some`, the response is sent via the `/rr/`
7682/// request-response path so saorsa-core can route it back to the caller's
7683/// `send_request` future. Otherwise it is sent as a plain message.
7684///
7685/// `protocol` overrides the id the body would route on by family. Exactly one
7686/// caller needs it: a possession challenge from a peer that predates the family
7687/// split has to be answered where it was asked (see
7688/// [`is_legacy_possession_challenge`]). Everything else passes `None` and gets
7689/// [`response_protocol_for`], which is what keeps send and receive symmetric.
7690async fn send_replication_response_checked(
7691    peer: &PeerId,
7692    p2p_node: &Arc<P2PNode>,
7693    request_id: u64,
7694    body: ReplicationMessageBody,
7695    rr_message_id: Option<&str>,
7696    protocol: Option<&'static str>,
7697) -> bool {
7698    let msg = ReplicationMessage { request_id, body };
7699    let encoded = match msg.encode() {
7700        Ok(data) => data,
7701        Err(e) => {
7702            warn!("Failed to encode replication response: {e}");
7703            return false;
7704        }
7705    };
7706    // V2-684: per-peer served-bytes attribution for the heavy serve paths.
7707    // `FetchResponse` carries ~99% of served bytes; `NeighborSyncResponse` is
7708    // included for completeness. Other response variants (verification/audit/
7709    // commitment) are intentionally excluded — the round-2 audit reply is now a
7710    // few-KB verified slice (V2-685), not a full-chunk transfer, so it is light.
7711    if matches!(
7712        msg.body,
7713        ReplicationMessageBody::FetchResponse(_) | ReplicationMessageBody::NeighborSyncResponse(_)
7714    ) {
7715        protocol::record_served(peer, encoded.len());
7716    }
7717    let protocol = protocol.unwrap_or_else(|| response_protocol_for(&msg.body));
7718    let result = if let Some(msg_id) = rr_message_id {
7719        p2p_node
7720            .send_response(peer, protocol, msg_id, encoded)
7721            .await
7722    } else {
7723        p2p_node.send_message(peer, protocol, encoded, &[]).await
7724    };
7725    if let Err(e) = result {
7726        debug!("Failed to send replication response to {peer}: {e}");
7727        return false;
7728    }
7729    true
7730}
7731
7732async fn record_sent_replica_hints(
7733    peer: &PeerId,
7734    hints: &[neighbor_sync::SentReplicaHint],
7735    repair_proofs: &Arc<RwLock<RepairProofs>>,
7736    sync_cycle_epoch: &Arc<RwLock<u64>>,
7737) {
7738    if hints.is_empty() {
7739        return;
7740    }
7741
7742    let hinted_at_epoch = *sync_cycle_epoch.read().await;
7743    let mut proofs = repair_proofs.write().await;
7744    for hint in hints {
7745        if proofs.record_replica_hint_sent(*peer, hint.key, &hint.close_peers, hinted_at_epoch) {
7746            debug!(
7747                "Recorded repair hint proof for peer {peer} and key {}",
7748                hex::encode(hint.key)
7749            );
7750        }
7751    }
7752}
7753
7754// ---------------------------------------------------------------------------
7755// Neighbor sync round
7756// ---------------------------------------------------------------------------
7757
7758/// Run one neighbor sync round.
7759#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
7760async fn run_neighbor_sync_round(
7761    p2p_node: &Arc<P2PNode>,
7762    storage: &Arc<ChunkStore>,
7763    paid_list: &Arc<PaidList>,
7764    queues: &Arc<RwLock<ReplicationQueues>>,
7765    config: &ReplicationConfig,
7766    sync_state: &Arc<RwLock<NeighborSyncState>>,
7767    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
7768    sync_cycle_epoch: &Arc<RwLock<u64>>,
7769    repair_proofs: &Arc<RwLock<RepairProofs>>,
7770    is_bootstrapping: &Arc<RwLock<bool>>,
7771    bootstrap_state: &Arc<RwLock<BootstrapState>>,
7772    commitment_state: &Arc<ResponderCommitmentState>,
7773    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
7774    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
7775    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
7776    audit_challenge_coordinator: &Arc<AuditChallengeCoordinator>,
7777    gossip_audit: &GossipAuditTrigger,
7778    pointers: Option<&Arc<pointer::PointerReplication>>,
7779) {
7780    let self_id = *p2p_node.peer_id();
7781    let bootstrapping = *is_bootstrapping.read().await;
7782
7783    // Check if cycle is complete; start new one if needed.
7784    // We check under a read lock, then release it before the expensive
7785    // prune pass and DHT snapshot so other tasks are not starved.
7786    let cycle_complete = sync_state.read().await.is_cycle_complete();
7787    if cycle_complete {
7788        // A completed local neighbor-sync cycle advances the epoch component
7789        // of repair-proof maturity. The per-key wall-clock minimum age is
7790        // checked when audits are selected.
7791        {
7792            let mut history = sync_history.write().await;
7793            for record in history.values_mut() {
7794                record.cycles_since_sync = record.cycles_since_sync.saturating_add(1);
7795            }
7796        }
7797        {
7798            let mut epoch = sync_cycle_epoch.write().await;
7799            *epoch = epoch.saturating_add(1);
7800        }
7801
7802        // Post-cycle pruning (Section 11) — runs without holding sync_state.
7803        // Prune candidacy is unconditional once the hysteresis elapses;
7804        // bootstrap state only defers the remote prune-confirmation audits
7805        // until bootstrap has drained.
7806        let allow_remote_prune_audits = !bootstrapping && bootstrap_state.read().await.is_drained();
7807        pruning::run_prune_pass_with_context(pruning::PrunePassContext {
7808            self_id: &self_id,
7809            storage,
7810            paid_list,
7811            p2p_node,
7812            config,
7813            sync_state,
7814            repair_proofs,
7815            allow_remote_prune_audits,
7816            commitment_state: Some(commitment_state),
7817            audit_challenge_coordinator,
7818        })
7819        .await;
7820        if let Some(pointers) = pointers {
7821            pointers
7822                .prune_pass(allow_remote_prune_audits, Some(commitment_state))
7823                .await;
7824        }
7825
7826        // Take fresh close-neighbor snapshot (DHT query, no lock held).
7827        let neighbors =
7828            neighbor_sync::snapshot_close_neighbors(p2p_node, &self_id, config.neighbor_sync_scope)
7829                .await;
7830
7831        // Now re-acquire write lock and re-check before swapping cycle.
7832        let mut state = sync_state.write().await;
7833        if state.is_cycle_complete() {
7834            // Preserve cooldown and bootstrap-claim tracking across cycles.
7835            // Claims have a 24h lifecycle vs 10-20 min cycles — dropping them
7836            // would reset the abuse detection timer every cycle.
7837            let old_sync_times = std::mem::take(&mut state.last_sync_times);
7838            let old_bootstrap_claims = std::mem::take(&mut state.bootstrap_claims);
7839            let old_bootstrap_claim_history = std::mem::take(&mut state.bootstrap_claim_history);
7840            let old_prune_cursor = state.prune_cursor;
7841            *state = NeighborSyncState::new_cycle(neighbors);
7842            state.last_sync_times = old_sync_times;
7843            state.bootstrap_claims = old_bootstrap_claims;
7844            state.bootstrap_claim_history = old_bootstrap_claim_history;
7845            state.prune_cursor = old_prune_cursor;
7846        }
7847    }
7848
7849    // Select batch of peers.
7850    let batch = {
7851        let mut state = sync_state.write().await;
7852        neighbor_sync::select_sync_batch(
7853            &mut state,
7854            config.neighbor_sync_peer_count,
7855            config.neighbor_sync_cooldown,
7856        )
7857    };
7858
7859    if batch.is_empty() {
7860        return;
7861    }
7862
7863    debug!("Neighbor sync: syncing with {} peers", batch.len());
7864    if let Some(pointers) = pointers {
7865        pointers.push_hints_detached(batch.clone());
7866    }
7867
7868    // Snapshot our current commitment once per round so all peers in
7869    // this batch see the same thing (gossip is the responder's attestation;
7870    // same value across the batch is fine and reduces RwLock churn). Atomically
7871    // snapshot + mark-gossiped so we stay answerable for exactly what we emit
7872    // (ADR-0002 retention), with no TOCTOU vs a concurrent retire/rotate.
7873    let gossiped = commitment_state.current_for_gossip();
7874    // The hash actually put on the wire, captured with the payload. A rotation later in
7875    // the round must not let a reply be credited to a root the peer never saw.
7876    let gossiped_hash = gossiped.as_ref().map(|b| b.hash());
7877    let my_commitment = gossiped.map(|b| b.commitment().clone());
7878
7879    let mut hints_by_peer = neighbor_sync::build_sync_hints_for_peers(
7880        &batch,
7881        storage,
7882        paid_list,
7883        p2p_node,
7884        config.close_group_size,
7885        config.paid_list_close_group_size,
7886    )
7887    .await;
7888
7889    // Sync with each peer in the batch.
7890    for peer in &batch {
7891        let hints = hints_by_peer.remove(peer).unwrap_or_default();
7892        let outcome = neighbor_sync::sync_with_peer_with_hints(
7893            peer,
7894            p2p_node,
7895            config,
7896            bootstrapping,
7897            hints,
7898            my_commitment.clone(),
7899        )
7900        .await;
7901
7902        if let Some(outcome) = outcome {
7903            // The peer answered, so the request that carried our commitment root arrived.
7904            // That is proof of delivery rather than proof of emission, and the storage
7905            // migration will not let a node give anything up until its close group has
7906            // actually seen the reduced root.
7907            if let Some(hash) = gossiped_hash {
7908                commitment_state.note_commitment_delivered(*peer, hash);
7909            }
7910            handle_sync_response(
7911                &self_id,
7912                peer,
7913                &outcome.response,
7914                &outcome.sent_replica_hints,
7915                p2p_node,
7916                config,
7917                bootstrapping,
7918                bootstrap_state,
7919                storage,
7920                paid_list,
7921                queues,
7922                sync_state,
7923                sync_history,
7924                sync_cycle_epoch,
7925                repair_proofs,
7926                last_commitment_by_peer,
7927                ever_capable_peers,
7928                sig_verify_attempts,
7929                gossip_audit,
7930            )
7931            .await;
7932        } else {
7933            // Sync failed -- remove peer and try to fill slot.
7934            let replacement = {
7935                let mut state = sync_state.write().await;
7936                neighbor_sync::handle_sync_failure(&mut state, peer, config.neighbor_sync_cooldown)
7937            };
7938
7939            // Attempt sync with the replacement peer (if one was found).
7940            if let Some(replacement_peer) = replacement {
7941                let mut replacement_hints = neighbor_sync::build_sync_hints_for_peers(
7942                    std::slice::from_ref(&replacement_peer),
7943                    storage,
7944                    paid_list,
7945                    p2p_node,
7946                    config.close_group_size,
7947                    config.paid_list_close_group_size,
7948                )
7949                .await;
7950                let hints = replacement_hints
7951                    .remove(&replacement_peer)
7952                    .unwrap_or_default();
7953                let replacement_outcome = neighbor_sync::sync_with_peer_with_hints(
7954                    &replacement_peer,
7955                    p2p_node,
7956                    config,
7957                    bootstrapping,
7958                    hints,
7959                    my_commitment.clone(),
7960                )
7961                .await;
7962
7963                if let Some(outcome) = replacement_outcome {
7964                    // Same payload, same round trip, same proof: a reply can only come
7965                    // back if the request carrying the root reached this peer. Omitting it
7966                    // here made the counter under-report on any node whose primary syncs
7967                    // often fall through to a replacement, which is exactly the node most
7968                    // likely to be short of disk, and stalled its migration indefinitely.
7969                    if let Some(hash) = gossiped_hash {
7970                        commitment_state.note_commitment_delivered(replacement_peer, hash);
7971                    }
7972                    handle_sync_response(
7973                        &self_id,
7974                        &replacement_peer,
7975                        &outcome.response,
7976                        &outcome.sent_replica_hints,
7977                        p2p_node,
7978                        config,
7979                        bootstrapping,
7980                        bootstrap_state,
7981                        storage,
7982                        paid_list,
7983                        queues,
7984                        sync_state,
7985                        sync_history,
7986                        sync_cycle_epoch,
7987                        repair_proofs,
7988                        last_commitment_by_peer,
7989                        ever_capable_peers,
7990                        sig_verify_attempts,
7991                        gossip_audit,
7992                    )
7993                    .await;
7994                }
7995            }
7996        }
7997    }
7998}
7999
8000/// Process a successful neighbor sync response: record the sync, check for
8001/// bootstrap claim abuse, and admit inbound hints.
8002#[allow(clippy::too_many_arguments)]
8003async fn handle_sync_response(
8004    self_id: &PeerId,
8005    peer: &PeerId,
8006    resp: &NeighborSyncResponse,
8007    sent_replica_hints: &[neighbor_sync::SentReplicaHint],
8008    p2p_node: &Arc<P2PNode>,
8009    config: &ReplicationConfig,
8010    bootstrapping: bool,
8011    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8012    storage: &Arc<ChunkStore>,
8013    paid_list: &Arc<PaidList>,
8014    queues: &Arc<RwLock<ReplicationQueues>>,
8015    sync_state: &Arc<RwLock<NeighborSyncState>>,
8016    sync_history: &Arc<RwLock<HashMap<PeerId, PeerSyncRecord>>>,
8017    sync_cycle_epoch: &Arc<RwLock<u64>>,
8018    repair_proofs: &Arc<RwLock<RepairProofs>>,
8019    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
8020    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
8021    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
8022    gossip_audit: &GossipAuditTrigger,
8023) {
8024    // Ingest the peer's commitment if they piggybacked one on the response.
8025    // Same verification as the request path (peer-id binding + signature);
8026    // forged commitments are dropped at the edge. A *changed* commitment here
8027    // is a gossip-audit trigger just like on the request path — so a peer that
8028    // only ever answers sync (never initiates) is still audited (ADR-0002).
8029    if let Some(target) = ingest_peer_commitment(
8030        peer,
8031        resp.commitment.as_ref(),
8032        p2p_node,
8033        last_commitment_by_peer,
8034        ever_capable_peers,
8035        sig_verify_attempts,
8036    )
8037    .await
8038    {
8039        maybe_trigger_gossip_audit(gossip_audit, peer, target).await;
8040    }
8041
8042    // Record successful sync.
8043    {
8044        let mut state = sync_state.write().await;
8045        neighbor_sync::record_successful_sync(&mut state, peer);
8046    }
8047    {
8048        let mut history = sync_history.write().await;
8049        let record = history.entry(*peer).or_insert(PeerSyncRecord {
8050            last_sync: None,
8051            cycles_since_sync: 0,
8052        });
8053        record.last_sync = Some(Instant::now());
8054        record.cycles_since_sync = 0;
8055    }
8056
8057    // Process inbound hints from response (skip if peer is bootstrapping).
8058    if resp.bootstrapping {
8059        // Gap 6: BootstrapClaimAbuse grace period enforcement.
8060        // Separate state mutation from network I/O to avoid holding the
8061        // write lock across report_trust_event.
8062        let should_report = {
8063            let now = Instant::now();
8064            let mut state = sync_state.write().await;
8065            match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period) {
8066                BootstrapClaimObservation::WithinGrace { .. } => false,
8067                BootstrapClaimObservation::PastGrace { first_seen } => {
8068                    warn!(
8069                        "Peer {peer} has been claiming bootstrap for {:?}, \
8070                         exceeding grace period of {:?} — reporting abuse",
8071                        now.duration_since(first_seen),
8072                        config.bootstrap_claim_grace_period,
8073                    );
8074                    true
8075                }
8076                BootstrapClaimObservation::Repeated { first_seen } => {
8077                    warn!(
8078                        "Peer {peer} repeated bootstrap claim after previously stopping; \
8079                         first claim was {:?} ago — reporting abuse",
8080                        now.duration_since(first_seen),
8081                    );
8082                    true
8083                }
8084            }
8085        };
8086        if should_report {
8087            p2p_node
8088                .report_trust_event(
8089                    peer,
8090                    TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8091                )
8092                .await;
8093        }
8094    } else {
8095        // Peer is not claiming bootstrap; clear active claim while retaining
8096        // history so the peer cannot start a second grace window later.
8097        {
8098            let mut state = sync_state.write().await;
8099            state.clear_active_bootstrap_claim(peer);
8100        }
8101        record_sent_replica_hints(peer, sent_replica_hints, repair_proofs, sync_cycle_epoch).await;
8102        let outcome = admit_and_queue_hints(
8103            self_id,
8104            peer,
8105            &resp.replica_hints,
8106            &resp.paid_hints,
8107            p2p_node,
8108            config,
8109            storage,
8110            paid_list,
8111            queues,
8112        )
8113        .await;
8114
8115        // Track discovered keys for bootstrap drain detection so that hints
8116        // admitted via regular neighbor sync are not missed. Capacity-
8117        // rejected hints keep this source on the "not yet drained" list
8118        // until its next sync replays them; a clean cycle clears it.
8119        if bootstrapping {
8120            let live_discovered = outcome.discovered.clone();
8121            let outcomes = [(*peer, outcome)];
8122            publish_bootstrap_admission_outcomes(bootstrap_state, &outcomes, &live_discovered)
8123                .await;
8124        }
8125    }
8126}
8127
8128/// Admit hints and queue them for verification, returning newly-discovered keys.
8129///
8130/// Shared by neighbor-sync request handling, response handling, and bootstrap
8131/// sync so that admission + queueing logic lives in one place.
8132#[allow(clippy::too_many_arguments)]
8133/// Outcome of [`admit_and_queue_hints`].
8134///
8135/// `capacity_rejected_count` tracks incoming hints for which no fair slot was
8136/// available; that source is kept outstanding until it re-hints. `displaced`
8137/// tracks older borrowed hints reclaimed for another sender; only the key is
8138/// dropped from bootstrap tracking — the former owner's standing is untouched
8139/// (see [`publish_bootstrap_admission_outcomes`]).
8140struct AdmissionOutcome {
8141    discovered: HashSet<XorName>,
8142    capacity_rejected_count: usize,
8143    displaced: Vec<CapacityDisplacement>,
8144}
8145
8146/// Publish one atomic admission unit into bootstrap drain accounting.
8147///
8148/// Only sources that were themselves capacity-rejected are kept outstanding.
8149/// A fairness displacement forfeits the displaced *key* but never stamps its
8150/// former owner: reclaiming a borrowed slot is this node's own fairness
8151/// decision, so charging it to the victim would let a sustained flooder wedge
8152/// our bootstrap drain open through an unrelated honest peer. Clean sources
8153/// are cleared only after every outcome in the unit is known, so peer
8154/// iteration order cannot falsely clear a rejection recorded later in the same
8155/// bootstrap batch.
8156async fn publish_bootstrap_admission_outcomes(
8157    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8158    outcomes: &[(PeerId, AdmissionOutcome)],
8159    live_discovered: &HashSet<XorName>,
8160) {
8161    let mut rejected_sources = HashSet::new();
8162    let mut clean_sources = HashSet::new();
8163    let mut displaced_keys = HashSet::new();
8164
8165    for (source, outcome) in outcomes {
8166        if outcome.capacity_rejected_count > 0 {
8167            rejected_sources.insert(*source);
8168        } else {
8169            clean_sources.insert(*source);
8170        }
8171        // Only the *key* of a fairness displacement is forfeited here, never
8172        // its owner's standing. Reclaiming a borrowed slot is our own fairness
8173        // decision, not a failure by the peer that held it: stamping the victim
8174        // would let a sustained flooder block our bootstrap drain through an
8175        // unrelated honest peer that never overflowed us. The displaced key
8176        // falls to the same post-bootstrap neighbor-sync and audit/repair
8177        // recovery path that TTL expiry already relies on.
8178        for displacement in &outcome.displaced {
8179            displaced_keys.insert(displacement.key);
8180        }
8181    }
8182    clean_sources.retain(|source| !rejected_sources.contains(source));
8183
8184    let now = Instant::now();
8185    let mut state = bootstrap_state.write().await;
8186    for key in displaced_keys {
8187        state.remove_key(&key);
8188    }
8189    state.pending_keys.extend(live_discovered);
8190    for source in clean_sources {
8191        state.capacity_rejected_sources.remove(&source);
8192    }
8193    for source in rejected_sources {
8194        // First-seen: a source that keeps overflowing us must not keep its own
8195        // record fresh, or bootstrap never drains and auditing stays off.
8196        state.note_capacity_rejected(source, now);
8197    }
8198}
8199
8200#[allow(clippy::too_many_arguments)]
8201async fn admit_and_queue_hints(
8202    self_id: &PeerId,
8203    source_peer: &PeerId,
8204    replica_hints: &[XorName],
8205    paid_hints: &[XorName],
8206    p2p_node: &Arc<P2PNode>,
8207    config: &ReplicationConfig,
8208    storage: &Arc<ChunkStore>,
8209    paid_list: &Arc<PaidList>,
8210    queues: &Arc<RwLock<ReplicationQueues>>,
8211) -> AdmissionOutcome {
8212    let pending_keys: HashSet<XorName> = {
8213        let q = queues.read().await;
8214        q.pending_keys().into_iter().collect()
8215    };
8216
8217    let admitted = admission::admit_hints(
8218        self_id,
8219        replica_hints,
8220        paid_hints,
8221        p2p_node,
8222        config,
8223        storage,
8224        paid_list,
8225        &pending_keys,
8226    )
8227    .await;
8228
8229    let mut q = queues.write().await;
8230    queue_admitted_hints(source_peer, admitted, storage, &mut q)
8231}
8232
8233fn queue_admitted_hints(
8234    source_peer: &PeerId,
8235    admitted: admission::AdmissionResult,
8236    storage: &ChunkStore,
8237    q: &mut ReplicationQueues,
8238) -> AdmissionOutcome {
8239    let mut discovered = HashSet::new();
8240    let mut capacity_rejected_count: usize = 0;
8241    let mut displaced = Vec::new();
8242    let now = Instant::now();
8243
8244    for key in admitted.replica_keys {
8245        if !storage.exists(&key).unwrap_or(false) {
8246            let result = q.add_pending_verify(
8247                key,
8248                VerificationEntry {
8249                    state: VerificationState::PendingVerify,
8250                    verified_sources: Vec::new(),
8251                    tried_sources: HashSet::new(),
8252                    created_at: now,
8253                    next_verify_at: now,
8254                    hint_sources: HashSet::from([*source_peer]),
8255                    // Non-empty: this peer claimed possession, so it is a
8256                    // fetch-source candidate. Derives HintPipeline::Replica.
8257                    replica_hint_sources: HashSet::from([*source_peer]),
8258                    unresolved_retries: 0,
8259                    no_holder_reported: false,
8260                },
8261            );
8262            match result {
8263                crate::replication::scheduling::AdmissionResult::Admitted => {
8264                    discovered.insert(key);
8265                }
8266                crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8267                crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8268                    capacity_rejected_count += 1;
8269                }
8270            }
8271        }
8272    }
8273
8274    for key in admitted.paid_only_keys {
8275        let result = q.add_pending_verify(
8276            key,
8277            VerificationEntry {
8278                state: VerificationState::PendingVerify,
8279                verified_sources: Vec::new(),
8280                tried_sources: HashSet::new(),
8281                created_at: now,
8282                next_verify_at: now,
8283                hint_sources: HashSet::from([*source_peer]),
8284                // Empty: a paid hint makes no possession claim, so this peer is
8285                // not a fetch source. Derives HintPipeline::PaidOnly.
8286                replica_hint_sources: HashSet::new(),
8287                unresolved_retries: 0,
8288                no_holder_reported: false,
8289            },
8290        );
8291        match result {
8292            crate::replication::scheduling::AdmissionResult::Admitted => {
8293                discovered.insert(key);
8294            }
8295            crate::replication::scheduling::AdmissionResult::AlreadyPresent => {}
8296            crate::replication::scheduling::AdmissionResult::CapacityRejected => {
8297                capacity_rejected_count += 1;
8298            }
8299        }
8300    }
8301
8302    if capacity_rejected_count > 0 {
8303        debug!(
8304            "admit_and_queue_hints from {source_peer}: {capacity_rejected_count} hints \
8305             rejected at queue capacity; source will need to re-hint after pending_verify drains"
8306        );
8307    }
8308
8309    displaced.extend(q.take_capacity_displacements());
8310
8311    AdmissionOutcome {
8312        discovered,
8313        capacity_rejected_count,
8314        displaced,
8315    }
8316}
8317
8318// ---------------------------------------------------------------------------
8319// Verification cycle
8320// ---------------------------------------------------------------------------
8321
8322/// Run one verification cycle: process pending keys through quorum checks.
8323#[allow(clippy::too_many_lines)]
8324async fn run_verification_cycle(ctx: VerificationCycleContext<'_>) {
8325    let cycle_started = Instant::now();
8326    let VerificationCycleContext {
8327        p2p_node,
8328        paid_list,
8329        storage,
8330        queues,
8331        config,
8332        bootstrap_state,
8333        is_bootstrapping,
8334        bootstrap_complete_notify,
8335        last_commitment_by_peer,
8336        ever_capable_peers,
8337        recent_provers,
8338    } = ctx;
8339
8340    // Self-heal the bootstrap drain before any early-return below: abandoned
8341    // capacity-rejection records must expire, and a drain condition that
8342    // became true without a triggering event must still be observed. Pending
8343    // peer requests legitimately block the drain check itself, but not this.
8344    expire_and_recheck_bootstrap_drain(
8345        bootstrap_state,
8346        queues,
8347        is_bootstrapping,
8348        bootstrap_complete_notify,
8349        config.capacity_rejected_max_age(),
8350    )
8351    .await;
8352
8353    // Bootstrap admits one concurrent neighbor batch as an atomic source
8354    // aggregation unit. Do not select newly queued keys until that batch's
8355    // hints and drain accounting have both been published.
8356    if bootstrap_state.read().await.pending_peer_requests > 0 {
8357        return;
8358    }
8359
8360    // Evict stale entries that have been pending too long (e.g. unreachable
8361    // verification targets during a network partition).
8362    let stale_pending_keys = {
8363        let mut q = queues.write().await;
8364        q.evict_stale(config::PENDING_VERIFY_MAX_AGE)
8365    };
8366    if !stale_pending_keys.is_empty() {
8367        update_bootstrap_after_verification(
8368            &stale_pending_keys,
8369            bootstrap_state,
8370            queues,
8371            is_bootstrapping,
8372            bootstrap_complete_notify,
8373        )
8374        .await;
8375    }
8376
8377    let pending_keys = {
8378        let mut q = queues.write().await;
8379        // Re-check while holding the queue write lock used by fair selection.
8380        // This closes the race
8381        // where a bootstrap batch starts after the early check: the batch
8382        // cannot publish its hints under the queue write lock until this
8383        // selection either returns or declines to run.
8384        if bootstrap_state.read().await.pending_peer_requests > 0 {
8385            return;
8386        }
8387        q.select_ready_pending_keys(Instant::now(), MAX_VERIFICATION_KEYS_PER_CYCLE)
8388    };
8389
8390    if pending_keys.is_empty() {
8391        return;
8392    }
8393    let initial_pending_count = pending_keys.len();
8394
8395    // Capacity verdict for this cycle — the same pre-check the PUT handler and
8396    // the fresh-offer path already run (V2-411), read once and reused below.
8397    //
8398    // It gates only the two steps that exist to enable a fetch: the presence
8399    // probe that discovers holders, and the promotion that queues the download.
8400    // Everything a cycle does that does not need a local write still runs on a
8401    // full node — the local paid-list fast path, `PaidForList` convergence
8402    // through the quorum round, and the terminal checks that retire a key this
8403    // node already holds or is no longer admitted for. Gating earlier than this
8404    // would stop a full node learning which of its keys were paid for, and
8405    // would strand keys that should have retired, which keeps bootstrap drain
8406    // pending and audits disabled until stale eviction.
8407    // Only a *full* disk is a standing condition worth minutes of backoff. A
8408    // failed `statvfs` says nothing about available space and may have cleared
8409    // by the next cycle, so it is treated as writable here and left to the
8410    // pre-check at the dial, which queries again and may well permit the write.
8411    let write_blocked = storage.capacity_verdict() == CapacityVerdict::Full;
8412    // Counted per gate rather than combined. `local_paid_probe` below counts
8413    // probes actually sent, so it reads zero once the first gate fires; keeping
8414    // the two deferral counts apart is what lets an operator see which branch a
8415    // full node's keys are taking without adding a code path to find out.
8416    let mut capacity_deferred_probe = 0usize;
8417    let mut capacity_deferred_promote = 0usize;
8418
8419    let self_id = *p2p_node.peer_id();
8420
8421    // Step 1: Check local PaidForList for fast-path authorization (Section 9,
8422    // step 4). Paid-list membership settles *validity* — the key is known-paid,
8423    // so no quorum round is needed. It says nothing about whether we must hold
8424    // the bytes; that is decided below.
8425    let mut local_paid_keys = Vec::new();
8426    let mut keys_needing_network = Vec::new();
8427    let mut terminal_keys: Vec<XorName> = Vec::new();
8428    {
8429        let mut q = queues.write().await;
8430        for key in &pending_keys {
8431            if paid_list.contains(key).unwrap_or(false) {
8432                if q.set_pending_state(key, VerificationState::PaidListVerified) {
8433                    local_paid_keys.push(*key);
8434                }
8435            } else {
8436                keys_needing_network.push(*key);
8437            }
8438        }
8439    }
8440
8441    // Storage responsibility is a live routing question, decided identically
8442    // for every known-paid key regardless of how the advertising peer labelled
8443    // its hint — a replica hint is a possession *claim* by the sender, never
8444    // permission for us to store. Held outside the queue lock: `is_responsible`
8445    // awaits into the DHT manager.
8446    let mut local_paid_presence_probe_keys = Vec::new();
8447    if !local_paid_keys.is_empty() {
8448        let mut terminal_paid = Vec::new();
8449        for key in local_paid_keys {
8450            if storage.exists(&key).unwrap_or(false) {
8451                terminal_paid.push(key);
8452            } else if is_storage_admitted(&self_id, &key, p2p_node, config).await {
8453                // We carry storage responsibility and lack the bytes. The
8454                // presence probe below discovers holders to fetch from; it is
8455                // source discovery, not re-verification.
8456                local_paid_presence_probe_keys.push(key);
8457            } else {
8458                terminal_paid.push(key);
8459            }
8460        }
8461
8462        if !terminal_paid.is_empty() {
8463            let mut q = queues.write().await;
8464            for key in terminal_paid {
8465                q.remove_pending(&key);
8466                terminal_keys.push(key);
8467            }
8468        }
8469
8470        // Capacity gate, first of two. Everything above this point has already
8471        // run: authorization succeeded via the local `PaidForList` hit, and the
8472        // keys that should retire (already held, or no longer storage-admitted)
8473        // have retired. What is left is a probe whose only purpose is finding a
8474        // holder to download from, and this node cannot write what it would
8475        // download.
8476        if write_blocked && !local_paid_presence_probe_keys.is_empty() {
8477            let mut q = queues.write().await;
8478            for key in std::mem::take(&mut local_paid_presence_probe_keys) {
8479                if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8480                    capacity_deferred_probe += 1;
8481                }
8482            }
8483        }
8484    }
8485
8486    let local_paid_probe_count = local_paid_presence_probe_keys.len();
8487    let keys_needing_network_count = keys_needing_network.len();
8488    // Keys this cycle put back because no peer claimed possession. Reported in
8489    // aggregate below; the per-key line is warned once per entry, not per retry.
8490    let mut no_holder_deferrals = 0usize;
8491
8492    // Step 1b: Local paid-list hit for fetch-eligible keys. Per Section 9
8493    // step 4, authorization succeeds immediately; run a presence-only probe
8494    // to find any holder we can fetch from.
8495    if !local_paid_presence_probe_keys.is_empty() {
8496        let targets = quorum::compute_presence_targets(
8497            &local_paid_presence_probe_keys,
8498            p2p_node,
8499            config,
8500            &self_id,
8501        )
8502        .await;
8503        let evidence = quorum::run_verification_round(
8504            &local_paid_presence_probe_keys,
8505            &targets,
8506            p2p_node,
8507            config,
8508        )
8509        .await;
8510
8511        let mut q = queues.write().await;
8512        for key in local_paid_presence_probe_keys {
8513            if storage.exists(&key).unwrap_or(false) {
8514                q.remove_pending(&key);
8515                terminal_keys.push(key);
8516                continue;
8517            }
8518            let mut sources = evidence.get(&key).map_or_else(Vec::new, |ev| {
8519                quorum::present_sources_for_key(&key, ev, &targets)
8520            });
8521            if let Some(entry) = q.get_pending(&key) {
8522                add_replica_hint_sources(&mut sources, &entry.replica_hint_sources);
8523            }
8524            if sources.is_empty() {
8525                no_holder_deferrals += 1;
8526                let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8527                let first_report = q.claim_no_holder_report(&key);
8528                report_unresolved_deferral("Locally paid key", &key, outcome, first_report);
8529            } else {
8530                // A holder answered, so whatever came before is not a run of
8531                // consecutive failures any more. Clear before promoting: if the
8532                // fetch queue is full the entry stays pending, and it must not
8533                // carry the old backoff.
8534                q.clear_unresolved(&key);
8535                let distance = crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8536                // Atomic remove+enqueue: if fetch_queue is at capacity, the
8537                // pending entry is preserved and retried next cycle (no
8538                // silent drop of verified replica-repair work).
8539                let _ = q.promote_pending_to_fetch(key, distance, sources);
8540            }
8541        }
8542    }
8543
8544    // Steps 2-5: Network verification (skipped if all keys resolved locally).
8545    if !keys_needing_network.is_empty() {
8546        // Step 2: Compute targets and run network verification round.
8547        let targets =
8548            quorum::compute_verification_targets(&keys_needing_network, p2p_node, config, &self_id)
8549                .await;
8550
8551        let evidence =
8552            quorum::run_verification_round(&keys_needing_network, &targets, p2p_node, config).await;
8553
8554        // Step 3: Evaluate results — collect outcomes without holding the write
8555        // lock across paid-list I/O.
8556        //
8557        // v12 §6 holder-eligibility: snapshot the per-peer last-commitment
8558        // table and recent_provers cache up front so the synchronous
8559        // evaluate_key_evidence_with_holder_check predicate can consult
8560        // them without awaiting. The predicate downgrades a Present
8561        // claim to Unresolved unless the peer is credited for that key.
8562        // Snapshot per-peer commitment data. We need two views:
8563        //   - `commitment_by_peer_snapshot`: peers that currently have
8564        //     a verified commitment record on file (used to look up
8565        //     their current hash).
8566        //   - `capable_peer_snapshot`: the sticky "ever v12-capable"
8567        //     set. Sourced from a separate set rather than the
8568        //     commitment map so eviction (PeerRemoved cleanup, sybil
8569        //     cap at `MAX_LAST_COMMITMENT_BY_PEER`) does NOT downgrade
8570        //     a previously-v12 peer to "legacy" credit-unconditionally.
8571        //     Legacy / pre-v12 peers that have never sent a commitment
8572        //     remain absent from the set and are credited via the
8573        //     legacy path so mixed-version networks stay live.
8574        let commitment_by_peer_snapshot: HashMap<PeerId, [u8; 32]> = {
8575            let map = last_commitment_by_peer.read().await;
8576            map.iter()
8577                // Read the CACHED hash (§13) — no per-cycle re-serialize/re-hash
8578                // of every peer's ~5 KiB commitment.
8579                .filter_map(|(p, rec)| rec.commitment_hash().map(|h| (*p, h)))
8580                .collect()
8581        };
8582        let capable_peer_snapshot: HashSet<PeerId> = ever_capable_peers.read().await.clone();
8583        // Take a full snapshot of recent_provers under the read lock,
8584        // then release. The cache is bounded (16/key × keys), so the
8585        // clone is cheap.
8586        let provers_snapshot = recent_provers.read().await.clone();
8587        // For the replica-fetch path, we need to know whether THIS
8588        // node already holds the key being verified. The v12 §6
8589        // holder-credit gate is meant to prevent uncredited Present
8590        // claims from contributing to paid-list / reward quorum for
8591        // keys we DO hold (and could audit ourselves). For keys we
8592        // are trying to FETCH (i.e. not in local storage), there is
8593        // no possible local audit credit, and gating the presence
8594        // quorum on credit would deadlock replica-repair in a
8595        // fully v12-capable close group.
8596        let mut locally_held: HashSet<XorName> = HashSet::new();
8597        for key in &keys_needing_network {
8598            if storage.exists(key).unwrap_or(false) {
8599                locally_held.insert(*key);
8600            }
8601        }
8602        let holder_credit = |peer: &PeerId, key: &XorName| -> bool {
8603            if !locally_held.contains(key) {
8604                // Replica-fetch path: we don't hold this key, so we
8605                // cannot have collected audit credit for it. Trust
8606                // Present claims to drive fetch-source promotion;
8607                // chunk-PUT payment_verifier is the security backstop
8608                // when the bytes actually arrive.
8609                return true;
8610            }
8611            if !capable_peer_snapshot.contains(peer) {
8612                // Pre-v12 / legacy peer that has never gossiped a
8613                // commitment. The v12 §6 holder-eligibility check
8614                // doesn't apply: their Present evidence comes through
8615                // the legacy path and we credit it unconditionally
8616                // so a mixed-version network stays live during
8617                // transition.
8618                return true;
8619            }
8620            let Some(hash) = commitment_by_peer_snapshot.get(peer) else {
8621                // Peer is commitment_capable (sticky) but currently
8622                // has no live commitment record on file (e.g. their
8623                // last gossip was evicted from the LRU cache, or it
8624                // failed verification). Withhold credit until they
8625                // re-prove storage under a fresh commitment.
8626                return false;
8627            };
8628            provers_snapshot.is_credited_holder(key, peer, hash)
8629        };
8630
8631        let mut evaluated: Vec<(XorName, KeyVerificationOutcome)> = Vec::new();
8632        {
8633            let q = queues.read().await;
8634            for key in &keys_needing_network {
8635                let Some(ev) = evidence.get(key) else {
8636                    continue;
8637                };
8638                if q.get_pending(key).is_none() {
8639                    continue;
8640                }
8641                let outcome = quorum::evaluate_key_evidence_with_holder_check(
8642                    key,
8643                    ev,
8644                    &targets,
8645                    config,
8646                    holder_credit,
8647                );
8648                evaluated.push((*key, outcome));
8649            }
8650        } // read lock released
8651
8652        // Step 4: Insert verified keys into PaidForList (no lock held).
8653        let mut paid_insert_keys: Vec<XorName> = Vec::new();
8654        for (key, outcome) in &evaluated {
8655            if matches!(
8656                outcome,
8657                KeyVerificationOutcome::QuorumVerified { .. }
8658                    | KeyVerificationOutcome::PaidListVerified { .. }
8659            ) {
8660                paid_insert_keys.push(*key);
8661            }
8662        }
8663        for key in &paid_insert_keys {
8664            if let Err(e) = paid_list.insert(key).await {
8665                warn!("Failed to add verified key to PaidForList: {e}");
8666            }
8667        }
8668
8669        // Verification established validity; the paid-list insert above records
8670        // it. Downloading the bytes is a separate duty, owed only by the
8671        // storage-admission group, asked on the same terms for every verified
8672        // key — the advertising peer's replica/paid labelling is a claim about
8673        // itself and carries no authority over what we store. This check is a
8674        // cheap pre-filter that keeps never-responsible keys out of the fetch
8675        // queue entirely; the authoritative gate is the per-attempt recheck in
8676        // `execute_single_fetch`, because a key can wait in the nearest-first
8677        // fetch queue long enough for this promotion-time answer to go stale.
8678        let mut fetch_allowed_keys: HashSet<XorName> = HashSet::new();
8679        for (key, outcome) in &evaluated {
8680            if matches!(
8681                outcome,
8682                KeyVerificationOutcome::QuorumVerified { .. }
8683                    | KeyVerificationOutcome::PaidListVerified { .. }
8684            ) && !storage.exists(key).unwrap_or(false)
8685                && is_storage_admitted(&self_id, key, p2p_node, config).await
8686            {
8687                fetch_allowed_keys.insert(*key);
8688            }
8689        }
8690
8691        // Step 5: Update queues with the evaluated outcomes.
8692        let mut bad_singleton_hints: HashMap<(PeerId, SingletonHintFault), usize> = HashMap::new();
8693        let mut q = queues.write().await;
8694        for (key, outcome) in evaluated {
8695            let replica_hint_sources = q
8696                .get_pending(&key)
8697                .map(|entry| entry.replica_hint_sources.clone())
8698                .unwrap_or_default();
8699            if let Some(ev) = evidence.get(&key) {
8700                if let Some(source) =
8701                    punishable_singleton_replica_hint_source(&replica_hint_sources, &outcome, ev)
8702                {
8703                    *bad_singleton_hints.entry(source).or_insert(0) += 1;
8704                }
8705            }
8706            match outcome {
8707                KeyVerificationOutcome::QuorumVerified { sources }
8708                | KeyVerificationOutcome::PaidListVerified { sources } => {
8709                    let mut fetch_sources = sources;
8710                    add_replica_hint_sources(&mut fetch_sources, &replica_hint_sources);
8711                    let fetch_eligible = fetch_allowed_keys.contains(&key);
8712                    if fetch_eligible && write_blocked {
8713                        // Capacity gate, second of two, and deliberately after
8714                        // Step 4: the key is now recorded in `PaidForList` and
8715                        // its verification stands. Only the download is held,
8716                        // because `execute_single_fetch` would refuse it and
8717                        // hand the key straight back here.
8718                        if q.defer_pending(&key, config::CAPACITY_BLOCKED_RETRY) {
8719                            capacity_deferred_promote += 1;
8720                        }
8721                    } else if fetch_eligible && !fetch_sources.is_empty() {
8722                        // A holder answered; see the matching clear on the
8723                        // local-paid path.
8724                        q.clear_unresolved(&key);
8725                        let distance =
8726                            crate::client::xor_distance(&key, p2p_node.peer_id().as_bytes());
8727                        // Atomic remove+enqueue: on fetch_queue capacity miss
8728                        // the pending entry is preserved so this verified key
8729                        // is retried on the next cycle (no silent drop).
8730                        let _ = q.promote_pending_to_fetch(key, distance, fetch_sources);
8731                        // Not terminal — either moved to fetch queue, or
8732                        // retained as pending until queue drains.
8733                    } else if fetch_eligible && fetch_sources.is_empty() {
8734                        no_holder_deferrals += 1;
8735                        let outcome = q.defer_unresolved(&key, config.verification_request_timeout);
8736                        let first_report = q.claim_no_holder_report(&key);
8737                        report_unresolved_deferral(
8738                            "Verified storage-admitted key",
8739                            &key,
8740                            outcome,
8741                            first_report,
8742                        );
8743                    } else {
8744                        q.remove_pending(&key);
8745                        terminal_keys.push(key);
8746                    }
8747                }
8748                KeyVerificationOutcome::QuorumFailed => {
8749                    q.remove_pending(&key);
8750                    terminal_keys.push(key);
8751                }
8752                KeyVerificationOutcome::QuorumInconclusive => {
8753                    q.set_pending_state(&key, VerificationState::QuorumInconclusive);
8754                    // Backed off like any other unresolved round, but it does
8755                    // NOT claim the no-holder report: nothing yet says this key
8756                    // has no holder, so the first round that does say so must
8757                    // still be the one that warns.
8758                    let _ = q.defer_unresolved(&key, config.verification_request_timeout);
8759                }
8760            }
8761        }
8762        drop(q);
8763
8764        for ((peer, fault), bad_hint_count) in bad_singleton_hints {
8765            let reports = bad_hint_count.min(MAX_BAD_HINT_TRUST_REPORTS_PER_PEER_PER_CYCLE);
8766            warn!(
8767                "Peer {peer} submitted {bad_hint_count} rejected or self-contradicting \
8768                 sole-source replica hints ({fault:?}); \
8769                 reporting {reports} bounded trust failure(s)"
8770            );
8771            for _ in 0..reports {
8772                match fault {
8773                    // A claim about a key that does not exist. Punishable whatever the
8774                    // sender's disk is doing.
8775                    SingletonHintFault::RejectedByCloseGroup => {
8776                        p2p_node
8777                            .report_trust_event(
8778                                &peer,
8779                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
8780                            )
8781                            .await;
8782                    }
8783                    // "I advertised it and no longer have it." That is the one statement a
8784                    // node short of disk cannot avoid making while it moves its chunks, so
8785                    // it goes through the release switch.
8786                    SingletonHintFault::DeniedPossession => {
8787                        config::penalise_unheld_close_group_chunk(
8788                            p2p_node,
8789                            &peer,
8790                            "replica_hint_denied_possession",
8791                            REPLICATION_TRUST_WEIGHT,
8792                        )
8793                        .await;
8794                    }
8795                }
8796            }
8797        }
8798    }
8799
8800    // Step 6: Remove terminal keys from bootstrap pending set and re-check
8801    // the drain condition.
8802    update_bootstrap_after_verification(
8803        &terminal_keys,
8804        bootstrap_state,
8805        queues,
8806        is_bootstrapping,
8807        bootstrap_complete_notify,
8808    )
8809    .await;
8810
8811    let (pending_after, fetch_after, in_flight_after) = {
8812        let q = queues.read().await;
8813        (
8814            q.pending_count(),
8815            q.fetch_queue_count(),
8816            q.in_flight_count(),
8817        )
8818    };
8819    let terminal_key_count = terminal_keys.len();
8820    let elapsed_ms = cycle_started.elapsed().as_millis();
8821
8822    if elapsed_ms >= VERIFICATION_CYCLE_SLOW_LOG_MS {
8823        info!(
8824            target: "ant_node::replication::verification",
8825            "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}",
8826        );
8827    } else {
8828        debug!(
8829            target: "ant_node::replication::verification",
8830            "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}",
8831        );
8832    }
8833}
8834
8835/// Report a verification round that left a key without a usable holder.
8836///
8837/// Warns once per entry — the first failure is news, and by the hundredth the
8838/// node is re-asking peers it has already exhausted. Later failures stay at
8839/// `debug`, and the per-cycle count is carried in the cycle summary so the
8840/// scale of a backlog is still visible without a line per key per retry.
8841///
8842/// `first_report` comes from `claim_no_holder_report`, not from the attempt
8843/// number: a round may advance the count without producing a no-holder result,
8844/// and such a round must not consume the warning.
8845///
8846/// Eviction at `PENDING_VERIFY_MAX_AGE` drops the entry, and a round that finds
8847/// a holder clears it, so a later relapse warns again: "once per episode", not
8848/// "once ever".
8849fn report_unresolved_deferral(
8850    what: &str,
8851    key: &XorName,
8852    outcome: Option<DeferralOutcome>,
8853    first_report: bool,
8854) {
8855    let Some(outcome) = outcome else {
8856        // The entry left `pending_verify` under the same lock; nothing deferred.
8857        return;
8858    };
8859    if first_report {
8860        warn!(
8861            "{what} {} has no responding holders yet; deferring retry",
8862            hex::encode(key)
8863        );
8864    } else {
8865        debug!(
8866            "{what} {} still has no responding holders after {} attempts; \
8867             retrying in {}s",
8868            hex::encode(key),
8869            outcome.attempt,
8870            outcome.retry_after.as_secs()
8871        );
8872    }
8873}
8874
8875/// Add peers that claimed possession as fallback fetch sources.
8876///
8877/// Paid-only advertisers make no possession claim and are absent from
8878/// `replica_hint_sources` by construction, so they are never added.
8879fn add_replica_hint_sources(sources: &mut Vec<PeerId>, replica_hint_sources: &HashSet<PeerId>) {
8880    for source in replica_hint_sources {
8881        if !sources.contains(source) {
8882            sources.push(*source);
8883        }
8884    }
8885}
8886
8887/// Why a sole-source replica hint is punishable.
8888///
8889/// The two cases look alike and are not. A hint the close group rejects outright is a
8890/// claim about a key that does not exist, which is a bad hint however the sender's disk is
8891/// doing. A sender that advertised a key and then answers `Absent` for it is making a
8892/// statement about its own storage, and that is the one thing a node short of disk cannot
8893/// avoid saying while it moves its chunks out of a store that will not give the space back.
8894#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8895enum SingletonHintFault {
8896    /// The close group says the key does not exist.
8897    RejectedByCloseGroup,
8898    /// The sender advertised the key and then denied holding it.
8899    DeniedPossession,
8900}
8901
8902/// Return the sole replica advertiser when either the close group definitively
8903/// rejects the key or the advertiser explicitly denies possessing it, and say which.
8904/// Paid-only advertisements, corroborated replica hints, and inconclusive
8905/// rounds without that direct contradiction are deliberately non-penalizing.
8906fn punishable_singleton_replica_hint_source(
8907    replica_hint_sources: &HashSet<PeerId>,
8908    outcome: &KeyVerificationOutcome,
8909    evidence: &crate::replication::types::KeyVerificationEvidence,
8910) -> Option<(PeerId, SingletonHintFault)> {
8911    // A paid-only advertiser leaves this set empty, so the sole-source lane is
8912    // reserved for peers that actually claimed possession.
8913    if replica_hint_sources.len() != 1 {
8914        return None;
8915    }
8916    let source = *replica_hint_sources.iter().next()?;
8917    if matches!(outcome, KeyVerificationOutcome::QuorumFailed) {
8918        return Some((source, SingletonHintFault::RejectedByCloseGroup));
8919    }
8920    if evidence.presence.get(&source) == Some(&PresenceEvidence::Absent) {
8921        return Some((source, SingletonHintFault::DeniedPossession));
8922    }
8923    None
8924}
8925
8926/// Post-verification bootstrap bookkeeping: remove terminal keys from the
8927/// bootstrap pending set and transition out of bootstrapping when drained.
8928async fn update_bootstrap_after_verification(
8929    terminal_keys: &[XorName],
8930    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8931    queues: &Arc<RwLock<ReplicationQueues>>,
8932    is_bootstrapping: &Arc<RwLock<bool>>,
8933    bootstrap_complete_notify: &Arc<Notify>,
8934) {
8935    if terminal_keys.is_empty() || bootstrap_state.read().await.is_drained() {
8936        return;
8937    }
8938    {
8939        let mut bs = bootstrap_state.write().await;
8940        for key in terminal_keys {
8941            bs.remove_key(key);
8942        }
8943    }
8944    let q = queues.read().await;
8945    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8946        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8947    }
8948}
8949
8950/// Retire bootstrap work owed by a peer that permanently left the routing
8951/// table, then immediately re-check drain so this removal can complete
8952/// bootstrap without waiting for an unrelated pipeline event.
8953async fn update_bootstrap_after_peer_removed(
8954    peer: &PeerId,
8955    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8956    queues: &Arc<RwLock<ReplicationQueues>>,
8957    is_bootstrapping: &Arc<RwLock<bool>>,
8958    bootstrap_complete_notify: &Arc<Notify>,
8959) {
8960    let orphaned_keys = queues.write().await.remove_hint_source(peer);
8961    let cleared_rejection = bootstrap::clear_capacity_rejected(bootstrap_state, peer).await;
8962
8963    if !orphaned_keys.is_empty() {
8964        let mut state = bootstrap_state.write().await;
8965        for key in &orphaned_keys {
8966            state.remove_key(key);
8967        }
8968    }
8969
8970    if orphaned_keys.is_empty() && !cleared_rejection {
8971        return;
8972    }
8973    let q = queues.read().await;
8974    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
8975        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
8976    }
8977}
8978
8979/// Periodic bootstrap-drain self-healing, run on every verification worker
8980/// tick until bootstrap drains.
8981///
8982/// Two liveness gaps make this necessary. A `PeerRemoved` that races the
8983/// recording of a capacity rejection leaves an entry no future event can
8984/// clear — `max_age` expiry is its only exit. And a clean-cycle
8985/// `clear_capacity_rejected` never triggers its own drain re-check, so on a
8986/// quiet node the drain condition can become true with nothing left to
8987/// observe it. Expiry must run even while `pending_peer_requests` blocks the
8988/// drain itself, so this is invoked before `run_verification_cycle`'s
8989/// early-returns.
8990async fn expire_and_recheck_bootstrap_drain(
8991    bootstrap_state: &Arc<RwLock<BootstrapState>>,
8992    queues: &Arc<RwLock<ReplicationQueues>>,
8993    is_bootstrapping: &Arc<RwLock<bool>>,
8994    bootstrap_complete_notify: &Arc<Notify>,
8995    max_age: Duration,
8996) {
8997    if bootstrap_state.read().await.is_drained() {
8998        return;
8999    }
9000    bootstrap::expire_capacity_rejected(bootstrap_state, max_age).await;
9001    let q = queues.read().await;
9002    if bootstrap::check_bootstrap_drained(bootstrap_state, &q).await {
9003        complete_bootstrap(is_bootstrapping, bootstrap_complete_notify).await;
9004    }
9005}
9006
9007/// Set `is_bootstrapping` to `false` and wake all waiters.
9008async fn complete_bootstrap(
9009    is_bootstrapping: &Arc<RwLock<bool>>,
9010    bootstrap_complete_notify: &Arc<Notify>,
9011) {
9012    *is_bootstrapping.write().await = false;
9013    bootstrap_complete_notify.notify_waiters();
9014    info!("Replication bootstrap complete");
9015}
9016
9017// ---------------------------------------------------------------------------
9018// Fetch types and single-fetch executor
9019// ---------------------------------------------------------------------------
9020
9021/// Result classification for a single fetch attempt.
9022enum FetchResult {
9023    /// Data fetched, integrity-checked, and stored successfully.
9024    Stored,
9025    /// Content-address integrity check failed — do not retry.
9026    IntegrityFailed,
9027    /// Source failed (network error or non-success response) — retryable.
9028    SourceFailed,
9029    /// This node could not write the chunk locally: the capacity pre-check
9030    /// refused before the dial, or `put` failed after the bytes arrived.
9031    ///
9032    /// Distinct from [`Self::SourceFailed`] because nothing about the source
9033    /// is implicated, and because the remedy is the opposite one. A source
9034    /// failure should move on to the next holder; a local write failure must
9035    /// not — every remaining source would send the same chunk into the same
9036    /// full disk. The key returns to verification instead, so a later cycle
9037    /// retries it once local capacity allows. That is a retry path, not a
9038    /// liveness guarantee: `evict_stale` still expires the entry at
9039    /// `PENDING_VERIFY_MAX_AGE` measured from when it was first queued, after
9040    /// which re-acquisition depends on a fresh hint.
9041    LocalWriteFailed,
9042    /// This node already holds the key, so there is nothing to fetch —
9043    /// terminal, exactly like [`Self::Stored`], because the duty is already
9044    /// discharged.
9045    ///
9046    /// Responsibility is rechecked at download time; possession has to be too.
9047    /// The earlier gates already drop held keys out of the fetch pipeline —
9048    /// `queue_admitted_hints` skips them, and the promotion-time
9049    /// `fetch_allowed_keys` filter and the local-paid probe both terminate
9050    /// them. (`is_relevant` is not one of them: possession there makes a key
9051    /// *relevant*, which is what keeps us tracking it.) So a held key reaches
9052    /// the dial only when it arrived *after* promotion — a fresh-offer push, a
9053    /// client PUT, or another source landing first. The nearest-first fetch
9054    /// queue is deep enough for that window to be real.
9055    ///
9056    /// This check must also precede the capacity pre-check below, because
9057    /// `ChunkStore::put` tests `exists` *before* it tests disk space: without
9058    /// it, a full node would decline a key it already holds, which `put` would
9059    /// have accepted as a duplicate.
9060    AlreadyHeld,
9061    /// Live routing state no longer places this node in the storage-admission
9062    /// group for the key — terminal, exactly like [`Self::Stored`]. The duty
9063    /// the fetch was serving has lapsed, so no alternate source is tried and
9064    /// no trust event is reported: the source did nothing wrong.
9065    NoLongerResponsible,
9066}
9067
9068/// Outcome produced by [`execute_single_fetch`] and consumed by the fetch
9069/// worker loop to update queue state.
9070struct FetchOutcome {
9071    key: XorName,
9072    result: FetchResult,
9073}
9074
9075/// What the fetch worker must do next for a key whose fetch attempt resolved.
9076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9077enum FetchFollowUp {
9078    /// The key terminally left the fetch pipeline (its in-flight entry is
9079    /// removed and any verification retry-slot reservation released); the
9080    /// caller must run bootstrap accounting for it.
9081    Terminal,
9082    /// The key returned to `pending_verify` for a later verification round.
9083    RequeuedForVerification,
9084    /// Retry immediately from this next untried verified source.
9085    RetryFrom(PeerId),
9086}
9087
9088/// Apply a resolved [`FetchResult`] to the queues and report the follow-up.
9089///
9090/// Split out of the fetch-worker loop so the per-variant queue transitions
9091/// are unit-testable without a live network. The caller holds the queues
9092/// write lock. [`FetchResult::NoLongerResponsible`] deliberately shares
9093/// [`FetchResult::Stored`]'s terminal path: `complete_fetch` releases the
9094/// retry-slot reservation, and the caller's terminal handling shrinks the
9095/// bootstrap pending set — dropping the key without that accounting would
9096/// stall bootstrap drain forever.
9097///
9098/// The nursery `option_if_let_else` rewrite is impossible here: both
9099/// `map_or_else` closures would need `&mut *q` simultaneously.
9100#[allow(clippy::option_if_let_else)]
9101fn apply_fetch_result(
9102    q: &mut ReplicationQueues,
9103    key: &XorName,
9104    result: &FetchResult,
9105    verification_retry_after: Duration,
9106) -> FetchFollowUp {
9107    match result {
9108        FetchResult::Stored | FetchResult::NoLongerResponsible | FetchResult::AlreadyHeld => {
9109            q.complete_fetch(key);
9110            FetchFollowUp::Terminal
9111        }
9112        FetchResult::IntegrityFailed | FetchResult::SourceFailed => {
9113            if let Some(next_peer) = q.retry_fetch(key) {
9114                FetchFollowUp::RetryFrom(next_peer)
9115            } else if q.requeue_fetch_for_verification(key, verification_retry_after) {
9116                FetchFollowUp::RequeuedForVerification
9117            } else {
9118                FetchFollowUp::Terminal
9119            }
9120        }
9121        // No `retry_fetch`: the local write is what failed, so every other
9122        // source would be asked to send the same chunk into the same full
9123        // disk. Requeueing for verification is what keeps the key from being
9124        // stranded — it comes back once capacity allows — and the fallthrough
9125        // to `Terminal` when there is no retry metadata is what keeps
9126        // bootstrap drain accounting correct, exactly as for a source failure.
9127        //
9128        // The ordinary requeue delay, deliberately. A standing capacity block
9129        // does not need a longer one here: the key returns to pending, and the
9130        // gate at the head of the next cycle defers it for minutes. A separate
9131        // backoff on this path would duplicate that to save one 15 s round, on
9132        // a race the gate already makes rare.
9133        FetchResult::LocalWriteFailed => {
9134            if q.requeue_fetch_for_verification(key, verification_retry_after) {
9135                FetchFollowUp::RequeuedForVerification
9136            } else {
9137                FetchFollowUp::Terminal
9138            }
9139        }
9140    }
9141}
9142
9143/// Whether this node currently sits inside the storage-admission group for
9144/// `key`, per live local routing state.
9145///
9146/// This is the one question every storage decision in this module asks; see
9147/// [`admission::is_responsible`]. A purely local routing-table lookup — no
9148/// network I/O — but it awaits into the DHT manager, so callers must not
9149/// hold the queues lock across it.
9150async fn is_storage_admitted(
9151    self_id: &PeerId,
9152    key: &XorName,
9153    p2p_node: &Arc<P2PNode>,
9154    config: &ReplicationConfig,
9155) -> bool {
9156    admission::is_responsible(
9157        self_id,
9158        key,
9159        p2p_node,
9160        storage_admission_width(config.close_group_size),
9161    )
9162    .await
9163}
9164
9165#[allow(clippy::too_many_lines)]
9166/// Execute a single fetch request against `source` for `key`.
9167///
9168/// Handles encoding, network I/O, integrity checking, storage, and trust
9169/// event reporting.  Returns a [`FetchOutcome`] so the caller can update
9170/// queue state without holding any locks during the network round-trip.
9171///
9172/// This is the authoritative storage-responsibility gate: each attempt —
9173/// including every per-source retry, which re-enters here — rechecks live
9174/// routing state before spending bandwidth, and once more before writing
9175/// bytes that arrived after a round-trip. The verification-time check that
9176/// promoted the key into the fetch queue is only a pre-filter; the queue is
9177/// nearest-first and deep, so a promotion decision can go stale under
9178/// topology churn before the key is ever dequeued.
9179async fn execute_single_fetch(
9180    p2p_node: Arc<P2PNode>,
9181    storage: Arc<ChunkStore>,
9182    config: Arc<ReplicationConfig>,
9183    key: XorName,
9184    source: PeerId,
9185) -> FetchOutcome {
9186    let self_id = *p2p_node.peer_id();
9187    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9188        debug!(
9189            "Skipping fetch for {}: no longer in the storage-admission group",
9190            hex::encode(key)
9191        );
9192        return FetchOutcome {
9193            key,
9194            result: FetchResult::NoLongerResponsible,
9195        };
9196    }
9197
9198    // Possession, then capacity — both before the dial, and in that order.
9199    //
9200    // `ChunkStore::put` tests `exists` before it tests disk space, so a full
9201    // node still accepts a key it already holds. Checking possession first is
9202    // what keeps this pair of gates from declining work `put` would have
9203    // taken.
9204    if storage.exists(&key).unwrap_or(false) {
9205        debug!(
9206            "Skipping fetch for {}: already held locally",
9207            hex::encode(key)
9208        );
9209        return FetchOutcome {
9210            key,
9211            result: FetchResult::AlreadyHeld,
9212        };
9213    }
9214
9215    // Capacity is checked before the dial rather than after the bytes arrive.
9216    // `put` runs this same check on every write of a key it does not already
9217    // hold, so this reaches the same verdict `put` would reach *at this
9218    // instant*. It is not a guarantee about the later write: both answers can
9219    // change across the round trip. Space freed in between would have let a
9220    // post-download `put` succeed, so a refusal here can cost a fleeting
9221    // acquisition and one retry cycle of delay; space lost in between is why
9222    // the check inside `put` still has to stay.
9223    //
9224    // What it buys is that the refusal costs no bandwidth. Without it a
9225    // disk-full node pulls the whole chunk over the network first, and the
9226    // failure is then classified as the source's — no trust event, but the
9227    // worker walks to every remaining holder, and each re-uploads the same
9228    // chunk into the same full disk.
9229    if let Err(e) = storage.check_capacity() {
9230        debug!(
9231            "Skipping fetch for {}: local storage cannot accept a write: {e}",
9232            hex::encode(key)
9233        );
9234        return FetchOutcome {
9235            key,
9236            result: FetchResult::LocalWriteFailed,
9237        };
9238    }
9239
9240    let request = protocol::FetchRequest { key };
9241    let msg = ReplicationMessage {
9242        request_id: rand::thread_rng().gen::<u64>(),
9243        body: ReplicationMessageBody::FetchRequest(request),
9244    };
9245
9246    let encoded = match msg.encode() {
9247        Ok(data) => data,
9248        Err(e) => {
9249            warn!("Failed to encode fetch request: {e}");
9250            return FetchOutcome {
9251                key,
9252                result: FetchResult::SourceFailed,
9253            };
9254        }
9255    };
9256
9257    let result = p2p_node
9258        .send_request(
9259            &source,
9260            REPLICATION_PROTOCOL_ID,
9261            encoded,
9262            config.fetch_request_timeout,
9263        )
9264        .await;
9265
9266    match result {
9267        Ok(response) => {
9268            let Ok(resp_msg) = ReplicationMessage::decode(&response.data) else {
9269                p2p_node
9270                    .report_trust_event(
9271                        &source,
9272                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9273                    )
9274                    .await;
9275                return FetchOutcome {
9276                    key,
9277                    result: FetchResult::SourceFailed,
9278                };
9279            };
9280
9281            match resp_msg.body {
9282                ReplicationMessageBody::FetchResponse(protocol::FetchResponse::Success {
9283                    key: resp_key,
9284                    data,
9285                }) => {
9286                    // Validate the response key matches the requested key.
9287                    // A malicious peer could serve valid data for a different
9288                    // key, passing integrity checks while the requested key
9289                    // is falsely marked as fetched.
9290                    if resp_key != key {
9291                        warn!(
9292                            "Fetch response key mismatch: requested {}, got {}",
9293                            hex::encode(key),
9294                            hex::encode(resp_key)
9295                        );
9296                        p2p_node
9297                            .report_trust_event(
9298                                &source,
9299                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9300                            )
9301                            .await;
9302                        return FetchOutcome {
9303                            key,
9304                            result: FetchResult::IntegrityFailed,
9305                        };
9306                    }
9307
9308                    // Enforce chunk size invariant on fetched data.
9309                    // Checked before the content-address hash to avoid
9310                    // hashing up to 10 MiB of oversized junk data.
9311                    if data.len() > crate::ant_protocol::MAX_CHUNK_SIZE {
9312                        warn!(
9313                            "Fetched record {} exceeds MAX_CHUNK_SIZE ({} > {})",
9314                            hex::encode(resp_key),
9315                            data.len(),
9316                            crate::ant_protocol::MAX_CHUNK_SIZE,
9317                        );
9318                        p2p_node
9319                            .report_trust_event(
9320                                &source,
9321                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9322                            )
9323                            .await;
9324                        return FetchOutcome {
9325                            key,
9326                            result: FetchResult::IntegrityFailed,
9327                        };
9328                    }
9329
9330                    // Content-address integrity check.
9331                    let computed = crate::client::compute_address(&data);
9332                    if computed != resp_key {
9333                        warn!(
9334                            "Fetched record integrity check failed: expected {}, got {}",
9335                            hex::encode(resp_key),
9336                            hex::encode(computed)
9337                        );
9338                        p2p_node
9339                            .report_trust_event(
9340                                &source,
9341                                TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9342                            )
9343                            .await;
9344                        return FetchOutcome {
9345                            key,
9346                            result: FetchResult::IntegrityFailed,
9347                        };
9348                    }
9349
9350                    // Responsibility can lapse during the network round-trip.
9351                    // The bandwidth is already spent; declining the write is
9352                    // what still avoids the disk write and the later
9353                    // fetch→store→prune churn. Edge flapping is dampened by
9354                    // the margin `storage_admission_width` adds over
9355                    // `close_group_size`.
9356                    if !is_storage_admitted(&self_id, &key, &p2p_node, &config).await {
9357                        debug!(
9358                            "Fetched {} but responsibility lapsed in transit; not storing",
9359                            hex::encode(key)
9360                        );
9361                        return FetchOutcome {
9362                            key,
9363                            result: FetchResult::NoLongerResponsible,
9364                        };
9365                    }
9366
9367                    if let Err(e) = storage.put(&resp_key, &data).await {
9368                        // The bytes arrived and passed the content-address
9369                        // check, so the source did its job; the failure is
9370                        // entirely local (disk-full, or an LMDB error). Any
9371                        // valid source must serve identical content, so trying
9372                        // the next one cannot cure a local error — it only
9373                        // re-downloads the same chunk into the same store.
9374                        warn!(
9375                            "Failed to store fetched record {}: {e}",
9376                            hex::encode(resp_key)
9377                        );
9378                        return FetchOutcome {
9379                            key,
9380                            result: FetchResult::LocalWriteFailed,
9381                        };
9382                    }
9383
9384                    FetchOutcome {
9385                        key,
9386                        result: FetchResult::Stored,
9387                    }
9388                }
9389                ReplicationMessageBody::FetchResponse(
9390                    ref response @ (protocol::FetchResponse::NotFound { .. }
9391                    | protocol::FetchResponse::Error { .. }),
9392                ) => {
9393                    // This peer was selected as a fetch source because it recently
9394                    // answered `Present` during verification, so either answer is
9395                    // evidence of something. Which one decides what it is charged: a peer
9396                    // that does not hold the chunk is the lane this release withholds, a
9397                    // peer whose own read failed is not.
9398                    if let protocol::FetchResponse::Error { reason, .. } = response {
9399                        warn!(
9400                            "Fetch: peer {source} returned error for {}: {reason}",
9401                            hex::encode(key)
9402                        );
9403                    } else {
9404                        warn!(
9405                            "Fetch: verified source {source} returned NotFound for {}",
9406                            hex::encode(key)
9407                        );
9408                    }
9409                    if let Some(fault) = fetch_fault_for(response) {
9410                        let lane = match fault {
9411                            FetchFault::UnheldChunk => "fetch_not_found",
9412                            FetchFault::ResponderFault => "fetch_error",
9413                        };
9414                        charge_fetch_fault(&p2p_node, &source, fault, lane).await;
9415                    }
9416                    FetchOutcome {
9417                        key,
9418                        result: FetchResult::SourceFailed,
9419                    }
9420                }
9421                _ => {
9422                    // Unexpected message type — treat as malformed.
9423                    p2p_node
9424                        .report_trust_event(
9425                            &source,
9426                            TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9427                        )
9428                        .await;
9429                    FetchOutcome {
9430                        key,
9431                        result: FetchResult::SourceFailed,
9432                    }
9433                }
9434            }
9435        }
9436        Err(e) => {
9437            debug!("Fetch request to {source} failed: {e}");
9438            // No ApplicationFailure here — P2PNode::send_request() already
9439            // reports ConnectionTimeout / ConnectionFailed to the TrustEngine.
9440            FetchOutcome {
9441                key,
9442                result: FetchResult::SourceFailed,
9443            }
9444        }
9445    }
9446}
9447
9448// ---------------------------------------------------------------------------
9449// Audit result handler
9450// ---------------------------------------------------------------------------
9451
9452/// Format the first confirmed-failed key as a 16-hex-char label.
9453///
9454/// Pairs with `challenged_peer` to form a stable cross-host correlation
9455/// handle in the audit-failure log line, e.g.
9456///
9457/// ```text
9458/// Audit failure for <peer>: …, `first_failed_key=0x18878f1d2d9e0612`
9459/// ```
9460///
9461/// Falls back to `"0x"` when the list is empty so the log line never
9462/// contains a misleading default.
9463fn first_failed_key_label(confirmed_failed_keys: &[XorName]) -> String {
9464    confirmed_failed_keys.first().map_or_else(
9465        || "0x".to_string(),
9466        |k| format!("0x{}", hex::encode(&k[..8])),
9467    )
9468}
9469
9470/// Execute the side effects for a subtree storage-commitment audit failure.
9471///
9472/// Subtree timeouts are fully graced: the multi-round, multi-chunk challenge can
9473/// legitimately time out on slow or loaded honest peers, so it never touches the
9474/// responsible-chunk audit path or its timeout accounting. Confirmed subtree
9475/// failures still penalise immediately and revoke holder credit.
9476async fn handle_subtree_failed_audit(
9477    challenged_peer: &PeerId,
9478    confirmed_failed_key_count: usize,
9479    reason: &AuditFailureReason,
9480    p2p_node: &Arc<P2PNode>,
9481    sync_state: &Arc<RwLock<NeighborSyncState>>,
9482    recent_provers: &Arc<RwLock<RecentProvers>>,
9483) {
9484    if matches!(reason, AuditFailureReason::Timeout) {
9485        debug!(
9486            "Audit timeout for {challenged_peer} fully graced \
9487             (subtree audit does not evict on timeout)"
9488        );
9489        return;
9490    }
9491
9492    // The caller already logged the rich failure line with reason + per-category
9493    // summary; avoid a redundant second error log here.
9494    let _ = confirmed_failed_key_count;
9495    {
9496        let mut state = sync_state.write().await;
9497        state.clear_active_bootstrap_claim(challenged_peer);
9498    }
9499    {
9500        let mut provers_guard = recent_provers.write().await;
9501        apply_audit_failure_credit_revocation(&mut provers_guard, challenged_peer, reason);
9502    }
9503    // Deliberately NOT routed through the release switch. This is the commitment-bound
9504    // subtree audit: the peer published a signed claim to hold these keys and could not
9505    // answer for them. That contract is enforced in every release, including the one that
9506    // withholds the penalty for merely not holding a close-group chunk, because the whole
9507    // migration depends on a node's reduced commitment still meaning something.
9508    p2p_node
9509        .report_trust_event(
9510            challenged_peer,
9511            TrustEvent::ApplicationFailure(config::AUDIT_FAILURE_TRUST_WEIGHT),
9512        )
9513        .await;
9514}
9515
9516/// Handle audit result: log findings and emit trust events.
9517async fn handle_subtree_audit_result(
9518    result: &AuditTickResult,
9519    p2p_node: &Arc<P2PNode>,
9520    sync_state: &Arc<RwLock<NeighborSyncState>>,
9521    recent_provers: &Arc<RwLock<RecentProvers>>,
9522    config: &ReplicationConfig,
9523) {
9524    match result {
9525        AuditTickResult::Passed {
9526            challenged_peer,
9527            keys_checked,
9528        } => {
9529            protocol::record_audit_pass(protocol::AuditOutcomeKind::Subtree);
9530            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9531            // Peer responded normally — clear the active bootstrap claim while
9532            // retaining history so a later claim is treated as repeated abuse.
9533            {
9534                let mut state = sync_state.write().await;
9535                state.clear_active_bootstrap_claim(challenged_peer);
9536            }
9537            p2p_node
9538                .report_trust_event(
9539                    challenged_peer,
9540                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9541                )
9542                .await;
9543        }
9544        AuditTickResult::Failed {
9545            evidence,
9546            no_response_class,
9547        } => {
9548            if let FailureEvidence::AuditFailure {
9549                challenged_peer,
9550                confirmed_failed_keys,
9551                summary,
9552                reason,
9553                ..
9554            } = evidence
9555            {
9556                protocol::record_audit_fail(protocol::AuditOutcomeKind::Subtree, reason);
9557                // Rich diagnostics (from main's audit-failure logging) + the
9558                // first-failed-key correlation handle.
9559                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9560                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9561                error!(
9562                    "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}",
9563                    audit_failure_class,
9564                    confirmed_failed_keys.len(),
9565                    summary.challenged_keys,
9566                    summary.absent_keys,
9567                    summary.digest_mismatch_keys,
9568                );
9569                // Route the side effects through the subtree-only failure path.
9570                // Responsible-chunk `AuditChallenge` handling intentionally uses
9571                // its own old immediate-penalty handler below.
9572                handle_subtree_failed_audit(
9573                    challenged_peer,
9574                    confirmed_failed_keys.len(),
9575                    reason,
9576                    p2p_node,
9577                    sync_state,
9578                    recent_provers,
9579                )
9580                .await;
9581            }
9582        }
9583        AuditTickResult::BootstrapClaim { peer } => {
9584            // Gap 6: BootstrapClaimAbuse grace period in audit path.
9585            // Separate state mutation from network I/O to avoid holding the
9586            // write lock across report_trust_event.
9587            let should_report = {
9588                let now = Instant::now();
9589                let mut state = sync_state.write().await;
9590                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9591                {
9592                    BootstrapClaimObservation::WithinGrace { .. } => {
9593                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9594                        false
9595                    }
9596                    BootstrapClaimObservation::PastGrace { first_seen } => {
9597                        warn!(
9598                            "Audit: peer {peer} claiming bootstrap past grace period \
9599                             ({:?} > {:?}), reporting abuse",
9600                            now.duration_since(first_seen),
9601                            config.bootstrap_claim_grace_period,
9602                        );
9603                        true
9604                    }
9605                    BootstrapClaimObservation::Repeated { first_seen } => {
9606                        warn!(
9607                            "Audit: peer {peer} repeated bootstrap claim after previously \
9608                             stopping; first claim was {:?} ago, reporting abuse",
9609                            now.duration_since(first_seen),
9610                        );
9611                        true
9612                    }
9613                }
9614            };
9615            if should_report {
9616                p2p_node
9617                    .report_trust_event(
9618                        peer,
9619                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9620                    )
9621                    .await;
9622            }
9623        }
9624        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9625    }
9626}
9627
9628/// Whether a confirmed audit failure with this reason clears the peer's active
9629/// bootstrap claim. A `Timeout` does not (the peer may still be legitimately
9630/// bootstrapping); every confirmed storage-integrity reason does.
9631///
9632/// Responsible-chunk `AuditChallenge` failures use this directly: timeouts keep
9633/// the bootstrap claim, matching the pre-ADR-0002 behaviour, while every failure
9634/// still reports the normal audit trust penalty.
9635fn audit_failure_clears_bootstrap_claim(reason: &AuditFailureReason) -> bool {
9636    !matches!(reason, AuditFailureReason::Timeout)
9637}
9638
9639/// Handle the result of a responsible-chunk audit tick (audit #2): emit trust
9640/// events and manage bootstrap-claim state.
9641///
9642/// This is intentionally separate from the subtree audit result handler. A
9643/// responsible-chunk `AuditChallenge` `Failed` result reports
9644/// `ApplicationFailure` immediately for every reason, including `Timeout`,
9645/// restoring the pre-ADR-0002 behaviour.
9646#[allow(clippy::too_many_lines)]
9647async fn handle_audit_result(
9648    result: &AuditTickResult,
9649    p2p_node: &Arc<P2PNode>,
9650    sync_state: &Arc<RwLock<NeighborSyncState>>,
9651    config: &ReplicationConfig,
9652) {
9653    match result {
9654        AuditTickResult::Passed {
9655            challenged_peer,
9656            keys_checked,
9657        } => {
9658            protocol::record_audit_pass(protocol::AuditOutcomeKind::Responsible);
9659            debug!("Audit passed for {challenged_peer} ({keys_checked} keys)");
9660            {
9661                let mut state = sync_state.write().await;
9662                state.clear_active_bootstrap_claim(challenged_peer);
9663            }
9664            p2p_node
9665                .report_trust_event(
9666                    challenged_peer,
9667                    TrustEvent::ApplicationSuccess(REPLICATION_TRUST_WEIGHT),
9668                )
9669                .await;
9670        }
9671        AuditTickResult::Failed {
9672            evidence,
9673            no_response_class,
9674        } => {
9675            if let FailureEvidence::AuditFailure {
9676                challenged_peer,
9677                confirmed_failed_keys,
9678                summary,
9679                reason,
9680                ..
9681            } = evidence
9682            {
9683                protocol::record_audit_fail(protocol::AuditOutcomeKind::Responsible, reason);
9684                let first_failed_key = first_failed_key_label(confirmed_failed_keys);
9685                let audit_failure_class = no_response_class.unwrap_or("confirmed");
9686                error!(
9687                    "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}",
9688                    audit_failure_class,
9689                    confirmed_failed_keys.len(),
9690                    summary.challenged_keys,
9691                    summary.absent_keys,
9692                    summary.digest_mismatch_keys,
9693                );
9694                if audit_failure_clears_bootstrap_claim(reason) {
9695                    let mut state = sync_state.write().await;
9696                    state.clear_active_bootstrap_claim(challenged_peer);
9697                } else {
9698                    debug!("Audit timeout for {challenged_peer}; retaining active bootstrap claim");
9699                }
9700                config::penalise_unheld_close_group_chunk(
9701                    p2p_node,
9702                    challenged_peer,
9703                    crate::replication::audit_metrics::AuditType::ResponsibleChunk.as_str(),
9704                    config::AUDIT_FAILURE_TRUST_WEIGHT,
9705                )
9706                .await;
9707            }
9708        }
9709        AuditTickResult::BootstrapClaim { peer } => {
9710            let should_report = {
9711                let now = Instant::now();
9712                let mut state = sync_state.write().await;
9713                match state.observe_bootstrap_claim(*peer, now, config.bootstrap_claim_grace_period)
9714                {
9715                    BootstrapClaimObservation::WithinGrace { .. } => {
9716                        debug!("Audit: peer {peer} claims bootstrapping (within grace period)");
9717                        false
9718                    }
9719                    BootstrapClaimObservation::PastGrace { first_seen } => {
9720                        warn!(
9721                            "Audit: peer {peer} claiming bootstrap past grace period \
9722                             ({:?} > {:?}), reporting abuse",
9723                            now.duration_since(first_seen),
9724                            config.bootstrap_claim_grace_period,
9725                        );
9726                        true
9727                    }
9728                    BootstrapClaimObservation::Repeated { first_seen } => {
9729                        warn!(
9730                            "Audit: peer {peer} repeated bootstrap claim after previously \
9731                             stopping; first claim was {:?} ago, reporting abuse",
9732                            now.duration_since(first_seen),
9733                        );
9734                        true
9735                    }
9736                }
9737            };
9738            if should_report {
9739                p2p_node
9740                    .report_trust_event(
9741                        peer,
9742                        TrustEvent::ApplicationFailure(REPLICATION_TRUST_WEIGHT),
9743                    )
9744                    .await;
9745            }
9746        }
9747        AuditTickResult::Idle | AuditTickResult::InsufficientKeys => {}
9748    }
9749}
9750
9751/// Whether a confirmed audit failure with this reason should revoke the
9752/// peer's `recent_provers` holder credit immediately (v12 §6).
9753///
9754/// `true` for any reason where the peer actually answered (or admitted
9755/// it cannot): `DigestMismatch`, `KeyAbsent`, `Rejected` ("missing
9756/// bytes for committed key"), `MalformedResponse` — these prove the
9757/// peer no longer holds what it committed to, so it must not keep
9758/// holder credit for the proof TTL. `false` for `Timeout`: a single
9759/// dropped packet must not strip an honest peer; the 40-min TTL is the
9760/// deliberate liveness cushion there.
9761fn audit_failure_revokes_holder_credit(reason: &AuditFailureReason) -> bool {
9762    !matches!(reason, AuditFailureReason::Timeout)
9763}
9764
9765/// Apply the holder-credit revocation decision for a confirmed audit
9766/// failure. Pure over `RecentProvers` so the handler wiring is unit-
9767/// testable without a live `P2PNode`: the production `Failed` arm of
9768/// `handle_subtree_audit_result` calls exactly this.
9769fn apply_audit_failure_credit_revocation(
9770    provers: &mut RecentProvers,
9771    challenged_peer: &PeerId,
9772    reason: &AuditFailureReason,
9773) {
9774    if audit_failure_revokes_holder_credit(reason) {
9775        provers.forget_peer(challenged_peer);
9776    }
9777}
9778
9779// `admit_bootstrap_hints` was consolidated into `admit_and_queue_hints`.
9780
9781// ---------------------------------------------------------------------------
9782// Storage-bound audit (ADR-0002) — gossip trigger + auditor-side ingestion
9783// ---------------------------------------------------------------------------
9784
9785/// State the gossip-audit trigger needs to spawn an audit. Bundled so the
9786/// message handler passes one value instead of a long argument list; all
9787/// fields are cheap `Arc` clones.
9788#[derive(Clone)]
9789struct GossipAuditTrigger {
9790    p2p_node: Arc<P2PNode>,
9791    config: Arc<ReplicationConfig>,
9792    recent_provers: Arc<RwLock<RecentProvers>>,
9793    sync_state: Arc<RwLock<NeighborSyncState>>,
9794    /// Shared "an audit actually launched" cooldown, consulted by BOTH the
9795    /// gossip-lottery path and the monetized first-audit scheduler. Stamped
9796    /// only when a real audit is about to be sent — never by a losing lottery
9797    /// ticket — so gossip traffic alone can never suppress a paid first audit.
9798    cooldown: Arc<RwLock<HashMap<PeerId, Instant>>>,
9799    detached_task_tracker: TaskTracker,
9800    /// Gossip-private lottery attempt window: stamped on every roll (win or
9801    /// lose) so a gossip flood cannot re-roll the lottery within the window.
9802    /// The first-audit scheduler never reads this map.
9803    lottery_attempts: Arc<RwLock<HashMap<PeerId, Instant>>>,
9804}
9805
9806/// What a gossip ingest yields for the audit trigger: the commitment hash to
9807/// pin and the `key_count` needed to size the response deadline from the actual
9808/// `ceil(sqrt(N))` subtree (ADR-0002). Returned on every VALID gossip (changed
9809/// or not) so a stable-keyset node stays auditable — not just on its first
9810/// commitment.
9811#[derive(Debug, Clone, Copy)]
9812struct AuditTarget {
9813    pin_hash: [u8; 32],
9814    key_count: u32,
9815}
9816
9817/// ADR-0004: a commitment that backed a payment, surfaced by the payment
9818/// verifier's cross-check so it can receive a **deterministic first audit**.
9819///
9820/// Sent from the verifier to the replication engine's first-audit drainer. The
9821/// drainer dedups by `pin` (a pin gets one deterministic first audit; later
9822/// audits of the same peer revert to the gossip lottery), orders most-recently-
9823/// monetized first, and runs the same `run_subtree_audit` under the same
9824/// per-peer cooldown and concurrency caps — only the lottery is bypassed.
9825#[derive(Debug, Clone, Copy)]
9826pub struct MonetizedPinEvent {
9827    /// The peer whose commitment backed the payment.
9828    pub peer: PeerId,
9829    /// The pinned commitment hash.
9830    pub pin: [u8; 32],
9831    /// The committed key count (sizes the audit deadline).
9832    pub key_count: u32,
9833    /// The accused's own SIGNED quote timestamp. The first-audit drainer skips a
9834    /// pin whose quote is older than the answerability window (ADR-0004 A1
9835    /// guardrail A): with grace removed, challenging an aged-out pin would
9836    /// false-convict, so a stale client-forwarded quote must not trigger an audit.
9837    pub quote_ts: SystemTime,
9838}
9839
9840/// Per-peer audit cooldown check-and-stamp (ADR-0002 "occasional surprise
9841/// exams, keeps load low"). Returns `true` if `peer` may be audited now (and
9842/// stamps `now`), `false` if it was audited within
9843/// `AUDIT_ON_GOSSIP_COOLDOWN_SECS`. Bounds the map under a flood of distinct
9844/// peers. Pure over the passed map so the flood/cooldown behaviour is testable
9845/// without a live node: a burst of gossips from one peer yields at most one
9846/// `true` per cooldown window.
9847fn cooldown_allows_audit(map: &mut HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9848    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9849    let known = match map.get(peer) {
9850        Some(&last) => {
9851            if now.saturating_duration_since(last) < cooldown {
9852                return false;
9853            }
9854            true
9855        }
9856        None => false,
9857    };
9858    // Bound the map under churn like its siblings (drop the oldest stamp) before
9859    // admitting a brand-new peer.
9860    if !known && map.len() >= MAX_LAST_COMMITMENT_BY_PEER {
9861        if let Some(victim) = map.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9862            map.remove(&victim);
9863        }
9864    }
9865    map.insert(*peer, now);
9866    true
9867}
9868
9869/// Read-only companion to [`cooldown_allows_audit`]: whether `peer` is OUTSIDE
9870/// its cooldown at `now`, WITHOUT stamping. Used by the first-audit reserve gate
9871/// (ADR-0004 Amendment 2 E′) to avoid reserving a peer that a recent audit
9872/// already covered; the authoritative check-and-stamp still runs at promotion,
9873/// so this is only an optimization and never the security boundary.
9874fn cooldown_would_allow(map: &HashMap<PeerId, Instant>, peer: &PeerId, now: Instant) -> bool {
9875    let cooldown = Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS);
9876    map.get(peer)
9877        .is_none_or(|&last| now.saturating_duration_since(last) >= cooldown)
9878}
9879
9880/// The gossip-audit launch decision in ONE place so the ordering is shared
9881/// between production and its test (ADR-0002 "occasional surprise exams").
9882///
9883/// Order matters and is the security-relevant property. Gate 1 checks-and-stamps
9884/// the gossip-PRIVATE `attempts` window, win or lose: if the lottery were
9885/// sampled first, a gossip flood would re-roll it on every message until one
9886/// won, multiplying audits, so each peer gets at most one lottery roll per
9887/// window regardless of how often it gossips. Gate 3 checks-and-stamps the
9888/// SHARED `launched` cooldown — the map the monetized first-audit scheduler
9889/// also consults — only after a WIN, i.e. only when a real audit is about to be
9890/// sent. A losing ticket must never stamp `launched`: no challenge went on the
9891/// wire, so it must not defer a paid first audit (repeatable losses could
9892/// otherwise hold a monetized pin past its answerability window). Production
9893/// calls this with `lottery_wins = gen_bool(AUDIT_ON_GOSSIP_PROBABILITY)`; the
9894/// test calls it with a deterministic `lottery_wins`, so a reorder regression
9895/// here fails the test.
9896fn audit_launch_decision(
9897    attempts: &mut HashMap<PeerId, Instant>,
9898    launched: &mut HashMap<PeerId, Instant>,
9899    peer: &PeerId,
9900    now: Instant,
9901    lottery_wins: bool,
9902) -> bool {
9903    // Gate 1: lottery-attempt window check-and-stamp (consumes the attempt
9904    // window even on a loss; private to the gossip path).
9905    if !cooldown_allows_audit(attempts, peer, now) {
9906        return false;
9907    }
9908    // Gate 2: the probability lottery. A loss stops here and stamps nothing
9909    // shared.
9910    if !lottery_wins {
9911        return false;
9912    }
9913    // Gate 3: the shared actual-audit cooldown (a recent real audit from
9914    // either path still suppresses this launch), stamped only on launch.
9915    cooldown_allows_audit(launched, peer, now)
9916}
9917
9918/// On a peer's *changed* gossiped commitment, maybe launch a subtree audit
9919/// (ADR-0002): fire with probability `AUDIT_ON_GOSSIP_PROBABILITY`, subject to a
9920/// per-peer cooldown, pinned to the just-ingested root. Detached so gossip
9921/// handling is never blocked on a network round-trip.
9922async fn maybe_trigger_gossip_audit(
9923    trigger: &GossipAuditTrigger,
9924    peer: &PeerId,
9925    target: AuditTarget,
9926) {
9927    // The launch decision (attempt-window, lottery, shared-cooldown ordering)
9928    // lives in the pure `audit_launch_decision` so the ordering is shared with
9929    // its test. Sample the lottery here, then let the helper apply the gates.
9930    let now = Instant::now();
9931    let lottery_wins = rand::thread_rng().gen_bool(config::AUDIT_ON_GOSSIP_PROBABILITY);
9932    {
9933        // Lock order: attempts before the shared cooldown; this is the only
9934        // place both are held together.
9935        let mut attempts = trigger.lottery_attempts.write().await;
9936        let mut launched = trigger.cooldown.write().await;
9937        if !audit_launch_decision(&mut attempts, &mut launched, peer, now, lottery_wins) {
9938            return;
9939        }
9940    }
9941
9942    let detached_task_tracker = trigger.detached_task_tracker.clone();
9943    let trigger = trigger.clone();
9944    let peer = *peer;
9945    detached_task_tracker.spawn(async move {
9946        let credit = storage_commitment_audit::AuditCredit {
9947            recent_provers: &trigger.recent_provers,
9948        };
9949        let result = storage_commitment_audit::run_subtree_audit_with_origin(
9950            &trigger.p2p_node,
9951            &trigger.config,
9952            &peer,
9953            target.pin_hash,
9954            target.key_count,
9955            Some(&credit),
9956            storage_commitment_audit::SubtreeAuditOrigin::Gossip,
9957        )
9958        .await;
9959        handle_subtree_audit_result(
9960            &result,
9961            &trigger.p2p_node,
9962            &trigger.sync_state,
9963            &trigger.recent_provers,
9964            &trigger.config,
9965        )
9966        .await;
9967    });
9968}
9969
9970/// Atomic check-and-stamp of the per-peer commitment sig-verify rate limit.
9971///
9972/// Returns `true` if a signature verify is allowed now (and stamps the attempt
9973/// time), `false` if the peer is within [`COMMITMENT_SIG_VERIFY_MIN_INTERVAL`]
9974/// of its last attempt. Holds one write lock across the decision so two
9975/// concurrent ingests from the same peer cannot both pass. Stamps BEFORE the
9976/// caller's expensive verify so a slow/failed verify still rate-limits the next
9977/// message. Bounds the map under a flood of distinct peer ids.
9978async fn sig_verify_rate_limit_ok(
9979    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
9980    source: &PeerId,
9981    now: Instant,
9982) -> bool {
9983    let mut attempts = sig_verify_attempts.write().await;
9984    if let Some(&last) = attempts.get(source) {
9985        if now.saturating_duration_since(last) < COMMITMENT_SIG_VERIFY_MIN_INTERVAL {
9986            return false;
9987        }
9988    }
9989    if attempts.len() >= MAX_LAST_COMMITMENT_BY_PEER && !attempts.contains_key(source) {
9990        if let Some(victim) = attempts.iter().min_by_key(|(_, &ts)| ts).map(|(p, _)| *p) {
9991            attempts.remove(&victim);
9992        }
9993    }
9994    attempts.insert(*source, now);
9995    true
9996}
9997
9998/// Verify + store an inbound commitment from a gossip peer.
9999///
10000/// Called from the inbound `NeighborSyncRequest`/`Response` handlers and
10001/// the bootstrap-sync loop. Drops the commitment unless all five gates
10002/// pass:
10003///   1. `source` is in our DHT routing table (sybil/churn cap).
10004///   2. `commitment.sender_peer_id == source.as_bytes()` (peer-id
10005///      binding to the authenticated transport peer).
10006///   3. `BLAKE3(commitment.sender_public_key) == commitment.sender_peer_id`
10007///      (the embedded pubkey actually belongs to the claimed identity —
10008///      saorsa-core derives `PeerId = BLAKE3(pubkey)`).
10009///   4. `verify_commitment_signature(commitment)` succeeds against the
10010///      embedded public key. The signed payload binds the pubkey, so an
10011///      adversary cannot swap the key while keeping the body.
10012///   5. The cache has room or this is an update for an existing entry
10013///      (sybil cap, `MAX_LAST_COMMITMENT_BY_PEER`).
10014///
10015/// On all-pass, the commitment is stored as the auditor's per-peer
10016/// "last known commitment" for use as `expected_commitment_hash` in
10017/// future audits.
10018///
10019/// Failures (no commitment / mismatched peer id / bad signature) are
10020/// silent drops — gossip is best-effort and a malformed commitment from
10021/// one peer should not affect anything else.
10022///
10023/// Returns `Some(AuditTarget)` whenever a VALID commitment was stored (whether
10024/// or not its root changed), so the caller can run a probabilistic,
10025/// cooldown-gated subtree audit. Returning on *every* valid gossip — not only
10026/// changed ones — is deliberate (ADR-0002): a node with a stable key set keeps
10027/// being auditable, so it cannot pass one audit and then delete data while
10028/// re-gossiping the same root forever. The cooldown + probability bound the
10029/// audit frequency. Returns `None` only if the commitment was dropped (failed a
10030/// gate) or there is nothing to pin.
10031///
10032/// Handle a capable peer gossiping `None` (a commitment downgrade).
10033///
10034/// A capable peer that previously gossiped a commitment but now gossips `None`
10035/// is trying to drop off the audit path. Within the answerability window we keep
10036/// the cached commitment pinned AND return it as an audit target so this gossip
10037/// still schedules a subtree audit against the peer's last known commitment — if
10038/// it genuinely dropped the data, the audit fails (there is no periodic tick, so
10039/// the trigger MUST fire here or the downgrade is never re-challenged).
10040///
10041/// But this only holds within the SAME `GOSSIP_ANSWERABILITY_TTL` the responder
10042/// honours for its own retired commitment: once that elapses since we last
10043/// received the peer's commitment, an honest peer has legitimately retired that
10044/// root (its responder side `retire_current`s and lets it age out) and can no
10045/// longer answer a pin on it. Auditing it past the TTL would manufacture a false
10046/// failure, so we then forget the cached commitment (keeping the sticky
10047/// `commitment_capable` bit) and stop pinning it.
10048async fn handle_commitment_downgrade(
10049    source: &PeerId,
10050    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
10051) -> Option<AuditTarget> {
10052    let now = Instant::now();
10053    let cached = {
10054        let map = last_commitment_by_peer.read().await;
10055        map.get(source).and_then(|rec| {
10056            if !rec.commitment_capable {
10057                return None;
10058            }
10059            let last = rec.last_commitment()?;
10060            let pin = rec.commitment_hash()?;
10061            let fresh = now.saturating_duration_since(rec.received_at) < GOSSIP_ANSWERABILITY_TTL;
10062            Some((pin, last.key_count, fresh))
10063        })
10064    };
10065    match cached {
10066        Some((pin, key_count, true)) => {
10067            warn!(
10068                "ingest_peer_commitment: commitment-capable peer {source} sent None \
10069                 (downgrade attempt); auditing against its last cached commitment"
10070            );
10071            Some(AuditTarget {
10072                pin_hash: pin,
10073                key_count,
10074            })
10075        }
10076        Some((_, _, false)) => {
10077            // Cached commitment has aged past the answerability window — forget
10078            // it so we stop pinning a root the peer is no longer obliged to
10079            // answer. Keep `commitment_capable` (sticky). Re-check freshness
10080            // UNDER the write lock (compare-and-clear): a concurrent valid gossip
10081            // from this peer may have refreshed `received_at` in the gap between
10082            // our read and write locks; if so, leave its fresh commitment intact.
10083            if let Some(rec) = last_commitment_by_peer.write().await.get_mut(source) {
10084                let still_stale =
10085                    now.saturating_duration_since(rec.received_at) >= GOSSIP_ANSWERABILITY_TTL;
10086                if still_stale {
10087                    rec.clear_commitment();
10088                    debug!(
10089                        "ingest_peer_commitment: capable peer {source} sent None and its cached \
10090                         commitment aged past the answerability TTL; forgetting it"
10091                    );
10092                }
10093            }
10094            None
10095        }
10096        None => None,
10097    }
10098}
10099
10100async fn ingest_peer_commitment(
10101    source: &PeerId,
10102    commitment: Option<&StorageCommitment>,
10103    p2p_node: &Arc<P2PNode>,
10104    last_commitment_by_peer: &Arc<RwLock<HashMap<PeerId, PeerCommitmentRecord>>>,
10105    ever_capable_peers: &Arc<RwLock<HashSet<PeerId>>>,
10106    sig_verify_attempts: &Arc<RwLock<HashMap<PeerId, Instant>>>,
10107) -> Option<AuditTarget> {
10108    let Some(c) = commitment else {
10109        return handle_commitment_downgrade(source, last_commitment_by_peer).await;
10110    };
10111    // RT-membership gate: only accept commitments from peers in our
10112    // routing table. Off-RT senders (sybils, drive-by relays) cannot
10113    // populate the cache, which closes the hole where a flood of
10114    // off-RT identities could fill the cap and evict honest
10115    // peers. The neighbor-sync request handler applies the same gate
10116    // before admitting inbound replication hints (see neighbor_sync.rs
10117    // `sender_in_rt`); we mirror that policy here for the commitment
10118    // piggyback.
10119    if !p2p_node.dht_manager().is_in_routing_table(source).await {
10120        debug!("ingest_peer_commitment: source {source} not in routing table (dropped)");
10121        return None;
10122    }
10123    // Peer-id binding: the commitment's claimed sender must match the
10124    // authenticated transport peer (`source`). Defeats relay/replay
10125    // and also pins which embedded public key we are about to verify
10126    // against — the verify itself trusts the embedded key, so the
10127    // peer-id binding is the link to a real identity.
10128    if &c.sender_peer_id != source.as_bytes() {
10129        warn!(
10130            "ingest_peer_commitment: sender_peer_id mismatch from {source} \
10131             (dropped, possible relay attempt)"
10132        );
10133        return None;
10134    }
10135    // Peer-id to embedded-pubkey binding: saorsa-core derives PeerId as
10136    // BLAKE3(pubkey_bytes). Without this check, a responder could sign
10137    // with a throwaway key they own and lie about which identity it
10138    // belongs to (the embedded-key signature would verify trivially).
10139    let derived_peer_id = *blake3::hash(&c.sender_public_key).as_bytes();
10140    if derived_peer_id != c.sender_peer_id {
10141        warn!(
10142            "ingest_peer_commitment: embedded pubkey does not hash to claimed peer_id for \
10143             {source} (dropped, throwaway-key attack)"
10144        );
10145        return None;
10146    }
10147    // §2 step 3 + §11 DoS: rate-limit per-peer to at most one ML-DSA
10148    // signature verify per `COMMITMENT_SIG_VERIFY_MIN_INTERVAL`. A
10149    // sybil/RT-membership-bypassing peer that flooded valid-looking
10150    // gossip would otherwise burn CPU on every message. The rate
10151    // limit is checked AFTER cheap structural gates (RT, peer-id
10152    // binding, pubkey-binding) and BEFORE the expensive sig verify.
10153    //
10154    // Tracked in `sig_verify_attempts` (separate from
10155    // last_commitment_by_peer) so EVERY attempt — successful or not —
10156    // bumps the rate-limit clock. Reading only from PeerCommitmentRecord
10157    // would skip the cap for peers we've never successfully verified,
10158    // letting a flood of invalid-but-structurally-plausible gossips
10159    // burn CPU.
10160    let now = Instant::now();
10161    if !sig_verify_rate_limit_ok(sig_verify_attempts, source, now).await {
10162        debug!(
10163            "ingest_peer_commitment: rate-limited sig verify from {source} \
10164             (< {COMMITMENT_SIG_VERIFY_MIN_INTERVAL:?} since last attempt); dropped"
10165        );
10166        return None;
10167    }
10168    // Signature verify, using the public key embedded in the commitment
10169    // itself. The pubkey is bound by the signature payload (see
10170    // commitment_signed_payload) so an adversary cannot keep the body
10171    // and swap the key to one they hold the secret for.
10172    if !crate::replication::commitment::verify_commitment_signature(c) {
10173        warn!(
10174            "ingest_peer_commitment: signature did not verify under embedded key for {source} \
10175             (dropped, forged commitment)"
10176        );
10177        return None;
10178    }
10179    // The new commitment's hash, used to store and to pin for the audit target.
10180    let new_hash = commitment_hash(c);
10181    let mut map = last_commitment_by_peer.write().await;
10182    // Sybil/churn cap: if we're at the hard cap AND this is a new peer,
10183    // evict an arbitrary existing entry to make room. Updates for peers
10184    // already in the map are always accepted (they replace, not grow).
10185    if map.len() >= MAX_LAST_COMMITMENT_BY_PEER && !map.contains_key(source) {
10186        // Drop one arbitrary entry. HashMap iter order is random which
10187        // is fine — over time PeerRemoved cleanup keeps the working set
10188        // anchored on the real RT membership; this cap only fires under
10189        // active flooding attempts.
10190        if let Some(victim) = map.keys().next().copied() {
10191            map.remove(&victim);
10192            warn!(
10193                "ingest_peer_commitment: cache full ({MAX_LAST_COMMITMENT_BY_PEER}); \
10194                 evicted {victim} to admit {source}"
10195            );
10196        }
10197    }
10198    // Preserve sticky commitment_capable across updates — once true,
10199    // always true. New entries start with capable = true (we just
10200    // verified a valid commitment from this peer).
10201    map.entry(*source)
10202        .and_modify(|r| {
10203            // set_commitment refreshes the cached hash (§13) alongside the
10204            // commitment + received_at so they never drift.
10205            r.set_commitment(c.clone(), now);
10206            r.last_sig_verify_at = now;
10207            r.commitment_capable = true; // sticky-redundant but explicit
10208        })
10209        .or_insert_with(|| PeerCommitmentRecord::from_verified(c.clone(), now));
10210    drop(map);
10211    // Record the sticky "ever v12-capable" bit in a set independent of
10212    // `last_commitment_by_peer` (whose entries can be evicted by
10213    // `PeerRemoved` and the sybil cap). This is what the §3 audit
10214    // shield and the §6 holder-eligibility closure consult to decide
10215    // whether the peer is expected to speak v12.
10216    //
10217    // Capped at `MAX_EVER_CAPABLE_PEERS` to bound memory under
10218    // identity-rotation attacks: once full, new entries are refused.
10219    // Refusal degrades over-cap peers to the behaviour before this set
10220    // existed (treated as legacy on rejoin), which is not a security
10221    // regression and preserves the historic set stable.
10222    {
10223        let mut set = ever_capable_peers.write().await;
10224        if set.contains(source) || set.len() < MAX_EVER_CAPABLE_PEERS {
10225            set.insert(*source);
10226        } else {
10227            warn!(
10228                "ingest_peer_commitment: ever_capable_peers at cap \
10229                 ({MAX_EVER_CAPABLE_PEERS}); refusing to record {source} as sticky-capable"
10230            );
10231        }
10232    }
10233    // Return an audit target for EVERY valid stored commitment (changed or
10234    // not), so the caller's cooldown+probability-gated trigger keeps a
10235    // stable-keyset peer auditable over time (ADR-0002). Only a serialization
10236    // failure (new_hash == None, unreachable for a real commitment) yields None.
10237    new_hash.map(|pin_hash| AuditTarget {
10238        pin_hash,
10239        key_count: c.key_count,
10240    })
10241}
10242
10243// ---------------------------------------------------------------------------
10244// Storage-bound audit (v12) — responder commitment rotation
10245// ---------------------------------------------------------------------------
10246
10247/// Reload persisted responder retention at startup (ADR-0004 A1). A missing file
10248/// is a normal fresh start; a corrupt snapshot is logged and skipped (fail-open
10249/// LOCALLY — the node re-gossips a fresh root — which never grants a remote grace).
10250async fn load_commitment_retention(state: &ResponderCommitmentState, path: &Path) {
10251    let bytes = match tokio::fs::read(path).await {
10252        Ok(b) => b,
10253        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
10254            debug!(
10255                "Commitment retention: no snapshot at {} (fresh start)",
10256                path.display()
10257            );
10258            return;
10259        }
10260        Err(e) => {
10261            warn!(
10262                "Commitment retention: failed to read {}: {e}",
10263                path.display()
10264            );
10265            return;
10266        }
10267    };
10268    if let Some(mut persisted) = PersistedRetention::from_bytes(&bytes) {
10269        let sidecar = pointer_leaves_path(path);
10270        match tokio::fs::read(&sidecar).await {
10271            Ok(leaves) => {
10272                if !persisted.attach_pointer_leaves(&leaves) {
10273                    warn!(
10274                        "Commitment retention: corrupt pointer leaves at {}; \
10275                         commitments holding pointers will not be restored",
10276                        sidecar.display()
10277                    );
10278                }
10279            }
10280            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
10281            Err(e) => warn!(
10282                "Commitment retention: failed to read {}: {e}",
10283                sidecar.display()
10284            ),
10285        }
10286        state.restore(&persisted);
10287        info!(
10288            "Commitment retention: reloaded {} slot(s) from {}",
10289            state.retained_slot_count(),
10290            path.display()
10291        );
10292    } else {
10293        warn!(
10294            "Commitment retention: corrupt snapshot at {}; starting with empty retention",
10295            path.display()
10296        );
10297    }
10298}
10299
10300/// Persist the responder retention snapshot IF it changed since `last` (ADR-0004
10301/// A1). Write-on-change keeps frequent gossip-stamp refreshes durable without
10302/// needless disk writes on idle nodes. On success updates `last` to the bytes
10303/// written; on a serialization/write error the existing on-disk snapshot is left
10304/// intact (never truncated).
10305///
10306/// The pointer leaves go to a sidecar written first (ADR-0016), so the
10307/// retention file never names a commitment whose pointer leaves are not yet
10308/// on disk. A crash between the two leaves a sidecar ahead of the file, which
10309/// is harmless: it is keyed by commitment hash.
10310async fn persist_retention_if_changed(
10311    state: &ResponderCommitmentState,
10312    path: &Path,
10313    last: &mut Option<Vec<u8>>,
10314) {
10315    let snapshot = state.snapshot();
10316    let (Some(bytes), Some(leaves)) = (snapshot.to_bytes(), snapshot.pointer_leaves_bytes()) else {
10317        warn!("Commitment retention: serialization failed; keeping previous snapshot");
10318        return;
10319    };
10320    let mut combined = leaves.clone();
10321    combined.extend_from_slice(&bytes);
10322    if last.as_deref() == Some(combined.as_slice()) {
10323        return;
10324    }
10325    if write_retention_atomic(&pointer_leaves_path(path), leaves).await
10326        && write_retention_atomic(path, bytes).await
10327    {
10328        *last = Some(combined);
10329    }
10330}
10331
10332/// Where the pointer leaves of the retention at `path` are kept.
10333fn pointer_leaves_path(path: &Path) -> PathBuf {
10334    path.with_file_name("commitment_retention_pointers.bin")
10335}
10336
10337/// Durably write `bytes` to `path`: temp file → fsync temp → atomic rename →
10338/// fsync parent dir (so the rename itself survives a crash). Returns `true` on
10339/// success. Only the retention-persist loop writes this path, so a fixed temp
10340/// name is safe.
10341async fn write_retention_atomic(path: &Path, bytes: Vec<u8>) -> bool {
10342    let path = path.to_path_buf();
10343    let res = tokio::task::spawn_blocking(move || -> std::io::Result<()> {
10344        let tmp = path.with_extension("tmp");
10345        std::fs::write(&tmp, &bytes)?;
10346        std::fs::File::open(&tmp)?.sync_all()?;
10347        std::fs::rename(&tmp, &path)?;
10348        // Fsync the directory so the rename (the durable-commit point) is not
10349        // lost on a crash right after it. An empty parent (relative filename)
10350        // means the current directory.
10351        let dir = path
10352            .parent()
10353            .filter(|p| !p.as_os_str().is_empty())
10354            .unwrap_or_else(|| Path::new("."));
10355        std::fs::File::open(dir)?.sync_all()?;
10356        Ok(())
10357    })
10358    .await;
10359    match res {
10360        Ok(Ok(())) => true,
10361        Ok(Err(e)) => {
10362            warn!("Commitment retention: persist failed: {e}");
10363            false
10364        }
10365        Err(e) => {
10366            warn!("Commitment retention: persist task join failed: {e}");
10367            false
10368        }
10369    }
10370}
10371
10372/// Read the current LMDB key set, build + sign a fresh
10373/// `StorageCommitment`, and rotate it into `state` as the new `current`.
10374/// The prior `current` is demoted to `previous`; the prior `previous` is
10375/// dropped (per `ResponderCommitmentState::rotate`).
10376///
10377/// For content-addressed chunks (Autonomi's chunk store), `address ==
10378/// BLAKE3(content)`, so `bytes_hash := key` and we don't have to
10379/// re-read each chunk's bytes to compute the leaf hash.
10380///
10381/// The pointers this node is responsible for are committed alongside, each as
10382/// `(address, pointer_leaf_hash(address))` (ADR-0016), so they are audited and
10383/// priced exactly as chunks are.
10384///
10385/// Skips (returns `Ok(())`) if the key set is empty — no commitment to
10386/// rotate. The auditor side handles "no commitment for this peer" by
10387/// falling back to the legacy plain-digest audit path.
10388async fn rebuild_and_rotate_commitment(
10389    storage: &Arc<ChunkStore>,
10390    pointers: Option<&PointerStore>,
10391    identity: &Arc<NodeIdentity>,
10392    state: &Arc<ResponderCommitmentState>,
10393    p2p: &Arc<P2PNode>,
10394    config: &Arc<ReplicationConfig>,
10395) -> Result<()> {
10396    // Not `all_keys()`. While the node is bridging off the legacy store these are the
10397    // same thing, but once it has settled on what it can hold this narrows to the
10398    // file-backed set, which is what stops it claiming keys it is about to give up. It is
10399    // also what lets `is_held` eventually go false for those keys, which is the gate on
10400    // removing the legacy environment at all.
10401    let stored_keys = storage
10402        .committable_keys()
10403        .await
10404        .map_err(|e| Error::Storage(format!("commitment build: read keys: {e}")))?;
10405
10406    // Commit only to keys we are still RESPONSIBLE for ("want-to-hold"), not
10407    // everything currently on disk ("hold"). This is the half of the retention
10408    // contract that lets out-of-range chunks age out: a key that has left our
10409    // close group is excluded from the NEXT commitment, so once its last gossip
10410    // ages past GOSSIP_ANSWERABILITY_TTL it falls out of the in-window retained
10411    // set, `ResponderCommitmentState::is_held` goes false,
10412    // and the pruner (which until then vetoes its deletion) reclaims it. Without
10413    // this filter the pruner's reprieve would keep re-committing stale keys
10414    // forever (the rebuild reads all_keys, so a retained-on-disk key would be
10415    // re-committed and re-gossiped every rotation — a permanent pin).
10416    let self_id = *p2p.peer_id();
10417    let mut keys = Vec::with_capacity(stored_keys.len());
10418    for k in stored_keys {
10419        if admission::is_responsible(&self_id, &k, p2p, config.close_group_size).await {
10420            keys.push(k);
10421        }
10422    }
10423    // The same rule for pointers: an out-of-range pointer leaves the next
10424    // commitment, and the pruner reclaims it once no retained slot holds it.
10425    let mut pointer_keys = Vec::new();
10426    for state in pointers.map(PointerStore::held_states).unwrap_or_default() {
10427        if admission::is_responsible(&self_id, &state.address, p2p, config.close_group_size).await {
10428            pointer_keys.push(state.address);
10429        }
10430    }
10431
10432    if keys.is_empty() && pointer_keys.is_empty() {
10433        // There used to be a second branch here that dropped every retained root outright
10434        // when the node looked empty. It is gone, and the reason is worth keeping.
10435        //
10436        // "Empty" was decided from key counts, and every version of that test was wrong in
10437        // the same direction. It read the committable set, which narrows to the file-backed
10438        // keys once the migration settles, so a node whose disk filled before it could copy
10439        // anything looked empty with a full legacy store beside it. Adding the raw file index
10440        // still missed a file dropped from the index by a failed read while its legacy copy
10441        // was being put back. Adding the legacy environment still missed a files-only node
10442        // that had published bytes to disk but not yet indexed them, because a file is
10443        // published before it is indexed. Each fix closed one window and left another.
10444        //
10445        // The asymmetry is what settles it. Clearing wrongly repudiates a root a peer is
10446        // pinning, and `UnknownCommitment` is a confirmed failure on the commitment-bound
10447        // lane, which is enforced in every release and is not the lane the migration holds
10448        // off — so a node that still holds the bytes is slashed for holding them. Retiring
10449        // wrongly costs a root that stops being advertised now and ages out by its gossip TTL
10450        // instead of vanishing now. Both set `has_current = false`; they differ only in
10451        // whether the node goes on being answerable in the meantime. A genuinely empty node
10452        // cannot answer either way, so retiring costs it nothing it had.
10453        //
10454        // So there is one branch, and no emptiness question to get wrong.
10455        //
10456        // A peer may still be pinning a root we gossiped
10457        // moments ago and could demand its bytes in a round-2 challenge, which
10458        // we can still answer (the bytes are present). But we must STOP
10459        // advertising the stale commitment: retire it so `current()` returns
10460        // `None` and the gossip-emit sites stop re-emitting and re-stamping it.
10461        // The retired slot then ages out by its gossip-answerability TTL while
10462        // remaining answerable for in-flight pins until then. Once it ages out,
10463        // `is_held` flips false and the pruner reclaims the now-uncommitted,
10464        // out-of-range chunks. (Calling `age_out` alone would leave `current()`
10465        // pointing at the stale root, which the gossip loop would keep
10466        // re-stamping — pinning its keys forever.)
10467        debug!(
10468            "Commitment rotation: no responsible keys to commit to; retiring current commitment \
10469             (stays answerable until its gossip TTL lapses, bytes still on disk)"
10470        );
10471        state.retire_current();
10472        storage.note_commitment_rebuilt();
10473        return Ok(());
10474    }
10475
10476    // Cap to MAX_COMMITMENT_KEY_COUNT for v12 (responder must not commit
10477    // to more than the protocol limit; auditor would reject the
10478    // commitment otherwise).
10479    let cap = commitment::MAX_COMMITMENT_KEY_COUNT as usize;
10480    let total = keys.len().saturating_add(pointer_keys.len());
10481    if total > cap {
10482        warn!(
10483            "Commitment rotation: key set ({total}) exceeds MAX_COMMITMENT_KEY_COUNT ({cap}); \
10484             truncating — investigate as this likely means a misconfiguration"
10485        );
10486    }
10487
10488    // INVARIANT: this module is only used with CONTENT-ADDRESSED chunks,
10489    // where `key == BLAKE3(content)`, so `bytes_hash := key` and we skip a
10490    // full chunk re-read per rotation.
10491    //
10492    // Consequence to be precise about: because the leaf is `(key, key)`,
10493    // the Merkle root commits to the SET OF KEYS, not to the bytes. The
10494    // commitment therefore binds "which keys I claim to hold"; it does NOT
10495    // by itself prove byte possession. Byte possession is enforced by the
10496    // round-2 slice audit: a Bao verified slice decoded against the chunk
10497    // ADDRESS plus a keyed nonced block-tree opening under a fresh per-audit
10498    // nonce, so a responder that holds the key list but dropped the bytes
10499    // cannot answer. This is sound ONLY while keys are content addresses;
10500    // the round-1 verifier enforces `bytes_hash == key` on every audited leaf
10501    // (`evaluate_subtree_structure`), so a non-content-addressed
10502    // `(key, bytes_hash)` leaf is rejected rather than letting a byte-less node
10503    // earn credit for `key`. If this module is ever reused for
10504    // non-content-addressed records, that `(k, k)` shortcut AND the verifier
10505    // gate must be replaced with `(key, BLAKE3(bytes))` computed from real bytes.
10506    //
10507    // Pointers are that case, and are handled by being told apart rather than
10508    // hashed: a pointer leaf is `(address, pointer_leaf_hash(address))`, which
10509    // the verifier accepts only for a leaf of exactly a pointer's size, and
10510    // round 2 then demands the whole signed record in place of a Bao slice.
10511    // The root binds which pointers are held, never their current state, so an
10512    // update does not move it.
10513    //
10514    // A pointer address that is also a chunk key would need a BLAKE3 preimage;
10515    // the dedup only keeps such a collision from failing the whole build.
10516    let mut entries: Vec<_> = keys
10517        .into_iter()
10518        .map(|k| (k, k))
10519        .chain(
10520            pointer_keys
10521                .into_iter()
10522                .map(|address| (address, commitment::pointer_leaf_hash(&address))),
10523        )
10524        .collect();
10525    entries.sort_by_key(|(k, _)| *k);
10526    entries.dedup_by_key(|(k, _)| *k);
10527    entries.truncate(cap);
10528
10529    // No-op-rotation guard: compute just the Merkle root from `entries`
10530    // and compare against the currently-advertised commitment's root.
10531    // If they match, the key set is unchanged and a new rotation would
10532    // only swap a randomized ML-DSA signature for a fresh one — same
10533    // content, different commitment_hash. That invalidates every
10534    // outstanding `recent_provers` credit on this node across the
10535    // close group with no security benefit, breaking steady-state
10536    // quorum liveness on large nodes that can't re-audit every key
10537    // every rotation interval. Skip the rotation entirely when the
10538    // tree is unchanged.
10539    // Build the tree ONCE here (moving `entries`): it serves both the no-op
10540    // root check below and, if we proceed, the signed commitment via
10541    // `build_from_tree` (§11 — previously the tree was built here and AGAIN
10542    // inside `BuiltCommitment::build`).
10543    let candidate_tree = commitment::MerkleTree::build(entries)
10544        .map_err(|e| Error::Crypto(format!("commitment tree build: {e}")))?;
10545    let candidate_root = candidate_tree.root();
10546    if let Some(current) = state.current() {
10547        if current.commitment().root == candidate_root {
10548            debug!(
10549                "Commitment rotation: key set unchanged (root={}); skipping no-op re-sign",
10550                hex::encode(candidate_root)
10551            );
10552            // Even though we skip re-signing (to avoid invalidating holder
10553            // credit), retention must still advance on the wall clock: a
10554            // previously-gossiped commitment that holds a now-out-of-range key
10555            // must be able to age out of the answerability window even when the
10556            // committed key set is frozen here for many rotations. Without this,
10557            // the no-op guard would pin a stale slot — and its key — forever.
10558            state.age_out();
10559            // The advertised commitment already equals the committable set, which is
10560            // exactly what the retirement gate is counting.
10561            storage.note_commitment_rebuilt();
10562            return Ok(());
10563        }
10564    }
10565
10566    let sk_bytes = identity.secret_key_bytes().to_vec();
10567    let sk = MlDsaSecretKey::from_bytes(MlDsaVariant::MlDsa65, &sk_bytes)
10568        .map_err(|e| Error::Crypto(format!("commitment build: load sk: {e}")))?;
10569    let pk_bytes = identity.public_key().as_bytes().to_vec();
10570    let peer_id_bytes = *p2p.peer_id().as_bytes();
10571
10572    let built = commitment_state::BuiltCommitment::build_from_tree(
10573        candidate_tree,
10574        &peer_id_bytes,
10575        &sk,
10576        &pk_bytes,
10577    )
10578    .map_err(|e| Error::Crypto(format!("commitment build: {e}")))?;
10579
10580    let hash = hex::encode(built.hash());
10581    let key_count = built.commitment().key_count;
10582    let pointer_count = built.tree().pointer_count();
10583    state.rotate(built);
10584    info!("Storage commitment rotated: hash={hash} key_count={key_count} pointers={pointer_count}");
10585    // Counted only on the paths where the advertised commitment now genuinely reflects
10586    // the committable set, never merely on having read it. The retirement gate is what
10587    // consumes this, and it authorises deleting the legacy store.
10588    storage.note_commitment_rebuilt();
10589    Ok(())
10590}
10591
10592#[cfg(test)]
10593#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
10594mod tests {
10595
10596    /// The two fetch failures mean different things and must be charged differently.
10597    ///
10598    /// `NotFound` is a peer saying it does not hold the chunk, which is what a node
10599    /// part-way through the migration says about chunks it has legitimately given up, so
10600    /// it is the lane this release withholds. `Error` has a single producer, the
10601    /// responder's own storage read failing, and that is never about the migration.
10602    #[test]
10603    fn a_missing_chunk_and_a_failed_read_are_different_faults() {
10604        let key = [7u8; 32];
10605        assert_eq!(
10606            fetch_fault_for(&protocol::FetchResponse::NotFound { key }),
10607            Some(FetchFault::UnheldChunk)
10608        );
10609        assert_eq!(
10610            fetch_fault_for(&protocol::FetchResponse::Error {
10611                key,
10612                reason: "read failed".to_string(),
10613            }),
10614            Some(FetchFault::ResponderFault)
10615        );
10616        assert_eq!(
10617            fetch_fault_for(&protocol::FetchResponse::Success {
10618                key,
10619                data: vec![1, 2, 3],
10620            }),
10621            None
10622        );
10623    }
10624
10625    /// The responder's answer says which fault it is, so the mapping from a storage read
10626    /// to a response is what the classification above rests on.
10627    ///
10628    /// A key the peer does not hold reads as `Ok(None)`. A read that fails, whether from
10629    /// an I/O fault or a failed integrity check, reads as `Err`. Nothing in the migration
10630    /// turns the first into the second.
10631    #[tokio::test]
10632    async fn a_missing_key_reads_as_a_plain_miss_and_a_failed_read_as_a_fault() {
10633        let dir = tempfile::tempdir().expect("temp dir");
10634        let storage = crate::storage::LmdbStorage::new(crate::storage::LmdbStorageConfig {
10635            root_dir: dir.path().to_path_buf(),
10636            verify_on_read: true,
10637            max_map_size: 0,
10638            disk_reserve: 0,
10639        })
10640        .await
10641        .expect("open store");
10642
10643        let absent = [9u8; 32];
10644        assert!(
10645            matches!(storage.get(&absent).await, Ok(None)),
10646            "a chunk this node does not hold must read as a plain miss, not a fault"
10647        );
10648
10649        // And the answer each read produces. A miss is `NotFound`, which is the withheld
10650        // lane; a failed read is `Error`, which is not.
10651        assert!(matches!(
10652            fetch_response_for(absent, Ok(None)),
10653            protocol::FetchResponse::NotFound { .. }
10654        ));
10655        assert!(matches!(
10656            fetch_response_for(absent, Ok(Some(vec![1, 2, 3]))),
10657            protocol::FetchResponse::Success { .. }
10658        ));
10659        assert!(matches!(
10660            fetch_response_for(
10661                absent,
10662                Err(crate::error::Error::Storage("read failed".into()))
10663            ),
10664            protocol::FetchResponse::Error { .. }
10665        ));
10666    }
10667    use super::*;
10668    use super::{
10669        apply_audit_failure_credit_revocation, audit_failure_clears_bootstrap_claim,
10670        audit_failure_revokes_holder_credit, audit_launch_decision, coalesce_first_audit_event,
10671        config, cooldown_allows_audit, first_audit_count_jump, first_audit_terminal_outcome,
10672        first_failed_key_label, fresh_offer_payment_context, paid_notify_payment_context,
10673        quote_answerable_through_nominal_jitter, quote_within_audit_window, FirstAuditLimiter,
10674        FirstAuditObservability, FirstAuditQueueOutcome, FirstAuditScheduler,
10675        FirstAuditTerminalOutcome, LimiterVerdict, MonetizedPinEvent,
10676        FIRST_AUDIT_SEND_LATENCY_SLACK, MONETIZED_AUDIT_SKEW_MARGIN,
10677    };
10678    use crate::payment::VerificationContext;
10679    use crate::replication::audit::AuditTickResult;
10680    use crate::replication::commitment_state::GOSSIP_ANSWERABILITY_TTL;
10681    use crate::replication::recent_provers::RecentProvers;
10682    use crate::replication::types::{AuditFailureReason, FailureEvidence};
10683    use lru::LruCache;
10684    use saorsa_core::identity::PeerId;
10685    use std::collections::HashMap;
10686    use std::num::NonZeroUsize;
10687    use std::sync::atomic::Ordering;
10688    use std::sync::Arc;
10689    use std::time::Duration;
10690    use std::time::Instant;
10691    use std::time::SystemTime;
10692
10693    #[test]
10694    fn match_replication_protocol_accepts_core_and_subtree_bare_and_rr() {
10695        for id in [REPLICATION_PROTOCOL_ID, SUBTREE_AUDIT_PROTOCOL_ID] {
10696            assert_eq!(match_replication_protocol(id), Some((id, false)));
10697            assert_eq!(
10698                match_replication_protocol(&format!("{RR_PREFIX}{id}")),
10699                Some((id, true))
10700            );
10701        }
10702        assert_eq!(
10703            match_replication_protocol("autonomi.ant.replication.possession-audit.v2"),
10704            None
10705        );
10706        assert_eq!(match_replication_protocol("autonomi.ant.dht.v1"), None);
10707        assert_eq!(match_replication_protocol(RR_PREFIX), None);
10708    }
10709
10710    #[test]
10711    fn body_matches_protocol_is_symmetric_over_core_and_subtree_bodies() {
10712        use crate::replication::protocol::{
10713            AuditChallenge, AuditResponse, FreshReplicationOffer, ReplicationMessageBody,
10714            SubtreeSliceChallenge,
10715        };
10716
10717        let subtree = ReplicationMessageBody::SubtreeSliceChallenge(SubtreeSliceChallenge {
10718            challenge_id: 1,
10719            nonce: [0u8; 32],
10720            challenged_peer_id: [0u8; 32],
10721            expected_commitment_hash: [0u8; 32],
10722            openings: vec![],
10723        });
10724        let digest_challenge = ReplicationMessageBody::AuditChallenge(AuditChallenge {
10725            challenge_id: 1,
10726            nonce: [0u8; 32],
10727            challenged_peer_id: [0u8; 32],
10728            keys: vec![[0u8; 32]],
10729        });
10730        let digest_response =
10731            ReplicationMessageBody::AuditResponse(AuditResponse::Bootstrapping { challenge_id: 1 });
10732        let core = ReplicationMessageBody::FreshReplicationOffer(FreshReplicationOffer {
10733            key: [0u8; 32],
10734            data: vec![],
10735            proof_of_payment: vec![],
10736        });
10737
10738        assert!(body_matches_protocol(&subtree, SUBTREE_AUDIT_PROTOCOL_ID));
10739        assert!(!body_matches_protocol(&subtree, REPLICATION_PROTOCOL_ID));
10740
10741        for body in [&digest_challenge, &digest_response, &core] {
10742            assert!(body_matches_protocol(body, REPLICATION_PROTOCOL_ID));
10743            assert!(!body_matches_protocol(body, SUBTREE_AUDIT_PROTOCOL_ID));
10744        }
10745
10746        for body in [&subtree, &digest_challenge, &digest_response, &core] {
10747            assert!(body_matches_protocol(body, response_protocol_for(body)));
10748        }
10749    }
10750
10751    fn test_peer(b: u8) -> PeerId {
10752        let mut bytes = [0u8; 32];
10753        bytes[0] = b;
10754        PeerId::from_bytes(bytes)
10755    }
10756
10757    /// A structurally valid offer for `data`: real content address, a proof of
10758    /// the minimum accepted size, distinguished by `proof_marker` so a test can
10759    /// tell whose proof came back out of the queue.
10760    fn test_fresh_offer(data: Vec<u8>, proof_marker: u8) -> protocol::FreshReplicationOffer {
10761        protocol::FreshReplicationOffer {
10762            key: crate::client::compute_address(&data),
10763            data,
10764            proof_of_payment: vec![proof_marker; MIN_PAYMENT_PROOF_SIZE_BYTES],
10765        }
10766    }
10767
10768    fn admit_test_offer(
10769        in_flight: &FreshOfferInFlight,
10770        offer: protocol::FreshReplicationOffer,
10771        source: PeerId,
10772    ) -> FreshOfferAdmission {
10773        FreshOfferEntryGuard::admit(in_flight, offer, source, 0, None, Instant::now())
10774    }
10775
10776    #[test]
10777    fn fresh_offer_entry_queues_one_proof_per_source_then_frees_the_key_on_drop() {
10778        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10779        let data = vec![0x11u8; 64];
10780
10781        let opened = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 1), test_peer(1));
10782        let FreshOfferAdmission::Opened(entry) = opened else {
10783            panic!("first offer for a key should open the entry")
10784        };
10785
10786        // A second sender contributes its proof instead of being turned away:
10787        // its bytes are provably the same, so only the proof is worth keeping.
10788        assert!(
10789            matches!(
10790                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 2), test_peer(2)),
10791                FreshOfferAdmission::Joined
10792            ),
10793            "a duplicate from a new source should queue its proof"
10794        );
10795        // The same peer twice is not extra evidence, just extra work.
10796        assert!(
10797            matches!(
10798                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 3), test_peer(1)),
10799                FreshOfferAdmission::DuplicateSource
10800            ),
10801            "one source should hold at most one queued proof per key"
10802        );
10803
10804        // An entry that outlived its handler would bar the key forever.
10805        drop(entry);
10806        assert!(
10807            matches!(
10808                admit_test_offer(&in_flight, test_fresh_offer(data, 4), test_peer(3)),
10809                FreshOfferAdmission::Opened(_)
10810            ),
10811            "a released key should be openable again"
10812        );
10813    }
10814
10815    #[test]
10816    fn fresh_offer_entries_are_independent_across_keys_sharing_a_prefix() {
10817        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10818
10819        // A node only receives offers for keys close to its own ID, so accepted
10820        // keys share a long prefix. Any prefix-derived shard index would have
10821        // funnelled these two onto one lock and serialized them.
10822        let _first = admit_test_offer(&in_flight, test_fresh_offer(vec![1u8; 8], 1), test_peer(1));
10823        assert!(
10824            matches!(
10825                admit_test_offer(&in_flight, test_fresh_offer(vec![2u8; 8], 1), test_peer(1)),
10826                FreshOfferAdmission::Opened(_)
10827            ),
10828            "distinct keys should never block each other"
10829        );
10830    }
10831
10832    /// The regression that motivated queueing proofs at all.
10833    ///
10834    /// A sender whose proof does not verify must cost the network its own
10835    /// attempt and nothing more. Refusing every later offer outright made the
10836    /// first arrival the only arrival, so one bad proof lost the record — and
10837    /// the delayed possession check then charged that absence to this node.
10838    #[test]
10839    fn a_failing_proof_hands_the_key_to_the_next_sender() {
10840        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10841        let data = vec![0x5Au8; 128];
10842        let forger = test_peer(0xF0);
10843        let genuine = test_peer(0x0F);
10844
10845        let FreshOfferAdmission::Opened(mut entry) =
10846            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0xBA), forger)
10847        else {
10848            panic!("the first offer should open the entry");
10849        };
10850        assert!(
10851            matches!(
10852                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0x60), genuine),
10853                FreshOfferAdmission::Joined
10854            ),
10855            "the genuine sender must not be turned away by the forger"
10856        );
10857
10858        let first = entry
10859            .next_attempt()
10860            .expect("the opener's proof comes first");
10861        assert_eq!(first.source, forger);
10862
10863        // Treat the forger's proof as failed: the next one is still reachable,
10864        // and it is tried against the bytes already held rather than a refetch.
10865        let second = entry
10866            .next_attempt()
10867            .expect("a failed proof must not consume the key");
10868        assert_eq!(second.source, genuine);
10869        assert_eq!(
10870            second.proof_of_payment,
10871            vec![0x60u8; MIN_PAYMENT_PROOF_SIZE_BYTES]
10872        );
10873        assert_eq!(
10874            entry.data(),
10875            data.as_slice(),
10876            "every proof is tried against the one copy of the bytes"
10877        );
10878
10879        // Draining the queue releases the key rather than stranding it.
10880        assert!(entry.next_attempt().is_none());
10881        assert!(
10882            matches!(
10883                admit_test_offer(&in_flight, test_fresh_offer(data, 0x70), test_peer(9)),
10884                FreshOfferAdmission::Opened(_)
10885            ),
10886            "an exhausted entry should release its key"
10887        );
10888    }
10889
10890    /// The cap has to be a lifetime budget, not a queue depth.
10891    ///
10892    /// The handler pops a proof before verifying it, so gating admission on the
10893    /// *instantaneous* queue length lets a fresh source refill the slot that pop
10894    /// just freed. Each refill is another on-chain payment verification, run
10895    /// sequentially while the entry holds its admission permit and a worker
10896    /// slot, so a stream of distinct sources could keep one key's handler — and
10897    /// one of only four workers — busy indefinitely.
10898    #[test]
10899    fn refilling_a_popped_slot_cannot_extend_a_keys_attempt_budget() {
10900        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10901        let data = vec![0x3Du8; 32];
10902
10903        let FreshOfferAdmission::Opened(mut entry) =
10904            admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0))
10905        else {
10906            panic!("the first offer should open the entry")
10907        };
10908
10909        // Drive pop-then-admit with a fresh source every time, exactly as a
10910        // sybil stream would. The budget must be spent by admissions, not
10911        // returned by pops.
10912        let mut admitted = 1;
10913        for i in 1..u8::try_from(MAX_FRESH_OFFER_ATTEMPTS_PER_KEY * 4).unwrap_or(u8::MAX) {
10914            let _ = entry.next_attempt();
10915            if matches!(
10916                admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(i)),
10917                FreshOfferAdmission::Joined
10918            ) {
10919                admitted += 1;
10920            }
10921        }
10922
10923        assert!(
10924            admitted <= MAX_FRESH_OFFER_ATTEMPTS_PER_KEY,
10925            "a key accepted {admitted} proofs over its lifetime, but the budget is \
10926             {MAX_FRESH_OFFER_ATTEMPTS_PER_KEY}: popping a proof must not return its slot"
10927        );
10928    }
10929
10930    #[test]
10931    fn a_fresh_offer_entry_queues_no_more_proofs_than_the_close_group_can_send() {
10932        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
10933        let data = vec![0x2Cu8; 32];
10934
10935        // The opener occupies the first slot, so the cap is reached after
10936        // MAX_FRESH_OFFER_ATTEMPTS_PER_KEY distinct sources in total.
10937        let _entry = admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), test_peer(0));
10938        for i in 1..MAX_FRESH_OFFER_ATTEMPTS_PER_KEY {
10939            let source = test_peer(u8::try_from(i).unwrap_or(u8::MAX));
10940            assert!(
10941                matches!(
10942                    admit_test_offer(&in_flight, test_fresh_offer(data.clone(), 0), source),
10943                    FreshOfferAdmission::Joined
10944                ),
10945                "sender {i} is within the legitimate close-group fan-out"
10946            );
10947        }
10948
10949        let surplus = test_peer(0xEE);
10950        assert!(
10951            matches!(
10952                admit_test_offer(&in_flight, test_fresh_offer(data, 0), surplus),
10953                FreshOfferAdmission::Full
10954            ),
10955            "past the cap a proof is surplus: enough are already queued to place the record"
10956        );
10957    }
10958
10959    #[test]
10960    fn verification_receiver_accepts_a_full_cycle_and_rejects_more() {
10961        assert!(!verification_request_exceeds_limit(
10962            config::MAX_VERIFICATION_KEYS_PER_CYCLE
10963        ));
10964        assert!(verification_request_exceeds_limit(
10965            config::MAX_VERIFICATION_KEYS_PER_CYCLE + 1
10966        ));
10967    }
10968
10969    // The heavy round-1 limiter enforces the per-peer rate cooldown
10970    // and single-use round-1 → round-2 sessions.
10971    #[tokio::test]
10972    async fn subtree_round1_limiter_cooldown_and_single_use_session() {
10973        let limiter = SubtreeRound1Limiter::new(
10974            Duration::from_hours(1),
10975            config::MAX_CONCURRENT_SUBTREE_ROUND1,
10976        );
10977        let peer = test_peer(1);
10978
10979        // First round-1 is admitted; drop the guard so concurrency is free again.
10980        let guard = limiter.admit(&peer).await;
10981        assert!(guard.is_some(), "first round-1 admitted");
10982        drop(guard);
10983        // A second round-1 within the cooldown is dropped even though the heavy
10984        // pool now has a free slot — the rate cooldown, not concurrency, blocks it.
10985        assert!(
10986            limiter.admit(&peer).await.is_none(),
10987            "second round-1 within cooldown is rate-dropped"
10988        );
10989        // A different peer has its own cooldown.
10990        assert!(limiter.admit(&test_peer(2)).await.is_some());
10991
10992        // Session: opened by round 1, consumed exactly once by the matching round 2.
10993        let hash = [7u8; 32];
10994        let nonce = [9u8; 32];
10995        assert!(
10996            limiter
10997                .open_session(peer, 42, hash, nonce, PointerBindings::new())
10998                .await
10999        );
11000        // Wrong nonce / commitment does not match.
11001        assert!(limiter
11002            .consume_session(&peer, 42, &hash, &[0u8; 32])
11003            .await
11004            .is_none());
11005        assert!(limiter
11006            .consume_session(&peer, 42, &[0u8; 32], &nonce)
11007            .await
11008            .is_none());
11009        // A round 2 with no prior round 1 (wrong challenge_id) misses.
11010        assert!(limiter
11011            .consume_session(&peer, 99, &hash, &nonce)
11012            .await
11013            .is_none());
11014        // The matching round 2 consumes it — and only once (single-use).
11015        assert!(limiter
11016            .consume_session(&peer, 42, &hash, &nonce)
11017            .await
11018            .is_some());
11019        assert!(limiter
11020            .consume_session(&peer, 42, &hash, &nonce)
11021            .await
11022            .is_none());
11023    }
11024
11025    // A session carries what its round 1 bound for each pointer to round 2,
11026    // and every live session together stays under the binding budget. A
11027    // session that does not fit is refused, and no session already opened
11028    // gives up its bindings or its place for it.
11029    #[tokio::test]
11030    async fn subtree_session_carries_pointer_bindings_within_the_budget() {
11031        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
11032        let (hash, nonce) = ([1u8; 32], [2u8; 32]);
11033        let bindings = |from: u64, count: usize| -> PointerBindings {
11034            (from..)
11035                .take(count)
11036                .map(|i| {
11037                    let mut key = [0u8; 32];
11038                    key[..8].copy_from_slice(&i.to_le_bytes());
11039                    (key, [0xAB; 32])
11040                })
11041                .collect()
11042        };
11043
11044        let half = MAX_SESSION_POINTER_BINDINGS / 2;
11045        let first = bindings(0, half);
11046        assert!(
11047            limiter
11048                .open_session(test_peer(1), 1, hash, nonce, first.clone())
11049                .await
11050        );
11051        assert!(
11052            limiter
11053                .open_session(test_peer(2), 2, hash, nonce, bindings(1 << 40, half))
11054                .await
11055        );
11056        // The budget is full: one more binding is refused, but a round 1 with
11057        // no pointers in it still opens.
11058        assert!(
11059            !limiter
11060                .open_session(test_peer(3), 3, hash, nonce, bindings(1 << 41, 1))
11061                .await
11062        );
11063        assert!(
11064            limiter
11065                .open_session(test_peer(4), 4, hash, nonce, PointerBindings::new())
11066                .await
11067        );
11068
11069        assert_eq!(
11070            limiter
11071                .consume_session(&test_peer(1), 1, &hash, &nonce)
11072                .await,
11073            Some(first.clone()),
11074            "an opened session keeps every binding it was given"
11075        );
11076        assert!(
11077            limiter
11078                .consume_session(&test_peer(3), 3, &hash, &nonce)
11079                .await
11080                .is_none(),
11081            "a refused session was never opened"
11082        );
11083        assert_eq!(
11084            limiter
11085                .consume_session(&test_peer(2), 2, &hash, &nonce)
11086                .await
11087                .map(|b| b.len()),
11088            Some(half)
11089        );
11090
11091        // Consumed sessions free their room.
11092        assert!(
11093            limiter
11094                .open_session(test_peer(5), 5, hash, nonce, bindings(1 << 42, half))
11095                .await
11096        );
11097    }
11098
11099    // A session refused for the binding budget is refused before the session
11100    // cap evicts anything: with both full, the refusal costs no session its
11101    // place.
11102    #[tokio::test]
11103    async fn a_session_refused_for_bindings_evicts_no_other_session() {
11104        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
11105        let (hash, nonce) = ([1u8; 32], [2u8; 32]);
11106        let full: PointerBindings = (0u64..)
11107            .take(MAX_SESSION_POINTER_BINDINGS)
11108            .map(|i| {
11109                let mut key = [0u8; 32];
11110                key[..8].copy_from_slice(&i.to_le_bytes());
11111                (key, [0xCD; 32])
11112            })
11113            .collect();
11114        assert!(
11115            limiter
11116                .open_session(test_peer(0), 0, hash, nonce, full)
11117                .await
11118        );
11119        for id in 1..MAX_SUBTREE_SESSIONS as u64 {
11120            assert!(
11121                limiter
11122                    .open_session(test_peer(1), id, hash, nonce, PointerBindings::new())
11123                    .await
11124            );
11125        }
11126
11127        let one: PointerBindings = std::iter::once(([0xEE; 32], [0xEE; 32])).collect();
11128        assert!(
11129            !limiter
11130                .open_session(test_peer(2), u64::MAX, hash, nonce, one)
11131                .await
11132        );
11133        assert_eq!(
11134            limiter.sessions.read().await.len(),
11135            MAX_SUBTREE_SESSIONS,
11136            "every session is still there"
11137        );
11138        assert!(
11139            limiter
11140                .consume_session(&test_peer(0), 0, &hash, &nonce)
11141                .await
11142                .is_some(),
11143            "including the oldest"
11144        );
11145    }
11146
11147    // The concurrency pool and the per-peer cooldown are both keyed by peer id,
11148    // so a party holding several identities refills its allowance by rotating
11149    // between them and can keep the heavy pool busy indefinitely. The work
11150    // budget is keyed by nothing: it is charged for bytes proved, whoever asked,
11151    // so a fresh identity is refused exactly like a repeat caller once it is
11152    // spent. That is the difference between bounding concurrency and bounding
11153    // sustained work.
11154    #[tokio::test]
11155    async fn round1_work_budget_is_not_refilled_by_a_fresh_identity() {
11156        // Cooldown disabled so only the work budget can refuse anything.
11157        let limiter =
11158            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11159        assert!(
11160            limiter.admit(&test_peer(1)).await.is_some(),
11161            "a node starts with budget in hand so it can serve audits at once"
11162        );
11163
11164        // Serve enough proof work to run the balance into debt. Charging exactly
11165        // the burst would leave it at zero, which the next nanosecond of refill
11166        // lifts back above the line — the debt is the point.
11167        limiter
11168            .charge_work(2 * SUBTREE_ROUND1_WORK_BURST_BYTES)
11169            .await;
11170
11171        for id in 2..8u8 {
11172            assert!(
11173                limiter.admit(&test_peer(id)).await.is_none(),
11174                "a never-seen peer must still be refused while the budget is spent"
11175            );
11176        }
11177    }
11178
11179    // The budget is a rate, not a quota: it comes back on its own, so an honest
11180    // auditor blocked by a flood is only delayed. Carrying the debt is what
11181    // prices an expensive proof above a cheap one — without it, a proof reading
11182    // a maximal subtree would cost no more of the next caller's wait than a
11183    // one-leaf proof.
11184    #[test]
11185    fn round1_work_budget_carries_debt_and_refills_over_time() {
11186        let now = Instant::now();
11187        let at = |secs: u64| {
11188            now.checked_add(Duration::from_secs(secs))
11189                .unwrap_or_else(Instant::now)
11190        };
11191        let mut budget = Round1WorkBudget {
11192            balance: 0,
11193            last_refill: now,
11194        };
11195        assert!(!budget.has_budget(now), "empty means empty");
11196
11197        // A proof costing four seconds' worth of refill leaves four seconds of
11198        // debt, so the wait scales with what was actually served.
11199        budget.charge(4 * SUBTREE_ROUND1_WORK_REFILL_BYTES_PER_SEC, now);
11200        assert!(
11201            !budget.has_budget(at(3)),
11202            "still in debt three seconds after an over-large proof"
11203        );
11204        assert!(
11205            budget.has_budget(at(5)),
11206            "the debt is worked off at the refill rate"
11207        );
11208
11209        // Idle time does not bank unbounded credit for a later flood.
11210        budget.refill(at(24 * 60 * 60));
11211        assert_eq!(
11212            budget.balance, SUBTREE_ROUND1_WORK_BURST_BYTES,
11213            "refill is capped at the burst size"
11214        );
11215    }
11216
11217    // The heavy round-1 pool size is the tightest bound the responder applies and
11218    // the one least backed by fleet measurement, so it is read from config rather
11219    // than baked into the binary: a fleet that lands on the wrong number retunes
11220    // instead of waiting for a release. These pin that the configured value is
11221    // what actually gates admission, and that a 0 degrades to slow, not to off —
11222    // a wedged-shut responder would read on every auditor as a graced timeout,
11223    // i.e. a silent audit outage with nobody penalised and nothing in the logs.
11224    #[tokio::test]
11225    async fn round1_pool_size_comes_from_config() {
11226        // Cooldown disabled so only concurrency can refuse anything.
11227        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 1);
11228        let held = limiter.admit(&test_peer(1)).await;
11229        assert!(held.is_some(), "the single configured slot is admitted");
11230        assert!(
11231            limiter.admit(&test_peer(2)).await.is_none(),
11232            "a second concurrent round 1 is refused at a configured pool of 1, \
11233             proving admission follows config rather than the compiled-in default"
11234        );
11235        drop(held);
11236        assert!(
11237            limiter.admit(&test_peer(2)).await.is_some(),
11238            "the slot is reusable once the first proof completes"
11239        );
11240    }
11241
11242    #[tokio::test]
11243    async fn round1_pool_size_of_zero_is_clamped_to_one() {
11244        let limiter = SubtreeRound1Limiter::new(Duration::ZERO, 0);
11245        assert!(
11246            limiter.admit(&test_peer(1)).await.is_some(),
11247            "a mis-set pool of 0 must still serve audits, not silently refuse every one"
11248        );
11249    }
11250
11251    fn test_key(b: u8) -> crate::ant_protocol::XorName {
11252        let mut k = [0u8; 32];
11253        k[0] = b;
11254        k
11255    }
11256
11257    #[test]
11258    fn bad_hint_penalty_rejects_or_directly_contradicts_sole_replica_source() {
11259        let source = test_peer(0x91);
11260        let corroborator = test_peer(0x92);
11261        let mut evidence = types::KeyVerificationEvidence {
11262            presence: HashMap::from([(source, PresenceEvidence::Absent)]),
11263            paid_list: HashMap::new(),
11264        };
11265        let failed = KeyVerificationOutcome::QuorumFailed;
11266
11267        assert_eq!(
11268            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11269            Some((source, SingletonHintFault::RejectedByCloseGroup)),
11270            "a close-group rejection outranks the denial: the key does not exist, which is \
11271             a bad hint however the sender's own disk is doing"
11272        );
11273        assert_eq!(
11274            punishable_singleton_replica_hint_source(
11275                &HashSet::from([source, corroborator]),
11276                &failed,
11277                &evidence,
11278            ),
11279            None,
11280            "corroborated hints must not use the sole-source penalty lane"
11281        );
11282        assert_eq!(
11283            punishable_singleton_replica_hint_source(&HashSet::new(), &failed, &evidence),
11284            None,
11285            "paid-list advertisements do not claim possession, so they leave the \
11286             replica-hint source set empty and cannot be penalized"
11287        );
11288
11289        evidence
11290            .presence
11291            .insert(source, PresenceEvidence::Unresolved);
11292        assert_eq!(
11293            punishable_singleton_replica_hint_source(&HashSet::from([source]), &failed, &evidence),
11294            Some((source, SingletonHintFault::RejectedByCloseGroup)),
11295            "definitive close-group rejection is punishable without direct contradiction"
11296        );
11297        assert_eq!(
11298            punishable_singleton_replica_hint_source(
11299                &HashSet::from([source]),
11300                &KeyVerificationOutcome::QuorumInconclusive,
11301                &evidence,
11302            ),
11303            None,
11304            "timeouts and inconclusive evidence are neutral"
11305        );
11306
11307        evidence.presence.insert(source, PresenceEvidence::Absent);
11308        assert_eq!(
11309            punishable_singleton_replica_hint_source(
11310                &HashSet::from([source]),
11311                &KeyVerificationOutcome::QuorumVerified {
11312                    sources: vec![corroborator],
11313                },
11314                &evidence,
11315            ),
11316            Some((source, SingletonHintFault::DeniedPossession)),
11317            "an explicit denial is punishable regardless of the overall outcome, and is \
11318             classified separately because it is a statement about the sender's own \
11319             storage rather than about the key"
11320        );
11321    }
11322
11323    /// Build a round-2 slice challenge matching an open session. `openings` is
11324    /// empty: these tests exercise admission and session handling only, which
11325    /// run before any block is opened.
11326    fn slice_challenge(
11327        challenge_id: u64,
11328        commitment_hash: [u8; 32],
11329        nonce: [u8; 32],
11330    ) -> protocol::SubtreeSliceChallenge {
11331        protocol::SubtreeSliceChallenge {
11332            challenge_id,
11333            nonce,
11334            challenged_peer_id: [0u8; 32],
11335            expected_commitment_hash: commitment_hash,
11336            openings: Vec::new(),
11337        }
11338    }
11339
11340    // Regression (Copilot, PR #181): a round-2 slice challenge refused at the
11341    // responder caps MUST NOT burn the single-use round-1 session.
11342    //
11343    // The handler used to consume the session first and admit second, so a
11344    // transient local capacity drop permanently destroyed that audit exchange —
11345    // every retry hit the `no live round-1 session` path and got `Transient`,
11346    // even after load cleared. Turning momentary local load into a deterministic
11347    // round-2 miss costs the responder its whole-slice credit for that round.
11348    #[tokio::test]
11349    async fn capacity_refused_slice_challenge_preserves_round1_session() {
11350        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11351        let inflight = Arc::new(RwLock::new(HashMap::new()));
11352        let round1 =
11353            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11354        let peer = test_peer(0xB1);
11355        let (id, hash, nonce) = (77u64, [3u8; 32], [4u8; 32]);
11356        let challenge = slice_challenge(id, hash, nonce);
11357
11358        assert!(
11359            round1
11360                .open_session(peer, id, hash, nonce, PointerBindings::new())
11361                .await
11362        );
11363
11364        // Saturate this peer's share so the next admission must be refused.
11365        let mut hold = Vec::new();
11366        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11367            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Byte)
11368                .await
11369            {
11370                Ok(guard) => hold.push(guard),
11371                Err(err) => panic!("unexpected admission failure below the cap: {err:?}"),
11372            }
11373        }
11374
11375        let refused =
11376            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11377        assert!(
11378            matches!(refused, SliceAdmission::Capacity(_)),
11379            "a saturated peer share must refuse on capacity, not on session"
11380        );
11381
11382        // Load clears. The session must have survived the refusal.
11383        drop(hold);
11384        let retried =
11385            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11386        assert!(
11387            matches!(retried, SliceAdmission::Admitted(..)),
11388            "the round-1 session must survive a capacity refusal so the retry succeeds"
11389        );
11390
11391        // Still single-use: the successful admission consumed it exactly once.
11392        drop(retried);
11393        let replayed =
11394            admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11395        assert!(
11396            matches!(replayed, SliceAdmission::NoSession),
11397            "a consumed session must not be replayable"
11398        );
11399    }
11400
11401    // The permit taken for the session probe is released when the probe misses,
11402    // so an unsessioned flood cannot pin the responder pool shut.
11403    #[tokio::test]
11404    async fn unsessioned_slice_challenge_releases_its_admission_slot() {
11405        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11406        let inflight = Arc::new(RwLock::new(HashMap::new()));
11407        let round1 =
11408            SubtreeRound1Limiter::new(Duration::ZERO, config::MAX_CONCURRENT_SUBTREE_ROUND1);
11409        let peer = test_peer(0xB2);
11410        let challenge = slice_challenge(1, [0u8; 32], [0u8; 32]);
11411
11412        // Far more unsessioned challenges than the per-peer cap would allow if
11413        // the slot leaked on the miss path.
11414        for _ in 0..(MAX_AUDIT_RESPONSES_PER_PEER * 4) {
11415            let outcome =
11416                admit_slice_challenge(&semaphore, &inflight, &round1, &peer, &challenge).await;
11417            assert!(
11418                matches!(outcome, SliceAdmission::NoSession),
11419                "no session was ever opened, so every attempt must miss"
11420            );
11421        }
11422
11423        assert_eq!(
11424            semaphore.available_permits(),
11425            MAX_CONCURRENT_AUDIT_RESPONSES,
11426            "every global permit must be returned"
11427        );
11428        assert!(
11429            inflight.read().await.get(&peer).copied().unwrap_or(0) == 0,
11430            "no per-peer slot may be left occupied"
11431        );
11432    }
11433
11434    #[test]
11435    fn holder_credit_revocation_distinguishes_timeout_from_confirmed_failure() {
11436        assert!(!audit_failure_revokes_holder_credit(
11437            &AuditFailureReason::Timeout
11438        ));
11439        assert!(audit_failure_revokes_holder_credit(
11440            &AuditFailureReason::DigestMismatch
11441        ));
11442    }
11443
11444    #[tokio::test]
11445    async fn audit_responder_admission_reports_per_peer_cap_full() {
11446        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11447        let inflight = Arc::new(RwLock::new(HashMap::new()));
11448        let peer = test_peer(0xA1);
11449
11450        let mut guards = Vec::new();
11451        for _ in 0..MAX_AUDIT_RESPONSES_PER_PEER {
11452            match admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree)
11453                .await
11454            {
11455                Ok(guard) => guards.push(guard),
11456                Err(err) => panic!("unexpected admission failure before peer cap: {err:?}"),
11457            }
11458        }
11459
11460        let Err(err) =
11461            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11462        else {
11463            panic!("admission should fail once per-peer cap is full");
11464        };
11465        assert_eq!(err.reason, ResponderRejectReason::PerPeerCapFull);
11466        assert_eq!(err.peer_inflight, MAX_AUDIT_RESPONSES_PER_PEER);
11467        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11468        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11469
11470        drop(guards);
11471    }
11472
11473    #[tokio::test]
11474    async fn audit_responder_admission_reports_global_pool_full() {
11475        let semaphore = Arc::new(Semaphore::new(MAX_CONCURRENT_AUDIT_RESPONSES));
11476        let inflight = Arc::new(RwLock::new(HashMap::new()));
11477        let peer = test_peer(0xA2);
11478
11479        let mut held_global_permits = Vec::new();
11480        for _ in 0..MAX_CONCURRENT_AUDIT_RESPONSES {
11481            held_global_permits.push(
11482                Arc::clone(&semaphore)
11483                    .try_acquire_owned()
11484                    .expect("test should be able to exhaust the global pool"),
11485            );
11486        }
11487
11488        let Err(err) =
11489            admit_audit_responder(&semaphore, &inflight, &peer, AuditResponderClass::Subtree).await
11490        else {
11491            panic!("admission should fail once global pool is full");
11492        };
11493        assert_eq!(err.reason, ResponderRejectReason::GlobalPoolFull);
11494        assert_eq!(err.global_inflight, MAX_CONCURRENT_AUDIT_RESPONSES);
11495        assert_eq!(err.global_limit, MAX_CONCURRENT_AUDIT_RESPONSES);
11496        assert_eq!(err.peer_inflight, 0);
11497        assert_eq!(err.peer_limit, MAX_AUDIT_RESPONSES_PER_PEER);
11498
11499        drop(held_global_permits);
11500    }
11501
11502    #[tokio::test]
11503    async fn bounded_responder_guard_releases_global_and_peer_slots_on_drop() {
11504        let semaphore = Arc::new(Semaphore::new(1));
11505        let inflight = Arc::new(RwLock::new(HashMap::new()));
11506        let peer = test_peer(0xA3);
11507
11508        let guard = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1)
11509            .await
11510            .expect("first responder should be admitted");
11511        assert_eq!(semaphore.available_permits(), 0);
11512        assert_eq!(inflight.read().await.get(&peer), Some(&1));
11513
11514        drop(guard);
11515        assert_eq!(semaphore.available_permits(), 1);
11516        assert!(!inflight.read().await.contains_key(&peer));
11517    }
11518
11519    #[tokio::test]
11520    async fn cancelled_bounded_responder_wait_does_not_leak_a_peer_slot() {
11521        let semaphore = Arc::new(Semaphore::new(1));
11522        let inflight = Arc::new(RwLock::new(HashMap::new()));
11523        let peer = test_peer(0xA4);
11524        let held_map = inflight.write().await;
11525
11526        let waiting = admit_bounded_responder(&semaphore, &inflight, &peer, 1, 1);
11527        assert!(
11528            tokio::time::timeout(Duration::from_millis(10), waiting)
11529                .await
11530                .is_err(),
11531            "admission should still be waiting for the peer map"
11532        );
11533
11534        drop(held_map);
11535        assert_eq!(semaphore.available_permits(), 1);
11536        assert!(!inflight.read().await.contains_key(&peer));
11537    }
11538
11539    #[test]
11540    fn responder_staleness_sheds_expired_requests_but_serves_fresh_ones() {
11541        let timeout = Duration::from_secs(1);
11542        let old_received_at = Instant::now()
11543            .checked_sub(timeout)
11544            .unwrap_or_else(Instant::now);
11545
11546        assert!(request_is_stale(old_received_at, timeout));
11547        assert!(!request_is_stale(Instant::now(), timeout));
11548    }
11549
11550    #[tokio::test]
11551    async fn neighbor_sync_admission_serializes_each_peer_but_allows_other_peers() {
11552        let semaphore = Arc::new(Semaphore::new(NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING));
11553        let inflight = Arc::new(RwLock::new(HashMap::new()));
11554        let first_peer = test_peer(0xB3);
11555        let second_peer = test_peer(0xB4);
11556
11557        let first_guard = admit_bounded_responder(
11558            &semaphore,
11559            &inflight,
11560            &first_peer,
11561            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11562            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11563        )
11564        .await
11565        .expect("first sync from a peer should be admitted");
11566        let duplicate = admit_bounded_responder(
11567            &semaphore,
11568            &inflight,
11569            &first_peer,
11570            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11571            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11572        )
11573        .await;
11574        let other_peer = admit_bounded_responder(
11575            &semaphore,
11576            &inflight,
11577            &second_peer,
11578            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING,
11579            NEIGHBOR_SYNC_RESPONDER_MAX_OUTSTANDING_PER_PEER,
11580        )
11581        .await;
11582
11583        assert!(matches!(
11584            duplicate,
11585            Err(ResponderAdmissionFailure {
11586                reason: ResponderRejectReason::PerPeerCapFull,
11587                ..
11588            })
11589        ));
11590        assert!(other_peer.is_ok());
11591        drop(first_guard);
11592        drop(other_peer);
11593    }
11594
11595    /// One flooding peer must not be able to hold every fresh-offer slot.
11596    ///
11597    /// This is the eviction primitive the per-peer share closes: with only a
11598    /// global bound, a single source occupies the pool, every honest offer in
11599    /// that window is refused, and because a refusal reads as absence to the
11600    /// sender's delayed possession check those refusals land as
11601    /// audit-severity penalties on *this* node.
11602    #[tokio::test]
11603    async fn fresh_offer_admission_reserves_capacity_for_other_peers() {
11604        let semaphore = Arc::new(Semaphore::new(FRESH_OFFER_MAX_OUTSTANDING));
11605        let inflight = Arc::new(RwLock::new(HashMap::new()));
11606        let flooder = test_peer(0xC1);
11607        let honest = test_peer(0xC2);
11608
11609        let mut held = Vec::new();
11610        for _ in 0..FRESH_OFFER_MAX_OUTSTANDING_PER_PEER {
11611            held.push(
11612                admit_bounded_responder(
11613                    &semaphore,
11614                    &inflight,
11615                    &flooder,
11616                    FRESH_OFFER_MAX_OUTSTANDING,
11617                    FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11618                )
11619                .await
11620                .expect("offers within the per-peer share are admitted"),
11621            );
11622        }
11623
11624        let flooder_excess = admit_bounded_responder(
11625            &semaphore,
11626            &inflight,
11627            &flooder,
11628            FRESH_OFFER_MAX_OUTSTANDING,
11629            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11630        )
11631        .await;
11632        assert!(
11633            matches!(
11634                flooder_excess,
11635                Err(ResponderAdmissionFailure {
11636                    reason: ResponderRejectReason::PerPeerCapFull,
11637                    ..
11638                })
11639            ),
11640            "one source must not exceed its fresh-offer share"
11641        );
11642
11643        let honest_offer = admit_bounded_responder(
11644            &semaphore,
11645            &inflight,
11646            &honest,
11647            FRESH_OFFER_MAX_OUTSTANDING,
11648            FRESH_OFFER_MAX_OUTSTANDING_PER_PEER,
11649        )
11650        .await;
11651        assert!(
11652            honest_offer.is_ok(),
11653            "an honest sender must still be admitted while another peer floods"
11654        );
11655
11656        assert!(
11657            usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX)
11658                < FRESH_OFFER_MAX_OUTSTANDING,
11659            "the per-peer share must leave room for other sources"
11660        );
11661
11662        drop(held);
11663        drop(honest_offer);
11664    }
11665
11666    /// Paid notifies get the same per-source treatment as every other class.
11667    #[tokio::test]
11668    async fn paid_notify_admission_reserves_capacity_for_other_peers() {
11669        let semaphore = Arc::new(Semaphore::new(PAID_NOTIFY_MAX_OUTSTANDING));
11670        let inflight = Arc::new(RwLock::new(HashMap::new()));
11671        let flooder = test_peer(0xC3);
11672        let honest = test_peer(0xC4);
11673
11674        let mut held = Vec::new();
11675        for _ in 0..PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER {
11676            held.push(
11677                admit_bounded_responder(
11678                    &semaphore,
11679                    &inflight,
11680                    &flooder,
11681                    PAID_NOTIFY_MAX_OUTSTANDING,
11682                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11683                )
11684                .await
11685                .expect("notifies within the per-peer share are admitted"),
11686            );
11687        }
11688
11689        assert!(
11690            matches!(
11691                admit_bounded_responder(
11692                    &semaphore,
11693                    &inflight,
11694                    &flooder,
11695                    PAID_NOTIFY_MAX_OUTSTANDING,
11696                    PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11697                )
11698                .await,
11699                Err(ResponderAdmissionFailure {
11700                    reason: ResponderRejectReason::PerPeerCapFull,
11701                    ..
11702                })
11703            ),
11704            "one source must not exceed its paid-notify share"
11705        );
11706        assert!(
11707            admit_bounded_responder(
11708                &semaphore,
11709                &inflight,
11710                &honest,
11711                PAID_NOTIFY_MAX_OUTSTANDING,
11712                PAID_NOTIFY_MAX_OUTSTANDING_PER_PEER,
11713            )
11714            .await
11715            .is_ok(),
11716            "an honest sender must still be admitted while another peer floods"
11717        );
11718
11719        drop(held);
11720    }
11721
11722    /// The fresh-offer per-source bound must guarantee headroom for a peer
11723    /// holding nothing, without throttling a single legitimate fan-out.
11724    ///
11725    /// Sized as a quota rather than a reserve, this bound refused offers during
11726    /// an ordinary upload (see `tests/e2e/fresh_offer_capacity.rs`), and every
11727    /// refusal is charged to THIS node at audit severity because the sender
11728    /// never reads it.
11729    #[test]
11730    fn fresh_offer_share_reserves_headroom_without_throttling_one_sender() {
11731        let share = usize::try_from(FRESH_OFFER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX);
11732
11733        assert_eq!(
11734            FRESH_OFFER_MAX_OUTSTANDING - share,
11735            FRESH_OFFER_RESERVED_FOR_OTHER_SOURCES,
11736            "a source holding none must always find a free slot"
11737        );
11738        assert!(
11739            share < FRESH_OFFER_MAX_OUTSTANDING,
11740            "one peer must not be able to take the whole pool"
11741        );
11742        // The failure this pins: a share sized like the request/response
11743        // classes (fetch 2, verification 1, neighbor sync 1) binds on ordinary
11744        // one-way bulk traffic.
11745        assert!(
11746            share > usize::try_from(FETCH_RESPONDER_MAX_OUTSTANDING_PER_PEER).unwrap_or(usize::MAX),
11747            "fresh offers are one-way bulk, not request/response — their share \
11748             must not be sized like the request classes'"
11749        );
11750    }
11751
11752    /// A malformed offer must be refused before it can occupy an admission
11753    /// slot, so junk cannot hold capacity for the length of a verification.
11754    #[test]
11755    fn structurally_invalid_fresh_offers_are_rejected_before_admission() {
11756        let key = test_key(0xC5);
11757
11758        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11759
11760        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &[])
11761            .expect("an offer with no proof must be refused");
11762        assert!(
11763            rejection.penalise,
11764            "an honest sender always attaches a proof"
11765        );
11766
11767        // A proof is retained per queued sender, so its size has to be bounded
11768        // here rather than at the verifier, which only sees it on a worker.
11769        let undersized = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES - 1];
11770        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &undersized)
11771            .expect("an undersized proof must be refused");
11772        assert!(
11773            rejection.penalise,
11774            "no honest sender constructs an undersized proof"
11775        );
11776        let oversized_proof = vec![1u8; MAX_PAYMENT_PROOF_SIZE_BYTES + 1];
11777        let rejection = fresh_offer_structural_rejection(&key, &[0u8; 1], &oversized_proof)
11778            .expect("an oversized proof must be refused");
11779        assert!(
11780            rejection.penalise,
11781            "no honest sender constructs an oversized proof"
11782        );
11783
11784        let rejection = fresh_offer_structural_rejection(
11785            &key,
11786            &vec![0u8; crate::ant_protocol::MAX_CHUNK_SIZE + 1],
11787            &valid_proof,
11788        )
11789        .expect("an oversized offer must be refused");
11790        assert!(
11791            rejection.penalise,
11792            "no honest sender constructs an oversized offer"
11793        );
11794
11795        let data = vec![0u8; 1];
11796        assert!(
11797            fresh_offer_structural_rejection(
11798                &crate::client::compute_address(&data),
11799                &data,
11800                &valid_proof
11801            )
11802            .is_none(),
11803            "a well-formed offer must reach admission"
11804        );
11805    }
11806
11807    /// Knowing a key must not be enough to enter its entry.
11808    ///
11809    /// Opening an entry on an unverified key/bytes association would let a peer
11810    /// that has only *learned* the key — every recipient of its `PaidNotify`,
11811    /// not just the close group that gets the chunk — seize it with junk.
11812    /// Joining one would be worse: the handler tries each queued proof against
11813    /// the *opener's* bytes, so an unchecked joiner could have its proof spent
11814    /// on bytes it never offered.
11815    #[test]
11816    fn a_fresh_offer_cannot_enter_an_entry_for_bytes_it_lacks() {
11817        let genuine_data = vec![0x5Au8; 128];
11818        let key = crate::client::compute_address(&genuine_data);
11819        let valid_proof = vec![1u8; MIN_PAYMENT_PROOF_SIZE_BYTES];
11820
11821        let rejection = fresh_offer_structural_rejection(&key, &[0xFFu8; 1], &valid_proof)
11822            .expect("bytes that do not hash to the advertised key must be refused");
11823        assert!(
11824            rejection.penalise,
11825            "no honest sender offers bytes that do not hash to the advertised key"
11826        );
11827
11828        // Dispatch reaches the entry only past that rejection, so the forged
11829        // offer never touched the key and the genuine one still opens it.
11830        assert!(
11831            fresh_offer_structural_rejection(&key, &genuine_data, &valid_proof).is_none(),
11832            "the offer that actually carries the key's bytes must reach the entry"
11833        );
11834
11835        let in_flight: FreshOfferInFlight = Arc::new(Mutex::new(HashMap::new()));
11836        assert!(
11837            matches!(
11838                admit_test_offer(&in_flight, test_fresh_offer(genuine_data, 1), test_peer(1)),
11839                FreshOfferAdmission::Opened(_)
11840            ),
11841            "an offer refused on payload shape must leave the key openable"
11842        );
11843    }
11844
11845    #[tokio::test]
11846    async fn peer_removed_clears_capacity_rejection_and_completes_bootstrap() {
11847        let peer = test_peer(0xA5);
11848        let key = test_key(0xA5);
11849        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11850        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
11851        let is_bootstrapping = Arc::new(RwLock::new(true));
11852        let bootstrap_complete_notify = Arc::new(Notify::new());
11853
11854        let now = Instant::now();
11855        queues.write().await.add_pending_verify(
11856            key,
11857            VerificationEntry {
11858                state: VerificationState::PendingVerify,
11859                verified_sources: Vec::new(),
11860                tried_sources: HashSet::new(),
11861                created_at: now,
11862                next_verify_at: now,
11863                hint_sources: HashSet::from([peer]),
11864                replica_hint_sources: HashSet::from([peer]),
11865                unresolved_retries: 0,
11866                no_holder_reported: false,
11867            },
11868        );
11869        super::bootstrap::track_discovered_keys(&bootstrap_state, &HashSet::from([key])).await;
11870        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
11871        {
11872            let q = queues.read().await;
11873            assert!(
11874                !super::bootstrap::check_bootstrap_drained(&bootstrap_state, &q).await,
11875                "capacity rejection should initially block bootstrap drain"
11876            );
11877        }
11878
11879        update_bootstrap_after_peer_removed(
11880            &peer,
11881            &bootstrap_state,
11882            &queues,
11883            &is_bootstrapping,
11884            &bootstrap_complete_notify,
11885        )
11886        .await;
11887
11888        let state = bootstrap_state.read().await;
11889        assert!(state.capacity_rejected_sources.is_empty());
11890        assert!(state.pending_keys.is_empty());
11891        assert!(state.is_drained());
11892        drop(state);
11893        assert!(!*is_bootstrapping.read().await);
11894    }
11895
11896    /// A fairness displacement forfeits the key but must not stamp its former
11897    /// owner: the owner did nothing wrong, and stamping it lets a flooding
11898    /// source block bootstrap drain through an unrelated honest peer.
11899    #[tokio::test]
11900    async fn fairness_displacement_does_not_stamp_its_victim() {
11901        let displaced_owner = test_peer(0xB1);
11902        let incoming_source = test_peer(0xB2);
11903        let displaced_key = test_key(0xB1);
11904        let admitted_key = test_key(0xB2);
11905        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11906        {
11907            let mut state = bootstrap_state.write().await;
11908            state.pending_keys.insert(displaced_key);
11909            state
11910                .capacity_rejected_sources
11911                .insert(incoming_source, Instant::now());
11912        }
11913        let outcomes = [(
11914            incoming_source,
11915            AdmissionOutcome {
11916                discovered: HashSet::from([admitted_key]),
11917                capacity_rejected_count: 0,
11918                displaced: vec![CapacityDisplacement {
11919                    key: displaced_key,
11920                    owner: displaced_owner,
11921                }],
11922            },
11923        )];
11924
11925        publish_bootstrap_admission_outcomes(
11926            &bootstrap_state,
11927            &outcomes,
11928            &HashSet::from([admitted_key]),
11929        )
11930        .await;
11931
11932        let state = bootstrap_state.read().await;
11933        assert!(!state.pending_keys.contains(&displaced_key));
11934        assert!(state.pending_keys.contains(&admitted_key));
11935        assert!(
11936            !state
11937                .capacity_rejected_sources
11938                .contains_key(&displaced_owner),
11939            "the displaced owner must not be charged for our own fairness reclaim"
11940        );
11941        assert!(!state
11942            .capacity_rejected_sources
11943            .contains_key(&incoming_source));
11944    }
11945
11946    /// A source that keeps overflowing us must not keep its own record fresh.
11947    ///
11948    /// This is the wedge the first-seen stamp closes: with refresh-on-every-
11949    /// rejection the debt could never age out, so `check_bootstrap_drained`
11950    /// stayed false forever and auditing never started (Invariant 19).
11951    #[tokio::test]
11952    async fn repeat_capacity_rejection_keeps_the_first_seen_stamp() {
11953        const REJECTION_ROUNDS: usize = 5;
11954
11955        let source = test_peer(0xB3);
11956        let key = test_key(0xB3);
11957        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
11958
11959        let first_seen = {
11960            let outcomes = [(
11961                source,
11962                AdmissionOutcome {
11963                    discovered: HashSet::new(),
11964                    capacity_rejected_count: 1,
11965                    displaced: Vec::new(),
11966                },
11967            )];
11968            publish_bootstrap_admission_outcomes(&bootstrap_state, &outcomes, &HashSet::new())
11969                .await;
11970            bootstrap_state
11971                .read()
11972                .await
11973                .capacity_rejected_sources
11974                .get(&source)
11975                .copied()
11976                .expect("first rejection recorded")
11977        };
11978
11979        for _ in 0..REJECTION_ROUNDS {
11980            let outcomes = [(
11981                source,
11982                AdmissionOutcome {
11983                    discovered: HashSet::from([key]),
11984                    capacity_rejected_count: 1,
11985                    displaced: Vec::new(),
11986                },
11987            )];
11988            publish_bootstrap_admission_outcomes(
11989                &bootstrap_state,
11990                &outcomes,
11991                &HashSet::from([key]),
11992            )
11993            .await;
11994        }
11995
11996        let recorded = bootstrap_state
11997            .read()
11998            .await
11999            .capacity_rejected_sources
12000            .get(&source)
12001            .copied()
12002            .expect("debt still outstanding");
12003        assert_eq!(
12004            recorded, first_seen,
12005            "repeat rejections must not restart the expiry clock"
12006        );
12007    }
12008
12009    /// The verification-worker tick's self-heal path: a capacity rejection
12010    /// recorded after the peer's `PeerRemoved` cleanup (the TOCTOU orphan)
12011    /// blocks drain until the TTL expires it, at which point the same tick
12012    /// completes bootstrap without any external event.
12013    #[tokio::test]
12014    async fn drain_self_heal_expires_orphaned_rejection_and_completes_bootstrap() {
12015        let peer = test_peer(0xA6);
12016        let bootstrap_state = Arc::new(RwLock::new(BootstrapState::new()));
12017        let queues = Arc::new(RwLock::new(ReplicationQueues::new()));
12018        let is_bootstrapping = Arc::new(RwLock::new(true));
12019        let bootstrap_complete_notify = Arc::new(Notify::new());
12020
12021        // PeerRemoved was fully processed before the rejection landed, so no
12022        // future event will ever clear this entry.
12023        super::bootstrap::note_capacity_rejected(&bootstrap_state, peer).await;
12024
12025        // Within the TTL the tick keeps waiting for re-delivery.
12026        expire_and_recheck_bootstrap_drain(
12027            &bootstrap_state,
12028            &queues,
12029            &is_bootstrapping,
12030            &bootstrap_complete_notify,
12031            ReplicationConfig::default().capacity_rejected_max_age(),
12032        )
12033        .await;
12034        assert!(!bootstrap_state.read().await.is_drained());
12035        assert!(*is_bootstrapping.read().await);
12036
12037        // Past the TTL the tick expires the orphan and completes bootstrap.
12038        expire_and_recheck_bootstrap_drain(
12039            &bootstrap_state,
12040            &queues,
12041            &is_bootstrapping,
12042            &bootstrap_complete_notify,
12043            Duration::ZERO,
12044        )
12045        .await;
12046        assert!(bootstrap_state.read().await.is_drained());
12047        assert!(!*is_bootstrapping.read().await);
12048    }
12049
12050    #[test]
12051    fn first_audit_terminal_outcomes_are_stable() {
12052        let peer = test_peer(1);
12053        let passed = AuditTickResult::Passed {
12054            challenged_peer: peer,
12055            keys_checked: 1,
12056        };
12057        let timed_out = AuditTickResult::Failed {
12058            evidence: FailureEvidence::AuditFailure {
12059                challenge_id: 1,
12060                challenged_peer: peer,
12061                confirmed_failed_keys: vec![test_key(1)],
12062                summary: crate::replication::types::AuditFailureSummary::default(),
12063                reason: AuditFailureReason::Timeout,
12064            },
12065            no_response_class: Some("timeout"),
12066        };
12067
12068        assert_eq!(
12069            first_audit_terminal_outcome(&passed),
12070            FirstAuditTerminalOutcome::Passed
12071        );
12072        assert_eq!(
12073            first_audit_terminal_outcome(&timed_out),
12074            FirstAuditTerminalOutcome::Timeout
12075        );
12076        assert_eq!(
12077            first_audit_terminal_outcome(&AuditTickResult::Idle),
12078            FirstAuditTerminalOutcome::Idle
12079        );
12080        assert_eq!(FirstAuditTerminalOutcome::Passed.as_str(), "passed");
12081        assert_eq!(FirstAuditTerminalOutcome::Timeout.as_str(), "timeout");
12082        assert_eq!(FirstAuditTerminalOutcome::Failed.as_str(), "failed");
12083        assert_eq!(FirstAuditTerminalOutcome::Idle.as_str(), "idle");
12084        assert_eq!(
12085            FirstAuditTerminalOutcome::InsufficientKeys.as_str(),
12086            "insufficient_keys"
12087        );
12088        assert_eq!(
12089            FirstAuditTerminalOutcome::BootstrapClaim.as_str(),
12090            "bootstrap_claim"
12091        );
12092    }
12093
12094    #[test]
12095    fn first_audit_coalescing_keeps_highest_count_and_exposes_eviction() {
12096        let mut pending = LruCache::new(NonZeroUsize::new(1).unwrap());
12097        let mut rng = StdRng::seed_from_u64(7);
12098        let peer = test_peer(1);
12099        let base = MonetizedPinEvent {
12100            peer,
12101            pin: [1; 32],
12102            key_count: 100,
12103            quote_ts: SystemTime::now(),
12104        };
12105
12106        // First insert into an empty slot: Queued.
12107        assert_eq!(
12108            coalesce_first_audit_event(&mut pending, base, true, &mut rng),
12109            FirstAuditQueueOutcome::Queued
12110        );
12111
12112        // A strictly LOWER-count same-peer nomination must NOT displace it.
12113        let lower = MonetizedPinEvent {
12114            pin: [2; 32],
12115            key_count: 50,
12116            ..base
12117        };
12118        assert_eq!(
12119            coalesce_first_audit_event(&mut pending, lower, true, &mut rng),
12120            FirstAuditQueueOutcome::SuppressedLower
12121        );
12122        assert_eq!(
12123            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12124            Some(([1; 32], 100)),
12125            "the higher-count pin is retained"
12126        );
12127
12128        // A HIGHER-count same-peer nomination wins (the inflated pin to audit).
12129        let higher = MonetizedPinEvent {
12130            pin: [3; 32],
12131            key_count: 400,
12132            ..base
12133        };
12134        assert_eq!(
12135            coalesce_first_audit_event(&mut pending, higher, true, &mut rng),
12136            FirstAuditQueueOutcome::Coalesced
12137        );
12138        assert_eq!(
12139            pending.peek(&peer).map(|e| (e.pin, e.key_count)),
12140            Some(([3; 32], 400))
12141        );
12142
12143        // EQUAL count: an ordinary (newer) enqueue replaces for freshness...
12144        let equal_newer = MonetizedPinEvent {
12145            pin: [4; 32],
12146            key_count: 400,
12147            ..base
12148        };
12149        assert_eq!(
12150            coalesce_first_audit_event(&mut pending, equal_newer, true, &mut rng),
12151            FirstAuditQueueOutcome::Coalesced
12152        );
12153        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12154        // ...but an equal-count OLDER requeue (incoming_is_newer=false) does not.
12155        let equal_older = MonetizedPinEvent {
12156            pin: [5; 32],
12157            key_count: 400,
12158            ..base
12159        };
12160        assert_eq!(
12161            coalesce_first_audit_event(&mut pending, equal_older, false, &mut rng),
12162            FirstAuditQueueOutcome::RetainedOnTie
12163        );
12164        assert_eq!(pending.peek(&peer).map(|e| e.pin), Some([4; 32]));
12165
12166        // A different peer at capacity 1 evicts the LRU (a DIFFERENT peer).
12167        let other_peer = MonetizedPinEvent {
12168            peer: test_peer(2),
12169            pin: [6; 32],
12170            key_count: 100,
12171            ..base
12172        };
12173        assert_eq!(
12174            coalesce_first_audit_event(&mut pending, other_peer, true, &mut rng),
12175            FirstAuditQueueOutcome::CapacityEvicted { peer, pin: [4; 32] }
12176        );
12177        assert_eq!(pending.len(), 1);
12178        assert_eq!(pending.peek(&other_peer.peer).map(|e| e.pin), Some([6; 32]));
12179    }
12180
12181    // -- ADR-0004 Amendment 2: first-audit launch limiter --------------------
12182
12183    #[test]
12184    fn first_audit_limiter_enforces_burst_then_refills() {
12185        let base = Instant::now();
12186        let mut limiter = FirstAuditLimiter::new(base);
12187        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12188
12189        // The full burst is admitted back-to-back (distinct peers).
12190        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12191            let peer = test_peer(u8::try_from(i).expect("small burst"));
12192            assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12193            limiter.commit_launch(peer, 10, base);
12194        }
12195        // Bucket empty: the next distinct peer is deferred, never dropped.
12196        let extra = test_peer(0xEE);
12197        assert_eq!(
12198            limiter.assess(&extra, 10, base, 0),
12199            LimiterVerdict::RateDeferred
12200        );
12201
12202        // One full interval later exactly one token is available again.
12203        let later = base + interval;
12204        assert_eq!(limiter.assess(&extra, 10, later, 0), LimiterVerdict::Admit);
12205        limiter.commit_launch(extra, 10, later);
12206        let extra2 = test_peer(0xEF);
12207        assert_eq!(
12208            limiter.assess(&extra2, 10, later, 0),
12209            LimiterVerdict::RateDeferred
12210        );
12211    }
12212
12213    #[test]
12214    fn first_audit_limiter_refill_keeps_fractional_remainder() {
12215        let base = Instant::now();
12216        let mut limiter = FirstAuditLimiter::new(base);
12217        let interval = config::FIRST_AUDIT_LAUNCH_INTERVAL;
12218        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12219            let peer = test_peer(u8::try_from(i).expect("small burst"));
12220            assert_eq!(limiter.assess(&peer, 1, base, 0), LimiterVerdict::Admit);
12221            limiter.commit_launch(peer, 1, base);
12222        }
12223        // 1.5 intervals later one token is earned and the half interval is
12224        // NOT lost to drift...
12225        let at_1_5 = base + interval + interval / 2;
12226        let p = test_peer(0xAA);
12227        assert_eq!(limiter.assess(&p, 1, at_1_5, 0), LimiterVerdict::Admit);
12228        limiter.commit_launch(p, 1, at_1_5);
12229        // ...so the next token arrives at 2.0 intervals, not 2.5.
12230        let at_2_0 = base + interval * 2;
12231        let q = test_peer(0xAB);
12232        assert_eq!(limiter.assess(&q, 1, at_2_0, 0), LimiterVerdict::Admit);
12233    }
12234
12235    #[test]
12236    fn first_audit_limiter_inflight_cap_defers_until_slot_frees() {
12237        let base = Instant::now();
12238        let mut limiter = FirstAuditLimiter::new(base);
12239        let peer = test_peer(1);
12240        assert_eq!(
12241            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT),
12242            LimiterVerdict::RateDeferred
12243        );
12244        // A freed slot admits without any clock movement.
12245        assert_eq!(
12246            limiter.assess(&peer, 1, base, config::FIRST_AUDIT_MAX_INFLIGHT - 1),
12247            LimiterVerdict::Admit
12248        );
12249    }
12250
12251    #[test]
12252    fn first_audit_limiter_assess_consumes_nothing() {
12253        let base = Instant::now();
12254        let mut limiter = FirstAuditLimiter::new(base);
12255        let peer = test_peer(3);
12256        // Repeated assessment must not burn budget or stamp the window: only
12257        // `commit_launch` consumes (the cooldown gate between assess and
12258        // commit can defer, and that deferral must be free).
12259        for _ in 0..10 {
12260            assert_eq!(limiter.assess(&peer, 5, base, 0), LimiterVerdict::Admit);
12261        }
12262        for i in 0..config::FIRST_AUDIT_BUDGET_BURST {
12263            let p = test_peer(0x20 + u8::try_from(i).expect("small burst"));
12264            assert_eq!(limiter.assess(&p, 5, base, 0), LimiterVerdict::Admit);
12265            limiter.commit_launch(p, 5, base);
12266        }
12267    }
12268
12269    #[test]
12270    fn first_audit_limiter_window_dedups_rotated_pins_and_count_jump_overrides() {
12271        let base = Instant::now();
12272        let mut limiter = FirstAuditLimiter::new(base);
12273        let peer = test_peer(7);
12274        assert_eq!(limiter.assess(&peer, 100, base, 0), LimiterVerdict::Admit);
12275        limiter.commit_launch(peer, 100, base);
12276
12277        // A rotated pin with a similar count inside the window is dropped...
12278        let soon = base + Duration::from_mins(1);
12279        assert_eq!(
12280            limiter.assess(&peer, 100, soon, 0),
12281            LimiterVerdict::WindowDeduped
12282        );
12283        // ...even at the exact jump boundary (new*DEN == old*NUM is no jump)...
12284        assert_eq!(
12285            limiter.assess(&peer, 150, soon, 0),
12286            LimiterVerdict::WindowDeduped
12287        );
12288        // ...but a >1.5x committed-count jump re-nominates immediately (an
12289        // inflated sidecar-only pin is invisible to the gossip lottery, so
12290        // the window must not shield it).
12291        assert_eq!(limiter.assess(&peer, 151, soon, 0), LimiterVerdict::Admit);
12292
12293        // Window expiry re-admits an unchanged count.
12294        let expired = base + config::FIRST_AUDIT_PEER_REAUDIT_INTERVAL;
12295        assert_eq!(
12296            limiter.assess(&peer, 100, expired, 0),
12297            LimiterVerdict::Admit
12298        );
12299    }
12300
12301    #[test]
12302    fn first_audit_limiter_window_verdict_outranks_empty_budget() {
12303        // A window-deduped nomination must be DROPPED, not kept pending as
12304        // rate-deferred, even when the bucket is also empty: re-queuing a
12305        // suppressed rotation would hold a pending slot for two hours.
12306        let base = Instant::now();
12307        let mut limiter = FirstAuditLimiter::new(base);
12308        let peer = test_peer(9);
12309        assert_eq!(limiter.assess(&peer, 10, base, 0), LimiterVerdict::Admit);
12310        limiter.commit_launch(peer, 10, base);
12311        let other = test_peer(10);
12312        assert_eq!(limiter.assess(&other, 10, base, 0), LimiterVerdict::Admit);
12313        limiter.commit_launch(other, 10, base);
12314        assert_eq!(
12315            limiter.assess(&peer, 10, base, 0),
12316            LimiterVerdict::WindowDeduped
12317        );
12318    }
12319
12320    /// ADR-0004 Amendment 2 (E'): the B horizon prefilter rejects a quote that
12321    /// is answerable now but would age out of the answerability window during
12322    /// the launch jitter, so scheduling state is only ever committed for a pin
12323    /// that can still be challenged when it actually sends.
12324    #[test]
12325    fn first_audit_horizon_prefilter_boundary() {
12326        let now = SystemTime::now();
12327        // C = the too-old cutoff; H = the worst-case send horizon.
12328        let c = GOSSIP_ANSWERABILITY_TTL.saturating_sub(MONETIZED_AUDIT_SKEW_MARGIN);
12329        let h = config::FIRST_AUDIT_LAUNCH_JITTER_MAX + FIRST_AUDIT_SEND_LATENCY_SLACK;
12330        // A quote whose age is exactly C at `now + H` (in the past, since C > H).
12331        let boundary = now
12332            .checked_add(h)
12333            .and_then(|t| t.checked_sub(c))
12334            .expect("boundary time");
12335
12336        // In window at `now` (age = C - H < C)...
12337        assert!(quote_within_audit_window(boundary, now));
12338        // ...but the horizon prefilter rejects it (age == C at now + H).
12339        assert!(!quote_answerable_through_nominal_jitter(boundary, now));
12340
12341        // A hair newer stays answerable through the horizon; a hair older does
12342        // not. Use 1µs (not 1ns): Windows `SystemTime` has 100ns granularity, so
12343        // a nanosecond step would round to the same instant there.
12344        let newer = boundary
12345            .checked_add(Duration::from_micros(1))
12346            .expect("newer");
12347        let older = boundary
12348            .checked_sub(Duration::from_micros(1))
12349            .expect("older");
12350        assert!(quote_answerable_through_nominal_jitter(newer, now));
12351        assert!(!quote_answerable_through_nominal_jitter(older, now));
12352
12353        // A quote too far in the FUTURE is rejected at `now`, independent of the
12354        // horizon.
12355        let future = now
12356            .checked_add(MONETIZED_AUDIT_SKEW_MARGIN)
12357            .and_then(|t| t.checked_add(Duration::from_mins(1)))
12358            .expect("future");
12359        assert!(!quote_answerable_through_nominal_jitter(future, now));
12360    }
12361
12362    /// ADR-0004 Amendment 2 (E'): a reservation whose AUTHORITATIVE post-jitter
12363    /// answerability check fails at promotion is fully state-neutral — it stamps
12364    /// no `first_audited`, no per-peer window, refunds its token, releases its
12365    /// in-flight slot, does not flip the lane, and does not count a launch — and
12366    /// a same-peer, same-count successor enqueued DURING the reservation is
12367    /// retained and becomes the next reservation after the cancel. This is the
12368    /// exact hole the reviewer flagged: suppression must never outlive a launch
12369    /// that did not send.
12370    /// A pending pin that has aged past the answerability horizon must not
12371    /// suppress a live lower-count nomination for the same peer: under token
12372    /// starvation no reserve scan ever collects the dead entry, so without the
12373    /// enqueue-time check the peer would stay unauditable through this path
12374    /// indefinitely (e.g. after a prune legitimately lowered its key count).
12375    #[test]
12376    fn first_audit_stale_incumbent_does_not_suppress_live_lower_count() {
12377        let obs = Arc::new(FirstAuditObservability::default());
12378        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12379        let peer = test_peer(1);
12380
12381        let dead_quote = SystemTime::now()
12382            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12383            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12384            .expect("past wall time");
12385        let stale_high = MonetizedPinEvent {
12386            peer,
12387            pin: [1; 32],
12388            key_count: 400,
12389            quote_ts: dead_quote,
12390        };
12391        scheduler.enqueue(stale_high, &obs);
12392        assert_eq!(scheduler.pending_len(), 1);
12393
12394        // A fresh, lower-count nomination (a post-prune commitment).
12395        let fresh_lower = MonetizedPinEvent {
12396            peer,
12397            pin: [2; 32],
12398            key_count: 100,
12399            quote_ts: SystemTime::now(),
12400        };
12401        scheduler.enqueue(fresh_lower, &obs);
12402
12403        assert_eq!(scheduler.pending_len(), 1);
12404        assert_eq!(
12405            scheduler.pending.peek(&peer).map(|e| e.pin),
12406            Some([2; 32]),
12407            "the live nomination replaced the dead incumbent"
12408        );
12409        assert_eq!(
12410            obs.suppressed_lower.load(Ordering::Relaxed),
12411            0,
12412            "no self-erasure signal for displacing a dead pin"
12413        );
12414        assert_eq!(obs.queued.load(Ordering::Relaxed), 2);
12415        assert_eq!(
12416            obs.outside_answerability_window.load(Ordering::Relaxed),
12417            1,
12418            "the dead incumbent is accounted as an expiry"
12419        );
12420    }
12421
12422    /// The self-erasure defence is untouched for LIVE incumbents: a lower-count
12423    /// nomination still loses to an answerable higher-count pending pin.
12424    #[test]
12425    fn first_audit_live_incumbent_still_suppresses_lower_count() {
12426        let obs = Arc::new(FirstAuditObservability::default());
12427        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12428        let peer = test_peer(1);
12429
12430        let live_high = MonetizedPinEvent {
12431            peer,
12432            pin: [1; 32],
12433            key_count: 400,
12434            quote_ts: SystemTime::now(),
12435        };
12436        scheduler.enqueue(live_high, &obs);
12437        let cheaper = MonetizedPinEvent {
12438            peer,
12439            pin: [2; 32],
12440            key_count: 100,
12441            quote_ts: SystemTime::now(),
12442        };
12443        scheduler.enqueue(cheaper, &obs);
12444
12445        assert_eq!(scheduler.pending_len(), 1);
12446        assert_eq!(
12447            scheduler.pending.peek(&peer).map(|e| e.pin),
12448            Some([1; 32]),
12449            "the higher-count live pin is retained"
12450        );
12451        assert_eq!(obs.suppressed_lower.load(Ordering::Relaxed), 1);
12452        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 0);
12453    }
12454
12455    /// A fresh nomination for peer `b` (distinct pin per peer).
12456    fn live_nomination(b: u8) -> MonetizedPinEvent {
12457        MonetizedPinEvent {
12458            peer: test_peer(b),
12459            pin: [b; 32],
12460            key_count: 100,
12461            quote_ts: SystemTime::now(),
12462        }
12463    }
12464
12465    /// The pending admission cap must equal the number of usable launches the
12466    /// token budget can perform inside one answerability window, counted by
12467    /// SIMULATING the shipped reserve-time predicate instant-by-instant (burst
12468    /// tokens at age zero, one refill per launch interval), not by repeating
12469    /// the derivation formula. Any larger and admitted work is guaranteed to
12470    /// expire unlaunched; any smaller and the budget idles while nominations
12471    /// are displaced.
12472    #[test]
12473    fn first_audit_pending_cap_matches_strict_launch_horizon() {
12474        let quote_ts = SystemTime::now();
12475        // Burst launches fire at age zero and must pass the reserve predicate.
12476        assert!(quote_answerable_through_nominal_jitter(quote_ts, quote_ts));
12477        let mut usable = usize::try_from(config::FIRST_AUDIT_BUDGET_BURST).expect("burst fits");
12478        let mut refill = 1u32;
12479        loop {
12480            let age = config::FIRST_AUDIT_LAUNCH_INTERVAL * refill;
12481            let at = quote_ts + age;
12482            if !quote_answerable_through_nominal_jitter(quote_ts, at) {
12483                break;
12484            }
12485            usable += 1;
12486            refill += 1;
12487            assert!(refill < 10_000, "runaway horizon simulation");
12488        }
12489        assert_eq!(
12490            FIRST_AUDIT_PENDING_CAP, usable,
12491            "cap must match the simulated strict launch horizon"
12492        );
12493    }
12494
12495    /// The pending queue is sized to the launch budget while the dedup set
12496    /// keeps the commitment-cache bound: shrinking `first_audited` would
12497    /// forget audited pins and re-admit duplicates.
12498    #[test]
12499    fn first_audit_pending_cap_independent_of_dedup_cap() {
12500        let scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12501        assert_eq!(scheduler.pending.cap().get(), FIRST_AUDIT_PENDING_CAP);
12502        assert_eq!(
12503            scheduler.first_audited.cap().get(),
12504            MAX_LAST_COMMITMENT_BY_PEER
12505        );
12506    }
12507
12508    /// Admission beyond the cap displaces exactly one incumbent per overflow
12509    /// and every displacement is accounted as `capacity_evicted` — the steady
12510    /// overload signal — never silent loss, and never an admission refusal.
12511    #[test]
12512    fn first_audit_admission_beyond_cap_displaces_and_counts() {
12513        let obs = Arc::new(FirstAuditObservability::default());
12514        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12515        let overflow: usize = 5;
12516        let total = FIRST_AUDIT_PENDING_CAP + overflow;
12517
12518        for i in 0..total {
12519            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12520            scheduler.enqueue(live_nomination(b), &obs);
12521        }
12522
12523        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12524        assert_eq!(
12525            obs.capacity_evicted.load(Ordering::Relaxed),
12526            u64::try_from(overflow).expect("overflow fits u64"),
12527            "each admission past the cap displaces exactly one entry"
12528        );
12529        assert_eq!(
12530            obs.queued.load(Ordering::Relaxed),
12531            u64::try_from(total).expect("total fits u64"),
12532            "displacement is not an admission refusal"
12533        );
12534        // Every arrival was admitted (the newest always enters the sample).
12535        let last = u8::try_from(total).expect("test peer count fits u8");
12536        assert!(
12537            scheduler.pending.peek(&test_peer(last)).is_some(),
12538            "the newest arrival always enters the sample"
12539        );
12540    }
12541
12542    /// The reviewer-demonstrated suppression route: a target followed by an
12543    /// ordered batch of distinct-peer nominations, all inside one ingress
12544    /// drain batch (`pending_cap < batch <= FIRST_AUDIT_DRAIN_BATCH`), with
12545    /// the token bucket EMPTY so no reservation can intervene. Under the old
12546    /// keep-newest LRU the target was evicted with certainty; under random
12547    /// displacement its per-overflow eviction probability is `1/cap`, so
12548    /// across repeated trials the target must survive some runs and be
12549    /// displaced in others — never deterministically flushed, and every
12550    /// displacement accounted.
12551    #[test]
12552    fn first_audit_ordered_flood_cannot_deterministically_evict_target() {
12553        let flood: usize = 60; // pending_cap < 60 <= FIRST_AUDIT_DRAIN_BATCH
12554        assert!(FIRST_AUDIT_PENDING_CAP < flood);
12555        assert!(flood <= config::FIRST_AUDIT_DRAIN_BATCH);
12556
12557        let trials = 100u64;
12558        let mut survived = 0u32;
12559        let mut evicted = 0u32;
12560        for trial in 0..trials {
12561            let obs = Arc::new(FirstAuditObservability::default());
12562            let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12563            // Deterministic per-trial seed: the run is fully reproducible (no
12564            // flake budget at all) while still exercising 100 distinct
12565            // eviction sequences.
12566            scheduler.rng = StdRng::seed_from_u64(trial);
12567            // Drain the burst tokens so the pre-overflow reservation
12568            // opportunity cannot fire: this isolates pure retention.
12569            scheduler.limiter.reserve_token();
12570            scheduler.limiter.reserve_token();
12571
12572            let target = test_peer(200);
12573            scheduler.enqueue(live_nomination(200), &obs);
12574            for i in 0..flood {
12575                let b = u8::try_from(i + 1).expect("flood peer fits u8");
12576                scheduler.enqueue(live_nomination(b), &obs);
12577            }
12578
12579            assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12580            let overflows = u64::try_from(1 + flood - FIRST_AUDIT_PENDING_CAP)
12581                .expect("overflow count fits u64");
12582            assert_eq!(
12583                obs.capacity_evicted.load(Ordering::Relaxed),
12584                overflows,
12585                "every overflow past the cap is accounted, none silent"
12586            );
12587            if scheduler.pending.peek(&target).is_some() {
12588                survived += 1;
12589            } else {
12590                evicted += 1;
12591            }
12592        }
12593        // With eviction probability 1/cap per overflow, P(target survives one
12594        // trial) ~= (1 - 1/31)^30 ~= 0.37, so both outcomes appear across the
12595        // 100 seeded trials — and the seeds make the split exactly
12596        // reproducible rather than a (vanishingly small) flake budget.
12597        assert!(
12598            survived > 0,
12599            "target must survive some ordered floods — deterministic eviction \
12600             would mean keep-newest retention regressed"
12601        );
12602        assert!(
12603            evicted > 0,
12604            "target must also be displaceable — otherwise overflow is refusing \
12605             admissions instead of sampling"
12606        );
12607    }
12608
12609    /// With a token AVAILABLE, an overflowing arrival must first give pending
12610    /// work a launch opportunity: the drainer's pre-overflow reservation pulls
12611    /// one entry out of the queue, so admission proceeds without any eviction.
12612    #[test]
12613    fn first_audit_overflow_reserves_before_destructive_eviction() {
12614        let obs = Arc::new(FirstAuditObservability::default());
12615        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12616        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12617
12618        for i in 0..FIRST_AUDIT_PENDING_CAP {
12619            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12620            scheduler.enqueue(live_nomination(b), &obs);
12621        }
12622        let overflowing = live_nomination(250);
12623        assert!(scheduler.would_displace(&overflowing));
12624
12625        // The drainer's pre-overflow sequence: reserve, then enqueue.
12626        assert!(scheduler.try_reserve(Instant::now(), 0, Duration::ZERO, &cooldown, &obs));
12627        assert!(
12628            !scheduler.would_displace(&overflowing),
12629            "a successful reservation frees the slot"
12630        );
12631        scheduler.enqueue(overflowing, &obs);
12632
12633        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12634        assert_eq!(
12635            obs.capacity_evicted.load(Ordering::Relaxed),
12636            0,
12637            "no destructive eviction when a launch opportunity existed"
12638        );
12639    }
12640
12641    /// Displacement stamps no suppression state: a displaced peer's next
12642    /// nomination re-enters like any newcomer (it is NOT window-deduped or
12643    /// treated as a duplicate), so under overload every peer keeps an
12644    /// unpredictable chance of prompt first audit.
12645    #[test]
12646    fn first_audit_displaced_peer_may_be_renominated() {
12647        let obs = Arc::new(FirstAuditObservability::default());
12648        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12649        let total = FIRST_AUDIT_PENDING_CAP + 1;
12650
12651        for i in 0..total {
12652            let b = u8::try_from(i + 1).expect("test peer count fits u8");
12653            scheduler.enqueue(live_nomination(b), &obs);
12654        }
12655        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 1);
12656        // Find whichever peer the random displacement removed.
12657        let displaced = (1..=total)
12658            .map(|i| u8::try_from(i).expect("test peer count fits u8"))
12659            .find(|b| scheduler.pending.peek(&test_peer(*b)).is_none())
12660            .expect("exactly one admitted peer was displaced");
12661
12662        scheduler.enqueue(live_nomination(displaced), &obs);
12663
12664        assert!(
12665            scheduler.pending.peek(&test_peer(displaced)).is_some(),
12666            "the displaced peer re-enters the sample"
12667        );
12668        assert_eq!(scheduler.pending_len(), FIRST_AUDIT_PENDING_CAP);
12669        assert_eq!(obs.capacity_evicted.load(Ordering::Relaxed), 2);
12670        assert_eq!(obs.duplicates.load(Ordering::Relaxed), 0);
12671        assert_eq!(obs.window_deduped.load(Ordering::Relaxed), 0);
12672    }
12673
12674    /// The periodic sweep collects expired pending entries even when the token
12675    /// bucket is empty — the reserve path returns at the budget gate and never
12676    /// scans — keeping the capped pending queue and the pending/oldest-age telemetry
12677    /// honest under fleet-wide starvation.
12678    #[test]
12679    fn first_audit_sweep_expired_collects_dead_entries_without_tokens() {
12680        let obs = Arc::new(FirstAuditObservability::default());
12681        let mono = Instant::now();
12682        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12683
12684        let dead_quote = SystemTime::now()
12685            .checked_sub(GOSSIP_ANSWERABILITY_TTL)
12686            .and_then(|t| t.checked_sub(Duration::from_mins(1)))
12687            .expect("past wall time");
12688        scheduler.enqueue(
12689            MonetizedPinEvent {
12690                peer: test_peer(1),
12691                pin: [1; 32],
12692                key_count: 100,
12693                quote_ts: dead_quote,
12694            },
12695            &obs,
12696        );
12697        scheduler.enqueue(
12698            MonetizedPinEvent {
12699                peer: test_peer(2),
12700                pin: [2; 32],
12701                key_count: 100,
12702                quote_ts: SystemTime::now(),
12703            },
12704            &obs,
12705        );
12706        assert_eq!(scheduler.pending_len(), 2);
12707
12708        // Empty the bucket so the reserve path is budget-gated (fleet-wide
12709        // starvation) and cannot collect the dead entry itself.
12710        scheduler.limiter.tokens = 0;
12711        let cooldown: HashMap<PeerId, Instant> = HashMap::new();
12712        assert!(!scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown, &obs));
12713        assert_eq!(
12714            scheduler.pending_len(),
12715            2,
12716            "budget-gated reserve scans nothing"
12717        );
12718
12719        let wall_now = SystemTime::now();
12720        assert_eq!(scheduler.sweep_expired(wall_now, &obs), 1);
12721        assert_eq!(scheduler.pending_len(), 1);
12722        assert!(
12723            scheduler.pending.peek(&test_peer(2)).is_some(),
12724            "the live entry survives the sweep"
12725        );
12726        assert_eq!(obs.outside_answerability_window.load(Ordering::Relaxed), 1);
12727        let age_ms = scheduler.oldest_pending_quote_age_ms(wall_now);
12728        assert!(
12729            Duration::from_millis(age_ms) < GOSSIP_ANSWERABILITY_TTL,
12730            "the age gauge reflects only live work after the sweep"
12731        );
12732    }
12733
12734    #[test]
12735    #[allow(clippy::too_many_lines)]
12736    fn first_audit_answerability_cancel_is_state_neutral_and_retains_successor() {
12737        let obs = Arc::new(FirstAuditObservability::default());
12738        let mono = Instant::now();
12739        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12740
12741        // A pre-existing window sentinel for an UNRELATED peer must survive the
12742        // cancel byte-for-byte (cancel never touches `recent`).
12743        let sentinel_peer = test_peer(0xAA);
12744        scheduler.limiter.promote(sentinel_peer, 500, mono);
12745        let sentinel_before = scheduler
12746            .limiter
12747            .recent
12748            .peek(&sentinel_peer)
12749            .copied()
12750            .expect("sentinel present");
12751
12752        let peer = test_peer(1);
12753        let a = MonetizedPinEvent {
12754            peer,
12755            pin: [1; 32],
12756            key_count: 100,
12757            quote_ts: SystemTime::now(), // fresh: passes the horizon prefilter now
12758        };
12759        scheduler.enqueue(a, &obs);
12760
12761        let tokens_before = scheduler.tokens();
12762        let lane_before = scheduler.oldest_first_lane;
12763        let launched_before = obs.launched.load(Ordering::Relaxed);
12764        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12765
12766        // Reserve A (jitter 0 so it is immediately due).
12767        let inflight0 = obs.inflight.load(Ordering::Relaxed);
12768        assert!(scheduler.try_reserve(mono, inflight0, Duration::ZERO, &cooldown, &obs));
12769        assert_eq!(scheduler.reserved_peer(), Some(peer));
12770        assert_eq!(
12771            scheduler.tokens(),
12772            tokens_before - 1,
12773            "reserve consumes a token"
12774        );
12775        assert_eq!(
12776            obs.inflight.load(Ordering::Relaxed),
12777            1,
12778            "reserve holds a slot"
12779        );
12780
12781        // A same-peer, same-count successor arrives DURING the reservation. It
12782        // must be retained (bypasses the window for the reserved peer) and must
12783        // NOT create a second reservation.
12784        let b = MonetizedPinEvent {
12785            peer,
12786            pin: [2; 32],
12787            key_count: 100,
12788            quote_ts: SystemTime::now(),
12789        };
12790        scheduler.enqueue(b, &obs);
12791        assert_eq!(scheduler.pending_len(), 1, "successor retained in pending");
12792        assert!(
12793            !scheduler.try_reserve(
12794                mono,
12795                obs.inflight.load(Ordering::Relaxed),
12796                Duration::ZERO,
12797                &cooldown,
12798                &obs
12799            ),
12800            "no second reservation while one is outstanding"
12801        );
12802
12803        // Resolve A with an injected wall time PAST A's answerability cutoff.
12804        let reservation = scheduler
12805            .take_due_reservation(mono)
12806            .expect("A is due at jitter 0");
12807        let wall_fail = a
12808            .quote_ts
12809            .checked_add(GOSSIP_ANSWERABILITY_TTL)
12810            .and_then(|t| t.checked_add(Duration::from_secs(1)))
12811            .expect("past-cutoff wall time");
12812        let promoted = scheduler.resolve(reservation, wall_fail, mono, &mut cooldown, &obs);
12813        assert!(
12814            promoted.is_none(),
12815            "answerability lapsed -> cancelled, not promoted"
12816        );
12817
12818        // State-neutral cancel.
12819        assert!(scheduler.first_audited.is_empty(), "no pin marked audited");
12820        assert!(
12821            scheduler.limiter.recent.peek(&peer).is_none(),
12822            "cancel stamps no per-peer window"
12823        );
12824        assert_eq!(
12825            scheduler.limiter.recent.peek(&sentinel_peer).copied(),
12826            Some(sentinel_before),
12827            "unrelated window sentinel untouched"
12828        );
12829        assert!(!cooldown.contains_key(&peer), "cancel stamps no cooldown");
12830        assert_eq!(
12831            scheduler.tokens(),
12832            tokens_before,
12833            "token refunded on cancel"
12834        );
12835        assert_eq!(
12836            obs.inflight.load(Ordering::Relaxed),
12837            0,
12838            "in-flight slot released"
12839        );
12840        assert_eq!(scheduler.oldest_first_lane, lane_before, "lane not flipped");
12841        assert_eq!(
12842            obs.launched.load(Ordering::Relaxed),
12843            launched_before,
12844            "no launch counted"
12845        );
12846        assert_eq!(
12847            obs.outside_answerability_window.load(Ordering::Relaxed),
12848            1,
12849            "the cancel reason is recorded"
12850        );
12851
12852        // The successor is still pending and is now fully schedulable: a fresh
12853        // reserve makes B the next reservation (proving eligibility, not merely
12854        // that the limiter would admit it).
12855        assert_eq!(
12856            scheduler.pending_len(),
12857            1,
12858            "successor still pending after cancel"
12859        );
12860        assert!(scheduler.reserved.is_none());
12861        assert!(scheduler.try_reserve(
12862            mono,
12863            obs.inflight.load(Ordering::Relaxed),
12864            Duration::ZERO,
12865            &cooldown,
12866            &obs
12867        ));
12868        assert_eq!(
12869            scheduler.reserved_peer(),
12870            Some(peer),
12871            "the retained successor becomes the next reservation"
12872        );
12873    }
12874
12875    /// ADR-0004 Amendment 2 (E'): when a promotion loses the shared-cooldown
12876    /// race, the reserved event is requeued ONLY if no same-peer successor is
12877    /// already pending. A successor arrived after the reservation, so it is the
12878    /// newer nomination (e.g. a count jump) and must not be overwritten by the
12879    /// older reserved event.
12880    #[test]
12881    fn first_audit_cooldown_race_requeue_preserves_newer_successor() {
12882        let obs = Arc::new(FirstAuditObservability::default());
12883        let mono = Instant::now();
12884        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
12885        let peer = test_peer(1);
12886
12887        // Reserve A.
12888        let a = MonetizedPinEvent {
12889            peer,
12890            pin: [1; 32],
12891            key_count: 100,
12892            quote_ts: SystemTime::now(),
12893        };
12894        scheduler.enqueue(a, &obs);
12895        let cooldown_reserve: HashMap<PeerId, Instant> = HashMap::new();
12896        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_reserve, &obs));
12897
12898        // A newer same-peer successor B (a count jump) arrives during the
12899        // reservation and is retained.
12900        let b = MonetizedPinEvent {
12901            peer,
12902            pin: [2; 32],
12903            key_count: 400,
12904            quote_ts: SystemTime::now(),
12905        };
12906        scheduler.enqueue(b, &obs);
12907        assert_eq!(scheduler.pending_len(), 1);
12908
12909        // Resolve A: answerability PASSES (fresh quote) but the shared cooldown
12910        // is already stamped for the peer, so promotion loses the race.
12911        let reservation = scheduler.take_due_reservation(mono).expect("due");
12912        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
12913        cooldown.insert(peer, mono); // freshly on cooldown
12914        let promoted = scheduler.resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs);
12915        assert!(promoted.is_none(), "cooldown race -> not promoted");
12916
12917        // B (newer) is preserved; A did NOT overwrite it.
12918        assert_eq!(scheduler.pending_len(), 1, "still exactly one pending");
12919        assert_eq!(
12920            scheduler.pending.peek(&peer).map(|e| e.pin),
12921            Some([2; 32]),
12922            "the newer successor B is retained, not the older reserved A"
12923        );
12924        assert!(scheduler.first_audited.is_empty());
12925        assert!(scheduler.limiter.recent.peek(&peer).is_none());
12926    }
12927
12928    /// The oldest-pending-quote-age gauge reports the age of the OLDEST quote
12929    /// still awaiting a first audit (not the newest), is `0` on an empty queue,
12930    /// and saturates to `0` for a future-dated quote (clock skew) without
12931    /// panicking. A climbing value is the pending-work-aging-out signal.
12932    #[test]
12933    fn first_audit_oldest_pending_quote_age_tracks_the_oldest() {
12934        let now = SystemTime::now();
12935        let mut scheduler = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12936        assert_eq!(
12937            scheduler.oldest_pending_quote_age_ms(now),
12938            0,
12939            "empty pending -> zero"
12940        );
12941
12942        // Two peers: quotes 10s and 2s old. The gauge must track the older.
12943        for (peer_id, pin, secs) in [(1u8, [1; 32], 10u64), (2, [2; 32], 2)] {
12944            let _ = coalesce_first_audit_event(
12945                &mut scheduler.pending,
12946                MonetizedPinEvent {
12947                    peer: test_peer(peer_id),
12948                    pin,
12949                    key_count: 100,
12950                    quote_ts: now - Duration::from_secs(secs),
12951                },
12952                true,
12953                &mut scheduler.rng,
12954            );
12955        }
12956        assert_eq!(
12957            scheduler.oldest_pending_quote_age_ms(now),
12958            10_000,
12959            "tracks the oldest (10s), not the newest (2s)"
12960        );
12961
12962        // A future-dated quote (clock skew) saturates to zero, never panics.
12963        let mut skewed = FirstAuditScheduler::new(Instant::now(), test_peer(99));
12964        let _ = coalesce_first_audit_event(
12965            &mut skewed.pending,
12966            MonetizedPinEvent {
12967                peer: test_peer(3),
12968                pin: [3; 32],
12969                key_count: 100,
12970                quote_ts: now + Duration::from_secs(5),
12971            },
12972            true,
12973            &mut skewed.rng,
12974        );
12975        assert_eq!(
12976            skewed.oldest_pending_quote_age_ms(now),
12977            0,
12978            "future quote_ts saturates to zero"
12979        );
12980    }
12981
12982    /// A flood of strictly-lower-count same-peer nominations must neither
12983    /// displace the retained higher pin NOR disturb its recency position (each
12984    /// is suppressed via `peek`, no `push`), and each must be counted as
12985    /// `suppressed_lower` — the attempted cheaper-pin self-erasure signal.
12986    /// Recency is asserted DIRECTLY via the queue's MRU-to-LRU iteration order
12987    /// (the documented `lru` contract that also drives the reserve scan's lane
12988    /// ordering), deliberately independent of the overflow policy: eviction is
12989    /// random-victim, so no assertion may require a particular peer to be
12990    /// displaced.
12991    #[test]
12992    fn first_audit_suppressed_lower_flood_leaves_recency_and_counts() {
12993        let mut pending: LruCache<PeerId, MonetizedPinEvent> =
12994            LruCache::new(NonZeroUsize::new(2).unwrap());
12995        let mut rng = StdRng::seed_from_u64(11);
12996        let victim = test_peer(1);
12997        let other = test_peer(2);
12998        // Victim (high count) inserted first (older), then `other` (newer/MRU).
12999        let _ = coalesce_first_audit_event(
13000            &mut pending,
13001            MonetizedPinEvent {
13002                peer: victim,
13003                pin: [1; 32],
13004                key_count: 400,
13005                quote_ts: SystemTime::now(),
13006            },
13007            true,
13008            &mut rng,
13009        );
13010        let _ = coalesce_first_audit_event(
13011            &mut pending,
13012            MonetizedPinEvent {
13013                peer: other,
13014                pin: [9; 32],
13015                key_count: 100,
13016                quote_ts: SystemTime::now(),
13017            },
13018            true,
13019            &mut rng,
13020        );
13021        let order_before: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
13022        assert_eq!(
13023            order_before,
13024            vec![other, victim],
13025            "sanity: `other` is MRU, the victim is LRU"
13026        );
13027
13028        // Flood the victim with cheaper nominations.
13029        let mut suppressed = 0u64;
13030        for i in 0..8u8 {
13031            let out = coalesce_first_audit_event(
13032                &mut pending,
13033                MonetizedPinEvent {
13034                    peer: victim,
13035                    pin: [i; 32],
13036                    key_count: 50,
13037                    quote_ts: SystemTime::now(),
13038                },
13039                true,
13040                &mut rng,
13041            );
13042            assert_eq!(out, FirstAuditQueueOutcome::SuppressedLower);
13043            suppressed += 1;
13044        }
13045        assert_eq!(suppressed, 8);
13046        // Victim pin/count unchanged.
13047        assert_eq!(
13048            pending.peek(&victim).map(|e| (e.pin, e.key_count)),
13049            Some(([1; 32], 400))
13050        );
13051        // Recency untouched: the iteration order (which the reserve lanes
13052        // consume) is byte-for-byte what it was before the flood.
13053        let order_after: Vec<PeerId> = pending.iter().map(|(p, _)| *p).collect();
13054        assert_eq!(
13055            order_after, order_before,
13056            "the suppressed-lower flood must not have changed any recency position"
13057        );
13058    }
13059
13060    /// The cooldown-race requeue counts a genuine different-peer capacity
13061    /// eviction (the ADR promises capacity loss is observable).
13062    #[test]
13063    fn first_audit_cooldown_race_requeue_counts_capacity_eviction() {
13064        let obs = Arc::new(FirstAuditObservability::default());
13065        let mono = Instant::now();
13066        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13067        // Pending capacity 1 so a requeue of a different peer must evict.
13068        scheduler.pending = LruCache::new(NonZeroUsize::new(1).unwrap());
13069        let reserved_peer = test_peer(1);
13070        let other_peer = test_peer(2);
13071
13072        // Reserve peer 1.
13073        scheduler.enqueue(
13074            MonetizedPinEvent {
13075                peer: reserved_peer,
13076                pin: [1; 32],
13077                key_count: 100,
13078                quote_ts: SystemTime::now(),
13079            },
13080            &obs,
13081        );
13082        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13083        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13084
13085        // A DIFFERENT peer fills the single pending slot during the reservation.
13086        scheduler.enqueue(
13087            MonetizedPinEvent {
13088                peer: other_peer,
13089                pin: [2; 32],
13090                key_count: 100,
13091                quote_ts: SystemTime::now(),
13092            },
13093            &obs,
13094        );
13095        assert_eq!(scheduler.pending_len(), 1);
13096
13097        // Resolve peer 1: cooldown race -> requeue peer 1, evicting peer 2.
13098        let reservation = scheduler.take_due_reservation(mono).expect("due");
13099        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13100        cooldown.insert(reserved_peer, mono);
13101        let cap_before = obs.capacity_evicted.load(Ordering::Relaxed);
13102        assert!(scheduler
13103            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13104            .is_none());
13105        assert_eq!(
13106            obs.capacity_evicted.load(Ordering::Relaxed),
13107            cap_before + 1,
13108            "the requeue eviction of a different peer is counted"
13109        );
13110        assert_eq!(
13111            scheduler.pending.peek(&reserved_peer).map(|e| e.pin),
13112            Some([1; 32])
13113        );
13114    }
13115
13116    /// ADR-0004 Amendment 2 (reviewer blocker): a strictly-lower-count same-peer
13117    /// nomination arriving while an inflated pin is PENDING must not displace it.
13118    /// The inflated pin stays and is the one launched.
13119    #[test]
13120    fn first_audit_pending_lower_count_does_not_replace_higher() {
13121        let obs = Arc::new(FirstAuditObservability::default());
13122        let mono = Instant::now();
13123        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13124        let peer = test_peer(1);
13125
13126        // Inflated (high-count) sidecar pin lands in pending.
13127        scheduler.enqueue(
13128            MonetizedPinEvent {
13129                peer,
13130                pin: [1; 32],
13131                key_count: 400,
13132                quote_ts: SystemTime::now(),
13133            },
13134            &obs,
13135        );
13136        // A cheaper same-peer settlement arrives right after.
13137        scheduler.enqueue(
13138            MonetizedPinEvent {
13139                peer,
13140                pin: [2; 32],
13141                key_count: 100,
13142                quote_ts: SystemTime::now(),
13143            },
13144            &obs,
13145        );
13146
13147        assert_eq!(scheduler.pending_len(), 1);
13148        assert_eq!(
13149            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13150            Some(([1; 32], 400)),
13151            "the inflated pin must not be erased by the cheaper successor"
13152        );
13153        // The dropped cheaper nomination is counted through the enqueue path.
13154        assert_eq!(
13155            obs.suppressed_lower.load(Ordering::Relaxed),
13156            1,
13157            "the attempted cheaper-pin self-erasure is observable"
13158        );
13159
13160        // It reserves and promotes as the inflated pin/count.
13161        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13162        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13163        let reservation = scheduler.take_due_reservation(mono).expect("due");
13164        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13165        let (event, _slot) = scheduler
13166            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13167            .expect("promotes");
13168        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13169    }
13170
13171    /// ADR-0004 Amendment 2 (reviewer blocker): a RESERVED inflated pin that
13172    /// loses the cooldown race must be requeued OVER a lower-count same-peer
13173    /// successor that arrived during its jitter, and must remain launchable once
13174    /// the shared cooldown expires — the cheaper successor cannot suppress it.
13175    #[test]
13176    fn first_audit_cooldown_race_requeues_reserved_higher_over_lower_successor() {
13177        let obs = Arc::new(FirstAuditObservability::default());
13178        let mono = Instant::now();
13179        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13180        let peer = test_peer(1);
13181
13182        // Reserve the inflated pin.
13183        scheduler.enqueue(
13184            MonetizedPinEvent {
13185                peer,
13186                pin: [1; 32],
13187                key_count: 400,
13188                quote_ts: SystemTime::now(),
13189            },
13190            &obs,
13191        );
13192        let cooldown_read: HashMap<PeerId, Instant> = HashMap::new();
13193        assert!(scheduler.try_reserve(mono, 0, Duration::ZERO, &cooldown_read, &obs));
13194
13195        // A cheaper successor arrives during the reservation (bypasses the
13196        // window as the reserved peer) and sits in pending.
13197        scheduler.enqueue(
13198            MonetizedPinEvent {
13199                peer,
13200                pin: [2; 32],
13201                key_count: 100,
13202                quote_ts: SystemTime::now(),
13203            },
13204            &obs,
13205        );
13206        assert_eq!(scheduler.pending_len(), 1);
13207
13208        // Resolve: answerability passes but the shared cooldown is already
13209        // stamped, so the reservation loses the race and requeues.
13210        let reservation = scheduler.take_due_reservation(mono).expect("due");
13211        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13212        cooldown.insert(peer, mono);
13213        assert!(scheduler
13214            .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13215            .is_none());
13216
13217        // The inflated pin (400) replaced the cheaper successor (100).
13218        assert_eq!(scheduler.pending_len(), 1);
13219        assert_eq!(
13220            scheduler.pending.peek(&peer).map(|e| (e.pin, e.key_count)),
13221            Some(([1; 32], 400)),
13222            "the inflated reserved pin must survive the requeue over the cheaper successor"
13223        );
13224        assert!(scheduler.first_audited.is_empty());
13225        assert!(scheduler.limiter.recent.peek(&peer).is_none());
13226
13227        // Once the shared cooldown expires, the inflated pin reserves and
13228        // promotes with its intended pin/count.
13229        let later = mono
13230            .checked_add(Duration::from_secs(
13231                config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1,
13232            ))
13233            .expect("later");
13234        let cooldown_read_later: HashMap<PeerId, Instant> = HashMap::new();
13235        assert!(scheduler.try_reserve(later, 0, Duration::ZERO, &cooldown_read_later, &obs));
13236        let reservation = scheduler.take_due_reservation(later).expect("due");
13237        let mut cooldown_later: HashMap<PeerId, Instant> = HashMap::new();
13238        let (event, _slot) = scheduler
13239            .resolve(
13240                reservation,
13241                SystemTime::now(),
13242                later,
13243                &mut cooldown_later,
13244                &obs,
13245            )
13246            .expect("promotes after cooldown");
13247        assert_eq!((event.pin, event.key_count), ([1; 32], 400));
13248    }
13249
13250    /// ADR-0004 Amendment 2 (E'): consecutive PROMOTIONS strictly alternate the
13251    /// launch lane, driven through the real scheduler (reserve -> resolve ->
13252    /// promote), so a stream of fresh nominations cannot keep every launch on
13253    /// the newest lane and starve the oldest.
13254    #[test]
13255    fn first_audit_lane_alternates_across_promotions() {
13256        let obs = Arc::new(FirstAuditObservability::default());
13257        let mono = Instant::now();
13258        let mut scheduler = FirstAuditScheduler::new(mono, test_peer(99));
13259        let mut cooldown: HashMap<PeerId, Instant> = HashMap::new();
13260
13261        // Two distinct peers; the newest-inserted is the MRU (newest lane end).
13262        let oldest_peer = test_peer(1);
13263        let newest_peer = test_peer(2);
13264        scheduler.enqueue(
13265            MonetizedPinEvent {
13266                peer: oldest_peer,
13267                pin: [1; 32],
13268                key_count: 100,
13269                quote_ts: SystemTime::now(),
13270            },
13271            &obs,
13272        );
13273        scheduler.enqueue(
13274            MonetizedPinEvent {
13275                peer: newest_peer,
13276                pin: [2; 32],
13277                key_count: 100,
13278                quote_ts: SystemTime::now(),
13279            },
13280            &obs,
13281        );
13282
13283        let mut launched_peers = Vec::new();
13284        for _ in 0..2 {
13285            assert!(scheduler.try_reserve(
13286                mono,
13287                obs.inflight.load(Ordering::Relaxed),
13288                Duration::ZERO,
13289                &cooldown,
13290                &obs
13291            ));
13292            let reservation = scheduler.take_due_reservation(mono).expect("due");
13293            // Answerable wall time == the quote's own time (age 0).
13294            let (event, _slot) = scheduler
13295                .resolve(reservation, SystemTime::now(), mono, &mut cooldown, &obs)
13296                .expect("fresh in-window quote promotes");
13297            launched_peers.push(event.peer);
13298        }
13299
13300        // First launch takes the newest lane (lane starts false = newest), the
13301        // second takes the oldest lane: strict alternation.
13302        assert_eq!(
13303            launched_peers,
13304            vec![newest_peer, oldest_peer],
13305            "consecutive promotions alternate newest-then-oldest lane"
13306        );
13307    }
13308
13309    #[test]
13310    fn first_audit_count_jump_boundaries() {
13311        // Exactly 1.5x is NOT a jump; strictly above is.
13312        assert!(!first_audit_count_jump(100, 150));
13313        assert!(first_audit_count_jump(100, 151));
13314        // Anything beats an audited zero; zero never jumps.
13315        assert!(first_audit_count_jump(0, 1));
13316        assert!(!first_audit_count_jump(0, 0));
13317        // Equal max counts must not jump (and must not overflow).
13318        assert!(!first_audit_count_jump(u32::MAX, u32::MAX));
13319    }
13320
13321    /// A verified payment's quote list includes the local node's own quote, so
13322    /// the verifier emits a monetized-pin event for the local peer on every
13323    /// payment it verifies. The node cannot network-audit itself, so the
13324    /// scheduler must drop such an event at ingress: never queued, and hence
13325    /// never launched nor marked first-audited.
13326    #[test]
13327    fn first_audit_queue_drops_self_targeting_events() {
13328        let obs = Arc::new(FirstAuditObservability::default());
13329        let self_peer = test_peer(1);
13330        let mut scheduler = FirstAuditScheduler::new(Instant::now(), self_peer);
13331        let self_event = MonetizedPinEvent {
13332            peer: self_peer,
13333            pin: [7; 32],
13334            key_count: 1,
13335            quote_ts: SystemTime::now(),
13336        };
13337
13338        scheduler.enqueue(self_event, &obs);
13339        assert_eq!(obs.self_target_skipped.load(Ordering::Relaxed), 1);
13340        assert_eq!(obs.queued.load(Ordering::Relaxed), 0);
13341        assert_eq!(scheduler.pending_len(), 0, "self-target must never queue");
13342
13343        // A remote peer's event still queues normally under the same filter.
13344        let remote_event = MonetizedPinEvent {
13345            peer: test_peer(2),
13346            pin: [8; 32],
13347            ..self_event
13348        };
13349        scheduler.enqueue(remote_event, &obs);
13350        assert_eq!(obs.queued.load(Ordering::Relaxed), 1);
13351        assert_eq!(scheduler.pending_len(), 1);
13352        assert_eq!(
13353            obs.self_target_skipped.load(Ordering::Relaxed),
13354            1,
13355            "remote event must not count as a self-target skip"
13356        );
13357    }
13358
13359    #[test]
13360    fn fresh_offer_runs_store_admission_payment_checks() {
13361        let context = fresh_offer_payment_context();
13362        assert_eq!(context, VerificationContext::FreshReplication);
13363        // Fresh replication must keep verifying exactly like a direct client
13364        // PUT (store-strength cache, same live checks); the variant only
13365        // exists so price-floor telemetry can tell the two paths apart.
13366        assert!(context.is_store_admission());
13367    }
13368
13369    #[test]
13370    fn paid_notify_uses_paid_list_admission_payment_checks() {
13371        assert_eq!(
13372            paid_notify_payment_context(),
13373            VerificationContext::PaidListAdmission
13374        );
13375    }
13376
13377    /// ADR-0004 A1 (guardrail A): the monetized first-audit only fires for a
13378    /// signed quote inside the answerability window, fail-closed on BOTH ends so a
13379    /// stale or future/skewed client-forwarded quote cannot frame an honest node.
13380    #[test]
13381    fn monetized_quote_audit_window_fails_closed_both_ends() {
13382        let now = SystemTime::now();
13383        // Fresh (just quoted) and small future/past skew -> audited.
13384        assert!(quote_within_audit_window(now, now));
13385        assert!(quote_within_audit_window(now + Duration::from_mins(1), now));
13386        assert!(quote_within_audit_window(
13387            now - Duration::from_hours(1),
13388            now
13389        ));
13390        // Far future (badly-skewed / replayed) -> skipped.
13391        assert!(!quote_within_audit_window(
13392            now + MONETIZED_AUDIT_SKEW_MARGIN + Duration::from_mins(1),
13393            now
13394        ));
13395        // Older than the window -> skipped (pin may have aged out).
13396        assert!(!quote_within_audit_window(
13397            now - commitment_state::GOSSIP_ANSWERABILITY_TTL,
13398            now
13399        ));
13400    }
13401
13402    #[tokio::test]
13403    async fn replication_branch_lagged_events_are_counted() {
13404        let before = audit_metrics::replication_event_lagged_total();
13405        let flow = handle_replication_event_recv_error(
13406            &tokio::sync::broadcast::error::RecvError::Lagged(3),
13407        );
13408        assert_eq!(flow, std::ops::ControlFlow::Continue(()));
13409        let after = audit_metrics::replication_event_lagged_total();
13410        assert_eq!(after.saturating_sub(before), 3);
13411    }
13412
13413    #[tokio::test]
13414    async fn replication_branch_closed_events_stop_the_loop() {
13415        let flow =
13416            handle_replication_event_recv_error(&tokio::sync::broadcast::error::RecvError::Closed);
13417        assert_eq!(flow, std::ops::ControlFlow::Break(()));
13418    }
13419
13420    #[tokio::test]
13421    async fn full_serial_queue_drops_instead_of_running_the_message_inline() {
13422        let (sender, mut receiver) = mpsc::channel(1);
13423        let dropped_body =
13424            ReplicationMessageBody::VerificationRequest(protocol::VerificationRequest {
13425                keys: Vec::new(),
13426                paid_list_check_indices: Vec::new(),
13427            });
13428        let overflow_before = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13429        let first = InboundReplicationMessage {
13430            source: test_peer(0xC1),
13431            msg: ReplicationMessage {
13432                request_id: 1,
13433                body: ReplicationMessageBody::FetchRequest(protocol::FetchRequest {
13434                    key: test_key(1),
13435                }),
13436            },
13437            rr_message_id: None,
13438            received_at: Instant::now(),
13439        };
13440        let second = InboundReplicationMessage {
13441            source: test_peer(0xC2),
13442            msg: ReplicationMessage {
13443                request_id: 2,
13444                body: dropped_body.clone(),
13445            },
13446            rr_message_id: None,
13447            received_at: Instant::now(),
13448        };
13449
13450        assert!(try_enqueue_serial_message(&sender, first).is_ok());
13451        let dropped = try_enqueue_serial_message(&sender, second)
13452            .expect_err("a full serial queue must refuse the second message");
13453        assert_eq!(dropped.reason, SerialQueueDropReason::Full);
13454        assert_eq!(dropped.message_class, "verification_request");
13455        assert_eq!(dropped.queue_depth, 1);
13456        let overflow_after = audit_metrics::serial_queue_overflow_drops_total(&dropped_body);
13457        assert_eq!(overflow_after.saturating_sub(overflow_before), 1);
13458
13459        let queued = receiver
13460            .recv()
13461            .await
13462            .expect("first message should remain queued");
13463        assert_eq!(queued.msg.request_id, 1);
13464        assert!(receiver.try_recv().is_err());
13465    }
13466
13467    #[tokio::test]
13468    async fn digest_admission_gets_higher_per_peer_cap_subtree_stays_at_two() {
13469        let peer = test_peer(0x44);
13470        let semaphore = Arc::new(Semaphore::new(config::MAX_CONCURRENT_AUDIT_RESPONSES));
13471
13472        let digest_inflight = Arc::new(RwLock::new(HashMap::new()));
13473        let mut digest_guards = Vec::new();
13474        for _ in 0..config::MAX_DIGEST_AUDIT_RESPONSES_PER_PEER {
13475            let guard = admit_audit_responder(
13476                &semaphore,
13477                &digest_inflight,
13478                &peer,
13479                AuditResponderClass::Digest,
13480            )
13481            .await;
13482            assert!(guard.is_ok());
13483            digest_guards.push(guard);
13484        }
13485        assert!(
13486            admit_audit_responder(
13487                &semaphore,
13488                &digest_inflight,
13489                &peer,
13490                AuditResponderClass::Digest,
13491            )
13492            .await
13493            .is_err(),
13494            "digest class must stop at its documented per-source cap"
13495        );
13496        drop(digest_guards);
13497
13498        let subtree_inflight = Arc::new(RwLock::new(HashMap::new()));
13499        let mut subtree_guards = Vec::new();
13500        for _ in 0..config::MAX_AUDIT_RESPONSES_PER_PEER {
13501            let guard = admit_audit_responder(
13502                &semaphore,
13503                &subtree_inflight,
13504                &peer,
13505                AuditResponderClass::Subtree,
13506            )
13507            .await;
13508            assert!(guard.is_ok());
13509            subtree_guards.push(guard);
13510        }
13511        assert!(
13512            admit_audit_responder(
13513                &semaphore,
13514                &subtree_inflight,
13515                &peer,
13516                AuditResponderClass::Subtree,
13517            )
13518            .await
13519            .is_err(),
13520            "subtree class must retain the deployed cap of two"
13521        );
13522        drop(subtree_guards);
13523    }
13524
13525    #[test]
13526    fn in_scope_audit_deadlines_share_one_formula() {
13527        let config = config::ReplicationConfig::default();
13528        for key_count in [1, 4, 16] {
13529            assert_eq!(
13530                audit::responsible_audit_response_timeout(&config, key_count),
13531                config.audit_response_timeout(key_count)
13532            );
13533            assert_eq!(
13534                pruning::prune_audit_response_timeout(&config, key_count),
13535                config.audit_response_timeout(key_count)
13536            );
13537        }
13538        assert_eq!(
13539            possession::possession_probe_response_timeout(&config),
13540            config.audit_response_timeout(1)
13541        );
13542    }
13543
13544    #[test]
13545    fn replica_hint_sources_are_added_as_fallback_fetch_sources() {
13546        const EXISTING_SOURCE_ID: u8 = 1;
13547        const HINT_SENDER_ID: u8 = 2;
13548
13549        let existing_source = test_peer(EXISTING_SOURCE_ID);
13550        let hint_sender = test_peer(HINT_SENDER_ID);
13551        let mut sources = vec![existing_source];
13552
13553        let hint_sources = HashSet::from([hint_sender]);
13554        add_replica_hint_sources(&mut sources, &hint_sources);
13555        add_replica_hint_sources(&mut sources, &hint_sources);
13556
13557        // A paid-only advertiser leaves the claim set empty (see
13558        // `queue_admitted_hints`), so it contributes no fetch source.
13559        add_replica_hint_sources(&mut sources, &HashSet::new());
13560
13561        assert_eq!(sources, vec![existing_source, hint_sender]);
13562    }
13563
13564    #[test]
13565    fn audit_timeout_preserves_active_bootstrap_claim() {
13566        assert!(!audit_failure_clears_bootstrap_claim(
13567            &AuditFailureReason::Timeout
13568        ));
13569    }
13570
13571    fn strike_peer(b: u8) -> PeerId {
13572        let mut bytes = [0u8; 32];
13573        bytes[0] = b;
13574        PeerId::from_bytes(bytes)
13575    }
13576
13577    // ADR-0002: "occasional surprise exams, keeps load low" — the per-peer
13578    // cooldown must collapse a gossip flood into at most one audit per window.
13579
13580    #[test]
13581    fn gossip_flood_yields_at_most_one_audit_per_cooldown_window() {
13582        let peer = strike_peer(1);
13583        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13584        let t0 = Instant::now();
13585        // First gossip in the window passes; a burst of further gossips at the
13586        // same instant are all suppressed.
13587        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13588        let mut passed = 1;
13589        for _ in 0..100 {
13590            if cooldown_allows_audit(&mut map, &peer, t0) {
13591                passed += 1;
13592            }
13593        }
13594        assert_eq!(
13595            passed, 1,
13596            "a flood at one instant must trigger exactly one audit"
13597        );
13598    }
13599
13600    // ADR-0002 ordering invariant: `maybe_trigger_gossip_audit` stamps the
13601    // per-peer cooldown BEFORE the probability lottery, so a LOSING ticket still
13602    // consumes the window. This is the property the isolated cooldown tests above
13603    // cannot see: they never sample the lottery, so a regression that reordered
13604    // the gates (sample probability first, only stamp the cooldown on a win)
13605    // would still pass them while breaking flood-resistance: a flood would then
13606    // re-roll the lottery on EVERY message until one won, multiplying audits.
13607    //
13608    // We model the exact production gate order (attempt-window, lottery,
13609    // shared cooldown) with a lottery driven by a fixed outcome instead of
13610    // `gen_bool(..)`. The first message LOSES the lottery; the remaining flood
13611    // messages all WIN. With the production order, the losing first ticket
13612    // burns the ATTEMPT window and every later winner in the same window is
13613    // blocked, so there are 0 audits this window. If the gates were flipped,
13614    // the second message's winning ticket would slip through. The window only
13615    // reopens after it elapses.
13616    //
13617    // FLIPS IF: the lottery is sampled before the attempt-window
13618    // check-and-stamp (a losing ticket no longer consumes the window),
13619    // re-enabling a flood-amplified audit storm.
13620    #[test]
13621    fn losing_lottery_still_consumes_attempt_window() {
13622        // Calls the SHIPPED `audit_launch_decision` (the same function
13623        // `maybe_trigger_gossip_audit` uses), so a reorder of the gates in
13624        // production fails this test — not a local reimplementation.
13625        let peer = strike_peer(3);
13626        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13627        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13628        let t0 = Instant::now();
13629
13630        // First flooded message at t0 LOSES the lottery, but the attempt window
13631        // is stamped BEFORE the lottery is consulted, so the window is consumed.
13632        assert!(
13633            !audit_launch_decision(&mut attempts, &mut launched, &peer, t0, false),
13634            "a losing ticket launches no audit"
13635        );
13636
13637        // 99 more flooded messages at the same instant would all WIN the lottery,
13638        // yet every one must be blocked by the attempt window the loser stamped.
13639        // (If production sampled the lottery FIRST, these would each get a fresh
13640        // roll and audits would multiply — this assertion catches that reorder.)
13641        let mut audits = 0;
13642        for _ in 0..99 {
13643            if audit_launch_decision(&mut attempts, &mut launched, &peer, t0, true) {
13644                audits += 1;
13645            }
13646        }
13647        assert_eq!(
13648            audits, 0,
13649            "a losing first ticket must consume the attempt window so no later \
13650             flooded message in the same window can audit"
13651        );
13652
13653        // The window only reopens after it elapses; the next winning ticket
13654        // then launches exactly one audit and stamps the SHARED cooldown.
13655        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13656        assert!(
13657            audit_launch_decision(&mut attempts, &mut launched, &peer, after, true),
13658            "after the window a winning ticket audits again"
13659        );
13660        assert!(
13661            launched.contains_key(&peer),
13662            "a real launch stamps the shared cooldown"
13663        );
13664    }
13665
13666    /// The reviewer-flagged suppression route: a LOSING gossip lottery must not
13667    /// stamp the SHARED audit cooldown, otherwise repeated losses (one per
13668    /// 30-minute window, no challenge ever sent) keep a paid monetized pin's
13669    /// first audit deferred until its answerability window expires.
13670    ///
13671    /// FLIPS IF: `audit_launch_decision` stamps the shared `launched` map on a
13672    /// loss (the pre-split behavior, where both paths shared one map).
13673    #[test]
13674    fn losing_lottery_does_not_suppress_monetized_first_audit() {
13675        let peer = strike_peer(4);
13676        let mut attempts: HashMap<PeerId, Instant> = HashMap::new();
13677        let mut launched: HashMap<PeerId, Instant> = HashMap::new();
13678        let t0 = Instant::now();
13679
13680        // A losing ticket consumes the gossip attempt window...
13681        assert!(!audit_launch_decision(
13682            &mut attempts,
13683            &mut launched,
13684            &peer,
13685            t0,
13686            false
13687        ));
13688        // ...but leaves the shared map untouched, so the first-audit reserve
13689        // gate (read-only) and the authoritative promotion check-and-stamp both
13690        // still allow the paid audit to launch immediately.
13691        assert!(
13692            cooldown_would_allow(&launched, &peer, t0),
13693            "reserve gate must not see a losing ticket as audit coverage"
13694        );
13695        assert!(
13696            cooldown_allows_audit(&mut launched, &peer, t0),
13697            "promotion must not be deferred by a losing ticket"
13698        );
13699
13700        // Conversely a WINNING ticket (real audit sent) does suppress the
13701        // first audit for the window, which is the intended shared semantics.
13702        let peer_won = strike_peer(5);
13703        assert!(audit_launch_decision(
13704            &mut attempts,
13705            &mut launched,
13706            &peer_won,
13707            t0,
13708            true
13709        ));
13710        assert!(
13711            !cooldown_would_allow(&launched, &peer_won, t0),
13712            "a real gossip audit still covers the peer for the window"
13713        );
13714    }
13715
13716    #[test]
13717    fn cooldown_lets_audit_through_after_the_window() {
13718        let peer = strike_peer(2);
13719        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13720        let t0 = Instant::now();
13721        assert!(cooldown_allows_audit(&mut map, &peer, t0));
13722        // Within the window: suppressed.
13723        let within = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS - 1);
13724        assert!(!cooldown_allows_audit(&mut map, &peer, within));
13725        // Past the window: allowed again.
13726        let after = t0 + Duration::from_secs(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS + 1);
13727        assert!(cooldown_allows_audit(&mut map, &peer, after));
13728    }
13729
13730    #[test]
13731    fn cooldown_is_per_peer_independent() {
13732        let mut map: HashMap<PeerId, Instant> = HashMap::new();
13733        let t0 = Instant::now();
13734        // Different peers each get their own first-audit pass at the same instant.
13735        for i in 0..20u8 {
13736            assert!(
13737                cooldown_allows_audit(&mut map, &strike_peer(i), t0),
13738                "peer {i} should be auditable independently"
13739            );
13740        }
13741    }
13742
13743    #[test]
13744    fn audit_on_gossip_constants_match_adr() {
13745        // Tripwire on the ADR-locked tunables. The spot-check count sits at the
13746        // top of the auditor's 3..=5 band (the auditor clamps to that band, so
13747        // values above 5 would silently never be requested).
13748        assert_eq!(config::AUDIT_SPOTCHECK_COUNT, 5);
13749        assert!((config::AUDIT_ON_GOSSIP_PROBABILITY - 0.2).abs() < f64::EPSILON);
13750        assert_eq!(config::AUDIT_ON_GOSSIP_COOLDOWN_SECS, 30 * 60);
13751    }
13752
13753    // (d) A confirmed storage-integrity failure penalizes immediately and
13754    // revokes credit; it is not a timeout.
13755    #[test]
13756    fn digest_mismatch_is_not_a_timeout_and_penalizes_immediately() {
13757        assert!(audit_failure_clears_bootstrap_claim(
13758            &AuditFailureReason::DigestMismatch
13759        ));
13760        assert!(audit_failure_revokes_holder_credit(
13761            &AuditFailureReason::DigestMismatch
13762        ));
13763    }
13764
13765    /// The exact decision the `Failed` arm of `handle_subtree_audit_result`
13766    /// uses: confirmed failures revoke credit, `Timeout` does not.
13767    #[test]
13768    fn confirmed_failures_revoke_credit_timeout_does_not() {
13769        for reason in [
13770            AuditFailureReason::MalformedResponse,
13771            AuditFailureReason::DigestMismatch,
13772            AuditFailureReason::KeyAbsent,
13773            AuditFailureReason::Rejected,
13774        ] {
13775            assert!(
13776                audit_failure_revokes_holder_credit(&reason),
13777                "confirmed failure {reason:?} must revoke holder credit"
13778            );
13779        }
13780        assert!(
13781            !audit_failure_revokes_holder_credit(&AuditFailureReason::Timeout),
13782            "Timeout must NOT revoke credit (single dropped packet != storage loss)"
13783        );
13784    }
13785
13786    /// Wiring test for the security fix: the helper the handler calls
13787    /// actually strips a credited peer on a confirmed failure
13788    /// (`DigestMismatch`), and actually RETAINS credit on `Timeout`.
13789    /// Records genuine credit first so neither assertion is vacuous;
13790    /// this fails if `forget_peer` stops being called, or if the
13791    /// `Timeout` exclusion is dropped (both verified by mutation).
13792    #[test]
13793    fn apply_revocation_strips_on_digest_mismatch_retains_on_timeout() {
13794        let peer = test_peer(0xAB);
13795        let key = test_key(1);
13796        let hash = [0xCD; 32];
13797
13798        // Confirmed failure -> credit revoked.
13799        let mut provers = RecentProvers::new();
13800        provers.record_proof(key, peer, hash, Instant::now());
13801        assert!(
13802            provers.is_credited_holder(&key, &peer, &hash),
13803            "precondition: peer credited before failure"
13804        );
13805        apply_audit_failure_credit_revocation(
13806            &mut provers,
13807            &peer,
13808            &AuditFailureReason::DigestMismatch,
13809        );
13810        assert!(
13811            !provers.is_credited_holder(&key, &peer, &hash),
13812            "DigestMismatch must strip the peer's holder credit"
13813        );
13814
13815        // Timeout -> credit retained.
13816        let mut provers_timeout = RecentProvers::new();
13817        provers_timeout.record_proof(key, peer, hash, Instant::now());
13818        apply_audit_failure_credit_revocation(
13819            &mut provers_timeout,
13820            &peer,
13821            &AuditFailureReason::Timeout,
13822        );
13823        assert!(
13824            provers_timeout.is_credited_holder(&key, &peer, &hash),
13825            "Timeout must retain holder credit (deliberate liveness cushion)"
13826        );
13827    }
13828
13829    #[test]
13830    fn decoded_audit_failures_clear_active_bootstrap_claim() {
13831        for reason in [
13832            AuditFailureReason::MalformedResponse,
13833            AuditFailureReason::DigestMismatch,
13834            AuditFailureReason::KeyAbsent,
13835            AuditFailureReason::Rejected,
13836        ] {
13837            assert!(
13838                audit_failure_clears_bootstrap_claim(&reason),
13839                "decoded non-bootstrap failure {reason:?} should clear active claim"
13840            );
13841        }
13842    }
13843
13844    #[test]
13845    fn first_failed_key_label_truncates_to_16_hex_chars() {
13846        // The high-order 8 bytes of the XorName determine the label so an
13847        // operator can group audit-failures on the same chunk prefix.
13848        let mut key = [0u8; 32];
13849        key[0] = 0x18;
13850        key[7] = 0xff;
13851        // Low-order bytes (positions 8..32) are deliberately set to 0xAA
13852        // to verify they are NOT included in the label.
13853        for byte in &mut key[8..] {
13854            *byte = 0xAA;
13855        }
13856        let label = first_failed_key_label(&[key]);
13857        // Only the first 8 bytes are encoded, low-order bytes are dropped.
13858        assert_eq!(label, "0x18000000000000ff");
13859        assert_eq!(label.len(), "0x".len() + 16);
13860    }
13861
13862    #[test]
13863    fn first_failed_key_label_falls_back_when_empty() {
13864        // Should never happen in production (audit failure handling rejects
13865        // empty sets), but the formatter must still produce a valid label
13866        // so the log line doesn't contain a misleading default.
13867        assert_eq!(first_failed_key_label(&[]), "0x");
13868    }
13869
13870    #[test]
13871    fn first_failed_key_label_uses_first_key_only() {
13872        let first = [0x11u8; 32];
13873        let second = [0x22u8; 32];
13874        assert_eq!(
13875            first_failed_key_label(&[first, second]),
13876            format!("0x{}", hex::encode(&first[..8]))
13877        );
13878    }
13879
13880    // -- apply_fetch_result --------------------------------------------------
13881    //
13882    // The worker's disposition of a fetch outcome. Note there is no trust
13883    // handle in `apply_fetch_result`'s signature: the worker cannot report a
13884    // trust event for ANY outcome, and `execute_single_fetch` returns
13885    // `NoLongerResponsible` before its trust-reporting paths — the source did
13886    // nothing wrong when this node's own responsibility lapsed.
13887
13888    /// Route `key` through the real pipeline stages (pending → promoted →
13889    /// dequeued → in-flight) so it carries a verification retry-slot
13890    /// reservation, exactly as a worker-dequeued key does. Returns the
13891    /// in-flight source.
13892    fn drive_key_in_flight(
13893        q: &mut ReplicationQueues,
13894        key: XorName,
13895        sources: Vec<PeerId>,
13896    ) -> PeerId {
13897        let hinter = sources.first().copied().unwrap_or_else(|| test_peer(0x01));
13898        let now = Instant::now();
13899        let entry = VerificationEntry {
13900            state: VerificationState::PendingVerify,
13901            verified_sources: Vec::new(),
13902            tried_sources: HashSet::new(),
13903            created_at: now,
13904            next_verify_at: now,
13905            hint_sources: HashSet::from([hinter]),
13906            replica_hint_sources: HashSet::from([hinter]),
13907            unresolved_retries: 0,
13908            no_holder_reported: false,
13909        };
13910        assert!(q.add_pending_verify(key, entry).admitted());
13911        assert!(q.promote_pending_to_fetch(key, key, sources));
13912        let candidate = q.dequeue_fetch().expect("promoted key must dequeue");
13913        let source = *candidate.sources.first().expect("candidate has a source");
13914        q.start_dequeued_fetch(candidate, source);
13915        source
13916    }
13917
13918    #[test]
13919    fn no_longer_responsible_is_terminal_and_releases_the_retry_slot() {
13920        const RETRY_AFTER: Duration = Duration::from_mins(1);
13921
13922        let mut q = ReplicationQueues::new();
13923        let key = test_key(0xAB);
13924        drive_key_in_flight(&mut q, key, vec![test_peer(0x01), test_peer(0x02)]);
13925        assert_eq!(q.retry_reserved_slot_count(), 1);
13926
13927        let follow_up =
13928            apply_fetch_result(&mut q, &key, &FetchResult::NoLongerResponsible, RETRY_AFTER);
13929
13930        assert_eq!(
13931            follow_up,
13932            FetchFollowUp::Terminal,
13933            "lapsed responsibility must run the caller's terminal bootstrap accounting"
13934        );
13935        assert!(
13936            !q.contains_key(&key),
13937            "the key must leave every pipeline stage — alternate sources included"
13938        );
13939        assert_eq!(
13940            q.pending_count(),
13941            0,
13942            "a lapsed-responsibility key must not be requeued for verification"
13943        );
13944        assert_eq!(
13945            q.retry_reserved_slot_count(),
13946            0,
13947            "terminal exit must release the verification retry-slot reservation"
13948        );
13949    }
13950
13951    #[test]
13952    fn no_longer_responsible_shares_the_stored_terminal_path() {
13953        const RETRY_AFTER: Duration = Duration::from_mins(1);
13954
13955        // Both variants must walk the identical terminal gate so the
13956        // battle-tested Stored accounting (retry-slot release + bootstrap
13957        // pending-set shrink in the caller) covers lapsed responsibility too.
13958        for result in [FetchResult::Stored, FetchResult::NoLongerResponsible] {
13959            let mut q = ReplicationQueues::new();
13960            let key = test_key(0xCD);
13961            drive_key_in_flight(&mut q, key, vec![test_peer(0x03)]);
13962
13963            let follow_up = apply_fetch_result(&mut q, &key, &result, RETRY_AFTER);
13964
13965            assert_eq!(follow_up, FetchFollowUp::Terminal);
13966            assert!(!q.contains_key(&key));
13967            assert_eq!(q.retry_reserved_slot_count(), 0);
13968        }
13969    }
13970
13971    #[test]
13972    fn source_failure_walks_alternate_sources_then_requeues_for_verification() {
13973        const RETRY_AFTER: Duration = Duration::from_mins(1);
13974
13975        let mut q = ReplicationQueues::new();
13976        let key = test_key(0xEF);
13977        let first = test_peer(0x04);
13978        let second = test_peer(0x05);
13979        drive_key_in_flight(&mut q, key, vec![first, second]);
13980
13981        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13982        assert_eq!(
13983            follow_up,
13984            FetchFollowUp::RetryFrom(second),
13985            "a failed source must not abandon the remaining verified sources"
13986        );
13987        assert_eq!(q.in_flight_count(), 1, "retry keeps the key in flight");
13988
13989        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
13990        assert_eq!(
13991            follow_up,
13992            FetchFollowUp::RequeuedForVerification,
13993            "exhausted sources must restore the reserved verification entry"
13994        );
13995        assert_eq!(q.pending_count(), 1);
13996        assert_eq!(
13997            q.retry_reserved_slot_count(),
13998            0,
13999            "the reservation converts back into the pending entry itself"
14000        );
14001    }
14002
14003    #[test]
14004    fn source_failure_without_retry_metadata_is_terminal() {
14005        const RETRY_AFTER: Duration = Duration::from_mins(1);
14006
14007        // Direct enqueue (no pending entry) models a fetch with no
14008        // verification retry reservation to restore.
14009        let mut q = ReplicationQueues::new();
14010        let key = test_key(0x1F);
14011        let source = test_peer(0x06);
14012        assert!(q.enqueue_fetch(key, key, vec![source]));
14013        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
14014        q.start_dequeued_fetch(candidate, source);
14015
14016        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::SourceFailed, RETRY_AFTER);
14017
14018        assert_eq!(follow_up, FetchFollowUp::Terminal);
14019        assert!(!q.contains_key(&key));
14020    }
14021
14022    #[test]
14023    fn already_held_key_leaves_the_pipeline_terminally() {
14024        const RETRY_AFTER: Duration = Duration::from_mins(1);
14025
14026        let mut q = ReplicationQueues::new();
14027        let key = test_key(0x4C);
14028        let source = test_peer(0x0B);
14029        drive_key_in_flight(&mut q, key, vec![source, test_peer(0x0C)]);
14030
14031        let follow_up = apply_fetch_result(&mut q, &key, &FetchResult::AlreadyHeld, RETRY_AFTER);
14032
14033        assert_eq!(
14034            follow_up,
14035            FetchFollowUp::Terminal,
14036            "holding the key already discharges the duty, so the key must leave \
14037             the pipeline exactly as a completed fetch does — requeueing it \
14038             would re-verify a key that needs nothing"
14039        );
14040        assert!(!q.contains_key(&key));
14041        assert_eq!(
14042            q.retry_reserved_slot_count(),
14043            0,
14044            "the terminal path must release the retry-slot reservation, or the \
14045             owner's verification budget leaks"
14046        );
14047    }
14048
14049    #[test]
14050    fn local_write_failure_does_not_conscript_the_remaining_sources() {
14051        const RETRY_AFTER: Duration = Duration::from_mins(1);
14052
14053        let mut q = ReplicationQueues::new();
14054        let key = test_key(0x2A);
14055        let first = test_peer(0x07);
14056        let second = test_peer(0x08);
14057        let third = test_peer(0x09);
14058        drive_key_in_flight(&mut q, key, vec![first, second, third]);
14059
14060        let follow_up =
14061            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
14062
14063        assert_eq!(
14064            follow_up,
14065            FetchFollowUp::RequeuedForVerification,
14066            "a local write failure must go straight back to verification: the two \
14067             untried sources would each re-upload the same chunk into the same \
14068             full disk, and neither of them did anything wrong"
14069        );
14070        assert_eq!(q.in_flight_count(), 0);
14071        assert_eq!(
14072            q.pending_count(),
14073            1,
14074            "the key must come back — capacity frees up, and a stranded key is \
14075             a replica this node silently stops owing"
14076        );
14077        assert_eq!(q.retry_reserved_slot_count(), 0);
14078    }
14079
14080    #[test]
14081    fn local_write_failure_without_retry_metadata_is_terminal() {
14082        const RETRY_AFTER: Duration = Duration::from_mins(1);
14083
14084        // No pending entry to restore, so the only way not to strand the key
14085        // in `in_flight_fetch` forever — which would also stall bootstrap
14086        // drain — is the terminal path.
14087        let mut q = ReplicationQueues::new();
14088        let key = test_key(0x3B);
14089        let source = test_peer(0x0A);
14090        assert!(q.enqueue_fetch(key, key, vec![source]));
14091        let candidate = q.dequeue_fetch().expect("enqueued key must dequeue");
14092        q.start_dequeued_fetch(candidate, source);
14093
14094        let follow_up =
14095            apply_fetch_result(&mut q, &key, &FetchResult::LocalWriteFailed, RETRY_AFTER);
14096
14097        assert_eq!(follow_up, FetchFollowUp::Terminal);
14098        assert!(!q.contains_key(&key));
14099        assert_eq!(q.retry_reserved_slot_count(), 0);
14100    }
14101}